From d957b87f44284bbce9addda40c00d462a953cae7 Mon Sep 17 00:00:00 2001 From: EeOneDown Date: Thu, 19 Oct 2017 00:36:01 +0300 Subject: [PATCH 1/2] new functions and user's customization for "suburbans", update schedule_sender: added sql updater before sender --- constants.py | 15 +++--- flask_app.py | 120 +++++++++++++++++++++++++++++++++++++++++---- functions.py | 81 ++++++++++++++++++++++++++++-- schedule_sender.py | 2 + sql_updater.py | 6 +-- 5 files changed, 201 insertions(+), 23 deletions(-) diff --git a/constants.py b/constants.py index fc3cf79..8f327de 100644 --- a/constants.py +++ b/constants.py @@ -51,16 +51,17 @@ "ЛР": "лабораторная работа", "СР": "сам. работа в присутствии преподавателя"} -all_stations = {"Санкт-Петербург": "c2", 'Ленинский Проспект': "s9603435", - "Лигово": "s9603837", "Сосновая Поляна": "s9603431", - "Старый Петергоф": "s9603547", +all_stations = {"Санкт-Петербург": "c2", "Броневая": "s9603500", + "Ленинский Проспект": "s9603435", "Лигово": "s9603837", + "Сосновая Поляна": "s9603431", "Стрельна": "s9603542", + "Новый Петергоф": "s9603887", "Старый Петергоф": "s9603547", "Университетская (Университет)": "s9603770", "Ораниенбаум-1": "s9603138", "Лебяжье": "s9602688", "Калище": "s9602687"} -all_stations_const = ["Санкт-Петербург", "Ленинский Проспект", "Лигово", - "Сосновая Поляна", "Старый Петергоф", - "Университетская (Университет)", "Ораниенбаум-1", - "Лебяжье", "Калище"] +all_stations_const = ["Санкт-Петербург", "Броневая", "Ленинский Проспект", + "Лигово", "Сосновая Поляна", "Стрельна", "Новый Петергоф", + "Старый Петергоф", "Университетская (Университет)", + "Ораниенбаум-1", "Лебяжье", "Калище"] full_info_answer = \ 'ИНФОРМАЦИЯ\n\n' \ diff --git a/flask_app.py b/flask_app.py index 8e1959a..cb87a78 100644 --- a/flask_app.py +++ b/flask_app.py @@ -165,9 +165,11 @@ def not_exist_user_handler(message): def help_handler(message): bot.send_chat_action(message.chat.id, "typing") inline_full_info_keyboard = telebot.types.InlineKeyboardMarkup() + ''' delete this? inline_full_info_keyboard.row( *[telebot.types.InlineKeyboardButton(text=name, callback_data=name) for name in ["Полное ИНФО"]]) + ''' answer = briefly_info_answer bot.send_message(message.chat.id, answer, parse_mode="HTML", @@ -292,8 +294,8 @@ def suburban_handler(message): bot.send_chat_action(message.chat.id, "typing") answer = "Меню расписания электричек" suburban_keyboard = telebot.types.ReplyKeyboardMarkup(True, False) - suburban_keyboard.row('Из Универа', 'В Универ') - suburban_keyboard.row('Назад', 'Свой маршрут') + suburban_keyboard.row("Домой", "В Универ", "Маршрут") + suburban_keyboard.row("Назад", "Персонализация") answer += "\n\nДанные предоставлены сервисом " answer += "Яндекс.Расписания" bot.send_message(message.chat.id, @@ -306,8 +308,13 @@ def suburban_handler(message): @bot.message_handler(func=lambda mess: mess.text == "В Универ") def to_university_handler(message): bot.send_chat_action(message.chat.id, "typing") - from_station = all_stations["Санкт-Петербург"] - to_station = all_stations["Университетская (Университет)"] + + from_station = func.get_fom_station_code(message.chat.id) + if func.is_univer(message.chat.id): + to_station = all_stations["Университетская (Университет)"] + else: + to_station = all_stations["Старый Петергоф"] + server_datetime = datetime.today() + server_timedelta data = get_yandex_timetable_data(from_station, to_station, server_datetime) answer = data["answer"] @@ -329,12 +336,15 @@ def to_university_handler(message): disable_web_page_preview=True) -@bot.message_handler(func=lambda mess: mess.text == "Из Универа") +@bot.message_handler(func=lambda mess: mess.text == "Домой") def from_university_handler(message): bot.send_chat_action(message.chat.id, "typing") - from_station = all_stations["Университетская (Университет)"] - to_station = all_stations["Санкт-Петербург"] + to_station = func.get_fom_station_code(message.chat.id) + if func.is_univer(message.chat.id): + from_station = all_stations["Университетская (Университет)"] + else: + from_station = all_stations["Старый Петергоф"] server_datetime = datetime.today() + server_timedelta data = get_yandex_timetable_data(from_station, to_station, server_datetime) @@ -357,7 +367,7 @@ def from_university_handler(message): disable_web_page_preview=True) -@bot.message_handler(func=lambda mess: mess.text == "Свой маршрут") +@bot.message_handler(func=lambda mess: mess.text == "Маршрут") def own_trail_handler(message): answer = "Выбери начальную станцию:" start_station_keyboard = telebot.types.InlineKeyboardMarkup(True) @@ -368,6 +378,20 @@ def own_trail_handler(message): reply_markup=start_station_keyboard) +@bot.message_handler(func=lambda mess: mess.text == "Персонализация") +def personalisation_handler(message): + answer = "Здесь ты можешь настроить домашнюю и " \ + "Университетскую станции для команд Домой и " \ + "В Универ" + inline_keyboard = telebot.types.InlineKeyboardMarkup(True) + inline_keyboard.row(*[telebot.types.InlineKeyboardButton( + text=name, callback_data=name) for name in ["Домашняя"]]) + inline_keyboard.row(*[telebot.types.InlineKeyboardButton( + text=name, callback_data=name) for name in ["Университетская"]]) + bot.send_message(message.chat.id, answer, + reply_markup=inline_keyboard, parse_mode="HTML") + + @bot.message_handler(func=lambda mess: mess.text == emoji["editor"]) def schedule_editor_handler(message): bot.send_chat_action(message.chat.id, "typing") @@ -492,14 +516,15 @@ def group_templates_handler(message): parse_mode="HTML") -@bot.message_handler(func=lambda mess: mess.text == "Скул", +@bot.message_handler(func=lambda mess: mess.text == "Скул" + and mess.chat.id == my_id, content_types=["text"]) def schedule_update_handler(message): bot.send_chat_action(message.chat.id, "typing") tic = time.time() schedule_update() toc = time.time() - tic - answer = "Done\n\nWork time: {}".format(toc) + answer = "Done\nWork time: {}".format(toc) bot.reply_to(message, answer) @@ -962,6 +987,72 @@ def build_trail_handler(call_back): parse_mode="HTML") +@bot.callback_query_handler(func=lambda call_back: + call_back.data == "Домашняя") +def home_station_handler(call_back): + answer = "Выбери домашнюю станцию:" + stations_keyboard = telebot.types.InlineKeyboardMarkup(True) + for station_title in all_stations_const: + if station_title in ("Старый Петергоф", + "Университетская (Университет)"): + continue + stations_keyboard.row(*[telebot.types.InlineKeyboardButton( + text=name, callback_data=name) for name in [station_title]]) + bot.edit_message_text(text=answer, + chat_id=call_back.message.chat.id, + message_id=call_back.message.message_id, + reply_markup=stations_keyboard) + + +@bot.callback_query_handler(func=lambda call_back: + call_back.message.text == "Выбери домашнюю " + "станцию:") +def change_home_station_handler(call_back): + answer = "Домашняя станция изменена на {}".format(call_back.data) + func.change_home_station(call_back.message.chat.id, call_back.data) + bot.edit_message_text(text=answer, + chat_id=call_back.message.chat.id, + message_id=call_back.message.message_id, + parse_mode="HTML") + + +@bot.callback_query_handler(func=lambda call_back: + call_back.data == "Университетская") +def univer_station_handler(call_back): + stations = ("Старый Петергоф", "Университетская (Университет)") + answer = "Изменить станцию {} на {}?" + if func.is_univer(call_back.message.chat.id): + answer = answer.format(stations[1], stations[0]) + else: + answer = answer.format(stations[0], stations[1]) + inline_keyboard = telebot.types.InlineKeyboardMarkup(True) + inline_keyboard.row(*[telebot.types.InlineKeyboardButton( + text=name, callback_data=name) for name in ["Отмена", "Да"]]) + bot.edit_message_text(text=answer, + chat_id=call_back.message.chat.id, + message_id=call_back.message.message_id, + reply_markup=inline_keyboard, + parse_mode="HTML") + + +@bot.callback_query_handler(func=lambda call_back: + call_back.data == "Да" and + "Изменить станцию" in call_back.message.text) +def change_univer_station_handler(call_back): + answer = "Используется {}" + if func.is_univer(call_back.message.chat.id): + is_univer = 0 + station = "Старый Петергоф" + else: + is_univer = 1 + station = "Университетская (Университет)" + func.change_univer_station(call_back.message.chat.id, is_univer) + bot.edit_message_text(text=answer.format(station), + chat_id=call_back.message.chat.id, + message_id=call_back.message.message_id, + parse_mode="HTML") + + @bot.callback_query_handler(func=lambda call_back: call_back.data == "Полностью") def full_place_on_handler(call_back): @@ -1187,6 +1278,15 @@ def statistics_handler(call_back): rate = emoji["star"] * round(data[0]) answer = "Средняя оценка: {}\n".format(round(data[0], 1)) answer += "{} ({})".format(rate, data[1]) + if call_back.message.chat.id == my_id: + admin_data = func.get_statistics_for_admin() + admin_answer = "\n\nКолличество пользователей: {}\n" \ + "Колличество групп: {}\nКолличество пользователей с " \ + "активной рассылкой: {}".format( + admin_data["count_of_users"], + admin_data["count_of_groups"], + admin_data["count_of_sending"]) + bot.send_message(my_id, admin_answer) try: bot.edit_message_text(text=answer, chat_id=call_back.message.chat.id, diff --git a/functions.py b/functions.py index 426ad72..face9cd 100644 --- a/functions.py +++ b/functions.py @@ -284,13 +284,13 @@ def get_rate_statistics(): cursor.execute("""SELECT sum(rate), count(id) FROM user_data WHERE rate != 0""") - date = cursor.fetchone() + data = cursor.fetchone() cursor.close() sql_con.close() - if date[0] is None: + if data[0] is None: return None else: - return [date[0] / date[1], date[1]] + return [data[0] / data[1], data[1]] def set_rate(user_id, count_of_stars): @@ -370,3 +370,78 @@ def delete_group(group_id, user_id): finally: cursor.close() sql_con.close() + + +def get_statistics_for_admin(): + data = {} + sql_con = sqlite3.connect("Bot_db") + cursor = sql_con.cursor() + + cursor.execute("""SELECT count(id) + FROM user_data""") + data["count_of_users"] = cursor.fetchone()[0] + + cursor.execute("""SELECT count(id) + FROM groups_data""") + data["count_of_groups"] = cursor.fetchone()[0] + + cursor.execute("""SELECT count(id) + FROM user_data + WHERE sending = 1 + GROUP BY sending;""") + data["count_of_sending"] = cursor.fetchone()[0] + + cursor.close() + sql_con.close() + return data + + +def get_fom_station_code(user_id): + sql_con = sqlite3.connect("Bot_db") + cursor = sql_con.cursor() + cursor.execute("""SELECT home_station_code + FROM user_data + WHERE id = ?""", (user_id, )) + from_station = cursor.fetchone()[0] + cursor.close() + sql_con.close() + return from_station + + +def is_univer(user_id): + sql_con = sqlite3.connect("Bot_db") + cursor = sql_con.cursor() + cursor.execute("""SELECT is_univer + FROM user_data + WHERE id = ?""", (user_id,)) + univer = cursor.fetchone()[0] + cursor.close() + sql_con.close() + return univer + + +def change_home_station(user_id, station_title): + from constants import all_stations + + home_station_code = all_stations[station_title] + sql_con = sqlite3.connect("Bot_db") + cursor = sql_con.cursor() + cursor.execute("""UPDATE user_data + SET home_station_code = ? + WHERE id = ?""", + (home_station_code, user_id)) + sql_con.commit() + cursor.close() + sql_con.close() + + +def change_univer_station(user_id, univer): + sql_con = sqlite3.connect("Bot_db") + cursor = sql_con.cursor() + cursor.execute("""UPDATE user_data + SET is_univer = ? + WHERE id = ?""", + (univer, user_id)) + sql_con.commit() + cursor.close() + sql_con.close() diff --git a/schedule_sender.py b/schedule_sender.py index aa1074e..ab50fea 100644 --- a/schedule_sender.py +++ b/schedule_sender.py @@ -6,6 +6,7 @@ from datetime import datetime, timedelta from functions import get_json_day_data, create_schedule_answer, is_full_place from constants import release_token +from sql_updater import schedule_update def schedule_sender(): @@ -43,4 +44,5 @@ def schedule_sender(): if __name__ == '__main__': + schedule_update("spbu4u/Bot_db") schedule_sender() diff --git a/sql_updater.py b/sql_updater.py index d66c9f2..900349c 100644 --- a/sql_updater.py +++ b/sql_updater.py @@ -4,10 +4,10 @@ import requests -def schedule_update(): - sql_con = sqlite3.connect("Bot_db") +def schedule_update(db_path="Bot_db"): + sql_con = sqlite3.connect(db_path) cursor = sql_con.cursor() - # WITH construction don't work :( + # WITH construction doesn't work :( cursor.execute("""DELETE FROM groups_data WHERE id in ( From fdb560debbaa5b231b7fdafbe9a56ec592e1cc34 Mon Sep 17 00:00:00 2001 From: EeOneDown Date: Thu, 19 Oct 2017 00:57:44 +0300 Subject: [PATCH 2/2] educator's schedule returned --- flask_app.py | 9 --------- 1 file changed, 9 deletions(-) diff --git a/flask_app.py b/flask_app.py index cb87a78..91d1431 100644 --- a/flask_app.py +++ b/flask_app.py @@ -528,8 +528,6 @@ def schedule_update_handler(message): bot.reply_to(message, answer) -# TODO educator schedule -''' @bot.message_handler(func=lambda mess: mess.text == emoji["bust_in_silhouette"], content_types=["text"]) def educator_schedule_handler(message): @@ -538,7 +536,6 @@ def educator_schedule_handler(message): markup = telebot.types.ForceReply(False) bot.send_message(message.chat.id, answer, reply_markup=markup, parse_mode="HTML") -''' @bot.message_handler(func=lambda mess: mess.reply_to_message is not None and @@ -1428,12 +1425,6 @@ def select_master_id_handler(call_back): parse_mode="HTML") -# TODO -@bot.callback_query_handler(func=lambda call_back: True) -def other_callback_handler(call_back): - logging.error(call_back) - - @app.route("/reset_webhook", methods=["GET", "HEAD"]) def reset_webhook(): bot.remove_webhook()