Skip to content

Commit

Permalink
Merge pull request #16 from EeOneDown/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
EeOneDown authored Oct 18, 2017
2 parents de29a10 + fdb560d commit e374ff6
Show file tree
Hide file tree
Showing 5 changed files with 201 additions and 32 deletions.
15 changes: 8 additions & 7 deletions constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -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' \
Expand Down
129 changes: 110 additions & 19 deletions flask_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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 += "<a href = 'http://rasp.yandex.ru/'>Яндекс.Расписания</a>"
bot.send_message(message.chat.id,
Expand All @@ -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"]
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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 = "Здесь ты можешь настроить <b>домашнюю</b> и " \
"<b>Университетскую</b> станции для команд <i>Домой</i> и " \
"<i>В Универ</i>"
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")
Expand Down Expand Up @@ -492,19 +516,18 @@ 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)


# TODO educator schedule
'''
@bot.message_handler(func=lambda mess: mess.text == emoji["bust_in_silhouette"],
content_types=["text"])
def educator_schedule_handler(message):
Expand All @@ -513,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
Expand Down Expand Up @@ -962,6 +984,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 = "Домашняя станция изменена на <b>{}</b>".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 = "Изменить станцию <i>{}</i> на <b>{}</b>?"
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(

This comment has been minimized.

Copy link
@EeOneDown

EeOneDown Oct 25, 2017

Author Owner

# TODO Change "Да" to "Изменить"

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:

This comment has been minimized.

Copy link
@EeOneDown

EeOneDown Oct 25, 2017

Author Owner

# TODO Here too

call_back.data == "Да" and
"Изменить станцию" in call_back.message.text)
def change_univer_station_handler(call_back):
answer = "Используется <b>{}</b>"
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):
Expand Down Expand Up @@ -1187,6 +1275,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,
Expand Down Expand Up @@ -1328,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()
Expand Down
81 changes: 78 additions & 3 deletions functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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()
2 changes: 2 additions & 0 deletions schedule_sender.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down Expand Up @@ -43,4 +44,5 @@ def schedule_sender():


if __name__ == '__main__':
schedule_update("spbu4u/Bot_db")
schedule_sender()
6 changes: 3 additions & 3 deletions sql_updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down

0 comments on commit e374ff6

Please sign in to comment.