From 6baed876c60a90b70c95bccfde03a4aa5440af0b Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Mon, 18 Sep 2017 14:37:17 +0300 Subject: [PATCH 001/284] PY-2017.2.3 + + + \ No newline at end of file diff --git a/_windows/laf.xml b/_windows/laf.xml new file mode 100644 index 0000000..c1f98d9 --- /dev/null +++ b/_windows/laf.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/codestyles/Default.xml b/codestyles/Default.xml new file mode 100644 index 0000000..e598e06 --- /dev/null +++ b/codestyles/Default.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/colors.scheme.xml b/colors.scheme.xml new file mode 100644 index 0000000..39308cd --- /dev/null +++ b/colors.scheme.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/debugger.xml b/debugger.xml new file mode 100644 index 0000000..544ab15 --- /dev/null +++ b/debugger.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/editor.codeinsight.xml b/editor.codeinsight.xml new file mode 100644 index 0000000..b43f2d4 --- /dev/null +++ b/editor.codeinsight.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/editor.xml b/editor.xml new file mode 100644 index 0000000..66a0938 --- /dev/null +++ b/editor.xml @@ -0,0 +1,10 @@ + + + + + + + + \ No newline at end of file diff --git a/filetypes.xml b/filetypes.xml new file mode 100644 index 0000000..59f1d09 --- /dev/null +++ b/filetypes.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/ide.general.xml b/ide.general.xml new file mode 100644 index 0000000..8329a5d --- /dev/null +++ b/ide.general.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/ignore.xml b/ignore.xml new file mode 100644 index 0000000..b26bee8 --- /dev/null +++ b/ignore.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From 959842900dcc2a36f025c0c92974e46d8fdad083 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Mon, 18 Sep 2017 16:00:45 +0300 Subject: [PATCH 002/284] PY-2017.2.3 + + + \ No newline at end of file From 247cb1cf7cdbf4a6eda12645e6131928040f4c73 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 19 Sep 2017 15:40:01 +0300 Subject: [PATCH 003/284] PY-2017.2.3 + + + \ No newline at end of file From 03ae07cd5909e5b1bfb3711a5879c5e2cdc0f80b Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Wed, 20 Sep 2017 12:45:30 +0300 Subject: [PATCH 004/284] =?UTF-8?q?=D0=9F=D0=BE=D0=B4=D0=BE=D0=B7=D1=80?= =?UTF-8?q?=D0=B8=D1=82=D0=B5=D0=BB=D1=8C=D0=BD=D1=8B=D0=B5=20=D1=84=D0=B0?= =?UTF-8?q?=D0=B9=D0=BB=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- _windows/git.xml | 5 ----- _windows/laf.xml | 5 ----- codestyles/Default.xml | 1 - colors.scheme.xml | 5 ----- debugger.xml | 13 ------------- editor.codeinsight.xml | 6 ------ editor.xml | 10 ---------- filetypes.xml | 8 -------- find.xml | 7 ------- ide.general.xml | 5 ----- ignore.xml | 32 -------------------------------- ui.lnf.xml | 5 ----- 12 files changed, 102 deletions(-) delete mode 100644 _windows/git.xml delete mode 100644 _windows/laf.xml delete mode 100644 codestyles/Default.xml delete mode 100644 colors.scheme.xml delete mode 100644 debugger.xml delete mode 100644 editor.codeinsight.xml delete mode 100644 editor.xml delete mode 100644 filetypes.xml delete mode 100644 find.xml delete mode 100644 ide.general.xml delete mode 100644 ignore.xml delete mode 100644 ui.lnf.xml diff --git a/_windows/git.xml b/_windows/git.xml deleted file mode 100644 index a8092bd..0000000 --- a/_windows/git.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - \ No newline at end of file diff --git a/_windows/laf.xml b/_windows/laf.xml deleted file mode 100644 index c1f98d9..0000000 --- a/_windows/laf.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/codestyles/Default.xml b/codestyles/Default.xml deleted file mode 100644 index e598e06..0000000 --- a/codestyles/Default.xml +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/colors.scheme.xml b/colors.scheme.xml deleted file mode 100644 index 39308cd..0000000 --- a/colors.scheme.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/debugger.xml b/debugger.xml deleted file mode 100644 index 544ab15..0000000 --- a/debugger.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/editor.codeinsight.xml b/editor.codeinsight.xml deleted file mode 100644 index b43f2d4..0000000 --- a/editor.codeinsight.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - \ No newline at end of file diff --git a/editor.xml b/editor.xml deleted file mode 100644 index 66a0938..0000000 --- a/editor.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/filetypes.xml b/filetypes.xml deleted file mode 100644 index 59f1d09..0000000 --- a/filetypes.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/find.xml b/find.xml deleted file mode 100644 index 965789e..0000000 --- a/find.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - \ No newline at end of file diff --git a/ide.general.xml b/ide.general.xml deleted file mode 100644 index 8329a5d..0000000 --- a/ide.general.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/ignore.xml b/ignore.xml deleted file mode 100644 index b26bee8..0000000 --- a/ignore.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/ui.lnf.xml b/ui.lnf.xml deleted file mode 100644 index 73792a4..0000000 --- a/ui.lnf.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - \ No newline at end of file From d9503ebd5643aef332a2f51d7953a2f3df277dc7 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Wed, 20 Sep 2017 12:53:30 +0300 Subject: [PATCH 005/284] =?UTF-8?q?=D0=A4=D0=B8=D0=BA=D1=81=20=D0=BF=D1=80?= =?UTF-8?q?=D0=B8=20=D0=BD=D0=B5=D1=81=D1=83=D1=89=D0=B5=D1=81=D1=82=D0=B2?= =?UTF-8?q?=D1=83=D1=8E=D1=89=D0=B8=D1=85=20=D1=87=D0=B0=D1=82=D0=B0=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index 6f6921c..eb02b1b 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -370,7 +370,11 @@ def callback_query(bot: Bot, update: Update, chat_data: dict): order.text = chat_data['order'] order.chat_id = data['id'] order.date = datetime.now() - order.confirmed_msg = send_async(bot, chat_id=order.chat_id, text=MSG_ORDER_CLEARED_BY_HEADER + MSG_EMPTY).result().message_id + msg = send_async(bot, chat_id=order.chat_id, text=MSG_ORDER_CLEARED_BY_HEADER + MSG_EMPTY).result() + if msg: + order.confirmed_msg = msg.message_id + else: + order.confirmed_msg = 0 session.add(order) session.commit() markup = generate_ok_markup(order.id, 0) @@ -389,7 +393,11 @@ def callback_query(bot: Bot, update: Update, chat_data: dict): order.text = chat_data['order'] order.chat_id = item.chat_id order.date = datetime.now() - order.confirmed_msg = send_async(bot, chat_id=order.chat_id, text=MSG_ORDER_CLEARED_BY_HEADER + MSG_EMPTY).result().message_id + msg = send_async(bot, chat_id=order.chat_id, text=MSG_ORDER_CLEARED_BY_HEADER + MSG_EMPTY).result() + if msg: + order.confirmed_msg = msg.message_id + else: + order.confirmed_msg = 0 session.add(order) session.commit() markup = generate_ok_markup(order.id, 0) From 7440d9698c4865b124b4862f3f0870830dda50b8 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Wed, 20 Sep 2017 14:26:58 +0300 Subject: [PATCH 006/284] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=20=D0=BF=D1=80=D0=B8=D0=BC=D0=B5=D1=80=20=D0=BA?= =?UTF-8?q?=D0=BE=D0=BD=D1=84=D0=B8=D0=B3=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config.py.sample | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 config.py.sample diff --git a/config.py.sample b/config.py.sample new file mode 100644 index 0000000..5d8186f --- /dev/null +++ b/config.py.sample @@ -0,0 +1,6 @@ +# Содержимое этого файла необходимо скопировать в config.py и изменить под себя + +TOKEN = '359865085:AAHaRfjbZ6c6Gq_6v4llFArSF9ZxwCSX-fo' # Токен телеграмбота (получается у @BotFather) +DB = 'mysql+pymysql://:@/?charset=utf8mb4' # Строчка подключения к базе данных (поддерживается только MySql, о формате можно прочитать тут http://docs.sqlalchemy.org/en/latest/dialects/mysql.html) +API_PORT = 88 # Порт, по которому будет доступен внешний апи бота (REST) +GOVERNMENT_CHAT = -1001149271906 # Чат, в который бот будет слать отчёты \ No newline at end of file From bdda17e9803f4b971008bc71c6e2e43ace527872 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Wed, 20 Sep 2017 14:33:28 +0300 Subject: [PATCH 007/284] =?UTF-8?q?=D0=9E=D0=B9=D0=BE=D0=B9,=20=D1=80?= =?UTF-8?q?=D0=B0=D0=B1=D0=BE=D1=87=D0=B8=D0=B9=20=D1=82=D0=BE=D0=BA=D0=B5?= =?UTF-8?q?=D0=BD=20=D1=83=D1=82=D1=91=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config.py.sample | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config.py.sample b/config.py.sample index 5d8186f..49c82c5 100644 --- a/config.py.sample +++ b/config.py.sample @@ -1,6 +1,6 @@ # Содержимое этого файла необходимо скопировать в config.py и изменить под себя -TOKEN = '359865085:AAHaRfjbZ6c6Gq_6v4llFArSF9ZxwCSX-fo' # Токен телеграмбота (получается у @BotFather) +TOKEN = '' # Токен телеграмбота (получается у @BotFather) DB = 'mysql+pymysql://:@/?charset=utf8mb4' # Строчка подключения к базе данных (поддерживается только MySql, о формате можно прочитать тут http://docs.sqlalchemy.org/en/latest/dialects/mysql.html) API_PORT = 88 # Порт, по которому будет доступен внешний апи бота (REST) GOVERNMENT_CHAT = -1001149271906 # Чат, в который бот будет слать отчёты \ No newline at end of file From 435281114fc31f0ec04ca95710ae3e4fa06c3a22 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Wed, 20 Sep 2017 14:33:34 +0300 Subject: [PATCH 008/284] PY-2017.2.3 - + + From 26b96340a03e84542ae9f74e9f822b3c933d70da Mon Sep 17 00:00:00 2001 From: Leo Date: Wed, 20 Sep 2017 15:16:20 +0300 Subject: [PATCH 009/284] Pylint --- .gitignore | 4 +- core/__init__.py | 2 +- core/functions/activity.py | 18 +- core/functions/admins.py | 147 ++++++-- core/functions/api.py | 37 +- core/functions/bosses.py | 1 + core/functions/common.py | 18 +- core/functions/inline_keyboard_handling.py | 29 +- core/regexp.py | 5 +- core/template.py | 9 +- core/texts.py | 183 +++++----- core/types.py | 63 ++-- core/utils.py | 32 +- main.py | 397 +++++++++++++-------- 14 files changed, 600 insertions(+), 345 deletions(-) diff --git a/.gitignore b/.gitignore index 88e8f67..a0f71a9 100644 --- a/.gitignore +++ b/.gitignore @@ -88,4 +88,6 @@ ENV/ # Rope project settings .ropeproject .idea/ -config.py \ No newline at end of file +config.py + +.vscode diff --git a/core/__init__.py b/core/__init__.py index 7c68785..40a96af 100644 --- a/core/__init__.py +++ b/core/__init__.py @@ -1 +1 @@ -# -*- coding: utf-8 -*- \ No newline at end of file +# -*- coding: utf-8 -*- diff --git a/core/functions/activity.py b/core/functions/activity.py index e8c5806..629c5e2 100644 --- a/core/functions/activity.py +++ b/core/functions/activity.py @@ -1,8 +1,10 @@ +from datetime import datetime, timedelta + from telegram import Update, Bot + +from core.texts import MSG_ORDER_STATISTIC, MSG_ORDER_STATISTIC_OUT_FORMAT from core.types import AdminType, admin, Session, Squad from core.utils import send_async -from datetime import datetime, timedelta -from core.texts import * def activity(squad, days=0, hours=0): @@ -33,7 +35,9 @@ def day_activity(bot: Bot, update: Update): if squad is not None: msg = activity(squad, days=1) send_async(bot, chat_id=update.message.chat.id, text=msg) - except: + + #FIX: слишком общая ошибка + except Exception: session.rollback() @@ -45,7 +49,9 @@ def week_activity(bot: Bot, update: Update): if squad is not None: msg = activity(squad, days=7) send_async(bot, chat_id=update.message.chat.id, text=msg) - except: + + #FIX: слишком общая ошибка + except Exception: session.rollback() @@ -57,5 +63,7 @@ def battle_activity(bot: Bot, update: Update): if squad is not None: msg = activity(squad, hours=4) send_async(bot, chat_id=update.message.chat.id, text=msg) - except: + + #FIX: слишком общая ошибка + except Exception: session.rollback() diff --git a/core/functions/admins.py b/core/functions/admins.py index 94ee713..edbd1c0 100644 --- a/core/functions/admins.py +++ b/core/functions/admins.py @@ -1,7 +1,17 @@ from telegram import Update, Bot + +# from core.texts import * +from core.texts import ( + MSG_USER_UNKNOWN, MSG_NEW_GROUP_ADMIN, MSG_DEL_GROUP_ADMIN, + MSG_NEW_GROUP_ADMIN_EXISTS, MSG_DEL_GROUP_ADMIN_NOT_EXIST, + MSG_LIST_ADMINS_HEADER, MSG_LIST_ADMINS_FORMAT, + MSG_EMPTY, MSG_LIST_ADMINS_USER_FORMAT, + MSG_NEW_GLOBAL_ADMIN, MSG_NEW_GLOBAL_ADMIN_EXISTS, + MSG_NEW_SUPER_ADMIN, MSG_NEW_SUPER_ADMIN_EXISTS, + MSG_DEL_GLOBAL_ADMIN, MSG_DEL_GLOBAL_ADMIN_NOT_EXIST +) from core.types import User, AdminType, Admin, admin, Session from core.utils import send_async -from core.texts import * @admin() @@ -13,37 +23,54 @@ def set_admin(bot: Bot, update: Update): session = Session() user = session.query(User).filter_by(username=msg).first() if user is None: - send_async(bot, chat_id=update.message.chat.id, text=MSG_USER_UNKNOWN) + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_USER_UNKNOWN) + else: - adm = session.query(Admin).filter_by(user_id=user.id, admin_group=update.message.chat.id).first() + adm = session.query(Admin).filter_by(user_id=user.id, + admin_group=update.message.chat.id).first() + if adm is None: new_group_admin = Admin(user_id=user.id, admin_type=AdminType.GROUP.value, admin_group=update.message.chat.id) + session.add(new_group_admin) session.commit() - send_async(bot, chat_id=update.message.chat.id, + send_async(bot, + chat_id=update.message.chat.id, text=MSG_NEW_GROUP_ADMIN.format(user.username)) + else: - send_async(bot, chat_id=update.message.chat.id, + send_async(bot, + chat_id=update.message.chat.id, text=MSG_NEW_GROUP_ADMIN_EXISTS.format(user.username)) - except Exception as e: + + except Exception: + # FIX: instance of scoped_session has no 'rollback' Session.rollback() def del_adm(bot, chat_id, user): session = Session() try: - adm = session.query(Admin).filter_by(user_id=user.id, admin_group=chat_id).first() + adm = session.query(Admin).filter_by(user_id=user.id, + admin_group=chat_id).first() + if adm is None: - send_async(bot, chat_id=chat_id, + send_async(bot, + chat_id=chat_id, text=MSG_DEL_GROUP_ADMIN_NOT_EXIST.format(user.username)) + else: session.delete(adm) session.commit() - send_async(bot, chat_id=chat_id, + send_async(bot, + chat_id=chat_id, text=MSG_DEL_GROUP_ADMIN.format(user.username)) - except: + + except Exception: session.rollback() @@ -57,16 +84,23 @@ def del_admin(bot: Bot, update: Update): if msg != '': user = session.query(User).filter_by(username=msg).first() if user is None: - send_async(bot, chat_id=update.message.chat.id, text=MSG_USER_UNKNOWN) + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_USER_UNKNOWN) + else: del_adm(bot, update.message.chat.id, user) else: user = session.query(User).filter_by(id=msg).first() if user is None: - send_async(bot, chat_id=update.message.chat.id, text=MSG_USER_UNKNOWN) + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_USER_UNKNOWN) + else: del_adm(bot, update.message.chat.id, user) - except: + + except Exception: session.rollback() @@ -80,9 +114,14 @@ def list_admins(bot: Bot, update: Update): users.append(session.query(User).filter_by(id=admin_user.user_id).first()) msg = MSG_LIST_ADMINS_HEADER for user in users: - msg += MSG_LIST_ADMINS_FORMAT.format(user.id, user.username, user.first_name, user.last_name) + msg += MSG_LIST_ADMINS_FORMAT.format(user.id, + user.username, + user.first_name, + user.last_name) + send_async(bot, chat_id=update.message.chat.id, text=msg) - except: + + except Exception: session.rollback() @@ -98,9 +137,13 @@ def admins_for_users(bot: Bot, update: Update): msg += MSG_EMPTY else: for user in users: - msg += MSG_LIST_ADMINS_USER_FORMAT.format(user.username or '', user.first_name or '', user.last_name or '') + msg += MSG_LIST_ADMINS_USER_FORMAT.format(user.username or '', + user.first_name or '', + user.last_name or '') + send_async(bot, chat_id=update.message.chat.id, text=msg) - except: + + except Exception: session.rollback() @@ -113,21 +156,30 @@ def set_global_admin(bot: Bot, update: Update): if msg != '': user = session.query(User).filter_by(username=msg).first() if user is None: - send_async(bot, chat_id=update.message.chat.id, text=MSG_USER_UNKNOWN) + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_USER_UNKNOWN) + else: - adm = session.query(Admin).filter_by(user_id=user.id, admin_type=AdminType.FULL.value).first() + adm = session.query(Admin).filter_by(user_id=user.id, + admin_type=AdminType.FULL.value).first() + if adm is None: new_group_admin = Admin(user_id=user.id, admin_type=AdminType.FULL.value, admin_group=0) session.add(new_group_admin) session.commit() - send_async(bot, chat_id=update.message.chat.id, + send_async(bot, + chat_id=update.message.chat.id, text=MSG_NEW_GLOBAL_ADMIN.format(user.username)) + else: - send_async(bot, chat_id=update.message.chat.id, + send_async(bot, + chat_id=update.message.chat.id, text=MSG_NEW_GLOBAL_ADMIN_EXISTS.format(user.username)) - except: + + except Exception: session.rollback() @@ -139,29 +191,38 @@ def set_super_admin(bot: Bot, update: Update): if msg != '': user = session.query(User).filter_by(username=msg).first() if user is None: - send_async(bot, chat_id=update.message.chat.id, text=MSG_USER_UNKNOWN) + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_USER_UNKNOWN) + else: if user.id == 79612802 and update.message.from_user.id == 79612802: adm = session.query(Admin).filter_by(user_id=user.id, admin_group=0).first() if adm is not None: if adm.admin_type == AdminType.SUPER.value: - send_async(bot, chat_id=update.message.chat.id, + send_async(bot, + chat_id=update.message.chat.id, text=MSG_NEW_SUPER_ADMIN_EXISTS.format(user.username)) + else: adm.admin_type = AdminType.SUPER.value session.add(adm) session.commit() - send_async(bot, chat_id=update.message.chat.id, + send_async(bot, + chat_id=update.message.chat.id, text=MSG_NEW_SUPER_ADMIN.format(user.username)) + else: new_super_admin = Admin(user_id=user.id, admin_type=AdminType.SUPER.value, admin_group=0) + session.add(new_super_admin) session.commit() - send_async(bot, chat_id=update.message.chat.id, + send_async(bot, + chat_id=update.message.chat.id, text=MSG_NEW_SUPER_ADMIN.format(user.username)) - except: + except Exception: session.rollback() @@ -175,30 +236,44 @@ def del_global_admin(bot: Bot, update: Update): if msg != '': user = session.query(User).filter_by(username=msg).first() if user is None: - send_async(bot, chat_id=update.message.chat.id, text=MSG_USER_UNKNOWN) + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_USER_UNKNOWN) + else: - adm = session.query(Admin).filter_by(user_id=user.id, admin_type=AdminType.FULL.value).first() + adm = session.query(Admin).filter_by(user_id=user.id, + admin_type=AdminType.FULL.value).first() + if adm is None: - send_async(bot, chat_id=update.message.chat.id, + send_async(bot, + chat_id=update.message.chat.id, text=MSG_DEL_GLOBAL_ADMIN_NOT_EXIST.format(user.username)) + else: session.delete(adm) session.commit() - send_async(bot, chat_id=update.message.chat.id, + send_async(bot, + chat_id=update.message.chat.id, text=MSG_DEL_GLOBAL_ADMIN.format(user.username)) else: user = session.query(User).filter_by(id=msg).first() if user is None: - send_async(bot, chat_id=update.message.chat.id, text=MSG_USER_UNKNOWN) + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_USER_UNKNOWN) + else: - adm = session.query(Admin).filter_by(user_id=user.id, admin_type=AdminType.FULL.value).first() + adm = session.query(Admin).filter_by(user_id=user.id, + admin_type=AdminType.FULL.value).first() if adm is None: - send_async(bot, chat_id=update.message.chat.id, + send_async(bot, + chat_id=update.message.chat.id, text=MSG_DEL_GLOBAL_ADMIN_NOT_EXIST.format(user.username)) else: session.delete(adm) session.commit() - send_async(bot, chat_id=update.message.chat.id, + send_async(bot, + chat_id=update.message.chat.id, text=MSG_DEL_GLOBAL_ADMIN.format(user.username)) - except: + except Exception: session.rollback() diff --git a/core/functions/api.py b/core/functions/api.py index 4688740..8f60405 100644 --- a/core/functions/api.py +++ b/core/functions/api.py @@ -1,9 +1,12 @@ -import json from datetime import datetime, timedelta +import json + import flask -from core.types import Order, Session, Squad, SquadMember, OrderCleared from werkzeug.routing import IntegerConverter as BaseIntegerConverter +from core.types import Order, Session, Squad, SquadMember, OrderCleared + + app = flask.Flask(__name__) @@ -25,9 +28,14 @@ def new_ready_to_battle(chat_id): order.date = datetime.now() session.add(order) session.commit() - order = session.query(Order).filter_by(chat_id=chat_id, date=order.date, text='К битве готовсь!').first() - return flask.Response(status=200, mimetype="application/json", response=json.dumps({'order_id': order.id})) - except: + order = session.query(Order).filter_by(chat_id=chat_id, + date=order.date, + text='К битве готовсь!').first() + + return flask.Response(status=200, + mimetype="application/json", + response=json.dumps({'order_id': order.id})) + except Exception: Session.rollback() return flask.Response(status=400) @@ -42,26 +50,32 @@ def new_order_click(order_id, user_id): if squad is not None: squad_member = session.query(SquadMember).filter_by(squad_id=squad.chat_id, user_id=user_id) + if squad_member is not None: order_ok = session.query(OrderCleared).filter_by(order_id=order_id, user_id=user_id).first() + if order_ok is None and datetime.now() - order.date < timedelta(minutes=10): order_ok = OrderCleared() order_ok.order_id = order_id order_ok.user_id = user_id session.add(order_ok) session.commit() + else: order_ok = session.query(OrderCleared).filter_by(order_id=order_id, user_id=user_id).first() + if order_ok is None and datetime.now() - order.date < timedelta(minutes=10): order_ok = OrderCleared() order_ok.order_id = order_id order_ok.user_id = user_id session.add(order_ok) session.commit() + return flask.Response(status=200) - except: + + except Exception: Session.rollback() return flask.Response(status=400) @@ -74,10 +88,15 @@ def order_status(order_id): if order is not None: users = [] for order_ok in order.cleared: - users.append({'username': order_ok.user.username, 'id': order_ok.user.id, + users.append({'username': order_ok.user.username, + 'id': order_ok.user.id, 'attack': order_ok.user.character.attack if order_ok.user.character else 0, 'defence': order_ok.user.character.defence if order_ok.user.character else 0}) - return flask.Response(status=200, mimetype="application/json", response=json.dumps({'users': users})) - except: + + return flask.Response(status=200, + mimetype="application/json", + response=json.dumps({'users': users})) + + except Exception: Session.rollback() return flask.Response(status=400) diff --git a/core/functions/bosses.py b/core/functions/bosses.py index 098f7dc..cb80237 100644 --- a/core/functions/bosses.py +++ b/core/functions/bosses.py @@ -1,4 +1,5 @@ from telegram import Update, Bot + from core.functions.triggers import trigger_decorator from core.utils import send_async, update_group diff --git a/core/functions/common.py b/core/functions/common.py index 5161342..edb8486 100644 --- a/core/functions/common.py +++ b/core/functions/common.py @@ -1,14 +1,17 @@ -from telegram import Update, Bot, ParseMode, TelegramError +from datetime import datetime +from enum import Enum import logging + +from telegram import Update, Bot, ParseMode, TelegramError + from core.functions.triggers import trigger_decorator -from core.types import AdminType, Admin, Stock, admin, Session, Group -from core.utils import send_async, add_user from core.functions.reply_markup import generate_admin_markup -from enum import Enum -from datetime import datetime from core.texts import * +from core.types import AdminType, Admin, Stock, admin, Session, Group +from core.utils import send_async, add_user + -logger = logging.getLogger(__name__) +LOGGER = logging.getLogger(__name__) class StockType(Enum): @@ -18,7 +21,7 @@ class StockType(Enum): def error(bot: Bot, update, error, **kwargs): """ Error handling """ - logger.error("An error (%s) occurred: %s" + LOGGER.error("An error (%s) occurred: %s" % (type(error), error.message)) @@ -32,6 +35,7 @@ def start(bot: Bot, update: Update): def admin_panel(bot: Bot, update: Update): if update.message.chat.type == 'private': session = Session() + # FIX: переопределение admin admin = session.query(Admin).filter_by(user_id=update.message.from_user.id).all() full_adm = False grp_adm = False diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index 6f6921c..6797e6c 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -1,23 +1,26 @@ +from datetime import datetime, timedelta +from enum import Enum import json +from json import loads +import logging +from multiprocessing.pool import ThreadPool from telegram import Bot, Update, InlineKeyboardButton, InlineKeyboardMarkup, TelegramError from telegram.ext.dispatcher import run_async -from core.template import fill_char_template -from core.types import User, Group, Admin, Session, admin, Order, OrderGroup, OrderGroupItem, OrderCleared, Squad, \ - Character, Session, SquadMember, MessageType -from core.utils import send_async, update_group, add_user -from core.functions.admins import del_adm -from enum import Enum from core.enums import Castle, Icons -import logging -from core.types import AdminType -from datetime import datetime, timedelta +from core.functions.admins import del_adm +from core.template import fill_char_template +from core.types import ( + User, Group, Admin, Session, admin, Order, OrderGroup, + OrderGroupItem, OrderCleared, Squad, + Character, Session, SquadMember, MessageType, AdminType +) from core.texts import * -from multiprocessing.pool import ThreadPool -from json import loads +from core.utils import send_async, update_group, add_user + -logger = logging.getLogger('MyApp') +LOGGER = logging.getLogger('MyApp') class QueryType(Enum): @@ -343,7 +346,7 @@ def callback_query(bot: Bot, update: Update, chat_data: dict): update_group(update.callback_query.message.chat) user = add_user(update.callback_query.from_user) data = json.loads(update.callback_query.data) - logger.warning(data) + LOGGER.warning(data) if data['t'] == QueryType.GroupList.value: msg = MSG_GROUP_STATUS_CHOOSE_CHAT squads = session.query(Squad).all() diff --git a/core/regexp.py b/core/regexp.py index b548269..3f0e010 100644 --- a/core/regexp.py +++ b/core/regexp.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- -profile = '(🇬🇵|🇮🇲|🇨🇾|🇻🇦|🇪🇺|🇲🇴|🇰🇮)(.+), (.+) .+ замка\n' \ +# FIX: переделать строки в """ +PROFILE = '(🇬🇵|🇮🇲|🇨🇾|🇻🇦|🇪🇺|🇲🇴|🇰🇮)(.+), (.+) .+ замка\n' \ '🏅Уровень: ([0-9]+)\n' \ '(?:.*)Атака: ([0-9]+) 🛡Защита: ([0-9]+)\n' \ '🔥Опыт: ([0-9]+)/([0-9]+)\n' \ @@ -10,7 +11,7 @@ '🎒Рюкзак: ([0-9]+)/([0-9]+) /inv' \ '(?:\n\nПомощник:\n(.+?) (?:.+?) (.+)? \(([0-9]+) ур\.\) (.+) /pet)?' -hero = '(🇬🇵|🇮🇲|🇨🇾|🇻🇦|🇪🇺|🇲🇴|🇰🇮)(.+), (.+) .+ замка\n' \ +HERO = '(🇬🇵|🇮🇲|🇨🇾|🇻🇦|🇪🇺|🇲🇴|🇰🇮)(.+), (.+) .+ замка\n' \ '🏅Уровень: ([0-9]+)\n' \ '(?:.*)Атака: ([0-9]+) 🛡Защита: ([0-9]+)\n' \ '🔥Опыт: ([0-9]+)/([0-9]+)\n' \ diff --git a/core/template.py b/core/template.py index 1a62f37..eeeec22 100644 --- a/core/template.py +++ b/core/template.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -from core.texts import MSG_NO_SQUAD -from core.types import * +from core.texts import MSG_NO_SQUAD, MSG_WANTS_TO_JOIN +from core.types import User, Character def fill_template(msg: str, user: User): @@ -33,9 +33,10 @@ def fill_char_template(msg: str, user: User, char: Character, squad_request=Fals else: msg = msg.replace('%squad%', MSG_NO_SQUAD) if char.pet is not None: - msg = msg.replace('%pet%', '{} {} lvl'.format(str(char.pet), str(char.petLevel))) + msg = msg.replace('%pet%', '{} {} lvl'.format(str(char.pet), + str(char.petLevel))) else: msg = msg.replace('%pet%', 'Животины нет') if squad_request: - msg += '\n\nХочет вступить в отряд {}'.format(user.member.squad.squad_name) + msg += MSG_WANTS_TO_JOIN.format(user.member.squad.squad_name) return msg diff --git a/core/texts.py b/core/texts.py index 29212e5..c2b913c 100644 --- a/core/texts.py +++ b/core/texts.py @@ -1,8 +1,11 @@ +""" Строки """ + MSG_ORDER_STATISTIC = 'Статистика выполнения приказов за {} дней:\n' MSG_ORDER_STATISTIC_OUT_FORMAT = '{}: {}/{}\n' MSG_USER_UNKNOWN = 'Не знаю таких' -MSG_NEW_GROUP_ADMIN = 'Приветствуйте нового админа: @{}!\nДля списка команд бота используй /help' +MSG_NEW_GROUP_ADMIN = """Приветствуйте нового админа: @{}! +Для списка команд бота используй /help""" MSG_NEW_GROUP_ADMIN_EXISTS = '@{} и без тебя тут правит!' MSG_DEL_GROUP_ADMIN_NOT_EXIST = 'У @{} здесь нет власти!' @@ -14,8 +17,8 @@ MSG_DEL_GLOBAL_ADMIN_NOT_EXIST = 'У @{} нет власти!' MSG_DEL_GLOBAL_ADMIN = '@{} разжалован.' -MSG_NEW_SUPER_ADMIN = 'Новый бог: @{}!' -MSG_NEW_SUPER_ADMIN_EXISTS = '@{} уже бог!' +MSG_NEW_SUPER_ADMIN = 'Новый суперадмин: @{}!' +MSG_NEW_SUPER_ADMIN_EXISTS = '@{} уже суперадмин!' MSG_LIST_ADMINS_HEADER = 'Список здешних админов:\n' MSG_LIST_ADMINS_FORMAT = '{} @{} {} {}\n' @@ -26,51 +29,51 @@ MSG_START_WELCOME = 'Привет' MSG_ADMIN_WELCOME = 'Да здравствует админ!' -MSG_HELP_GLOBAL_ADMIN = 'Команды приветствия:\n'\ - '/enable_welcome - Включить приветствие\n'\ - '/disable_welcome - Выключить приветствие\n'\ - '/set_welcome <текст> - Установить текст приветствия. '\ - 'Может содержать %username% - будет заменено на @username, '\ - 'если не установлено на Имя Фамилия, %first_name% - на имя, '\ - '%last_name% - на фамилию, %id% - на id\n'\ - '/show_welcome - Показать текущий текст приветствия для '\ - 'данного чата'\ - '\n\n'\ - 'Команды триггеров:\n'\ - '/set_trigger <триггер>::<сообщение> - Установить сообщение, '\ - 'которое бот будет кидать по триггеру.\n'\ - '/add_trigger <триггер>::<сообщение> - Добавляет сообщение, '\ - 'которое бот будет кидать по триггеру, но не заменяет старый.\n'\ - '/del_trigger <триггер> - Удалить соответствующий триггер\n'\ - '/list_triggers - Показать все существующие триггеры'\ - '\n\n'\ - 'Команды глобаладмина:\n'\ - '/add_admin <юзернэйм> - Добавить админа для текущего чата\n'\ - '/del_admin <юзернэйм> - Забрать привелегии у админа текущего '\ - 'чата\n'\ - '/list_admins - Показать список местных админов\n'\ - '/enable_trigger - Разрешить триггерить всем в группе\n'\ - '/disable_trigger - Запретить триггерить всем в группе' - -MSG_HELP_GROUP_ADMIN = 'Команды приветствия:\n'\ - '/enable_welcome - Включить приветствие\n'\ - '/disable_welcome - Выключить приветствие\n'\ - '/set_welcome <текст> - Установить текст приветствия. '\ - 'Может содержать %username% - будет заменено на @username, '\ - 'если не установлено на Имя Фамилия, %first_name% - на имя, '\ - '%last_name% - на фамилию, %id% - на id\n'\ - '/show_welcome - Показать текущий текст приветствия для '\ - 'данного чата'\ - '\n\n'\ - 'Команды триггеров:\n'\ - '/add_trigger <триггер>::<сообщение> - Добавляет сообщение, '\ - 'которое бот будет кидать по триггеру, но не заменяет старый.\n'\ - '/list_triggers - Показать все существующие триггеры\n'\ - '/enable_trigger - Разрешить триггерить всем в группе\n'\ - '/disable_trigger - Запретить триггерить всем в группе' - -MSG_HELP_USER = 'Команды триггеров:\n'\ - '/list_triggers - Показать все существующие триггеры' +MSG_HELP_GLOBAL_ADMIN = """Команды приветствия: +/enable_welcome — включить приветствие. +/disable_welcome — выключить приветствие. +/set_welcome <текст> — установить текст приветствия. \ +Может содержать %username% — будет заменено на @username, \ +если не установлено на Имя Фамилия, %first_name% — на имя, +%last_name% — на фамилию, %id% — на id. +/show_welcome — показать текущий текст приветствия для данного чата. + +Команды триггеров: +/set_trigger <триггер>::<сообщение> — \ +установить сообщение, которое бот будет отправлять по триггеру. +/add_trigger <триггер>::<сообщение> — \ +добавить сообщение, которое бот будет отправлять по триггеру. \ +Старое сообщение не заменяется. +/del_trigger <триггер> — удалить триггер. +/list_triggers — показать все триггеры. + +Команды суперадмина: +/add_admin <пользователь> — добавить админа для текущего чата. +/del_admin <пользователь> — забрать привилегии у админа текущего чата. +/list_admins — показать список админов в чате. +/enable_trigger — разрешить триггерить всем в группе. +/disable_trigger — запретить триггерить всем в группе. +""" + +MSG_HELP_GROUP_ADMIN = """Команды приветствия: +/enable_welcome — включить приветствие. +/disable_welcome — выключить приветствие. +/set_welcome <текст> — установить текст приветствия. \ +Может содержать %username% — будет заменено на @username, \ +если не установлено на Имя Фамилия, %first_name% — на имя, +%last_name% — на фамилию, %id% — на id. +/show_welcome — показать текущий текст приветствия для данного чата. + +Команды триггеров: +/add_trigger <триггер>::<сообщение> — \ +добавить сообщение, которое бот будет отправлять по триггеру. \ +Старое сообщение не заменяется. +/list_triggers — показать список триггеров. +/enable_trigger — разрешить триггерить всем в группе. +/disable_trigger — запретить триггерить всем в группе. +""" + +MSG_HELP_USER = "/list_triggers — показать список триггеров." MSG_PING = 'Иди освежись, @{}!' @@ -80,12 +83,14 @@ MSG_STOCK_COMPARE_WAIT = 'Жду с чем сравнивать...' MSG_GROUP_STATUS_CHOOSE_CHAT = 'Выбери чат' -MSG_GROUP_STATUS = 'Группа: {}\n\n' \ - 'Админы:\n' \ - '{}\n' \ - 'Приветствие: {}\n' \ - 'Триггерят все: {}\n' \ - 'Тернии: {}' +MSG_GROUP_STATUS = """Группа: {} + +Админы: +{} +Приветствие: {} +Триггерят все: {} +Тернии: {}""" + MSG_GROUP_STATUS_ADMIN_FORMAT = '{} @{} {} {}\n' MSG_GROUP_STATUS_DEL_ADMIN = 'Разжаловать {} {}' @@ -115,35 +120,41 @@ MSG_ORDER_GROUP_ADD = '➕Добавить группу' MSG_ORDER_GROUP_DEL = '🔥🚨Удалить группу🚨🔥' -MSG_NEWBIE = 'Новый игрок в замке!\n' \ - 'Все на вербовку %username%!' +MSG_NEWBIE = """Новый игрок в замке!\n +Все на вербовку %username%!""" MSG_FLAG_CHOOSE_HEADER = 'Выбирай' MSG_PROFILE_OLD = 'Твой профиль завял, нужно что-то посвежей...' -MSG_PROFILE_SAVED = 'Располагайся в зарослях мяты, {}!\nНе забывай поливать свой профиль хотя бы раз в день. 🌱' -MSG_PROFILE_CASTLE_MISTAKE = 'Перед тобой во всей красе предстали обширные заросли мяты. '\ - 'Ты бесстрашно зашёл в них, в надежде добраться до таинственных новых земель. '\ - 'Однако долгие часы скитаний не привели тебя ни к чему. '\ - 'Повезло хоть, что выбраться смог! Без проводника здесь делать нечего...' -MSG_PROFILE_SHOW_FORMAT = '👤 %first_name% %last_name% (%username%)\n' \ - '%castle% %name%\n' \ - '🏅 %prof% %level% уровня\n' \ - '⚜️ Отряд %squad%\n' \ - '⚔️ %attack% | 🛡 %defence% | 🔥 %exp%/%needExp%\n' \ - '💰 %gold% | 🔋 %maxStamina%\n' \ - '%pet%\n' \ - '🕑 Последнее обновление %date%' +MSG_PROFILE_SAVED = """Располагайся в зарослях мяты, {}! +Не забывай поливать свой профиль хотя бы раз в день. 🌱""" +MSG_PROFILE_CASTLE_MISTAKE = """\ +Перед тобой во всей красе предстали обширные заросли мяты. +Ты бесстрашно зашёл в них, в надежде добраться до таинственных новых земель. +Однако долгие часы скитаний не привели тебя ни к чему. +Повезло хоть, что выбраться смог! Без проводника здесь делать нечего...""" +MSG_PROFILE_SHOW_FORMAT = """\ +👤 %first_name% %last_name% (%username%) +%castle% %name% +🏅 %prof% %level% уровня +⚜️ Отряд %squad% +⚔️ %attack% | 🛡 %defence% | 🔥 %exp%/%needExp% +💰 %gold% | 🔋 %maxStamina% +%pet% +🕑 Последнее обновление %date%""" + MSG_PROFILE_NOT_FOUND = 'В мятных записях ещё нет данных об этом герое' MSG_SQUAD_REQUEST_EMPTY = 'На данный момент к вам никто не хочет.' -MSG_SQUAD_NEW = 'Теперь здесь будет обитать отряд {}!\n'\ - 'Не забудьте задать ссылку для приглашения новых участников.' -MSG_SQUAD_LINK_SAVED = 'Ссылка приглашений сохранена!\nНовые участники теперь не пройдут мимо!' +MSG_SQUAD_NEW = """Теперь здесь будет обитать отряд {}! +Не забудьте задать ссылку для приглашения новых участников.""" +MSG_SQUAD_LINK_SAVED = """Ссылка приглашений сохранена! +Новые участники теперь не пройдут мимо!""" MSG_SQUAD_RENAMED = 'Теперь этот отряд будет называться {}!' MSG_SQUAD_DELETE = 'Отряд распущен' MSG_SQUAD_THORNS_ENABLED = 'Непроходимые тернии выросли вокруг' -MSG_SQUAD_THORNS_DISABLED = 'Тернии завяли, теперь каждый может видеть происходящее' +MSG_SQUAD_THORNS_DISABLED = 'Тернии завяли, \ +теперь каждый может видеть происходящее' MSG_TRIGGER_NEW = 'Триггер на фразу "{}" установлен.' MSG_TRIGGER_NEW_ERROR = 'Какие-то у тебя несвежие мысли, попробуй ещё раз.' @@ -154,7 +165,8 @@ MSG_TRIGGER_DEL_ERROR = 'Где ты такой триггер видел? 0_о' MSG_TRIGGER_LIST_HEADER = 'Список текущих триггеров:\n' -MSG_THORNS = '{} не смог пробраться через МЯТНЫЕ, МАТЬ ЕГО, тернии и ему пришлось уйти' +MSG_THORNS = '{} не смог пробраться через МЯТНЫЕ, МАТЬ ЕГО, \ +тернии и ему пришлось уйти' MSG_WELCOME_DEFAULT = 'Привет, %username%!' MSG_WELCOME_SET = 'Текст приветствия установлен.' @@ -164,25 +176,34 @@ MSG_PIN_ALL_ENABLED = 'Пусть пинят...' MSG_PIN_ALL_DISABLED = 'Совсем уже распустились, вот мучайтесь теперь 😡' -MSG_ORDER_CLEARED_BY_DUMMY = 'эта функция перерабатывается в связи с высокой нагрузкой от постоянного обновления' +MSG_ORDER_CLEARED_BY_DUMMY = 'Функция перерабатывается в связи с высокой \ +нагрузкой от постоянного обновления' MSG_NO_SQUAD = 'Безотрядный тунеядец' +MSG_WANTS_TO_JOIN = '\n\nХочет вступить в отряд {}' MSG_CLEARED = 'Выполнено' MSG_SQUAD_LIST = 'Список ваших отрядов:' -MSG_SQUAD_REQUEST_EXISTS = 'Вы уже состоите в отряде или подали запрос. Выйдите из текущего отряда или отмените запрос, чтобы создать новый.' +MSG_SQUAD_REQUEST_EXISTS = 'Вы уже состоите в отряде или подали запрос. \ +Выйдите из текущего отряда или отмените запрос, чтобы создать новый.' MSG_SQUAD_REQUEST = 'Вот отряды, в которые тебя могут принять:' -MSG_SQUAD_LEAVED = '{} покинул отряд {}, теперь он бесполезен и никто ему больше не поможет.' -MSG_SQUAD_REQUESTED = 'Ты попросился в отряд {}. Чтобы ускорить процесс принятия решения ты можешь пофлудить главам отряда: {}.' +MSG_SQUAD_LEAVED = '{} покинул отряд {}, теперь он бесполезен, \ +и никто ему больше не поможет.' +MSG_SQUAD_REQUESTED = 'Ты попросился в отряд {}. \ +Чтобы ускорить процесс принятия решения, можешь написать главам отряда: {}.' MSG_SQUAD_REQUEST_ACCEPTED = 'Заявка от {} принята.' MSG_SQUAD_REQUEST_DECLINED = '{} бесполезен и никто ему не поможет.' MSG_SQUAD_REQUEST_NEW = 'К вам в отряд есть новые заявки.' MSG_SQUAD_REQUEST_ACCEPTED_ANSWER = 'Вас приняли в отряд.' MSG_SQUAD_REQUEST_DECLINED_ANSWER = 'Ваша заявка в отряд отклонена.' -MSG_SQUAD_CLEAN = 'Чистка отряда {}.\n' \ - 'Кого сегодня отправим на покой?' +MSG_SQUAD_CLEAN = """Чистка отряда {}. +Кого сегодня отправим на покой?""" MSG_SQUAD_ADD = '{}, вас хотят в отряд. А вы хотите?' -MSG_SQUAD_ADD_IN_SQUAD = '{} уже в отряде (возможно не в вашем, мне честно лень проверять).' +MSG_SQUAD_ADD_IN_SQUAD = '{} уже в отряде (возможно не в вашем).' MSG_SQUAD_ADD_ACCEPTED = '{} принял предложение.' MSG_SQUAD_ADD_DECLINED = '{} бесполезен и никто ему не поможет.' + +MSG_SQUAD_READY = '{} бойцов отряда {} к битве готовы!\n{}⚔ {}🛡' +MSG_FULL_TEXT_LINE = '{}: {}👥 {}⚔ {}🛡\n' +MSG_FULL_TEXT_TOTAL = '\nВсего: {}👥 {}⚔ {}🛡' diff --git a/core/types.py b/core/types.py index 71be4f1..f788f44 100644 --- a/core/types.py +++ b/core/types.py @@ -1,19 +1,20 @@ # -*- coding: utf-8 -*- -from sqlalchemy import create_engine -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy import Column, Integer, DateTime, Boolean, ForeignKey, UnicodeText, BigInteger +from datetime import datetime +from enum import Enum +import logging +import requests +import threading + +from sqlalchemy import ( + create_engine, event, + Column, Integer, DateTime, Boolean, ForeignKey, UnicodeText, BigInteger +) from sqlalchemy.dialects.mysql import DATETIME -from datetime import datetime, timedelta +from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, relationship, scoped_session -from sqlalchemy import event from sqlalchemy.pool import Pool -import logging -from enum import Enum + from config import DB -import requests -from json import loads -from core.enums import Castle -import threading class AdminType(Enum): @@ -35,11 +36,16 @@ class MessageType(Enum): PHOTO = 9 -engine = create_engine(DB, echo=False, pool_size=200, max_overflow=50, isolation_level="READ UNCOMMITTED") -logger = logging.getLogger('sqlalchemy.engine') +ENGINE = create_engine(DB, + echo=False, + pool_size=200, + max_overflow=50, + isolation_level="READ UNCOMMITTED") + +# FIX: имена констант? +LOGGER = logging.getLogger('sqlalchemy.engine') Base = declarative_base() -Session = scoped_session(sessionmaker(bind=engine)) -last_update = datetime.now() - timedelta(minutes=10) +Session = scoped_session(sessionmaker(bind=ENGINE)) @event.listens_for(Pool, "connect") @@ -47,14 +53,16 @@ def set_unicode(dbapi_conn, conn_record): cursor = dbapi_conn.cursor() try: cursor.execute("SET NAMES 'utf8mb4' COLLATE 'utf8mb4_unicode_ci'") - except Exception as e: - logger.error(e) + + # FIX: слишком общая ошибка + except Exception as err: + LOGGER.error(err) class Group(Base): __tablename__ = 'groups' - id = Column(BigInteger, primary_key=True) + id = Column(BigInteger, primary_key=True) # FIX: invalid name username = Column(UnicodeText(250)) title = Column(UnicodeText(250)) welcome_enabled = Column(Boolean, default=False) @@ -76,11 +84,22 @@ class User(Base): last_name = Column(UnicodeText(250)) date_added = Column(DateTime, default=datetime.now()) - character = relationship('Character', back_populates='user', order_by='Character.date.desc()', uselist=False) + character = relationship('Character', + back_populates='user', + order_by='Character.date.desc()', + uselist=False) + orders_confirmed = relationship('OrderCleared', back_populates='user') member = relationship('SquadMember', back_populates='user', uselist=False) - equip = relationship('Equip', back_populates='user', order_by='Equip.date.desc()', uselist=False) - stock = relationship('Stock', back_populates='user', order_by='Stock.date.desc()', uselist=False) + equip = relationship('Equip', + back_populates='user', + order_by='Equip.date.desc()', + uselist=False) + + stock = relationship('Stock', + back_populates='user', + order_by='Stock.date.desc()', + uselist=False) def __repr__(self): user = '' @@ -281,4 +300,4 @@ def wrapper(bot, update, *args, **kwargs): return decorate -Base.metadata.create_all(engine) +Base.metadata.create_all(ENGINE) diff --git a/core/utils.py b/core/utils.py index c9a8cdd..03d8789 100644 --- a/core/utils.py +++ b/core/utils.py @@ -1,33 +1,39 @@ +import http.client + from telegram import Bot +from telegram.error import ChatMigrated from telegram.ext.dispatcher import run_async + from core.types import Session, User, Group -from telegram.error import ChatMigrated @run_async def send_async(bot: Bot, *args, **kwargs): try: return bot.sendMessage(*args, **kwargs) - except ChatMigrated as e: + + except ChatMigrated as err: session = Session() group = session.query(Group).filter_by(id=kwargs['chat_id']).first() if group is not None: group.bot_in_group = False session.add(group) session.commit() - kwargs['chat_id'] = e.new_chat_id + kwargs['chat_id'] = err.new_chat_id return bot.sendMessage(*args, **kwargs) - except Exception as e: - print(e) + + # FIX: слишком общая ошибка + except Exception as err: + print(err) def send_pin_async(bot: Bot, *args, **kwargs): try: msg = bot.sendMessage(*args, **kwargs) - except ChatMigrated as e: - kwargs['chat_id'] = e.new_chat_id + except ChatMigrated as err: + kwargs['chat_id'] = err.new_chat_id msg = bot.sendMessage(*args, **kwargs) - import http.client + conn = http.client.HTTPConnection("127.0.0.1") conn.request("GET", "/{}/{}/".format(msg.message_id, msg.chat.id)) @@ -56,7 +62,9 @@ def add_user(tg_user): session.add(user) session.commit() return user - except Exception as e: + + # FIX: слишком общая ошибка + except Exception: session.rollback() @@ -69,6 +77,7 @@ def update_group(grp): group = Group(id=grp.id, title=grp.title, username=grp.username) session.add(group) + else: updated = False if group.username != grp.username: @@ -82,8 +91,11 @@ def update_group(grp): updated = True if updated: session.add(group) + session.commit() return group return None - except Exception as e: + + # FIX: слишком общая ошибка + except Exception: session.rollback() diff --git a/main.py b/main.py index 9c234a5..47fd278 100644 --- a/main.py +++ b/main.py @@ -1,53 +1,76 @@ # -*- coding: utf-8 -*- + +from datetime import datetime, time import json import logging +import re from threading import Thread -from telegram import Bot, Update, InlineKeyboardButton, InlineKeyboardMarkup, ParseMode -from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler, JobQueue +from telegram import ( + Bot, Update, InlineKeyboardButton, InlineKeyboardMarkup, ParseMode +) +from telegram.ext import ( + Updater, CommandHandler, MessageHandler, + Filters, CallbackQueryHandler +) from telegram.ext.dispatcher import run_async -from core.functions.bosses import boss_leader, boss_zhalo, boss_monoeye, boss_hydra -from core.functions.orders import order, orders, MSG_ORDER_ACCEPT -from core.functions.admins import list_admins, admins_for_users, set_admin, del_admin, set_global_admin, \ - set_super_admin, del_global_admin -from core.functions.common import help_msg, ping, start, error, kick, admin_panel, stock_compare, trade_compare, \ +from config import TOKEN, GOVERNMENT_CHAT +from core.functions.activity import ( + day_activity, week_activity, battle_activity +) +from core.functions.admins import ( + list_admins, admins_for_users, set_admin, del_admin, + set_global_admin, set_super_admin, del_global_admin +) +from core.functions.bosses import ( + boss_leader, boss_zhalo, boss_monoeye, boss_hydra) +from core.functions.orders import order, orders + +from core.functions.common import ( + help_msg, ping, start, error, kick, + admin_panel, stock_compare, trade_compare, check_bot_in_chats, delete_msg, delete_user -from core.functions.inline_keyboard_handling import callback_query, send_status, generate_ok_markup, send_order, \ - QueryType -from core.functions.pin import pin, not_pin_all, pin_all, silent_pin -from core.functions.triggers import set_trigger, add_trigger, del_trigger, list_triggers, enable_trigger_all, \ - disable_trigger_all, trigger_show, set_global_trigger, add_global_trigger, del_global_trigger -from core.functions.welcome import welcome, set_welcome, show_welcome, enable_welcome, disable_welcome +) +from core.functions.inline_keyboard_handling import ( + callback_query, send_status, send_order, QueryType +) from core.functions.order_groups import group_list, add_group -from core.types import Session, Group, Order, Squad, Admin -from core.utils import add_user, send_async -from config import TOKEN, API_PORT, GOVERNMENT_CHAT -from core.regexp import profile, hero -import re +from core.functions.pin import pin, not_pin_all, pin_all, silent_pin from core.functions.profile import char_update, char_show, find_by_username -from core.functions.squad import add_squad, del_squad, set_invite_link, set_squad_name, enable_thorns, disable_thorns, \ - squad_list, squad_request, list_squad_requests, open_hiring, close_hiring, remove_from_squad, add_to_squad -from core.functions.activity import day_activity, week_activity, battle_activity -from datetime import datetime, time -from core.functions.api import app +from core.functions.squad import ( + add_squad, del_squad, set_invite_link, set_squad_name, + enable_thorns, disable_thorns, + squad_list, squad_request, list_squad_requests, + open_hiring, close_hiring, remove_from_squad, add_to_squad +) +from core.functions.triggers import ( + set_trigger, add_trigger, del_trigger, list_triggers, enable_trigger_all, + disable_trigger_all, trigger_show, + set_global_trigger, add_global_trigger, del_global_trigger +) +from core.functions.welcome import ( + welcome, set_welcome, show_welcome, enable_welcome, disable_welcome +) +from core.regexp import PROFILE, HERO +from core.texts import ( + MSG_SQUAD_READY, MSG_FULL_TEXT_LINE, MSG_FULL_TEXT_TOTAL +) +from core.types import Session, Order, Squad, Admin +from core.utils import add_user, send_async last_welcome = 0 -logging.basicConfig(level=logging.WARNING, - format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') +logging.basicConfig( + level=logging.WARNING, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' +) def battle_time(): + """ Определяет, наступило ли время битвы """ now = datetime.now().time() - _BATTLE_TIME = [[time(7, 57), time(8, 0)], - [time(11, 57), time(12, 0)], - [time(15, 57), time(16, 0)], - [time(19, 57), time(20, 0)], - [time(23, 57), time(0, 0)]] - for time_start, time_end in _BATTLE_TIME: - if time_start <= time_end and time_start <= now <= time_end or \ - not time_start <= time_end and (time_start <= now or now <= time_end): - return True + if now.hour % 4 == 3 and now.minute >= 57: + return True return False @@ -61,135 +84,168 @@ def manage_all(bot: Bot, update: Update, chat_data, job_queue): add_user(update.message.from_user) if update.message.chat.type in ['group', 'supergroup', 'channel']: session = Session() - squad = session.query(Squad).filter_by(chat_id=update.message.chat.id).first() - admin = session.query(Admin).filter(Admin.user_id == update.message.from_user.id and - Admin.admin_group in [update.message.chat.id, 0]).first() + squad = session.query(Squad).filter_by( + chat_id=update.message.chat.id).first() + admin = session.query(Admin).filter( + Admin.user_id == update.message.from_user.id and + Admin.admin_group in [update.message.chat.id, 0]).first() + if squad is not None and admin is None and battle_time(): - bot.delete_message(update.message.chat.id, update.message.message_id) - if update.message.text and update.message.text.upper().startswith('Приветствие:'.upper()): + bot.delete_message(update.message.chat.id, + update.message.message_id) + + if not update.message.text: + return + + text = update.message.text.lower() + + if text.startswith('приветствие:'): set_welcome(bot, update) - elif update.message.text and 'Твои результаты в бою:' in update.message.text and \ - update.message.forward_from and update.message.forward_from.id == 265204902: - job_queue.run_once(del_msg, 2, (update.message.chat.id, update.message.message_id)) - elif update.message.text and update.message.text.upper() == 'Помощь'.upper(): + elif text == 'помощь': help_msg(bot, update) - elif update.message.text and update.message.text.upper() == 'Покажи приветствие'.upper(): + elif text == 'покажи приветствие': show_welcome(bot, update) - elif update.message.text and update.message.text.upper() == 'Включи приветствие'.upper(): + elif text == 'включи приветствие': enable_welcome(bot, update) - elif update.message.text and update.message.text.upper() == 'Выключи приветствие'.upper(): + elif text == 'выключи приветствие': disable_welcome(bot, update) - elif update.message.text and update.message.text.upper().startswith('Затриггерь:'.upper()): + elif text.startswith('затриггерь:'): set_trigger(bot, update) - elif update.message.text and update.message.text.upper().startswith('Разтриггерь:'.upper()): + elif text.startswith('разтриггерь:'): del_trigger(bot, update) - elif update.message.text and update.message.text.upper() == 'Список триггеров'.upper(): + elif text == 'список триггеров': list_triggers(bot, update) - elif update.message.text and update.message.text.upper() == 'Список админов'.upper(): + elif text == 'список админов': list_admins(bot, update) - elif update.message.text and update.message.text.upper() == 'Пинг'.upper(): + elif text == 'пинг': ping(bot, update) - elif update.message.text and update.message.text.upper() == 'Статистика за день'.upper(): + elif text == 'статистика за день': day_activity(bot, update) - elif update.message.text and update.message.text.upper() == 'Статистика за неделю'.upper(): + elif text == 'cтатистика за неделю': week_activity(bot, update) - elif update.message.text and update.message.text.upper() == 'Статистика за бой'.upper(): + elif text == 'cтатистика за бой': battle_activity(bot, update) - elif update.message.text and update.message.text.upper() == 'Разрешить триггерить всем'.upper(): + elif text == 'разрешить триггерить всем': enable_trigger_all(bot, update) - elif update.message.text and update.message.text.upper() == 'Запретить триггерить всем'.upper(): + elif text == 'запретить триггерить всем': disable_trigger_all(bot, update) - elif update.message.text and update.message.text.upper() in ['Админы'.upper(), 'офицер'.upper()]: + elif text in ['админы', 'офицер']: admins_for_users(bot, update) - elif update.message.text and update.message.text.upper() == 'Пинят все'.upper(): + elif text == 'пинят все': pin_all(bot, update) - elif update.message.text and update.message.text.upper() == 'Хорош пинить'.upper(): + elif text == 'хорош пинить': not_pin_all(bot, update) - elif update.message.text and update.message.text.upper() == 'Пин'.upper() and update.message.reply_to_message is not None: - pin(bot, update) - elif update.message.text and update.message.text.upper() == 'сайлентпин'.upper() and update.message.reply_to_message is not None: - silent_pin(bot, update) - elif update.message.text and update.message.text.upper() in ['бандит'.upper(), 'краб'.upper()]: + elif text in ['бандит', 'краб']: boss_leader(bot, update) - elif update.message.text and update.message.text.upper() in ['жало'.upper(), 'королева роя'.upper()]: + elif text in ['жало', 'королева роя']: boss_zhalo(bot, update) - elif update.message.text and update.message.text.upper() in ['циклоп'.upper(), 'борода'.upper()]: + elif text in ['циклоп', 'борода']: boss_monoeye(bot, update) - elif update.message.text and update.message.text.upper() in ['гидра'.upper(), 'лич'.upper()]: + elif text in ['гидра', 'лич']: boss_hydra(bot, update) - elif update.message.text and update.message.text.upper() == 'открыть набор'.upper(): + elif text == 'открыть набор': open_hiring(bot, update) - elif update.message.text and update.message.text.upper() == 'закрыть набор'.upper(): + elif text == 'закрыть набор': close_hiring(bot, update) - elif update.message.text and update.message.text.upper() == 'удоли'.upper() and update.message.reply_to_message is not None: - delete_msg(bot, update) - elif update.message.text and update.message.text.upper() == 'свали'.upper() and update.message.reply_to_message is not None: - delete_user(bot, update) elif update.message.text: trigger_show(bot, update) + elif update.message.reply_to_message is not None: + if text == 'пин': + pin(bot, update) + elif text == 'сайлентпин': + silent_pin(bot, update) + elif text == 'удоли': + delete_msg(bot, update) + elif text == 'свали': + delete_user(bot, update) + + elif 'твои результаты в бою:' in text: + if update.message.forward_from.id == 265204902: + job_queue.run_once(del_msg, 2, (update.message.chat.id, + update.message.message_id)) + elif update.message.chat.type == 'private': - if update.message.text and update.message.text.upper() == 'Статус'.upper(): + if text == 'статус': send_status(bot, update) - elif update.message.text and update.message.text.upper() == 'хочу в отряд'.upper(): + elif text == 'хочу в отряд': squad_request(bot, update) - elif update.message.text and update.message.text.upper() == 'заявки в отряд'.upper(): + elif text == 'заявки в отряд': list_squad_requests(bot, update) - elif update.message.text and update.message.text.upper() in ['Приказы'.upper(), 'пин'.upper()]: + elif text in ['приказы', 'пин']: orders(bot, update, chat_data) - elif update.message.text and update.message.text.upper() in ['список отряда'.upper(), 'список'.upper()]: + elif text in ['список отряда', 'список']: Thread(target=squad_list, args=(bot, update)).start() - elif update.message.text and update.message.text.upper() == 'Группы'.upper(): + elif text == 'группы': group_list(bot, update) - elif update.message.text and update.message.text.upper() == 'чистка отряда'.upper(): + elif text == 'чистка отряда': remove_from_squad(bot, update) - elif update.message.forward_from and update.message.forward_from.id == 265204902 and \ - update.message.text.startswith('📦Содержимое склада'): - stock_compare(bot, update, chat_data) - elif update.message.forward_from and update.message.forward_from.id == 278525885 and \ - '📦Твой склад с материалами:' in update.message.text: - trade_compare(bot, update, chat_data) elif 'wait_group_name' in chat_data and chat_data['wait_group_name']: add_group(bot, update, chat_data) - elif update.message.text and update.message.forward_from and update.message.forward_from.id == 265204902 and \ - (re.search(profile, update.message.text) or re.search(hero, update.message.text)): - char_update(bot, update) + + elif update.message.forward_from: + from_id = update.message.forward_from.id + + if from_id == 265204902: + if text.startswith('📦содержимое склада'): + stock_compare(bot, update, chat_data) + elif re.search(PROFILE, text) or re.search(HERO, text): + char_update(bot, update) + + elif from_id == 278525885: + if '📦твой склад с материалами:' in text: + trade_compare(bot, update, chat_data) else: order(bot, update, chat_data) - except Exception as e: + + # FIX: слишком общая ошибка + except Exception: Session.rollback() @run_async -def ready_to_battle(bot, job_queue): +def ready_to_battle(bot): session = Session() try: group = session.query(Squad).all() for item in group: if item.chat_id == -1001062678288: continue - order = Order() + + order = Order() # FIX: переопределяется order #22 order.text = 'К битве готовсь!' order.chat_id = item.chat_id order.date = datetime.now() order.confirmed_msg = 0 session.add(order) session.commit() - markup = InlineKeyboardMarkup([[InlineKeyboardButton('ГРАБЬНАСИЛУЙУБИВАЙ!', - callback_data=json.dumps({'t': QueryType.OrderOk.value, 'id': order.id}))]]) + + callback_data = json.dumps( + {'t': QueryType.OrderOk.value, 'id': order.id}) + markup = InlineKeyboardMarkup([ + [InlineKeyboardButton('ГРАБЬНАСИЛУЙУБИВАЙ!', + callback_data=callback_data)]]) + msg = send_order(bot, order.text, 0, order.chat_id, markup) + try: msg = msg.result().result() bot.request.post(bot.base_url + '/pinChatMessage', - {'chat_id': order.chat_id, 'message_id': msg.message_id, + {'chat_id': order.chat_id, + 'message_id': msg.message_id, 'disable_notification': False}) - except Exception as e: - print(e) - except Exception as e: + + # FIX: слишком общая ошибка + except Exception as err: + print(err) + + + # FIX: слишком общая ошибка + except Exception: Session.rollback() @run_async -def ready_to_battle_result(bot, job_queue): +def ready_to_battle_result(bot): session = Session() try: group = session.query(Squad).all() @@ -197,8 +253,13 @@ def ready_to_battle_result(bot, job_queue): full_defence = 0 full_text = '' full_count = 0 + for item in group: - order = session.query(Order).filter_by(chat_id=item.chat_id, text='К битве готовсь!').order_by(Order.date.desc()).first() + # FIX: переопределяется order #22 + order = session.query(Order).filter_by( + chat_id=item.chat_id, + text='К битве готовсь!').order_by(Order.date.desc()).first() + if order is not None: attack = 0 defence = 0 @@ -206,16 +267,37 @@ def ready_to_battle_result(bot, job_queue): if clear.user.character: attack += clear.user.character.attack defence += clear.user.character.defence - text = '{} бойцов отряда {} к битве готовы!\n{}⚔ {}🛡'\ - .format(len(order.cleared), item.squad_name, attack, defence) - send_async(bot, chat_id=item.chat_id, text=text, parse_mode=ParseMode.HTML) - full_text += '{}: {}👥 {}⚔ {}🛡\n'.format(item.squad_name, len(order.cleared), attack, defence) + + text = MSG_SQUAD_READY.format(len(order.cleared), + item.squad_name, + attack, + defence) + + send_async(bot, + chat_id=item.chat_id, + text=text, + parse_mode=ParseMode.HTML) + full_attack += attack full_defence += defence full_count += len(order.cleared) - send_async(bot, chat_id=GOVERNMENT_CHAT, text=full_text + '\nВсего: {}👥 {}⚔ {}🛡' - .format(full_count, full_attack, full_defence), parse_mode=ParseMode.HTML) - except Exception as e: + full_text += MSG_FULL_TEXT_LINE.format(item.squad_name, + len(order.cleared), + attack, + defence) + + + full_text += MSG_FULL_TEXT_TOTAL.format(full_count, + full_attack, + full_defence) + + send_async(bot, + chat_id=GOVERNMENT_CHAT, + text=full_text, + parse_mode=ParseMode.HTML) + + # FIX: слишком общая ошибка + except Exception: Session.rollback() @@ -225,65 +307,72 @@ def main(): updater = Updater(TOKEN) # Get the dispatcher to register handlers - dp = updater.dispatcher + disp = updater.dispatcher # on different commands - answer in Telegram - dp.add_handler(CommandHandler("start", start)) - dp.add_handler(CommandHandler("admin", admin_panel)) - dp.add_handler(CommandHandler("help", help_msg)) - dp.add_handler(CommandHandler("ping", ping)) - dp.add_handler(CommandHandler("set_global_trigger", set_global_trigger)) - dp.add_handler(CommandHandler("add_global_trigger", add_global_trigger)) - dp.add_handler(CommandHandler("del_global_trigger", del_global_trigger)) - dp.add_handler(CommandHandler("set_trigger", set_trigger)) - dp.add_handler(CommandHandler("add_trigger", add_trigger)) - dp.add_handler(CommandHandler("del_trigger", del_trigger)) - dp.add_handler(CommandHandler("list_triggers", list_triggers)) - dp.add_handler(CommandHandler("set_welcome", set_welcome)) - dp.add_handler(CommandHandler("enable_welcome", enable_welcome)) - dp.add_handler(CommandHandler("disable_welcome", disable_welcome)) - dp.add_handler(CommandHandler("show_welcome", show_welcome)) - dp.add_handler(CommandHandler("add_admin", set_admin)) - dp.add_handler(CommandHandler("add_global_admin", set_global_admin)) - dp.add_handler(CommandHandler("del_global_admin", del_global_admin)) - dp.add_handler(CommandHandler("add_super_admin", set_super_admin)) - dp.add_handler(CommandHandler("del_admin", del_admin)) - dp.add_handler(CommandHandler("list_admins", list_admins)) - dp.add_handler(CommandHandler("kick", kick)) - dp.add_handler(CommandHandler("enable_trigger", enable_trigger_all)) - dp.add_handler(CommandHandler("disable_trigger", disable_trigger_all)) - dp.add_handler(CommandHandler("me", char_show)) - dp.add_handler(CommandHandler("check_bot_in_chats", check_bot_in_chats)) - - dp.add_handler(CommandHandler("add_squad", add_squad)) - dp.add_handler(CommandHandler("del_squad", del_squad)) - dp.add_handler(CommandHandler("enable_thorns", enable_thorns)) - dp.add_handler(CommandHandler("disable_thorns", disable_thorns)) - dp.add_handler(CommandHandler("set_squad_name", set_squad_name)) - dp.add_handler(CommandHandler("set_invite_link", set_invite_link)) - dp.add_handler(CommandHandler("find", find_by_username)) - dp.add_handler(CommandHandler("add", add_to_squad)) - - dp.add_handler(CallbackQueryHandler(callback_query, pass_chat_data=True)) + disp.add_handler(CommandHandler("start", start)) + disp.add_handler(CommandHandler("admin", admin_panel)) + disp.add_handler(CommandHandler("help", help_msg)) + disp.add_handler(CommandHandler("ping", ping)) + disp.add_handler(CommandHandler("set_global_trigger", set_global_trigger)) + disp.add_handler(CommandHandler("add_global_trigger", add_global_trigger)) + disp.add_handler(CommandHandler("del_global_trigger", del_global_trigger)) + disp.add_handler(CommandHandler("set_trigger", set_trigger)) + disp.add_handler(CommandHandler("add_trigger", add_trigger)) + disp.add_handler(CommandHandler("del_trigger", del_trigger)) + disp.add_handler(CommandHandler("list_triggers", list_triggers)) + disp.add_handler(CommandHandler("set_welcome", set_welcome)) + disp.add_handler(CommandHandler("enable_welcome", enable_welcome)) + disp.add_handler(CommandHandler("disable_welcome", disable_welcome)) + disp.add_handler(CommandHandler("show_welcome", show_welcome)) + disp.add_handler(CommandHandler("add_admin", set_admin)) + disp.add_handler(CommandHandler("add_global_admin", set_global_admin)) + disp.add_handler(CommandHandler("del_global_admin", del_global_admin)) + disp.add_handler(CommandHandler("add_super_admin", set_super_admin)) + disp.add_handler(CommandHandler("del_admin", del_admin)) + disp.add_handler(CommandHandler("list_admins", list_admins)) + disp.add_handler(CommandHandler("kick", kick)) + disp.add_handler(CommandHandler("enable_trigger", enable_trigger_all)) + disp.add_handler(CommandHandler("disable_trigger", disable_trigger_all)) + disp.add_handler(CommandHandler("me", char_show)) + disp.add_handler(CommandHandler("check_bot_in_chats", check_bot_in_chats)) + + disp.add_handler(CommandHandler("add_squad", add_squad)) + disp.add_handler(CommandHandler("del_squad", del_squad)) + disp.add_handler(CommandHandler("enable_thorns", enable_thorns)) + disp.add_handler(CommandHandler("disable_thorns", disable_thorns)) + disp.add_handler(CommandHandler("set_squad_name", set_squad_name)) + disp.add_handler(CommandHandler("set_invite_link", set_invite_link)) + disp.add_handler(CommandHandler("find", find_by_username)) + disp.add_handler(CommandHandler("add", add_to_squad)) + + disp.add_handler(CallbackQueryHandler(callback_query, pass_chat_data=True)) # on noncommand i.e message - echo the message on Telegram - dp.add_handler(MessageHandler(Filters.status_update, welcome)) - # dp.add_handler(MessageHandler(Filters.text, manage_text, pass_chat_data=True)) - dp.add_handler(MessageHandler(Filters.all, manage_all, pass_chat_data=True, pass_job_queue=True)) + disp.add_handler(MessageHandler(Filters.status_update, welcome)) + # disp.add_handler(MessageHandler( + # Filters.text, manage_text, pass_chat_data=True)) + disp.add_handler(MessageHandler( + Filters.all, manage_all, pass_chat_data=True, pass_job_queue=True)) # log all errors - dp.add_error_handler(error) + disp.add_error_handler(error) updater.job_queue.run_daily(ready_to_battle, time(hour=7, minute=50)) - updater.job_queue.run_daily(ready_to_battle_result, time(hour=7, minute=55)) + updater.job_queue.run_daily(ready_to_battle_result, + time(hour=7, minute=55)) updater.job_queue.run_daily(ready_to_battle, time(hour=11, minute=50)) - updater.job_queue.run_daily(ready_to_battle_result, time(hour=11, minute=55)) + updater.job_queue.run_daily(ready_to_battle_result, + time(hour=11, minute=55)) updater.job_queue.run_daily(ready_to_battle, time(hour=15, minute=50)) - updater.job_queue.run_daily(ready_to_battle_result, time(hour=15, minute=55)) + updater.job_queue.run_daily(ready_to_battle_result, + time(hour=15, minute=55)) updater.job_queue.run_daily(ready_to_battle, time(hour=19, minute=50)) - updater.job_queue.run_daily(ready_to_battle_result, time(hour=19, minute=55)) + updater.job_queue.run_daily(ready_to_battle_result, + time(hour=19, minute=55)) updater.job_queue.run_daily(ready_to_battle, time(hour=23, minute=50)) - updater.job_queue.run_daily(ready_to_battle_result, time(hour=23, minute=55)) + updater.job_queue.run_daily(ready_to_battle_result, + time(hour=23, minute=55)) # Start the Bot updater.start_polling() From 0c3b207a1be4ab9e9571d10d9eaf4706738ff95d Mon Sep 17 00:00:00 2001 From: Alexander Bridges Date: Thu, 21 Sep 2017 09:54:58 +0300 Subject: [PATCH 010/284] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 902ca8f..fdae37f 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,4 @@ # MasterBot CW Master Castle Bot + +'''Trello tuskboard https://trello.com/b/mIKI2omk/%D1%81%D1%83%D0%BC%D1%80%D0%B0%D0%BA%D0%BE%D0%B1%D0%BE%D1%82 From 0ec569620bbf86ddd13fa283f5d4c024b84ad5d5 Mon Sep 17 00:00:00 2001 From: Alexander Bridges Date: Thu, 21 Sep 2017 09:55:15 +0300 Subject: [PATCH 011/284] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fdae37f..c8002f4 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ # MasterBot CW Master Castle Bot -'''Trello tuskboard https://trello.com/b/mIKI2omk/%D1%81%D1%83%D0%BC%D1%80%D0%B0%D0%BA%D0%BE%D0%B1%D0%BE%D1%82 +Trello tuskboard ```https://trello.com/b/mIKI2omk/%D1%81%D1%83%D0%BC%D1%80%D0%B0%D0%BA%D0%BE%D0%B1%D0%BE%D1%82 From d029d70f938f0da7f4bf67ccd4785d59a91a3648 Mon Sep 17 00:00:00 2001 From: Alexander Bridges Date: Thu, 21 Sep 2017 09:55:27 +0300 Subject: [PATCH 012/284] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c8002f4..c483ac1 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ # MasterBot CW Master Castle Bot -Trello tuskboard ```https://trello.com/b/mIKI2omk/%D1%81%D1%83%D0%BC%D1%80%D0%B0%D0%BA%D0%BE%D0%B1%D0%BE%D1%82 +Trello taskboard ```https://trello.com/b/mIKI2omk/%D1%81%D1%83%D0%BC%D1%80%D0%B0%D0%BA%D0%BE%D0%B1%D0%BE%D1%82 From 47b900d0ff611ad247312d853de60ee69022ff96 Mon Sep 17 00:00:00 2001 From: Alexander Bridges Date: Thu, 21 Sep 2017 09:56:04 +0300 Subject: [PATCH 013/284] Update README.md --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c483ac1..f011dd3 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ # MasterBot CW Master Castle Bot -Trello taskboard ```https://trello.com/b/mIKI2omk/%D1%81%D1%83%D0%BC%D1%80%D0%B0%D0%BA%D0%BE%D0%B1%D0%BE%D1%82 +#Trello taskboard: + +https://trello.com/b/mIKI2omk/%D1%81%D1%83%D0%BC%D1%80%D0%B0%D0%BA%D0%BE%D0%B1%D0%BE%D1%82 From c0ce14c20d6a5efe617cb07c37fadf36eb3dfb85 Mon Sep 17 00:00:00 2001 From: Alexander Bridges Date: Thu, 21 Sep 2017 09:56:14 +0300 Subject: [PATCH 014/284] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f011dd3..332e674 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # MasterBot CW Master Castle Bot -#Trello taskboard: +# Trello taskboard: https://trello.com/b/mIKI2omk/%D1%81%D1%83%D0%BC%D1%80%D0%B0%D0%BA%D0%BE%D0%B1%D0%BE%D1%82 From 31c94ec83d0d3222c6445643a2f981bf7febfdb4 Mon Sep 17 00:00:00 2001 From: Alexander Bridges Date: Thu, 21 Sep 2017 10:16:59 +0300 Subject: [PATCH 015/284] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 332e674..e3a85ed 100644 --- a/README.md +++ b/README.md @@ -3,4 +3,4 @@ CW Master Castle Bot # Trello taskboard: -https://trello.com/b/mIKI2omk/%D1%81%D1%83%D0%BC%D1%80%D0%B0%D0%BA%D0%BE%D0%B1%D0%BE%D1%82 +"ТЫЦ" From f23a54563e07552c78b3adc27261e179e1d6d19a Mon Sep 17 00:00:00 2001 From: Alexander Bridges Date: Thu, 21 Sep 2017 10:18:17 +0300 Subject: [PATCH 016/284] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e3a85ed..6a544fc 100644 --- a/README.md +++ b/README.md @@ -3,4 +3,4 @@ CW Master Castle Bot # Trello taskboard: -"ТЫЦ" +ТЫЦ From beb6bc7821704b58e1638008093ddf246d848919 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Thu, 21 Sep 2017 10:44:45 +0300 Subject: [PATCH 017/284] =?UTF-8?q?=D0=A1=D1=81=D1=8B=D0=BB=D0=BA=D0=B0=20?= =?UTF-8?q?=D0=B2=20=D0=BC=D0=B0=D1=80=D0=BA=D0=B4=D0=B0=D1=83=D0=BD=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 6a544fc..3e95c9d 100644 --- a/README.md +++ b/README.md @@ -2,5 +2,4 @@ CW Master Castle Bot # Trello taskboard: - -ТЫЦ +[ТЫЦ]("https://trello.com/b/mIKI2omk/%D1%81%D1%83%D0%BC%D1%80%D0%B0%D0%BA%D0%BE%D0%B1%D0%BE%D1%82") From e1bc638efd1b09ed6e14257026d3288f38ec6f3a Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Thu, 21 Sep 2017 10:45:26 +0300 Subject: [PATCH 018/284] =?UTF-8?q?=D0=A5=D0=BC=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3e95c9d..07a7de1 100644 --- a/README.md +++ b/README.md @@ -2,4 +2,4 @@ CW Master Castle Bot # Trello taskboard: -[ТЫЦ]("https://trello.com/b/mIKI2omk/%D1%81%D1%83%D0%BC%D1%80%D0%B0%D0%BA%D0%BE%D0%B1%D0%BE%D1%82") +[ТЫЦ](https://trello.com/b/mIKI2omk/%D1%81%D1%83%D0%BC%D1%80%D0%B0%D0%BA%D0%BE%D0%B1%D0%BE%D1%82) From b820bdad47408827cc4639289321c7d98d16889c Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Thu, 21 Sep 2017 10:51:06 +0300 Subject: [PATCH 019/284] PY-2017.2.3 + + + + + + + + + \ No newline at end of file From d1b566ebe09753c9ef75d63dfad6e785d7f3bc38 Mon Sep 17 00:00:00 2001 From: toxydose Date: Thu, 21 Sep 2017 13:00:04 +0300 Subject: [PATCH 020/284] add requirements.txt --- requirements.txt | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 requirements.txt diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..37a8ebb --- /dev/null +++ b/requirements.txt @@ -0,0 +1,16 @@ +certifi==2017.7.27.1 +chardet==3.0.4 +click==6.7 +Flask==0.12.2 +future==0.16.0 +idna==2.6 +itsdangerous==0.24 +Jinja2==2.9.6 +MarkupSafe==1.0 +pkg-resources==0.0.0 +PyMySQL==0.7.11 +python-telegram-bot==8.0 +requests==2.18.4 +SQLAlchemy==1.1.14 +urllib3==1.22 +Werkzeug==0.12.2 From f324913c0da0853fa391619673cebd7b6ad310e7 Mon Sep 17 00:00:00 2001 From: toxydose Date: Thu, 21 Sep 2017 13:04:53 +0300 Subject: [PATCH 021/284] update README.md --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 07a7de1..b82cda5 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,10 @@ # MasterBot CW Master Castle Bot +###installation in venv (recommended): +```virtualenv -p python3 .env #make sure you creating python3 venv +source .env/bin/activate +python3 -m pip install -r requirements.txt + # Trello taskboard: [ТЫЦ](https://trello.com/b/mIKI2omk/%D1%81%D1%83%D0%BC%D1%80%D0%B0%D0%BA%D0%BE%D0%B1%D0%BE%D1%82) From 49aaf249200ef9f2c6acbeeb7a6ee3fbefc69288 Mon Sep 17 00:00:00 2001 From: Alexander Bridges Date: Thu, 21 Sep 2017 13:06:25 +0300 Subject: [PATCH 022/284] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b82cda5..fe026bb 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ # MasterBot CW Master Castle Bot -###installation in venv (recommended): +### installation in venv (recommended): ```virtualenv -p python3 .env #make sure you creating python3 venv source .env/bin/activate python3 -m pip install -r requirements.txt - +``` # Trello taskboard: [ТЫЦ](https://trello.com/b/mIKI2omk/%D1%81%D1%83%D0%BC%D1%80%D0%B0%D0%BA%D0%BE%D0%B1%D0%BE%D1%82) From b953b2a7fb127442b8a51d86a9b34ede2d20ffe2 Mon Sep 17 00:00:00 2001 From: Alexander Bridges Date: Thu, 21 Sep 2017 13:06:56 +0300 Subject: [PATCH 023/284] Update README.md --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index fe026bb..70f52b8 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,11 @@ CW Master Castle Bot ### installation in venv (recommended): -```virtualenv -p python3 .env #make sure you creating python3 venv +``` +virtualenv -p python3 .env #make sure you creating python3 venv source .env/bin/activate python3 -m pip install -r requirements.txt + ``` # Trello taskboard: [ТЫЦ](https://trello.com/b/mIKI2omk/%D1%81%D1%83%D0%BC%D1%80%D0%B0%D0%BA%D0%BE%D0%B1%D0%BE%D1%82) From 9cbc48ae73a4d54c6341c0924df2b1b160081af9 Mon Sep 17 00:00:00 2001 From: Alexander Bridges Date: Thu, 21 Sep 2017 13:07:12 +0300 Subject: [PATCH 024/284] Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 70f52b8..e060d01 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,6 @@ CW Master Castle Bot virtualenv -p python3 .env #make sure you creating python3 venv source .env/bin/activate python3 -m pip install -r requirements.txt - ``` # Trello taskboard: [ТЫЦ](https://trello.com/b/mIKI2omk/%D1%81%D1%83%D0%BC%D1%80%D0%B0%D0%BA%D0%BE%D0%B1%D0%BE%D1%82) From b2d1dde18ef2bd483931819d6a4d4fb2aeaaf607 Mon Sep 17 00:00:00 2001 From: toxydose Date: Thu, 21 Sep 2017 15:57:39 +0300 Subject: [PATCH 025/284] update README.md --- README.md | 45 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e060d01..53e0043 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,52 @@ # MasterBot CW Master Castle Bot +# Trello taskboard: +[ТЫЦ](https://trello.com/b/mIKI2omk/%D1%81%D1%83%D0%BC%D1%80%D0%B0%D0%BA%D0%BE%D0%B1%D0%BE%D1%82) + ### installation in venv (recommended): ``` virtualenv -p python3 .env #make sure you creating python3 venv source .env/bin/activate python3 -m pip install -r requirements.txt ``` -# Trello taskboard: -[ТЫЦ](https://trello.com/b/mIKI2omk/%D1%81%D1%83%D0%BC%D1%80%D0%B0%D0%BA%D0%BE%D0%B1%D0%BE%D1%82) + +### configuration mysql database (only mysql is supported): + +1)Install the current mysql-server version +e.g. for GNU/Linux: +``` +sudo apt-get install mysql-server +``` + +2)create root user (if it was not created during installation process) +``` +sudo mysqladmin -u root password 'mynewpassword' +``` + +3)open mysql command line as root: +``` +sudo mysql -u root -h localhost -p +``` + +4)create the new user: +``` +CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass'; +``` + +5)log in to your new user as shown in (3). + +6)create the new database +``` +CREATE DATABASE 'test'; +``` + +7)exit to CLI + +8)open the file 'config.py.sample', enter your new database user's credentials, your database name and your telegram bot API token + +9)launch the bot: +``` +python3 main.py +``` +and the mysql database schema will be created automatically by the built-in script. \ No newline at end of file From 1810838c2e7f5e1ef48e1ee7288b7fb92b1a2166 Mon Sep 17 00:00:00 2001 From: Alexander Bridges Date: Thu, 21 Sep 2017 16:01:42 +0300 Subject: [PATCH 026/284] Update README.md --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 53e0043..e3b1c52 100644 --- a/README.md +++ b/README.md @@ -42,11 +42,13 @@ CREATE DATABASE 'test'; ``` 7)exit to CLI - +``` +exit +``` 8)open the file 'config.py.sample', enter your new database user's credentials, your database name and your telegram bot API token 9)launch the bot: ``` python3 main.py ``` -and the mysql database schema will be created automatically by the built-in script. \ No newline at end of file +and the mysql database schema will be created automatically by the built-in script. From e06753679c1003b8e63ce890e477f7dd2d670b9d Mon Sep 17 00:00:00 2001 From: Alexander Bridges Date: Thu, 21 Sep 2017 16:08:10 +0300 Subject: [PATCH 027/284] Update README.md --- README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index e3b1c52..ab39286 100644 --- a/README.md +++ b/README.md @@ -18,36 +18,36 @@ e.g. for GNU/Linux: ``` sudo apt-get install mysql-server ``` - 2)create root user (if it was not created during installation process) ``` sudo mysqladmin -u root password 'mynewpassword' ``` - 3)open mysql command line as root: ``` sudo mysql -u root -h localhost -p ``` - 4)create the new user: ``` CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass'; ``` +5)give the privileges to the new user: +''' +GRANT ALL PRIVILEGES ON * . * TO 'myuser'@'localhost'; +''' +6)log in to your new user as shown in (3). -5)log in to your new user as shown in (3). - -6)create the new database +7)create the new database ``` CREATE DATABASE 'test'; ``` -7)exit to CLI +8)exit to CLI ``` exit ``` -8)open the file 'config.py.sample', enter your new database user's credentials, your database name and your telegram bot API token +9)open the file 'config.py.sample', enter your new database user's credentials, your database name and your telegram bot API token -9)launch the bot: +10)launch the bot: ``` python3 main.py ``` From 97cfeda274d7af317c3050f37176cd8552bbaa34 Mon Sep 17 00:00:00 2001 From: Alexander Bridges Date: Thu, 21 Sep 2017 16:08:27 +0300 Subject: [PATCH 028/284] Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index ab39286..712d57b 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,6 @@ GRANT ALL PRIVILEGES ON * . * TO 'myuser'@'localhost'; ``` CREATE DATABASE 'test'; ``` - 8)exit to CLI ``` exit From 54e27899fdf823d425d171ab4520d4beff5f0d07 Mon Sep 17 00:00:00 2001 From: Alexander Bridges Date: Thu, 21 Sep 2017 16:08:59 +0300 Subject: [PATCH 029/284] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 712d57b..931e26a 100644 --- a/README.md +++ b/README.md @@ -31,9 +31,9 @@ sudo mysql -u root -h localhost -p CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass'; ``` 5)give the privileges to the new user: -''' +``` GRANT ALL PRIVILEGES ON * . * TO 'myuser'@'localhost'; -''' +``` 6)log in to your new user as shown in (3). 7)create the new database From 2e36025ea03a0238eca253d3514922b0cf453079 Mon Sep 17 00:00:00 2001 From: Alexander Bridges Date: Thu, 21 Sep 2017 16:10:23 +0300 Subject: [PATCH 030/284] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 931e26a..25bcfca 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass'; 5)give the privileges to the new user: ``` GRANT ALL PRIVILEGES ON * . * TO 'myuser'@'localhost'; +exit ``` 6)log in to your new user as shown in (3). From 2f13016b142438a59b130222155eab97833f8265 Mon Sep 17 00:00:00 2001 From: Alexander Bridges Date: Thu, 21 Sep 2017 17:04:24 +0300 Subject: [PATCH 031/284] Update README.md --- README.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 25bcfca..8f49164 100644 --- a/README.md +++ b/README.md @@ -4,40 +4,40 @@ CW Master Castle Bot # Trello taskboard: [ТЫЦ](https://trello.com/b/mIKI2omk/%D1%81%D1%83%D0%BC%D1%80%D0%B0%D0%BA%D0%BE%D0%B1%D0%BE%D1%82) -### installation in venv (recommended): +### installation into venv (recommended): ``` virtualenv -p python3 .env #make sure you creating python3 venv source .env/bin/activate python3 -m pip install -r requirements.txt ``` -### configuration mysql database (only mysql is supported): +### mysql database setup (only mysql is supported): -1)Install the current mysql-server version +1)Install recent mysql-server distribution e.g. for GNU/Linux: ``` sudo apt-get install mysql-server ``` -2)create root user (if it was not created during installation process) +2)create a root user (if it was not created during installation process) ``` sudo mysqladmin -u root password 'mynewpassword' ``` -3)open mysql command line as root: +3)login to mysql as root: ``` sudo mysql -u root -h localhost -p ``` -4)create the new user: +4)create a new user: ``` CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass'; ``` -5)give the privileges to the new user: +5)grant privileges to the new user: ``` GRANT ALL PRIVILEGES ON * . * TO 'myuser'@'localhost'; exit ``` -6)log in to your new user as shown in (3). +6)log in to your new user similarly to step (3). -7)create the new database +7)create a new database ``` CREATE DATABASE 'test'; ``` @@ -45,10 +45,10 @@ CREATE DATABASE 'test'; ``` exit ``` -9)open the file 'config.py.sample', enter your new database user's credentials, your database name and your telegram bot API token +9)open the file 'config.py.sample', enter your new database user's credentials, database name and your telegram bot API token 10)launch the bot: ``` python3 main.py ``` -and the mysql database schema will be created automatically by the built-in script. +the mysql database schema will be created automatically by a built-in script. From 5729780984c8253ba49af94ebdbad395b6ceed2c Mon Sep 17 00:00:00 2001 From: Alexander Bridges Date: Thu, 21 Sep 2017 20:05:32 +0300 Subject: [PATCH 032/284] =?UTF-8?q?=D1=83=D0=B1=D1=80=D0=B0=D0=BB=20=D0=BC?= =?UTF-8?q?=D1=8F=D1=82=D0=BD=D1=8B=D0=B9=20=D1=84=D1=83=D0=BD=D0=BA=D1=86?= =?UTF-8?q?=D0=B8=D0=BE=D0=BD=D0=B0=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit проверка условия на соответствие id мятного чата, который не хотел получать пины от бота. --- main.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/main.py b/main.py index 9c234a5..54dcccc 100644 --- a/main.py +++ b/main.py @@ -165,8 +165,6 @@ def ready_to_battle(bot, job_queue): try: group = session.query(Squad).all() for item in group: - if item.chat_id == -1001062678288: - continue order = Order() order.text = 'К битве готовсь!' order.chat_id = item.chat_id From 1fafa3d62e67a6c7b276581d4e3a37678000dbb0 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Thu, 28 Sep 2017 17:22:01 +0300 Subject: [PATCH 033/284] =?UTF-8?q?=D0=9D=D0=B0=D1=87=D0=B0=D0=BB=D0=BE=20?= =?UTF-8?q?=D0=BF=D0=B5=D1=80=D0=B5=D0=B4=D0=B5=D0=BB=D0=BA=D0=B8=20=D1=80?= =?UTF-8?q?=D0=B0=D0=B1=D0=BE=D1=82=D1=8B=20=D1=81=20=D0=B1=D0=B0=D0=B7?= =?UTF-8?q?=D0=BE=D0=B9=20=D0=B8=20=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B8=20?= =?UTF-8?q?"=D1=81=D0=BB=D0=B8=D1=88=D0=BA=D0=BE=D0=BC=20=D0=BE=D0=B1?= =?UTF-8?q?=D1=89=D0=B8=D1=85=20=D1=8D=D0=BA=D1=81=D1=8D=D0=BF=D1=88=D0=BE?= =?UTF-8?q?=D0=BD=D0=BE=D0=B2"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/types.py | 57 +++++++------- core/utils.py | 111 +++++++++++---------------- main.py | 203 +++++++++++++++++++++++++------------------------- 3 files changed, 170 insertions(+), 201 deletions(-) diff --git a/core/types.py b/core/types.py index f788f44..586d93c 100644 --- a/core/types.py +++ b/core/types.py @@ -2,17 +2,17 @@ from datetime import datetime from enum import Enum import logging -import requests -import threading from sqlalchemy import ( - create_engine, event, + create_engine, Column, Integer, DateTime, Boolean, ForeignKey, UnicodeText, BigInteger ) from sqlalchemy.dialects.mysql import DATETIME from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, relationship, scoped_session -from sqlalchemy.pool import Pool +from sqlalchemy.exc import SQLAlchemyError + +from telegram import Bot from config import DB @@ -22,6 +22,8 @@ class AdminType(Enum): FULL = 1 GROUP = 2 + NOT_ADMIN = 100 + class MessageType(Enum): TEXT = 0 @@ -48,17 +50,6 @@ class MessageType(Enum): Session = scoped_session(sessionmaker(bind=ENGINE)) -@event.listens_for(Pool, "connect") -def set_unicode(dbapi_conn, conn_record): - cursor = dbapi_conn.cursor() - try: - cursor.execute("SET NAMES 'utf8mb4' COLLATE 'utf8mb4_unicode_ci'") - - # FIX: слишком общая ошибка - except Exception as err: - LOGGER.error(err) - - class Group(Base): __tablename__ = 'groups' @@ -275,29 +266,37 @@ class LocalTrigger(Base): def admin(adm_type=AdminType.FULL): def decorate(func): - def wrapper(bot, update, *args, **kwargs): + def wrapper(bot: Bot, update, *args, **kwargs): session = Session() try: - adms = session.query(Admin).filter_by(user_id=update.message.from_user.id).all() allowed = False - for adm in adms: - if adm is not None and adm.admin_type <= adm_type.value and \ - (adm.admin_group in [0, update.message.chat.id] or - update.message.chat.id == update.message.from_user.id): - if adm.admin_group != 0: - group = session.query(Group).filter_by(id=adm.admin_group).first() - if group and group.bot_in_group: + if adm_type == AdminType.NOT_ADMIN: + allowed = True + else: + admins = session.query(Admin).filter_by(user_id=update.message.from_user.id).all() + for adm in admins: + if adm is not None and adm.admin_type <= adm_type.value and \ + (adm.admin_group in [0, update.message.chat.id] or + update.message.chat.id == update.message.from_user.id): + if adm.admin_group != 0: + group = session.query(Group).filter_by(id=adm.admin_group).first() + if group and group.bot_in_group: + allowed = True + break + else: allowed = True break - else: - allowed = True - break if allowed: - func(bot, update, *args, **kwargs) - except Exception as e: + func(bot, update, session, *args, **kwargs) + except SQLAlchemyError as err: + bot.logger.error(str(err)) session.rollback() return wrapper return decorate +def user(func): + admin(AdminType.NOT_ADMIN)(func) + + Base.metadata.create_all(ENGINE) diff --git a/core/utils.py b/core/utils.py index 03d8789..a4ba5b6 100644 --- a/core/utils.py +++ b/core/utils.py @@ -1,7 +1,7 @@ import http.client from telegram import Bot -from telegram.error import ChatMigrated +from telegram.error import TelegramError from telegram.ext.dispatcher import run_async from core.types import Session, User, Group @@ -12,90 +12,63 @@ def send_async(bot: Bot, *args, **kwargs): try: return bot.sendMessage(*args, **kwargs) - except ChatMigrated as err: + except TelegramError as err: + bot.logger.error(err.message) session = Session() group = session.query(Group).filter_by(id=kwargs['chat_id']).first() if group is not None: group.bot_in_group = False session.add(group) session.commit() - kwargs['chat_id'] = err.new_chat_id - return bot.sendMessage(*args, **kwargs) - - # FIX: слишком общая ошибка - except Exception as err: - print(err) + return None -def send_pin_async(bot: Bot, *args, **kwargs): - try: - msg = bot.sendMessage(*args, **kwargs) - except ChatMigrated as err: - kwargs['chat_id'] = err.new_chat_id - msg = bot.sendMessage(*args, **kwargs) +def add_user(tg_user, session): + user = session.query(User).filter_by(id=tg_user.id).first() + if user is None: + user = User(id=tg_user.id, username=tg_user.username or '', + first_name=tg_user.first_name or '', + last_name=tg_user.last_name or '') + session.add(user) + else: + updated = False + if user.username != tg_user.username: + user.username = tg_user.username + updated = True + if user.first_name != tg_user.first_name: + user.first_name = tg_user.first_name + updated = True + if user.last_name != tg_user.last_name: + user.last_name = tg_user.last_name + updated = True + if updated: + session.add(user) + session.commit() + return user - conn = http.client.HTTPConnection("127.0.0.1") - conn.request("GET", "/{}/{}/".format(msg.message_id, msg.chat.id)) +def update_group(grp, session): + if grp.type in ['group', 'supergroup', 'channel']: + group = session.query(Group).filter_by(id=grp.id).first() + if group is None: + group = Group(id=grp.id, title=grp.title, + username=grp.username) + session.add(group) -def add_user(tg_user): - session = Session() - try: - user = session.query(User).filter_by(id=tg_user.id).first() - if user is None: - user = User(id=tg_user.id, username=tg_user.username or '', - first_name=tg_user.first_name or '', - last_name=tg_user.last_name or '') - session.add(user) else: updated = False - if user.username != tg_user.username: - user.username = tg_user.username + if group.username != grp.username: + group.username = grp.username updated = True - if user.first_name != tg_user.first_name: - user.first_name = tg_user.first_name + if group.title != grp.title: + group.title = grp.title updated = True - if user.last_name != tg_user.last_name: - user.last_name = tg_user.last_name + if not group.bot_in_group: + group.bot_in_group = True updated = True if updated: - session.add(user) - session.commit() - return user - - # FIX: слишком общая ошибка - except Exception: - session.rollback() - - -def update_group(grp): - session = Session() - try: - if grp.type in ['group', 'supergroup', 'channel']: - group = session.query(Group).filter_by(id=grp.id).first() - if group is None: - group = Group(id=grp.id, title=grp.title, - username=grp.username) session.add(group) - else: - updated = False - if group.username != grp.username: - group.username = grp.username - updated = True - if group.title != grp.title: - group.title = grp.title - updated = True - if not group.bot_in_group: - group.bot_in_group = True - updated = True - if updated: - session.add(group) - - session.commit() - return group - return None - - # FIX: слишком общая ошибка - except Exception: - session.rollback() + session.commit() + return group + return None diff --git a/main.py b/main.py index aaacb75..700c65a 100644 --- a/main.py +++ b/main.py @@ -14,6 +14,7 @@ Filters, CallbackQueryHandler ) from telegram.ext.dispatcher import run_async +from telegram.error import TelegramError from config import TOKEN, GOVERNMENT_CHAT from core.functions.activity import ( @@ -56,9 +57,11 @@ from core.texts import ( MSG_SQUAD_READY, MSG_FULL_TEXT_LINE, MSG_FULL_TEXT_TOTAL ) -from core.types import Session, Order, Squad, Admin +from core.types import Session, Order, Squad, Admin, user from core.utils import add_user, send_async +from sqlalchemy.exc import SQLAlchemyError + last_welcome = 0 logging.basicConfig( level=logging.WARNING, @@ -79,92 +82,94 @@ def del_msg(bot, job): @run_async -def manage_all(bot: Bot, update: Update, chat_data, job_queue): - try: - add_user(update.message.from_user) - if update.message.chat.type in ['group', 'supergroup', 'channel']: - session = Session() - squad = session.query(Squad).filter_by( - chat_id=update.message.chat.id).first() - admin = session.query(Admin).filter( - Admin.user_id == update.message.from_user.id and - Admin.admin_group in [update.message.chat.id, 0]).first() - - if squad is not None and admin is None and battle_time(): - bot.delete_message(update.message.chat.id, - update.message.message_id) - - if not update.message.text: - return - +@user +def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): + add_user(update.message.from_user, session) + if update.message.chat.type in ['group', 'supergroup', 'channel']: + squad = session.query(Squad).filter_by( + chat_id=update.message.chat.id).first() + admin = session.query(Admin).filter( + Admin.user_id == update.message.from_user.id and + Admin.admin_group in [update.message.chat.id, 0]).first() + + if squad is not None and admin is None and battle_time(): + bot.delete_message(update.message.chat.id, + update.message.message_id) + + if not update.message.text: + return + + text = update.message.text.lower() + + if text.startswith('приветствие:'): + set_welcome(bot, update) + elif text == 'помощь': + help_msg(bot, update) + elif text == 'покажи приветствие': + show_welcome(bot, update) + elif text == 'включи приветствие': + enable_welcome(bot, update) + elif text == 'выключи приветствие': + disable_welcome(bot, update) + elif text.startswith('затриггерь:'): + set_trigger(bot, update) + elif text.startswith('разтриггерь:'): + del_trigger(bot, update) + elif text == 'список триггеров': + list_triggers(bot, update) + elif text == 'список админов': + list_admins(bot, update) + elif text == 'пинг': + ping(bot, update) + elif text == 'статистика за день': + day_activity(bot, update) + elif text == 'cтатистика за неделю': + week_activity(bot, update) + elif text == 'cтатистика за бой': + battle_activity(bot, update) + elif text == 'разрешить триггерить всем': + enable_trigger_all(bot, update) + elif text == 'запретить триггерить всем': + disable_trigger_all(bot, update) + elif text in ['админы', 'офицер']: + admins_for_users(bot, update) + elif text == 'пинят все': + pin_all(bot, update) + elif text == 'хорош пинить': + not_pin_all(bot, update) + elif text in ['бандит', 'краб']: + boss_leader(bot, update) + elif text in ['жало', 'королева роя']: + boss_zhalo(bot, update) + elif text in ['циклоп', 'борода']: + boss_monoeye(bot, update) + elif text in ['гидра', 'лич']: + boss_hydra(bot, update) + elif text == 'открыть набор': + open_hiring(bot, update) + elif text == 'закрыть набор': + close_hiring(bot, update) + elif update.message.text: + trigger_show(bot, update) + elif update.message.reply_to_message is not None: + if text == 'пин': + pin(bot, update) + elif text == 'сайлентпин': + silent_pin(bot, update) + elif text == 'удоли': + delete_msg(bot, update) + elif text == 'свали': + delete_user(bot, update) + + elif 'твои результаты в бою:' in text: + if update.message.forward_from.id == 265204902: + job_queue.run_once(del_msg, 2, (update.message.chat.id, + update.message.message_id)) + + elif update.message.chat.type == 'private': + if update.message.text: text = update.message.text.lower() - if text.startswith('приветствие:'): - set_welcome(bot, update) - elif text == 'помощь': - help_msg(bot, update) - elif text == 'покажи приветствие': - show_welcome(bot, update) - elif text == 'включи приветствие': - enable_welcome(bot, update) - elif text == 'выключи приветствие': - disable_welcome(bot, update) - elif text.startswith('затриггерь:'): - set_trigger(bot, update) - elif text.startswith('разтриггерь:'): - del_trigger(bot, update) - elif text == 'список триггеров': - list_triggers(bot, update) - elif text == 'список админов': - list_admins(bot, update) - elif text == 'пинг': - ping(bot, update) - elif text == 'статистика за день': - day_activity(bot, update) - elif text == 'cтатистика за неделю': - week_activity(bot, update) - elif text == 'cтатистика за бой': - battle_activity(bot, update) - elif text == 'разрешить триггерить всем': - enable_trigger_all(bot, update) - elif text == 'запретить триггерить всем': - disable_trigger_all(bot, update) - elif text in ['админы', 'офицер']: - admins_for_users(bot, update) - elif text == 'пинят все': - pin_all(bot, update) - elif text == 'хорош пинить': - not_pin_all(bot, update) - elif text in ['бандит', 'краб']: - boss_leader(bot, update) - elif text in ['жало', 'королева роя']: - boss_zhalo(bot, update) - elif text in ['циклоп', 'борода']: - boss_monoeye(bot, update) - elif text in ['гидра', 'лич']: - boss_hydra(bot, update) - elif text == 'открыть набор': - open_hiring(bot, update) - elif text == 'закрыть набор': - close_hiring(bot, update) - elif update.message.text: - trigger_show(bot, update) - elif update.message.reply_to_message is not None: - if text == 'пин': - pin(bot, update) - elif text == 'сайлентпин': - silent_pin(bot, update) - elif text == 'удоли': - delete_msg(bot, update) - elif text == 'свали': - delete_user(bot, update) - - elif 'твои результаты в бою:' in text: - if update.message.forward_from.id == 265204902: - job_queue.run_once(del_msg, 2, (update.message.chat.id, - update.message.message_id)) - - elif update.message.chat.type == 'private': if text == 'статус': send_status(bot, update) elif text == 'хочу в отряд': @@ -194,16 +199,12 @@ def manage_all(bot: Bot, update: Update, chat_data, job_queue): elif from_id == 278525885: if '📦твой склад с материалами:' in text: trade_compare(bot, update, chat_data) - else: - order(bot, update, chat_data) - - # FIX: слишком общая ошибка - except Exception: - Session.rollback() + else: + order(bot, update, chat_data) @run_async -def ready_to_battle(bot): +def ready_to_battle(bot: Bot): session = Session() try: group = session.query(Squad).all() @@ -231,18 +232,16 @@ def ready_to_battle(bot): 'message_id': msg.message_id, 'disable_notification': False}) - # FIX: слишком общая ошибка - except Exception as err: - print(err) - + except TelegramError as err: + bot.logger(err.message) - # FIX: слишком общая ошибка - except Exception: + except SQLAlchemyError as err: + bot.logger(str(err)) Session.rollback() @run_async -def ready_to_battle_result(bot): +def ready_to_battle_result(bot: Bot): session = Session() try: group = session.query(Squad).all() @@ -283,7 +282,6 @@ def ready_to_battle_result(bot): attack, defence) - full_text += MSG_FULL_TEXT_TOTAL.format(full_count, full_attack, full_defence) @@ -293,12 +291,11 @@ def ready_to_battle_result(bot): text=full_text, parse_mode=ParseMode.HTML) - # FIX: слишком общая ошибка - except Exception: + except SQLAlchemyError as err: + bot.logger(str(err)) Session.rollback() - def main(): # Create the EventHandler and pass it your bot's token. updater = Updater(TOKEN) From 78c0ecd22c68eeea5a3f0f533f7aa89c6beb9a90 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Thu, 28 Sep 2017 18:48:46 +0300 Subject: [PATCH 034/284] =?UTF-8?q?=D0=A1=D0=B5=D1=81=D1=81=D0=B8=D0=B8=20?= =?UTF-8?q?=D0=B1=D0=BE=D0=BB=D1=8C=D1=88=D0=B5=20=D0=BD=D0=B5=20=D0=BF?= =?UTF-8?q?=D0=BB=D0=BE=D0=B4=D1=8F=D1=82=D1=81=D1=8F=20=D0=BA=D0=B0=D0=BA?= =?UTF-8?q?=20=D0=BA=D1=80=D0=BE=D0=BB=D0=B8=D0=BA=D0=B8.=20=D0=97=D0=B0?= =?UTF-8?q?=D0=BE=D0=B4=D0=BD=D0=BE=20=D0=BD=D0=B5=D0=BC=D0=BD=D0=BE=D0=B3?= =?UTF-8?q?=D0=BE=20=D0=BF=D0=BE=D1=87=D0=B8=D1=81=D1=82=D0=B8=D0=BB=20?= =?UTF-8?q?=D0=BA=D0=BE=D0=B4,=20=D0=B8=D0=B7=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=D1=81=D1=8F=20=D0=BF=D0=BE=D1=87=D1=82=D0=B8=20=D0=BE?= =?UTF-8?q?=D1=82=D0=BE=20=D0=B2=D1=81=D0=B5=D1=85=20=D0=BF=D1=80=D0=B5?= =?UTF-8?q?=D0=B4=D1=83=D0=BF=D1=80=D0=B5=D0=B6=D0=B4=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=B9=20PyCharm=20=D0=B8=20=D0=BF=D0=BE=D1=84=D0=B8=D0=BA?= =?UTF-8?q?=D1=81=D0=B8=D0=BB=20=D0=BD=D0=B5=D1=81=D0=BA=D0=BE=D0=BB=D1=8C?= =?UTF-8?q?=D0=BA=D0=BE=20=D1=84=D1=83=D0=BD=D0=BA=D1=86=D0=B8=D0=B9.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/activity.py | 56 ++-- core/functions/admins.py | 371 ++++++++++----------- core/functions/api.py | 8 +- core/functions/bosses.py | 16 +- core/functions/common.py | 54 ++- core/functions/inline_keyboard_handling.py | 132 ++++---- core/functions/newbies.py | 6 +- core/functions/order_groups.py | 13 +- core/functions/orders.py | 11 +- core/functions/pin.py | 40 +-- core/functions/profile.py | 44 +-- core/functions/reply_markup.py | 3 +- core/functions/squad.py | 69 ++-- core/functions/triggers.py | 100 +++--- core/functions/welcome.py | 38 +-- core/types.py | 45 +-- main.py | 38 +-- 17 files changed, 479 insertions(+), 565 deletions(-) diff --git a/core/functions/activity.py b/core/functions/activity.py index 629c5e2..71835f4 100644 --- a/core/functions/activity.py +++ b/core/functions/activity.py @@ -3,7 +3,7 @@ from telegram import Update, Bot from core.texts import MSG_ORDER_STATISTIC, MSG_ORDER_STATISTIC_OUT_FORMAT -from core.types import AdminType, admin, Session, Squad +from core.types import AdminType, admin_allowed, Squad from core.utils import send_async @@ -27,43 +27,25 @@ def activity(squad, days=0, hours=0): return msg -@admin(adm_type=AdminType.GROUP) -def day_activity(bot: Bot, update: Update): - session = Session() - try: - squad = session.query(Squad).filter_by(chat_id=update.message.chat.id).first() - if squad is not None: - msg = activity(squad, days=1) - send_async(bot, chat_id=update.message.chat.id, text=msg) +@admin_allowed(adm_type=AdminType.GROUP) +def day_activity(bot: Bot, update: Update, session): + squad = session.query(Squad).filter_by(chat_id=update.message.chat.id).first() + if squad is not None: + msg = activity(squad, days=1) + send_async(bot, chat_id=update.message.chat.id, text=msg) - #FIX: слишком общая ошибка - except Exception: - session.rollback() +@admin_allowed(adm_type=AdminType.GROUP) +def week_activity(bot: Bot, update: Update, session): + squad = session.query(Squad).filter_by(chat_id=update.message.chat.id).first() + if squad is not None: + msg = activity(squad, days=7) + send_async(bot, chat_id=update.message.chat.id, text=msg) -@admin(adm_type=AdminType.GROUP) -def week_activity(bot: Bot, update: Update): - session = Session() - try: - squad = session.query(Squad).filter_by(chat_id=update.message.chat.id).first() - if squad is not None: - msg = activity(squad, days=7) - send_async(bot, chat_id=update.message.chat.id, text=msg) - #FIX: слишком общая ошибка - except Exception: - session.rollback() - - -@admin(adm_type=AdminType.GROUP) -def battle_activity(bot: Bot, update: Update): - session = Session() - try: - squad = session.query(Squad).filter_by(chat_id=update.message.chat.id).first() - if squad is not None: - msg = activity(squad, hours=4) - send_async(bot, chat_id=update.message.chat.id, text=msg) - - #FIX: слишком общая ошибка - except Exception: - session.rollback() +@admin_allowed(adm_type=AdminType.GROUP) +def battle_activity(bot: Bot, update: Update, session): + squad = session.query(Squad).filter_by(chat_id=update.message.chat.id).first() + if squad is not None: + msg = activity(squad, hours=4) + send_async(bot, chat_id=update.message.chat.id, text=msg) diff --git a/core/functions/admins.py b/core/functions/admins.py index edbd1c0..69ae4b5 100644 --- a/core/functions/admins.py +++ b/core/functions/admins.py @@ -10,148 +10,63 @@ MSG_NEW_SUPER_ADMIN, MSG_NEW_SUPER_ADMIN_EXISTS, MSG_DEL_GLOBAL_ADMIN, MSG_DEL_GLOBAL_ADMIN_NOT_EXIST ) -from core.types import User, AdminType, Admin, admin, Session +from core.types import User, AdminType, Admin, admin_allowed, user_allowed from core.utils import send_async -@admin() -def set_admin(bot: Bot, update: Update): - try: - msg = update.message.text.split(' ', 1)[1] - msg = msg.replace('@', '') - if msg != '': - session = Session() - user = session.query(User).filter_by(username=msg).first() - if user is None: - send_async(bot, - chat_id=update.message.chat.id, - text=MSG_USER_UNKNOWN) - - else: - adm = session.query(Admin).filter_by(user_id=user.id, - admin_group=update.message.chat.id).first() - - if adm is None: - new_group_admin = Admin(user_id=user.id, - admin_type=AdminType.GROUP.value, - admin_group=update.message.chat.id) - - session.add(new_group_admin) - session.commit() - send_async(bot, - chat_id=update.message.chat.id, - text=MSG_NEW_GROUP_ADMIN.format(user.username)) - - else: - send_async(bot, - chat_id=update.message.chat.id, - text=MSG_NEW_GROUP_ADMIN_EXISTS.format(user.username)) - - except Exception: - # FIX: instance of scoped_session has no 'rollback' - Session.rollback() - - -def del_adm(bot, chat_id, user): - session = Session() - try: - adm = session.query(Admin).filter_by(user_id=user.id, - admin_group=chat_id).first() - - if adm is None: +@admin_allowed() +def set_admin(bot: Bot, update: Update, session): + msg = update.message.text.split(' ', 1)[1] + msg = msg.replace('@', '') + if msg != '': + user = session.query(User).filter_by(username=msg).first() + if user is None: send_async(bot, - chat_id=chat_id, - text=MSG_DEL_GROUP_ADMIN_NOT_EXIST.format(user.username)) + chat_id=update.message.chat.id, + text=MSG_USER_UNKNOWN) else: - session.delete(adm) - session.commit() - send_async(bot, - chat_id=chat_id, - text=MSG_DEL_GROUP_ADMIN.format(user.username)) - - except Exception: - session.rollback() - - -@admin() -def del_admin(bot: Bot, update: Update): - session = Session() - try: - msg = update.message.text.split(' ', 1)[1] - if msg.find('@') != -1: - msg = msg.replace('@', '') - if msg != '': - user = session.query(User).filter_by(username=msg).first() - if user is None: - send_async(bot, - chat_id=update.message.chat.id, - text=MSG_USER_UNKNOWN) + adm = session.query(Admin).filter_by(user_id=user.id, + admin_group=update.message.chat.id).first() - else: - del_adm(bot, update.message.chat.id, user) - else: - user = session.query(User).filter_by(id=msg).first() - if user is None: + if adm is None: + new_group_admin = Admin(user_id=user.id, + admin_type=AdminType.GROUP.value, + admin_group=update.message.chat.id) + + session.add(new_group_admin) + session.commit() send_async(bot, chat_id=update.message.chat.id, - text=MSG_USER_UNKNOWN) + text=MSG_NEW_GROUP_ADMIN.format(user.username)) else: - del_adm(bot, update.message.chat.id, user) + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_NEW_GROUP_ADMIN_EXISTS.format(user.username)) - except Exception: - session.rollback() +def del_adm(bot, chat_id, user, session): + adm = session.query(Admin).filter_by(user_id=user.id, + admin_group=chat_id).first() -@admin() -def list_admins(bot: Bot, update: Update): - session = Session() - try: - admins = session.query(Admin).filter(Admin.admin_group == update.message.chat.id).all() - users = [] - for admin_user in admins: - users.append(session.query(User).filter_by(id=admin_user.user_id).first()) - msg = MSG_LIST_ADMINS_HEADER - for user in users: - msg += MSG_LIST_ADMINS_FORMAT.format(user.id, - user.username, - user.first_name, - user.last_name) - - send_async(bot, chat_id=update.message.chat.id, text=msg) - - except Exception: - session.rollback() - - -def admins_for_users(bot: Bot, update: Update): - session = Session() - try: - admins = session.query(Admin).filter(Admin.admin_group == update.message.chat.id).all() - users = [] - for admin_user in admins: - users.append(session.query(User).filter_by(id=admin_user.user_id).first()) - msg = MSG_LIST_ADMINS_HEADER - if users is None: - msg += MSG_EMPTY - else: - for user in users: - msg += MSG_LIST_ADMINS_USER_FORMAT.format(user.username or '', - user.first_name or '', - user.last_name or '') + if adm is None: + send_async(bot, + chat_id=chat_id, + text=MSG_DEL_GROUP_ADMIN_NOT_EXIST.format(user.username)) - send_async(bot, chat_id=update.message.chat.id, text=msg) + else: + session.delete(adm) + session.commit() + send_async(bot, + chat_id=chat_id, + text=MSG_DEL_GROUP_ADMIN.format(user.username)) - except Exception: - session.rollback() - -@admin(adm_type=AdminType.SUPER) -def set_global_admin(bot: Bot, update: Update): - session = Session() - try: - msg = update.message.text.split(' ', 1)[1] +@admin_allowed() +def del_admin(bot: Bot, update: Update, session): + msg = update.message.text.split(' ', 1)[1] + if msg.find('@') != -1: msg = msg.replace('@', '') if msg != '': user = session.query(User).filter_by(username=msg).first() @@ -161,102 +76,130 @@ def set_global_admin(bot: Bot, update: Update): text=MSG_USER_UNKNOWN) else: - adm = session.query(Admin).filter_by(user_id=user.id, - admin_type=AdminType.FULL.value).first() + del_adm(bot, update.message.chat.id, user, session) + else: + user = session.query(User).filter_by(id=msg).first() + if user is None: + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_USER_UNKNOWN) - if adm is None: - new_group_admin = Admin(user_id=user.id, - admin_type=AdminType.FULL.value, - admin_group=0) - session.add(new_group_admin) - session.commit() - send_async(bot, - chat_id=update.message.chat.id, - text=MSG_NEW_GLOBAL_ADMIN.format(user.username)) + else: + del_adm(bot, update.message.chat.id, user, session) + + +@admin_allowed() +def list_admins(bot: Bot, update: Update, session): + admins = session.query(Admin).filter(Admin.admin_group == update.message.chat.id).all() + users = [] + for admin_user in admins: + users.append(session.query(User).filter_by(id=admin_user.user_id).first()) + msg = MSG_LIST_ADMINS_HEADER + for user in users: + msg += MSG_LIST_ADMINS_FORMAT.format(user.id, + user.username, + user.first_name, + user.last_name) + + send_async(bot, chat_id=update.message.chat.id, text=msg) + + +@user_allowed +def admins_for_users(bot: Bot, update: Update, session): + admins = session.query(Admin).filter(Admin.admin_group == update.message.chat.id).all() + users = [] + for admin_user in admins: + users.append(session.query(User).filter_by(id=admin_user.user_id).first()) + msg = MSG_LIST_ADMINS_HEADER + if users is None: + msg += MSG_EMPTY + else: + for user in users: + msg += MSG_LIST_ADMINS_USER_FORMAT.format(user.username or '', + user.first_name or '', + user.last_name or '') - else: - send_async(bot, - chat_id=update.message.chat.id, - text=MSG_NEW_GLOBAL_ADMIN_EXISTS.format(user.username)) + send_async(bot, chat_id=update.message.chat.id, text=msg) - except Exception: - session.rollback() +@admin_allowed(adm_type=AdminType.SUPER) +def set_global_admin(bot: Bot, update: Update, session): + msg = update.message.text.split(' ', 1)[1] + msg = msg.replace('@', '') + if msg != '': + user = session.query(User).filter_by(username=msg).first() + if user is None: + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_USER_UNKNOWN) -def set_super_admin(bot: Bot, update: Update): - session = Session() - try: - msg = update.message.text.split(' ', 1)[1] - msg = msg.replace('@', '') - if msg != '': - user = session.query(User).filter_by(username=msg).first() - if user is None: + else: + adm = session.query(Admin).filter_by(user_id=user.id, + admin_type=AdminType.FULL.value).first() + + if adm is None: + new_group_admin = Admin(user_id=user.id, + admin_type=AdminType.FULL.value, + admin_group=0) + session.add(new_group_admin) + session.commit() send_async(bot, chat_id=update.message.chat.id, - text=MSG_USER_UNKNOWN) + text=MSG_NEW_GLOBAL_ADMIN.format(user.username)) else: - if user.id == 79612802 and update.message.from_user.id == 79612802: - adm = session.query(Admin).filter_by(user_id=user.id, admin_group=0).first() - if adm is not None: - if adm.admin_type == AdminType.SUPER.value: - send_async(bot, - chat_id=update.message.chat.id, - text=MSG_NEW_SUPER_ADMIN_EXISTS.format(user.username)) - - else: - adm.admin_type = AdminType.SUPER.value - session.add(adm) - session.commit() - send_async(bot, - chat_id=update.message.chat.id, - text=MSG_NEW_SUPER_ADMIN.format(user.username)) - - else: - new_super_admin = Admin(user_id=user.id, - admin_type=AdminType.SUPER.value, - admin_group=0) + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_NEW_GLOBAL_ADMIN_EXISTS.format(user.username)) - session.add(new_super_admin) - session.commit() - send_async(bot, - chat_id=update.message.chat.id, - text=MSG_NEW_SUPER_ADMIN.format(user.username)) - except Exception: - session.rollback() - - -@admin(adm_type=AdminType.SUPER) -def del_global_admin(bot: Bot, update: Update): - session = Session() - try: - msg = update.message.text.split(' ', 1)[1] - if msg.find('@') != -1: - msg = msg.replace('@', '') - if msg != '': - user = session.query(User).filter_by(username=msg).first() - if user is None: - send_async(bot, - chat_id=update.message.chat.id, - text=MSG_USER_UNKNOWN) - else: - adm = session.query(Admin).filter_by(user_id=user.id, - admin_type=AdminType.FULL.value).first() +@user_allowed +def set_super_admin(bot: Bot, update: Update, session): + msg = update.message.text.split(' ', 1)[1] + msg = msg.replace('@', '') + if msg != '': + user = session.query(User).filter_by(username=msg).first() + if user is None: + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_USER_UNKNOWN) - if adm is None: + else: + if user.id == 79612802 and update.message.from_user.id == 79612802: + adm = session.query(Admin).filter_by(user_id=user.id, admin_group=0).first() + if adm is not None: + if adm.admin_type == AdminType.SUPER.value: send_async(bot, chat_id=update.message.chat.id, - text=MSG_DEL_GLOBAL_ADMIN_NOT_EXIST.format(user.username)) + text=MSG_NEW_SUPER_ADMIN_EXISTS.format(user.username)) else: - session.delete(adm) + adm.admin_type = AdminType.SUPER.value + session.add(adm) session.commit() send_async(bot, chat_id=update.message.chat.id, - text=MSG_DEL_GLOBAL_ADMIN.format(user.username)) - else: - user = session.query(User).filter_by(id=msg).first() + text=MSG_NEW_SUPER_ADMIN.format(user.username)) + + else: + new_super_admin = Admin(user_id=user.id, + admin_type=AdminType.SUPER.value, + admin_group=0) + + session.add(new_super_admin) + session.commit() + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_NEW_SUPER_ADMIN.format(user.username)) + + +@admin_allowed(adm_type=AdminType.SUPER) +def del_global_admin(bot: Bot, update: Update, session): + msg = update.message.text.split(' ', 1)[1] + if msg.find('@') != -1: + msg = msg.replace('@', '') + if msg != '': + user = session.query(User).filter_by(username=msg).first() if user is None: send_async(bot, chat_id=update.message.chat.id, @@ -265,15 +208,35 @@ def del_global_admin(bot: Bot, update: Update): else: adm = session.query(Admin).filter_by(user_id=user.id, admin_type=AdminType.FULL.value).first() + if adm is None: send_async(bot, chat_id=update.message.chat.id, text=MSG_DEL_GLOBAL_ADMIN_NOT_EXIST.format(user.username)) + else: session.delete(adm) session.commit() send_async(bot, chat_id=update.message.chat.id, text=MSG_DEL_GLOBAL_ADMIN.format(user.username)) - except Exception: - session.rollback() + else: + user = session.query(User).filter_by(id=msg).first() + if user is None: + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_USER_UNKNOWN) + + else: + adm = session.query(Admin).filter_by(user_id=user.id, + admin_type=AdminType.FULL.value).first() + if adm is None: + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_DEL_GLOBAL_ADMIN_NOT_EXIST.format(user.username)) + else: + session.delete(adm) + session.commit() + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_DEL_GLOBAL_ADMIN.format(user.username)) diff --git a/core/functions/api.py b/core/functions/api.py index 8f60405..f37ffed 100644 --- a/core/functions/api.py +++ b/core/functions/api.py @@ -6,6 +6,8 @@ from core.types import Order, Session, Squad, SquadMember, OrderCleared +from sqlalchemy.exc import SQLAlchemyError + app = flask.Flask(__name__) @@ -35,7 +37,7 @@ def new_ready_to_battle(chat_id): return flask.Response(status=200, mimetype="application/json", response=json.dumps({'order_id': order.id})) - except Exception: + except SQLAlchemyError: Session.rollback() return flask.Response(status=400) @@ -75,7 +77,7 @@ def new_order_click(order_id, user_id): return flask.Response(status=200) - except Exception: + except SQLAlchemyError: Session.rollback() return flask.Response(status=400) @@ -97,6 +99,6 @@ def order_status(order_id): mimetype="application/json", response=json.dumps({'users': users})) - except Exception: + except SQLAlchemyError: Session.rollback() return flask.Response(status=400) diff --git a/core/functions/bosses.py b/core/functions/bosses.py index cb80237..acec968 100644 --- a/core/functions/bosses.py +++ b/core/functions/bosses.py @@ -5,8 +5,8 @@ @trigger_decorator -def boss_leader(bot: Bot, update: Update): - group = update_group(update.message.chat) +def boss_leader(bot: Bot, update: Update, session): + group = update_group(update.message.chat, session) if len(group.squad) == 1: members = [] for member in group.squad[0].members: @@ -18,8 +18,8 @@ def boss_leader(bot: Bot, update: Update): @trigger_decorator -def boss_zhalo(bot: Bot, update: Update): - group = update_group(update.message.chat) +def boss_zhalo(bot: Bot, update: Update, session): + group = update_group(update.message.chat, session) if len(group.squad) == 1: members = [] for member in group.squad[0].members: @@ -31,8 +31,8 @@ def boss_zhalo(bot: Bot, update: Update): @trigger_decorator -def boss_monoeye(bot: Bot, update: Update): - group = update_group(update.message.chat) +def boss_monoeye(bot: Bot, update: Update, session): + group = update_group(update.message.chat, session) if len(group.squad) == 1: members = [] for member in group.squad[0].members: @@ -44,8 +44,8 @@ def boss_monoeye(bot: Bot, update: Update): @trigger_decorator -def boss_hydra(bot: Bot, update: Update): - group = update_group(update.message.chat) +def boss_hydra(bot: Bot, update: Update, session): + group = update_group(update.message.chat, session) if len(group.squad) == 1: members = [] for member in group.squad[0].members: diff --git a/core/functions/common.py b/core/functions/common.py index edb8486..58cef5b 100644 --- a/core/functions/common.py +++ b/core/functions/common.py @@ -2,12 +2,12 @@ from enum import Enum import logging -from telegram import Update, Bot, ParseMode, TelegramError +from telegram import Update, Bot, ParseMode from core.functions.triggers import trigger_decorator from core.functions.reply_markup import generate_admin_markup from core.texts import * -from core.types import AdminType, Admin, Stock, admin, Session, Group +from core.types import AdminType, Admin, Stock, admin_allowed, user_allowed from core.utils import send_async, add_user @@ -25,17 +25,16 @@ def error(bot: Bot, update, error, **kwargs): % (type(error), error.message)) -def start(bot: Bot, update: Update): - add_user(update.message.from_user) +@user_allowed +def start(bot: Bot, update: Update, session): + add_user(update.message.from_user, session) if update.message.chat.type == 'private': send_async(bot, chat_id=update.message.chat.id, text=MSG_START_WELCOME) -@admin(adm_type=AdminType.GROUP) -def admin_panel(bot: Bot, update: Update): +@admin_allowed(adm_type=AdminType.GROUP) +def admin_panel(bot: Bot, update: Update, session): if update.message.chat.type == 'private': - session = Session() - # FIX: переопределение admin admin = session.query(Admin).filter_by(user_id=update.message.from_user.id).all() full_adm = False grp_adm = False @@ -48,26 +47,13 @@ def admin_panel(bot: Bot, update: Update): reply_markup=generate_admin_markup(full_adm, grp_adm)) -def check_bot_in_chats(bot: Bot, update: Update): - session = Session() - groups = session.query(Group).filter_by(bot_in_group=True).all() - for group in groups: - try: - bot.getChatMember(group.id, bot.id) - except TelegramError as e: - group.bot_in_group = False - session.add(group) - session.commit() - - -@admin() -def kick(bot: Bot, update: Update): +@admin_allowed() +def kick(bot: Bot, update: Update, session): bot.leave_chat(update.message.chat.id) @trigger_decorator -def help_msg(bot: Bot, update): - session = Session() +def help_msg(bot: Bot, update, session): admin_user = session.query(Admin).filter_by(user_id=update.message.from_user.id).all() global_adm = False for adm in admin_user: @@ -82,8 +68,8 @@ def help_msg(bot: Bot, update): send_async(bot, chat_id=update.message.chat.id, text=MSG_HELP_USER) -@admin(adm_type=AdminType.GROUP) -def ping(bot: Bot, update: Update): +@admin_allowed(adm_type=AdminType.GROUP) +def ping(bot: Bot, update: Update, session): send_async(bot, chat_id=update.message.chat.id, text=MSG_PING.format(update.message.from_user.username)) @@ -107,8 +93,8 @@ def get_diff(dict_one, dict_two): return resource_diff_add, resource_diff_del -def stock_compare(bot: Bot, update: Update, chat_data: dict): - session = Session() +@user_allowed +def stock_compare(bot: Bot, update: Update, session, chat_data: dict): old_stock = session.query(Stock).filter_by(user_id=update.message.from_user.id, stock_type=StockType.Stock.value).order_by(Stock.date.desc()).first() new_stock = Stock() @@ -149,20 +135,20 @@ def stock_compare(bot: Bot, update: Update, chat_data: dict): send_async(bot, chat_id=update.message.chat.id, text=MSG_STOCK_COMPARE_WAIT) -@admin(adm_type=AdminType.GROUP) -def delete_msg(bot: Bot, update: Update): +@admin_allowed(adm_type=AdminType.GROUP) +def delete_msg(bot: Bot, update: Update, session): bot.delete_message(update.message.reply_to_message.chat_id, update.message.reply_to_message.message_id) bot.delete_message(update.message.reply_to_message.chat_id, update.message.message_id) -@admin() -def delete_user(bot: Bot, update: Update): +@admin_allowed() +def delete_user(bot: Bot, update: Update, session): bot.kickChatMember(update.message.reply_to_message.chat_id, update.message.reply_to_message.from_user.id) bot.unbanChatMember(update.message.reply_to_message.chat_id, update.message.reply_to_message.from_user.id) -def trade_compare(bot: Bot, update: Update, chat_data: dict): - session = Session() +@user_allowed +def trade_compare(bot: Bot, update: Update, session, chat_data: dict): old_stock = session.query(Stock).filter_by(user_id=update.message.from_user.id, stock_type=StockType.TradeBot.value).order_by(Stock.date.desc()).first() new_stock = Stock() diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index f58a10f..cfb6f65 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -12,9 +12,9 @@ from core.functions.admins import del_adm from core.template import fill_char_template from core.types import ( - User, Group, Admin, Session, admin, Order, OrderGroup, - OrderGroupItem, OrderCleared, Squad, - Character, Session, SquadMember, MessageType, AdminType + User, Group, Admin, admin_allowed, Order, OrderGroup, + OrderGroupItem, OrderCleared, Squad, user_allowed, + Character, SquadMember, MessageType, AdminType ) from core.texts import * from core.utils import send_async, update_group, add_user @@ -49,9 +49,8 @@ class QueryType(Enum): TriggerOrderPin = 22 -@admin() -def send_status(bot: Bot, update: Update): - session = Session() +@admin_allowed() +def send_status(bot: Bot, update: Update, session): msg = MSG_GROUP_STATUS_CHOOSE_CHAT squads = session.query(Squad).all() inline_keys = [] @@ -63,16 +62,17 @@ def send_status(bot: Bot, update: Update): send_async(bot, chat_id=update.message.chat.id, text=msg, reply_markup=inline_markup) -def generate_group_info(group_id): - session = Session() +def generate_group_info(group_id, session): group = session.query(Group).filter(Group.id == group_id).first() admins = session.query(Admin).filter(Admin.admin_group == group_id).all() adm_msg = '' adm_del_keys = [] for adm in admins: user = session.query(User).filter_by(id=adm.user_id).first() - adm_msg += MSG_GROUP_STATUS_ADMIN_FORMAT.format(user.id, user.username or '', user.first_name or '', user.last_name or '') - adm_del_keys.append([InlineKeyboardButton(MSG_GROUP_STATUS_DEL_ADMIN.format(user.first_name or '', user.last_name or ''), + adm_msg += MSG_GROUP_STATUS_ADMIN_FORMAT.\ + format(user.id, user.username or '', user.first_name or '', user.last_name or '') + adm_del_keys.append([InlineKeyboardButton(MSG_GROUP_STATUS_DEL_ADMIN. + format(user.first_name or '', user.last_name or ''), callback_data=json.dumps( {'t': QueryType.DelAdm.value, 'uid': user.id, 'gid': group_id}))]) @@ -112,8 +112,7 @@ def generate_flag_orders(): return inline_markup -def generate_order_chats_markup(bot: Bot, pin=True): - session = Session() +def generate_order_chats_markup(session, pin=True): squads = session.query(Squad).all() inline_keys = [] for squad in squads: @@ -125,8 +124,7 @@ def generate_order_chats_markup(bot: Bot, pin=True): return inline_markup -def generate_order_groups_markup(bot: Bot, admin_user: list=None, pin: bool=True): - session = Session() +def generate_order_groups_markup(session, admin_user: list=None, pin: bool=True): if admin_user: group_adm = True for adm in admin_user: @@ -165,8 +163,7 @@ def generate_ok_markup(order_id, count): return inline_markup -def generate_groups_manage(): - session = Session() +def generate_groups_manage(session): groups = session.query(OrderGroup).all() inline_keys = [] for group in groups: @@ -177,8 +174,7 @@ def generate_groups_manage(): return InlineKeyboardMarkup(inline_keys) -def generate_group_manage(group_id): - session = Session() +def generate_group_manage(group_id, session): squads = session.query(Squad).all() inline_keys = [] for squad in squads: @@ -198,9 +194,8 @@ def generate_group_manage(group_id): def generate_profile_buttons(user): - inline_keys = [] - inline_keys.append([InlineKeyboardButton('🏅Герой', callback_data=json.dumps( - {'t': QueryType.ShowHero.value, 'id': user.id}))]) + inline_keys = [[InlineKeyboardButton('🏅Герой', callback_data=json.dumps( + {'t': QueryType.ShowHero.value, 'id': user.id}))]] if user.stock: inline_keys.append([InlineKeyboardButton('📦Склад', callback_data=json.dumps( {'t': QueryType.ShowStock.value, 'id': user.id}))]) @@ -210,13 +205,15 @@ def generate_profile_buttons(user): return InlineKeyboardMarkup(inline_keys) -def generate_squad_list_key(squad): - session = Session() +def generate_squad_list_key(squad, session): attack = 0 defence = 0 members = session.query(SquadMember).filter_by(squad_id=squad.chat_id).all() for member in members: - character = session.query(Character).filter_by(user_id=member.user_id).order_by(Character.date.desc()).limit(1).first() + character = session.query(Character).\ + filter_by(user_id=member.user_id).\ + order_by(Character.date.desc()).\ + limit(1).first() attack += character.attack defence += character.defence return [InlineKeyboardButton( @@ -241,14 +238,13 @@ def generate_squad_list(squads): def generate_leave_squad(user_id): - inline_keys = [] - inline_keys.append([InlineKeyboardButton('Выйти', - callback_data=json.dumps({'t': QueryType.LeaveSquad.value, 'id': user_id}))]) + inline_keys = [[InlineKeyboardButton('Выйти', + callback_data=json.dumps({'t': QueryType.LeaveSquad.value, + 'id': user_id}))]] return InlineKeyboardMarkup(inline_keys) -def generate_squad_request(): - session = Session() +def generate_squad_request(session): inline_keys = [] squads = session.query(Squad).filter_by(hiring=True).all() for squad in squads: @@ -263,30 +259,35 @@ def generate_squad_members(members): for member in members: user = member.user character = user.character - inline_keys.append([InlineKeyboardButton('{}: {}⚔ {}🛡'.format(user, character.attack, character.defence), callback_data=json.dumps( - {'t': QueryType.ShowHero.value, 'id': member.user_id}))]) + inline_keys.append( + [InlineKeyboardButton('{}: {}⚔ {}🛡'. + format(user, + character.attack, + character.defence), + callback_data=json.dumps( + {'t': QueryType.ShowHero.value, + 'id': member.user_id} + ))]) return InlineKeyboardMarkup(inline_keys) def generate_squad_request_answer(user_id): - inline_keys = [] - inline_keys.append(InlineKeyboardButton('✅Принять', - callback_data=json.dumps( - {'t': QueryType.RequestSquadAccept.value, 'id': user_id}))) - inline_keys.append(InlineKeyboardButton('❌Отклонить', - callback_data=json.dumps( - {'t': QueryType.RequestSquadDecline.value, 'id': user_id}))) + inline_keys = [InlineKeyboardButton('✅Принять', + callback_data=json.dumps( + {'t': QueryType.RequestSquadAccept.value, 'id': user_id})), + InlineKeyboardButton('❌Отклонить', + callback_data=json.dumps( + {'t': QueryType.RequestSquadDecline.value, 'id': user_id}))] return InlineKeyboardMarkup([inline_keys]) def generate_squad_invite_answer(user_id): - inline_keys = [] - inline_keys.append(InlineKeyboardButton('✅Зелёное Да', - callback_data=json.dumps( - {'t': QueryType.InviteSquadAccept.value, 'id': user_id}))) - inline_keys.append(InlineKeyboardButton('❌Красное Да', - callback_data=json.dumps( - {'t': QueryType.InviteSquadDecline.value, 'id': user_id}))) + inline_keys = [InlineKeyboardButton('✅Зелёное Да', + callback_data=json.dumps( + {'t': QueryType.InviteSquadAccept.value, 'id': user_id})), + InlineKeyboardButton('❌Красное Да', + callback_data=json.dumps( + {'t': QueryType.InviteSquadDecline.value, 'id': user_id}))] return InlineKeyboardMarkup([inline_keys]) @@ -341,10 +342,10 @@ def send_order(bot, order, order_type, chat_id, markup): @run_async -def callback_query(bot: Bot, update: Update, chat_data: dict): - session = Session() - update_group(update.callback_query.message.chat) - user = add_user(update.callback_query.from_user) +@user_allowed +def callback_query(bot: Bot, update: Update, session, chat_data: dict): + update_group(update.callback_query.message.chat, session) + user = add_user(update.callback_query.from_user, session) data = json.loads(update.callback_query.data) LOGGER.warning(data) if data['t'] == QueryType.GroupList.value: @@ -359,12 +360,12 @@ def callback_query(bot: Bot, update: Update, chat_data: dict): bot.editMessageText(msg, update.callback_query.message.chat.id, update.callback_query.message.message_id, reply_markup=inline_markup) elif data['t'] == QueryType.GroupInfo.value: - msg, inline_markup = generate_group_info(data['id']) + msg, inline_markup = generate_group_info(data['id'], session) bot.editMessageText(msg, update.callback_query.message.chat.id, update.callback_query.message.message_id, reply_markup=inline_markup) elif data['t'] == QueryType.DelAdm.value: - del_adm(bot, data['gid'], user) - msg, inline_markup = generate_group_info(data['gid']) + del_adm(bot, data['gid'], data['uid'], session) + msg, inline_markup = generate_group_info(data['gid'], session) bot.editMessageText(msg, update.callback_query.message.chat.id, update.callback_query.message.message_id, reply_markup=inline_markup) elif data['t'] == QueryType.Order.value: @@ -387,8 +388,8 @@ def callback_query(bot: Bot, update: Update, chat_data: dict): bot.request.post(bot.base_url + '/pinChatMessage', {'chat_id': order.chat_id, 'message_id': msg.message_id, 'disable_notification': False}) - except: - pass + except TelegramError as err: + bot.logger.error(err.message) else: group = session.query(OrderGroup).filter_by(id=data['id']).first() for item in group.items: @@ -410,8 +411,8 @@ def callback_query(bot: Bot, update: Update, chat_data: dict): bot.request.post(bot.base_url + '/pinChatMessage', {'chat_id': order.chat_id, 'message_id': msg.message_id, 'disable_notification': False}) - except: - pass + except TelegramError as err: + bot.logger.error(err.message) update.callback_query.answer(text=MSG_ORDER_SENT) elif data['t'] == QueryType.OrderOk.value: order = session.query(Order).filter_by(id=data['id']).first() @@ -462,7 +463,7 @@ def callback_query(bot: Bot, update: Update, chat_data: dict): chat_data['order'] = Castle.SEA.value else: chat_data['order'] = data['txt'] - markup = generate_order_chats_markup(bot, chat_data['pin'] if 'pin' in chat_data else True) + markup = generate_order_chats_markup(session, chat_data['pin'] if 'pin' in chat_data else True) bot.editMessageText(MSG_ORDER_SEND_HEADER.format(chat_data['order']), update.callback_query.message.chat.id, update.callback_query.message.message_id, @@ -479,14 +480,14 @@ def callback_query(bot: Bot, update: Update, chat_data: dict): else: chat_data['order'] = data['txt'] admin_user = session.query(Admin).filter(Admin.user_id == update.callback_query.from_user.id).all() - markup = generate_order_groups_markup(bot, admin_user, chat_data['pin'] if 'pin' in chat_data else True) + markup = generate_order_groups_markup(session, admin_user, chat_data['pin'] if 'pin' in chat_data else True) bot.editMessageText(MSG_ORDER_SEND_HEADER.format(chat_data['order']), update.callback_query.message.chat.id, update.callback_query.message.message_id, reply_markup=markup) elif data['t'] == QueryType.OrderGroupManage.value: group = session.query(OrderGroup).filter_by(id=data['id']).first() - markup = generate_group_manage(data['id']) + markup = generate_group_manage(data['id'], session) bot.editMessageText(MSG_ORDER_GROUP_CONFIG_HEADER.format(group.name), update.callback_query.message.chat.id, update.callback_query.message.message_id, @@ -505,7 +506,7 @@ def callback_query(bot: Bot, update: Update, chat_data: dict): item.chat_id = data['c'] session.add(item) session.commit() - markup = generate_group_manage(data['id']) + markup = generate_group_manage(data['id'], session) bot.editMessageText(MSG_ORDER_GROUP_CONFIG_HEADER.format(group.name), update.callback_query.message.chat.id, update.callback_query.message.message_id, @@ -521,12 +522,12 @@ def callback_query(bot: Bot, update: Update, chat_data: dict): bot.editMessageText(MSG_ORDER_GROUP_LIST, update.callback_query.message.chat.id, update.callback_query.message.message_id, - reply_markup=generate_groups_manage()) + reply_markup=generate_groups_manage(session)) elif data['t'] == QueryType.OrderGroupList.value: bot.editMessageText(MSG_ORDER_GROUP_LIST, update.callback_query.message.chat.id, update.callback_query.message.message_id, - reply_markup=generate_groups_manage()) + reply_markup=generate_groups_manage(session)) elif data['t'] == QueryType.ShowEquip.value: user = session.query(User).filter_by(id=data['id']).first() update.callback_query.answer(text=MSG_CLEARED) @@ -537,7 +538,8 @@ def callback_query(bot: Bot, update: Update, chat_data: dict): elif data['t'] == QueryType.ShowStock.value: user = session.query(User).filter_by(id=data['id']).first() update.callback_query.answer(text=MSG_CLEARED) - bot.editMessageText('{}\n🕑 Последнее обновление {}'.format(user.stock.stock, user.stock.date.strftime("%Y-%m-%d %H:%M:%S")), + bot.editMessageText('{}\n🕑 Последнее обновление {}'. + format(user.stock.stock, user.stock.date.strftime("%Y-%m-%d %H:%M:%S")), update.callback_query.message.chat.id, update.callback_query.message.message_id, reply_markup=generate_profile_buttons(user)) @@ -658,13 +660,13 @@ def callback_query(bot: Bot, update: Update, chat_data: dict): chat_data['pin'] = False if data['g']: admin_user = session.query(Admin).filter(Admin.user_id == update.callback_query.from_user.id).all() - markup = generate_order_groups_markup(bot, admin_user, chat_data['pin'] if 'pin' in chat_data else True) + markup = generate_order_groups_markup(session, admin_user, chat_data['pin'] if 'pin' in chat_data else True) bot.editMessageText(MSG_ORDER_SEND_HEADER.format(chat_data['order']), update.callback_query.message.chat.id, update.callback_query.message.message_id, reply_markup=markup) else: - markup = generate_order_chats_markup(bot, chat_data['pin'] if 'pin' in chat_data else True) + markup = generate_order_chats_markup(session, chat_data['pin'] if 'pin' in chat_data else True) bot.editMessageText(MSG_ORDER_SEND_HEADER.format(chat_data['order']), update.callback_query.message.chat.id, update.callback_query.message.message_id, diff --git a/core/functions/newbies.py b/core/functions/newbies.py index 1715739..08104f1 100644 --- a/core/functions/newbies.py +++ b/core/functions/newbies.py @@ -1,14 +1,14 @@ from telegram import Update, Bot -from core.types import User, Group, Session +from core.types import User, Group, user_allowed from core.template import fill_template from core.utils import send_async from core.texts import * -def newbie(bot: Bot, update: Update): +@user_allowed +def newbie(bot: Bot, update: Update, session): if update.message.chat.id in [-1001045426965]: if update.message.new_chat_member is not None: - session = Session() user = session.query(User).filter(User.id == update.message.new_chat_member.id).first() if user is None: group = session.query(Group).filter(Group.id == -1001146975451).first() diff --git a/core/functions/order_groups.py b/core/functions/order_groups.py index 35ff068..9fd6956 100644 --- a/core/functions/order_groups.py +++ b/core/functions/order_groups.py @@ -1,22 +1,23 @@ from telegram import Update, Bot -from core.types import Session, OrderGroup +from core.types import OrderGroup, admin_allowed, AdminType from core.utils import send_async from core.functions.inline_keyboard_handling import generate_groups_manage, generate_group_manage from core.texts import * -def group_list(bot: Bot, update: Update): - markup = generate_groups_manage() +@admin_allowed(AdminType.FULL) +def group_list(bot: Bot, update: Update, session): + markup = generate_groups_manage(session) send_async(bot, chat_id=update.message.chat.id, text=MSG_ORDER_GROUP_LIST, reply_markup=markup) -def add_group(bot: Bot, update: Update, chat_data): - session = Session() +@admin_allowed(AdminType.FULL) +def add_group(bot: Bot, update: Update, chat_data, session): chat_data['wait_group_name'] = False group = OrderGroup() group.name = update.message.text session.add(group) session.commit() - markup = generate_group_manage(group.id) + markup = generate_group_manage(group.id, session) send_async(bot, chat_id=update.message.chat.id, text=MSG_ORDER_GROUP_CONFIG_HEADER.format(group.name), reply_markup=markup) diff --git a/core/functions/orders.py b/core/functions/orders.py index 4ebcab1..c78130c 100644 --- a/core/functions/orders.py +++ b/core/functions/orders.py @@ -1,13 +1,12 @@ from telegram import Update, Bot -from core.types import AdminType, Admin, admin, Session, MessageType +from core.types import AdminType, Admin, admin_allowed, MessageType from core.utils import send_async from core.functions.inline_keyboard_handling import generate_order_groups_markup, generate_flag_orders from core.texts import * -@admin(adm_type=AdminType.GROUP) -def order(bot: Bot, update: Update, chat_data): - session = Session() +@admin_allowed(adm_type=AdminType.GROUP) +def order(bot: Bot, update: Update, chat_data, session): admin_user = session.query(Admin).filter(Admin.user_id == update.message.from_user.id).all() markup = generate_order_groups_markup(bot, admin_user, chat_data['pin'] if 'pin' in chat_data else True) msg = update.message @@ -45,7 +44,7 @@ def order(bot: Bot, update: Update, chat_data): reply_markup=markup) -@admin(adm_type=AdminType.GROUP) -def orders(bot: Bot, update: Update, chat_data): +@admin_allowed(adm_type=AdminType.GROUP) +def orders(bot: Bot, update: Update, session, chat_data): markup = generate_flag_orders() send_async(bot, chat_id=update.message.chat.id, text=MSG_FLAG_CHOOSE_HEADER, reply_markup=markup) diff --git a/core/functions/pin.py b/core/functions/pin.py index 82d7575..ade330c 100644 --- a/core/functions/pin.py +++ b/core/functions/pin.py @@ -1,24 +1,26 @@ -from telegram import Bot, Update, Message +from telegram import Bot, Update from core.texts import MSG_PIN_ALL_ENABLED, MSG_PIN_ALL_DISABLED -from core.types import AdminType, admin, Session +from core.types import AdminType, admin_allowed, user_allowed, check_admin from core.utils import update_group, send_async def pin_decorator(func): - def wrapper(bot, update, *args, **kwargs): - group = update_group(update.message.chat) - if group is None: - ((admin(adm_type=AdminType.FULL))(func))(bot, update, *args, **kwargs) - elif group.allow_pin_all: - func(bot, update, *args, **kwargs) - else: - ((admin(adm_type=AdminType.GROUP))(func))(bot, update, *args, **kwargs) + @user_allowed + def wrapper(bot, update, session, *args, **kwargs): + group = update_group(update.message.chat, session) + if group is None and \ + check_admin(update, session, AdminType.FULL) or \ + group is not None and \ + (group.allow_pin_all or + check_admin(update, session, AdminType.GROUP)): + func(bot, update, session, *args, **kwargs) + return wrapper @pin_decorator -def pin(bot: Bot, update: Update): +def pin(bot: Bot, update: Update, session): bot.request.post(bot.base_url + '/pinChatMessage', {'chat_id': update.message.reply_to_message.chat.id, 'message_id': update.message.reply_to_message.message_id, @@ -26,17 +28,16 @@ def pin(bot: Bot, update: Update): @pin_decorator -def silent_pin(bot: Bot, update: Update): +def silent_pin(bot: Bot, update: Update, session): bot.request.post(bot.base_url + '/pinChatMessage', {'chat_id': update.message.reply_to_message.chat.id, 'message_id': update.message.reply_to_message.message_id, 'disable_notification': True}) -@admin(AdminType.GROUP) -def pin_all(bot: Bot, update: Update): - group = update_group(update.message.chat) - session = Session() +@admin_allowed(AdminType.GROUP) +def pin_all(bot: Bot, update: Update, session): + group = update_group(update.message.chat, session) if not group.allow_pin_all: group.allow_pin_all = True session.add(group) @@ -44,10 +45,9 @@ def pin_all(bot: Bot, update: Update): send_async(bot, chat_id=update.message.chat.id, text=MSG_PIN_ALL_ENABLED) -@admin(AdminType.GROUP) -def not_pin_all(bot: Bot, update: Update): - group = update_group(update.message.chat) - session = Session() +@admin_allowed(AdminType.GROUP) +def not_pin_all(bot: Bot, update: Update, session): + group = update_group(update.message.chat, session) if group.allow_pin_all: group.allow_pin_all = False session.add(group) diff --git a/core/functions/profile.py b/core/functions/profile.py index e38d78e..f9c601d 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -1,19 +1,17 @@ from telegram import Update, Bot from core.functions.inline_keyboard_handling import generate_profile_buttons -from core.regexp import hero, profile -from core.types import Character, User, admin, Session, Equip +from core.regexp import HERO, PROFILE +from core.types import Character, User, admin_allowed, Equip, user_allowed from core.utils import send_async from datetime import timedelta import re -from core import regexp from core.template import fill_char_template from core.texts import * -def parse_profile(profile, user_id, date): - session = Session() - parsed_data = re.search(regexp.profile, profile) +def parse_profile(profile, user_id, date, session): + parsed_data = re.search(PROFILE, profile) char = session.query(Character).filter_by(user_id=user_id, date=date).first() if char is None: char = Character() @@ -38,9 +36,8 @@ def parse_profile(profile, user_id, date): return char -def parse_hero(profile, user_id, date): - session = Session() - parsed_data = re.search(regexp.hero, profile) +def parse_hero(profile, user_id, date, session): + parsed_data = re.search(HERO, profile) char = session.query(Character).filter_by(user_id=user_id, date=date).first() if char is None: char = Character() @@ -71,37 +68,42 @@ def parse_hero(profile, user_id, date): return char -def char_update(bot: Bot, update: Update): +@user_allowed +def char_update(bot: Bot, update: Update, session): if update.message.date - update.message.forward_date > timedelta(minutes=1): send_async(bot, chat_id=update.message.chat.id, text=MSG_PROFILE_OLD) else: char = None - if re.search(hero, update.message.text): - char = parse_hero(update.message.text, update.message.from_user.id, update.message.forward_date) - elif re.search(profile, update.message.text): - char = parse_profile(update.message.text, update.message.from_user.id, update.message.forward_date) + if re.search(HERO, update.message.text): + char = parse_hero(update.message.text, + update.message.from_user.id, + update.message.forward_date, + session) + elif re.search(PROFILE, update.message.text): + char = parse_profile(update.message.text, + update.message.from_user.id, + update.message.forward_date, + session) send_async(bot, chat_id=update.message.chat.id, text=MSG_PROFILE_SAVED.format(char.name)) -def char_show(bot: Bot, update: Update): +@user_allowed +def char_show(bot: Bot, update: Update, session): if update.message.chat.type == 'private': - session = Session() user = session.query(User).filter_by(id=update.message.from_user.id).first() if user is not None and user.character is not None: - char =user.character + char = user.character text = fill_char_template(MSG_PROFILE_SHOW_FORMAT, user, char) btns = generate_profile_buttons(user) send_async(bot, chat_id=update.message.chat.id, text=text, reply_markup=btns) -#@data_update -@admin() -def find_by_username(bot: Bot, update: Update): +@admin_allowed() +def find_by_username(bot: Bot, update: Update, session): if update.message.chat.type == 'private': msg = update.message.text.split(' ', 1)[1] msg = msg.replace('@', '') if msg != '': - session = Session() user = session.query(User).filter_by(username=msg).first() if user is not None and user.character: char = user.character diff --git a/core/functions/reply_markup.py b/core/functions/reply_markup.py index 9f35991..df5b2fd 100644 --- a/core/functions/reply_markup.py +++ b/core/functions/reply_markup.py @@ -2,8 +2,7 @@ def generate_admin_markup(full=False, grp=False): - buttons = [] - buttons.append([KeyboardButton('Приказы')]) + buttons = [[KeyboardButton('Приказы')]] if full: buttons.append([KeyboardButton('Статус'), KeyboardButton('Группы')]) if grp: diff --git a/core/functions/squad.py b/core/functions/squad.py index 48cdde2..343a996 100644 --- a/core/functions/squad.py +++ b/core/functions/squad.py @@ -1,8 +1,7 @@ -from sqlalchemy.orm import scoped_session from telegram import Update, Bot from core.template import fill_char_template -from core.types import User, AdminType, Admin, admin, Group, Squad, Session, SquadMember +from core.types import User, AdminType, Admin, admin_allowed, Group, Squad, SquadMember, user_allowed from core.utils import send_async from core.functions.inline_keyboard_handling import generate_squad_list, \ generate_leave_squad, generate_squad_request, generate_squad_request_answer, generate_fire_up, \ @@ -10,10 +9,9 @@ from core.texts import * -@admin() -def add_squad(bot: Bot, update: Update): +@admin_allowed() +def add_squad(bot: Bot, update: Update, session): if update.message.chat.type == 'supergroup': - session = Session() squad = session.query(Squad).filter_by(chat_id=update.message.chat.id).first() if squad is None: squad = Squad() @@ -30,9 +28,8 @@ def add_squad(bot: Bot, update: Update): send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_NEW.format(squad.squad_name)) -@admin() -def set_invite_link(bot: Bot, update: Update): - session = Session() +@admin_allowed() +def set_invite_link(bot: Bot, update: Update, session): squad = session.query(Squad).filter_by(chat_id=update.message.chat.id).first() if update.message.chat.type == 'supergroup' and squad is not None: msg = update.message.text.split(' ', 1) @@ -43,9 +40,8 @@ def set_invite_link(bot: Bot, update: Update): send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_LINK_SAVED) -@admin() -def set_squad_name(bot: Bot, update: Update): - session = Session() +@admin_allowed() +def set_squad_name(bot: Bot, update: Update, session): squad = session.query(Squad).filter_by(chat_id=update.message.chat.id).first() if update.message.chat.type == 'supergroup' and squad is not None: msg = update.message.text.split(' ', 1) @@ -56,9 +52,8 @@ def set_squad_name(bot: Bot, update: Update): send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_RENAMED.format(squad.squad_name)) -@admin() -def del_squad(bot: Bot, update: Update): - session = Session() +@admin_allowed() +def del_squad(bot: Bot, update: Update, session): squad = session.query(Squad).filter_by(chat_id=update.message.chat.id).first() if update.message.chat.type == 'supergroup' and squad is not None: for member in squad.members: @@ -68,9 +63,8 @@ def del_squad(bot: Bot, update: Update): send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_DELETE) -@admin(AdminType.GROUP) -def enable_thorns(bot: Bot, update: Update): - session = Session() +@admin_allowed(AdminType.GROUP) +def enable_thorns(bot: Bot, update: Update, session): group = session.query(Group).filter_by(id=update.message.chat.id).first() if update.message.chat.type == 'supergroup' and group is not None and len(group.squad) == 1: group.squad[0].thorns_enabled = True @@ -79,9 +73,8 @@ def enable_thorns(bot: Bot, update: Update): send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_THORNS_ENABLED) -@admin(AdminType.GROUP) -def disable_thorns(bot: Bot, update: Update): - session = Session() +@admin_allowed(AdminType.GROUP) +def disable_thorns(bot: Bot, update: Update, session): group = session.query(Group).filter_by(id=update.message.chat.id).first() if update.message.chat.type == 'supergroup' and group is not None and len(group.squad) == 1: group.squad[0].thorns_enabled = False @@ -90,9 +83,8 @@ def disable_thorns(bot: Bot, update: Update): send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_THORNS_DISABLED) -@admin(AdminType.GROUP) -def squad_list(bot: Bot, update: Update): - session = scoped_session(Session)() +@admin_allowed(AdminType.GROUP) +def squad_list(bot: Bot, update: Update, session): admin = session.query(Admin).filter_by(user_id=update.message.from_user.id).all() global_adm = False for adm in admin: @@ -111,8 +103,8 @@ def squad_list(bot: Bot, update: Update): send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_LIST, reply_markup=markup) -def squad_request(bot: Bot, update: Update): - session = Session() +@user_allowed +def squad_request(bot: Bot, update: Update, session): user = session.query(User).filter_by(id=update.message.from_user.id).first() if user is not None: if user.character: @@ -120,15 +112,14 @@ def squad_request(bot: Bot, update: Update): markup = generate_leave_squad(user.id) send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_REQUEST_EXISTS, reply_markup=markup) else: - markup = generate_squad_request() + markup = generate_squad_request(session) send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_REQUEST, reply_markup=markup) else: send_async(bot, chat_id=update.message.chat.id, text='Сначала дай мне профиль!') -@admin(AdminType.GROUP) -def list_squad_requests(bot: Bot, update: Update): - session = Session() +@admin_allowed(AdminType.GROUP) +def list_squad_requests(bot: Bot, update: Update, session): admin = session.query(Admin).filter_by(user_id=update.message.from_user.id).all() group_admin = [] for adm in admin: @@ -148,9 +139,8 @@ def list_squad_requests(bot: Bot, update: Update): text=MSG_SQUAD_REQUEST_EMPTY) -@admin(AdminType.GROUP) -def open_hiring(bot: Bot, update: Update): - session = Session() +@admin_allowed(AdminType.GROUP) +def open_hiring(bot: Bot, update: Update, session): squad = session.query(Squad).filter_by(chat_id=update.message.chat.id).first() if squad is not None: squad.hiring = True @@ -159,9 +149,8 @@ def open_hiring(bot: Bot, update: Update): send_async(bot, chat_id=update.message.chat.id, text='Набор открыт') -@admin(AdminType.GROUP) -def close_hiring(bot: Bot, update: Update): - session = Session() +@admin_allowed(AdminType.GROUP) +def close_hiring(bot: Bot, update: Update, session): squad = session.query(Squad).filter_by(chat_id=update.message.chat.id).first() if squad is not None: squad.hiring = False @@ -170,9 +159,8 @@ def close_hiring(bot: Bot, update: Update): send_async(bot, chat_id=update.message.chat.id, text='Набор закрыт') -@admin(AdminType.GROUP) -def remove_from_squad(bot: Bot, update: Update): - session = Session() +@admin_allowed(AdminType.GROUP) +def remove_from_squad(bot: Bot, update: Update, session): admin = session.query(Admin).filter_by(user_id=update.message.from_user.id).all() group_admin = [] for adm in admin: @@ -188,9 +176,8 @@ def remove_from_squad(bot: Bot, update: Update): reply_markup=markup) -@admin(AdminType.GROUP) -def add_to_squad(bot: Bot, update: Update): - session = Session() +@admin_allowed(AdminType.GROUP) +def add_to_squad(bot: Bot, update: Update, session): squad = session.query(Squad).filter_by(chat_id=update.message.chat.id).first() if squad is not None: username = update.message.text.split(' ', 1) diff --git a/core/functions/triggers.py b/core/functions/triggers.py index b622ba1..60f8e95 100644 --- a/core/functions/triggers.py +++ b/core/functions/triggers.py @@ -1,24 +1,24 @@ from telegram import Update, Bot, Message, ParseMode -from core.types import Trigger, AdminType, admin, Session, MessageType, LocalTrigger +from core.types import Trigger, AdminType, admin_allowed, MessageType, LocalTrigger, user_allowed, check_admin from core.utils import send_async, update_group from core.texts import * from json import loads def trigger_decorator(func): - def wrapper(bot, update, *args, **kwargs): - group = update_group(update.message.chat) - if group is None: - ((admin(adm_type=AdminType.FULL))(func))(bot, update, *args, **kwargs) - elif group.allow_trigger_all: - func(bot, update, *args, **kwargs) - else: - ((admin(adm_type=AdminType.GROUP))(func))(bot, update, *args, **kwargs) + @user_allowed + def wrapper(bot, update, session, *args, **kwargs): + group = update_group(update.message.chat, session) + if group is None and \ + check_admin(update, session, AdminType.FULL) or \ + group is not None and \ + (group.allow_trigger_all or + check_admin(update, session, AdminType.GROUP)): + func(bot, update, session, *args, **kwargs) return wrapper -def add_global_trigger_db(msg: Message, trigger_text: str): - session = Session() +def add_global_trigger_db(msg: Message, trigger_text: str, session): trigger = session.query(Trigger).filter_by(trigger=trigger_text).first() if trigger is None: trigger = Trigger() @@ -57,28 +57,27 @@ def add_global_trigger_db(msg: Message, trigger_text: str): session.commit() -@admin() -def set_global_trigger(bot: Bot, update: Update): +@admin_allowed() +def set_global_trigger(bot: Bot, update: Update, session): msg = update.message.text.split(' ', 1) if len(msg) == 2 and len(msg[1]) > 0 and update.message.reply_to_message: trigger = msg[1].strip() data = update.message.reply_to_message - add_global_trigger_db(data, trigger) + add_global_trigger_db(data, trigger, session) send_async(bot, chat_id=update.message.chat.id, text=MSG_TRIGGER_NEW.format(trigger)) else: send_async(bot, chat_id=update.message.chat.id, text=MSG_TRIGGER_NEW_ERROR) -@admin() -def add_global_trigger(bot: Bot, update: Update): +@admin_allowed() +def add_global_trigger(bot: Bot, update: Update, session): msg = update.message.text.split(' ', 1) if len(msg) == 2 and len(msg[1]) > 0 and update.message.reply_to_message: trigger_text = msg[1].strip() - session = Session() trigger = session.query(Trigger).filter_by(trigger=trigger_text).first() if trigger is None: data = update.message.reply_to_message - add_global_trigger_db(data, trigger_text) + add_global_trigger_db(data, trigger_text, session) send_async(bot, chat_id=update.message.chat.id, text=MSG_TRIGGER_NEW.format(trigger_text)) else: send_async(bot, chat_id=update.message.chat.id, text=MSG_TRIGGER_EXISTS.format(trigger_text)) @@ -87,8 +86,7 @@ def add_global_trigger(bot: Bot, update: Update): @trigger_decorator -def trigger_show(bot: Bot, update: Update): - session = Session() +def trigger_show(bot: Bot, update: Update, session): trigger = session.query(LocalTrigger).filter_by(chat_id=update.message.chat.id, trigger=update.message.text).first() if trigger is None: trigger = session.query(Trigger).filter_by(trigger=update.message.text).first() @@ -110,7 +108,10 @@ def trigger_show(bot: Bot, update: Update): contact['first_name'] = None if 'last_name' not in contact.keys(): contact['last_name'] = None - bot.send_contact(update.message.chat.id, contact['phone_number'], contact['first_name'], contact['last_name']) + bot.send_contact(update.message.chat.id, + contact['phone_number'], + contact['first_name'], + contact['last_name']) elif trigger.message_type == MessageType.VIDEO.value: bot.send_video(update.message.chat.id, trigger.message) elif trigger.message_type == MessageType.VIDEO_NOTE.value: @@ -125,30 +126,27 @@ def trigger_show(bot: Bot, update: Update): send_async(bot, chat_id=update.message.chat.id, text=trigger.message, disable_web_page_preview=True) -@admin(adm_type=AdminType.GROUP) -def enable_global_trigger_all(bot: Bot, update: Update): - session = Session() - group = update_group(update.message.chat) +@admin_allowed(adm_type=AdminType.GROUP) +def enable_global_trigger_all(bot: Bot, update: Update, session): + group = update_group(update.message.chat, session) group.allow_trigger_all = True session.add(group) session.commit() send_async(bot, chat_id=update.message.chat.id, text=MSG_TRIGGER_ALL_ENABLED) -@admin(adm_type=AdminType.GROUP) -def disable_global_trigger_all(bot: Bot, update: Update): - session = Session() - group = update_group(update.message.chat) +@admin_allowed(adm_type=AdminType.GROUP) +def disable_global_trigger_all(bot: Bot, update: Update, session): + group = update_group(update.message.chat, session) group.allow_trigger_all = False session.add(group) session.commit() send_async(bot, chat_id=update.message.chat.id, text=MSG_TRIGGER_ALL_DISABLED) -@admin() -def del_global_trigger(bot: Bot, update: Update): +@admin_allowed() +def del_global_trigger(bot: Bot, update: Update, session): msg = update.message.text.split(' ', 1)[1] - session = Session() trigger = session.query(Trigger).filter_by(trigger=msg).first() if trigger is not None: session.delete(trigger) @@ -159,8 +157,7 @@ def del_global_trigger(bot: Bot, update: Update): @trigger_decorator -def list_triggers(bot: Bot, update: Update): - session = Session() +def list_triggers(bot: Bot, update: Update, session): triggers = session.query(Trigger).all() local_triggers = session.query(LocalTrigger).filter_by(chat_id=update.message.chat.id).all() msg = MSG_TRIGGER_LIST_HEADER + \ @@ -169,8 +166,7 @@ def list_triggers(bot: Bot, update: Update): send_async(bot, chat_id=update.message.chat.id, text=msg, parse_mode=ParseMode.HTML) -def add_trigger_db(msg: Message, chat, trigger_text: str): - session = Session() +def add_trigger_db(msg: Message, chat, trigger_text: str, session): trigger = session.query(LocalTrigger).filter_by(chat_id=chat.id, trigger=trigger_text).first() if trigger is None: trigger = LocalTrigger() @@ -210,28 +206,27 @@ def add_trigger_db(msg: Message, chat, trigger_text: str): session.commit() -@admin(adm_type=AdminType.GROUP) -def set_trigger(bot: Bot, update: Update): +@admin_allowed(adm_type=AdminType.GROUP) +def set_trigger(bot: Bot, update: Update, session): msg = update.message.text.split(' ', 1) if len(msg) == 2 and len(msg[1]) > 0 and update.message.reply_to_message: trigger = msg[1].strip() data = update.message.reply_to_message - add_trigger_db(data, update.message.chat, trigger) + add_trigger_db(data, update.message.chat, trigger, session) send_async(bot, chat_id=update.message.chat.id, text=MSG_TRIGGER_NEW.format(trigger)) else: send_async(bot, chat_id=update.message.chat.id, text=MSG_TRIGGER_NEW_ERROR) -@admin(adm_type=AdminType.GROUP) -def add_trigger(bot: Bot, update: Update): +@admin_allowed(adm_type=AdminType.GROUP) +def add_trigger(bot: Bot, update: Update, session): msg = update.message.text.split(' ', 1) if len(msg) == 2 and len(msg[1]) > 0 and update.message.reply_to_message: trigger_text = msg[1].strip() - session = Session() trigger = session.query(LocalTrigger).filter_by(chat_id=update.message.chat.id, trigger=trigger_text).first() if trigger is None: data = update.message.reply_to_message - add_trigger_db(data, update.message.chat, trigger_text) + add_trigger_db(data, update.message.chat, trigger_text, session) send_async(bot, chat_id=update.message.chat.id, text=MSG_TRIGGER_NEW.format(trigger_text)) else: send_async(bot, chat_id=update.message.chat.id, text=MSG_TRIGGER_EXISTS.format(trigger_text)) @@ -239,30 +234,27 @@ def add_trigger(bot: Bot, update: Update): send_async(bot, chat_id=update.message.chat.id, text=MSG_TRIGGER_NEW_ERROR) -@admin(adm_type=AdminType.GROUP) -def enable_trigger_all(bot: Bot, update: Update): - session = Session() - group = update_group(update.message.chat) +@admin_allowed(adm_type=AdminType.GROUP) +def enable_trigger_all(bot: Bot, update: Update, session): + group = update_group(update.message.chat, session) group.allow_trigger_all = True session.add(group) session.commit() send_async(bot, chat_id=update.message.chat.id, text=MSG_TRIGGER_ALL_ENABLED) -@admin(adm_type=AdminType.GROUP) -def disable_trigger_all(bot: Bot, update: Update): - session = Session() - group = update_group(update.message.chat) +@admin_allowed(adm_type=AdminType.GROUP) +def disable_trigger_all(bot: Bot, update: Update, session): + group = update_group(update.message.chat, session) group.allow_trigger_all = False session.add(group) session.commit() send_async(bot, chat_id=update.message.chat.id, text=MSG_TRIGGER_ALL_DISABLED) -@admin(adm_type=AdminType.GROUP) -def del_trigger(bot: Bot, update: Update): +@admin_allowed(adm_type=AdminType.GROUP) +def del_trigger(bot: Bot, update: Update, session): msg = update.message.text.split(' ', 1)[1] - session = Session() trigger = session.query(LocalTrigger).filter_by(trigger=msg).first() if trigger is not None: session.delete(trigger) diff --git a/core/functions/welcome.py b/core/functions/welcome.py index 5c60ff1..fce1ae7 100644 --- a/core/functions/welcome.py +++ b/core/functions/welcome.py @@ -1,5 +1,5 @@ from telegram import Update, Bot -from core.types import Wellcomed, WelcomeMsg, AdminType, admin, Session, Admin +from core.types import Wellcomed, WelcomeMsg, AdminType, admin_allowed, Admin, user_allowed from core.template import fill_template from time import time from core.utils import send_async, add_user, update_group @@ -9,14 +9,14 @@ last_welcome = 0 -def welcome(bot: Bot, update: Update): +@user_allowed +def welcome(bot: Bot, update: Update, session): newbie(bot, update) global last_welcome if update.message.chat.type in ['group', 'supergroup']: - group = update_group(update.message.chat) + group = update_group(update.message.chat, session) for new_chat_member in update.message.new_chat_members: - session = Session() - user = add_user(new_chat_member) + user = add_user(new_chat_member, session) administrator = session.query(Admin).filter_by(user_id=user.id).all() allow_anywhere = False for adm in administrator: @@ -48,11 +48,10 @@ def welcome(bot: Bot, update: Update): session.commit() -@admin(adm_type=AdminType.GROUP) -def set_welcome(bot: Bot, update: Update): +@admin_allowed(adm_type=AdminType.GROUP) +def set_welcome(bot: Bot, update: Update, session): if update.message.chat.type in ['group', 'supergroup']: - group = update_group(update.message.chat) - session = Session() + group = update_group(update.message.chat, session) welcome_msg = session.query(WelcomeMsg).filter_by(chat_id=group.id).first() if welcome_msg is None: welcome_msg = WelcomeMsg(chat_id=group.id, message=update.message.text.split(' ', 1)[1]) @@ -63,33 +62,30 @@ def set_welcome(bot: Bot, update: Update): send_async(bot, chat_id=update.message.chat.id, text=MSG_WELCOME_SET) -@admin(adm_type=AdminType.GROUP) -def enable_welcome(bot: Bot, update: Update): +@admin_allowed(adm_type=AdminType.GROUP) +def enable_welcome(bot: Bot, update: Update, session): if update.message.chat.type in ['group', 'supergroup']: - session = Session() - group = update_group(update.message.chat) + group = update_group(update.message.chat, session) group.welcome_enabled = True session.add(group) session.commit() send_async(bot, chat_id=update.message.chat.id, text=MSG_WELCOME_ENABLED) -@admin(adm_type=AdminType.GROUP) -def disable_welcome(bot: Bot, update: Update): +@admin_allowed(adm_type=AdminType.GROUP) +def disable_welcome(bot: Bot, update: Update, session): if update.message.chat.type in ['group', 'supergroup']: - session = Session() - group = update_group(update.message.chat) + group = update_group(update.message.chat, session) group.welcome_enabled = False session.add(group) session.commit() send_async(bot, chat_id=update.message.chat.id, text=MSG_WELCOME_DISABLED) -@admin(adm_type=AdminType.GROUP) -def show_welcome(bot: Bot, update): +@admin_allowed(adm_type=AdminType.GROUP) +def show_welcome(bot: Bot, update, session): if update.message.chat.type in ['group', 'supergroup']: - session = Session() - group = update_group(update.message.chat) + group = update_group(update.message.chat, session) welcome_msg = session.query(WelcomeMsg).filter_by(chat_id=group.id).first() if welcome_msg is None: welcome_msg = WelcomeMsg(chat_id=group.id, message=MSG_WELCOME_DEFAULT) diff --git a/core/types.py b/core/types.py index 586d93c..d8c76d7 100644 --- a/core/types.py +++ b/core/types.py @@ -264,28 +264,33 @@ class LocalTrigger(Base): message_type = Column(Integer, default=0) -def admin(adm_type=AdminType.FULL): +def check_admin(update, session, adm_type): + allowed = False + if adm_type == AdminType.NOT_ADMIN: + allowed = True + else: + admins = session.query(Admin).filter_by(user_id=update.message.from_user.id).all() + for adm in admins: + if adm is not None and adm.admin_type <= adm_type.value and \ + (adm.admin_group in [0, update.message.chat.id] or + update.message.chat.id == update.message.from_user.id): + if adm.admin_group != 0: + group = session.query(Group).filter_by(id=adm.admin_group).first() + if group and group.bot_in_group: + allowed = True + break + else: + allowed = True + break + return allowed + + +def admin_allowed(adm_type=AdminType.FULL): def decorate(func): def wrapper(bot: Bot, update, *args, **kwargs): session = Session() try: - allowed = False - if adm_type == AdminType.NOT_ADMIN: - allowed = True - else: - admins = session.query(Admin).filter_by(user_id=update.message.from_user.id).all() - for adm in admins: - if adm is not None and adm.admin_type <= adm_type.value and \ - (adm.admin_group in [0, update.message.chat.id] or - update.message.chat.id == update.message.from_user.id): - if adm.admin_group != 0: - group = session.query(Group).filter_by(id=adm.admin_group).first() - if group and group.bot_in_group: - allowed = True - break - else: - allowed = True - break + allowed = check_admin(update, session, adm_type) if allowed: func(bot, update, session, *args, **kwargs) except SQLAlchemyError as err: @@ -295,8 +300,8 @@ def wrapper(bot: Bot, update, *args, **kwargs): return decorate -def user(func): - admin(AdminType.NOT_ADMIN)(func) +def user_allowed(func): + admin_allowed(AdminType.NOT_ADMIN)(func) Base.metadata.create_all(ENGINE) diff --git a/main.py b/main.py index 700c65a..7280b33 100644 --- a/main.py +++ b/main.py @@ -31,7 +31,7 @@ from core.functions.common import ( help_msg, ping, start, error, kick, admin_panel, stock_compare, trade_compare, - check_bot_in_chats, delete_msg, delete_user + delete_msg, delete_user ) from core.functions.inline_keyboard_handling import ( callback_query, send_status, send_order, QueryType @@ -57,7 +57,7 @@ from core.texts import ( MSG_SQUAD_READY, MSG_FULL_TEXT_LINE, MSG_FULL_TEXT_TOTAL ) -from core.types import Session, Order, Squad, Admin, user +from core.types import Session, Order, Squad, Admin, user_allowed from core.utils import add_user, send_async from sqlalchemy.exc import SQLAlchemyError @@ -82,7 +82,7 @@ def del_msg(bot, job): @run_async -@user +@user_allowed def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): add_user(update.message.from_user, session) if update.message.chat.type in ['group', 'supergroup', 'channel']: @@ -209,26 +209,26 @@ def ready_to_battle(bot: Bot): try: group = session.query(Squad).all() for item in group: - order = Order() - order.text = 'К битве готовсь!' - order.chat_id = item.chat_id - order.date = datetime.now() - order.confirmed_msg = 0 - session.add(order) + new_order = Order() + new_order.text = 'К битве готовсь!' + new_order.chat_id = item.chat_id + new_order.date = datetime.now() + new_order.confirmed_msg = 0 + session.add(new_order) session.commit() callback_data = json.dumps( - {'t': QueryType.OrderOk.value, 'id': order.id}) + {'t': QueryType.OrderOk.value, 'id': new_order.id}) markup = InlineKeyboardMarkup([ [InlineKeyboardButton('ГРАБЬНАСИЛУЙУБИВАЙ!', callback_data=callback_data)]]) - msg = send_order(bot, order.text, 0, order.chat_id, markup) + msg = send_order(bot, new_order.text, 0, new_order.chat_id, markup) try: msg = msg.result().result() bot.request.post(bot.base_url + '/pinChatMessage', - {'chat_id': order.chat_id, + {'chat_id': new_order.chat_id, 'message_id': msg.message_id, 'disable_notification': False}) @@ -251,20 +251,19 @@ def ready_to_battle_result(bot: Bot): full_count = 0 for item in group: - # FIX: переопределяется order #22 - order = session.query(Order).filter_by( + ready_order = session.query(Order).filter_by( chat_id=item.chat_id, text='К битве готовсь!').order_by(Order.date.desc()).first() - if order is not None: + if ready_order is not None: attack = 0 defence = 0 - for clear in order.cleared: + for clear in ready_order.cleared: if clear.user.character: attack += clear.user.character.attack defence += clear.user.character.defence - text = MSG_SQUAD_READY.format(len(order.cleared), + text = MSG_SQUAD_READY.format(len(ready_order.cleared), item.squad_name, attack, defence) @@ -276,9 +275,9 @@ def ready_to_battle_result(bot: Bot): full_attack += attack full_defence += defence - full_count += len(order.cleared) + full_count += len(ready_order.cleared) full_text += MSG_FULL_TEXT_LINE.format(item.squad_name, - len(order.cleared), + len(ready_order.cleared), attack, defence) @@ -329,7 +328,6 @@ def main(): disp.add_handler(CommandHandler("enable_trigger", enable_trigger_all)) disp.add_handler(CommandHandler("disable_trigger", disable_trigger_all)) disp.add_handler(CommandHandler("me", char_show)) - disp.add_handler(CommandHandler("check_bot_in_chats", check_bot_in_chats)) disp.add_handler(CommandHandler("add_squad", add_squad)) disp.add_handler(CommandHandler("del_squad", del_squad)) From 685a1dd3d99c2c63627186333d8e0305f7145f76 Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Thu, 28 Sep 2017 23:01:24 +0300 Subject: [PATCH 035/284] =?UTF-8?q?=D0=A4=D0=B0=D1=81=D1=82=D1=84=D0=B8?= =?UTF-8?q?=D0=BA=D1=81=D1=8B=20=D0=B4=D0=B5=D0=BA=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=B0,=20=D0=BD=D0=B5=D1=81=D0=BA=D0=BE=D0=BB?= =?UTF-8?q?=D1=8C=D0=BA=D0=B8=D1=85=20=D1=84=D1=83=D0=BD=D0=BA=D1=86=D0=B8?= =?UTF-8?q?=D0=B9=20=D0=B8=20=D1=83=D0=B4=D0=B0=D0=BB=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D1=8F=20=D0=B0=D0=B4=D0=BC=D0=B8=D0=BD=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 4 +++- core/functions/order_groups.py | 2 +- core/functions/orders.py | 4 ++-- core/types.py | 2 +- main.py | 2 ++ 5 files changed, 9 insertions(+), 5 deletions(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index cfb6f65..5ab1c3c 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -364,7 +364,9 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): bot.editMessageText(msg, update.callback_query.message.chat.id, update.callback_query.message.message_id, reply_markup=inline_markup) elif data['t'] == QueryType.DelAdm.value: - del_adm(bot, data['gid'], data['uid'], session) + admin_user = session.query(User).filter_by(id=data['uid']).first() + if admin_user: + del_adm(bot, data['gid'], admin_user, session) msg, inline_markup = generate_group_info(data['gid'], session) bot.editMessageText(msg, update.callback_query.message.chat.id, update.callback_query.message.message_id, reply_markup=inline_markup) diff --git a/core/functions/order_groups.py b/core/functions/order_groups.py index 9fd6956..3ef5638 100644 --- a/core/functions/order_groups.py +++ b/core/functions/order_groups.py @@ -12,7 +12,7 @@ def group_list(bot: Bot, update: Update, session): @admin_allowed(AdminType.FULL) -def add_group(bot: Bot, update: Update, chat_data, session): +def add_group(bot: Bot, update: Update, session, chat_data): chat_data['wait_group_name'] = False group = OrderGroup() group.name = update.message.text diff --git a/core/functions/orders.py b/core/functions/orders.py index c78130c..b6cc52f 100644 --- a/core/functions/orders.py +++ b/core/functions/orders.py @@ -6,9 +6,9 @@ @admin_allowed(adm_type=AdminType.GROUP) -def order(bot: Bot, update: Update, chat_data, session): +def order(bot: Bot, update: Update, session, chat_data): admin_user = session.query(Admin).filter(Admin.user_id == update.message.from_user.id).all() - markup = generate_order_groups_markup(bot, admin_user, chat_data['pin'] if 'pin' in chat_data else True) + markup = generate_order_groups_markup(session, admin_user, chat_data['pin'] if 'pin' in chat_data else True) msg = update.message if msg.audio: chat_data['order'] = msg.audio.file_id diff --git a/core/types.py b/core/types.py index d8c76d7..8864528 100644 --- a/core/types.py +++ b/core/types.py @@ -301,7 +301,7 @@ def wrapper(bot: Bot, update, *args, **kwargs): def user_allowed(func): - admin_allowed(AdminType.NOT_ADMIN)(func) + return admin_allowed(AdminType.NOT_ADMIN)(func) Base.metadata.create_all(ENGINE) diff --git a/main.py b/main.py index 7280b33..e96445d 100644 --- a/main.py +++ b/main.py @@ -199,6 +199,8 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): elif from_id == 278525885: if '📦твой склад с материалами:' in text: trade_compare(bot, update, chat_data) + else: + order(bot, update, chat_data) else: order(bot, update, chat_data) From 382af829b3d9b9cf0b644c5d7dfca1a56f6f895b Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Thu, 28 Sep 2017 23:31:14 +0300 Subject: [PATCH 036/284] =?UTF-8?q?=D0=A4=D0=B8=D0=BA=D1=81=D1=8B=20=D0=BF?= =?UTF-8?q?=D0=BE=D1=81=D0=BB=D0=B5=20=D1=80=D0=B5=D1=84=D0=B0=D0=BA=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=B8=D0=BD=D0=B3=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/main.py b/main.py index e96445d..ccf2fcb 100644 --- a/main.py +++ b/main.py @@ -149,8 +149,6 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): open_hiring(bot, update) elif text == 'закрыть набор': close_hiring(bot, update) - elif update.message.text: - trigger_show(bot, update) elif update.message.reply_to_message is not None: if text == 'пин': pin(bot, update) @@ -160,11 +158,12 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): delete_msg(bot, update) elif text == 'свали': delete_user(bot, update) - elif 'твои результаты в бою:' in text: if update.message.forward_from.id == 265204902: job_queue.run_once(del_msg, 2, (update.message.chat.id, update.message.message_id)) + elif update.message.text: + trigger_show(bot, update) elif update.message.chat.type == 'private': if update.message.text: From d8a1a4b401305e44a4adb2bea9d5b5fa27fb7088 Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Thu, 28 Sep 2017 23:52:36 +0300 Subject: [PATCH 037/284] =?UTF-8?q?=D0=95=D1=89=D1=91=20=D0=BA=D0=BE=D1=81?= =?UTF-8?q?=D1=8F=D0=BA=20=D1=87=D0=B8=D1=81=D1=82=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/main.py b/main.py index ccf2fcb..4ce14c1 100644 --- a/main.py +++ b/main.py @@ -205,7 +205,7 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): @run_async -def ready_to_battle(bot: Bot): +def ready_to_battle(bot: Bot, job_queue): session = Session() try: group = session.query(Squad).all() @@ -242,7 +242,7 @@ def ready_to_battle(bot: Bot): @run_async -def ready_to_battle_result(bot: Bot): +def ready_to_battle_result(bot: Bot, job_queue): session = Session() try: group = session.query(Squad).all() From 07ad509d35ac1c855011a3261935e94583edea68 Mon Sep 17 00:00:00 2001 From: toxydose Date: Fri, 29 Sep 2017 10:37:20 +0300 Subject: [PATCH 038/284] add reports --- core/regexp.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/core/regexp.py b/core/regexp.py index 3f0e010..9d40b50 100644 --- a/core/regexp.py +++ b/core/regexp.py @@ -24,3 +24,9 @@ '📦Склад: (?:[0-9]+) /stock(?:\n\n' \ 'Помощник:\n' \ '(.+?) (?:.+?) (.+)? \(([0-9]+) ур\.\) (.+) /pet)?' + +REPORT = '(🇬🇵|🇮🇲|🇨🇾|🇻🇦|🇪🇺|🇲🇴|🇰🇮)(.+) ⚔️:([0-9]+) 🛡:([0-9]+) \(([0-9]+) ур.\)\n' \ + 'Твои результаты в бою:\n' \ + '🔥Опыт: ([0-9]+) ед\n' \ + '💰Золото: ([0-9]+)\n' \ + '📦Склад: ([0-9]+)' \ No newline at end of file From fc33350458097832785f903a411fb96982b91ab2 Mon Sep 17 00:00:00 2001 From: Alexander Bridges Date: Fri, 29 Sep 2017 10:38:54 +0300 Subject: [PATCH 039/284] Update regexp.py --- core/regexp.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/regexp.py b/core/regexp.py index 9d40b50..a52e4f0 100644 --- a/core/regexp.py +++ b/core/regexp.py @@ -29,4 +29,5 @@ 'Твои результаты в бою:\n' \ '🔥Опыт: ([0-9]+) ед\n' \ '💰Золото: ([0-9]+)\n' \ - '📦Склад: ([0-9]+)' \ No newline at end of file + '📦Склад: ([0-9]+)' + From 8e40652cdabeb3960fbdbb3ce74fd93b91136d5f Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Fri, 29 Sep 2017 12:10:07 +0300 Subject: [PATCH 040/284] PY-2017.2.3 + + + \ No newline at end of file From 461a27ed4a710e69ba1b9d6e27b9c0e02f577da6 Mon Sep 17 00:00:00 2001 From: toxydose Date: Fri, 29 Sep 2017 12:12:02 +0300 Subject: [PATCH 041/284] =?UTF-8?q?=D0=BE=D1=82=D1=81=D1=82=D1=83=D0=BF?= =?UTF-8?q?=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/regexp.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/core/regexp.py b/core/regexp.py index a52e4f0..61efca7 100644 --- a/core/regexp.py +++ b/core/regexp.py @@ -26,8 +26,7 @@ '(.+?) (?:.+?) (.+)? \(([0-9]+) ур\.\) (.+) /pet)?' REPORT = '(🇬🇵|🇮🇲|🇨🇾|🇻🇦|🇪🇺|🇲🇴|🇰🇮)(.+) ⚔️:([0-9]+) 🛡:([0-9]+) \(([0-9]+) ур.\)\n' \ - 'Твои результаты в бою:\n' \ - '🔥Опыт: ([0-9]+) ед\n' \ - '💰Золото: ([0-9]+)\n' \ - '📦Склад: ([0-9]+)' - + 'Твои результаты в бою:\n' \ + '🔥Опыт: ([0-9]+) ед\n' \ + '💰Золото: ([0-9]+)\n' \ + '📦Склад: ([0-9]+)' From c9d86599e48fa1920493f37a17a5f1d1cf32528b Mon Sep 17 00:00:00 2001 From: toxydose Date: Fri, 29 Sep 2017 12:30:58 +0300 Subject: [PATCH 042/284] chat id constants --- main.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/main.py b/main.py index 4ce14c1..05b158e 100644 --- a/main.py +++ b/main.py @@ -62,6 +62,11 @@ from sqlalchemy.exc import SQLAlchemyError +#-----constants---- +chatwars_id = 265204902 +tradebot_id = 278525885 +#------------------- + last_welcome = 0 logging.basicConfig( level=logging.WARNING, @@ -159,7 +164,7 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): elif text == 'свали': delete_user(bot, update) elif 'твои результаты в бою:' in text: - if update.message.forward_from.id == 265204902: + if update.message.forward_from.id == chatwars_id: job_queue.run_once(del_msg, 2, (update.message.chat.id, update.message.message_id)) elif update.message.text: @@ -189,13 +194,13 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): elif update.message.forward_from: from_id = update.message.forward_from.id - if from_id == 265204902: + if from_id == chatwars_id: if text.startswith('📦содержимое склада'): stock_compare(bot, update, chat_data) elif re.search(PROFILE, text) or re.search(HERO, text): char_update(bot, update) - elif from_id == 278525885: + elif from_id == tradebot_id: if '📦твой склад с материалами:' in text: trade_compare(bot, update, chat_data) else: From 45d6e2e2d3f9011ac5782c05f04e644440cf5762 Mon Sep 17 00:00:00 2001 From: toxydose Date: Fri, 29 Sep 2017 12:36:38 +0300 Subject: [PATCH 043/284] .. --- main.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/main.py b/main.py index 05b158e..81a3d60 100644 --- a/main.py +++ b/main.py @@ -62,10 +62,10 @@ from sqlalchemy.exc import SQLAlchemyError -#-----constants---- +# -----constants---- chatwars_id = 265204902 tradebot_id = 278525885 -#------------------- +# ------------------- last_welcome = 0 logging.basicConfig( From 87926213fe45d3c5be91d51d95faa74e9dc0ddf8 Mon Sep 17 00:00:00 2001 From: toxydose Date: Fri, 29 Sep 2017 12:44:55 +0300 Subject: [PATCH 044/284] =?UTF-8?q?=D0=BD=D0=B5=D0=B8=D1=81=D0=BF=D0=BE?= =?UTF-8?q?=D0=BB=D1=8C=D0=B7=D1=83=D0=B5=D0=BC=D0=B0=D1=8F=20=D0=BF=D0=B5?= =?UTF-8?q?=D1=80=D0=B5=D0=BC=D0=B5=D0=BD=D0=BD=D0=B0=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 1 - 1 file changed, 1 deletion(-) diff --git a/main.py b/main.py index 81a3d60..a5a9b80 100644 --- a/main.py +++ b/main.py @@ -67,7 +67,6 @@ tradebot_id = 278525885 # ------------------- -last_welcome = 0 logging.basicConfig( level=logging.WARNING, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' From 48e34c861fadc34295bf1992c5cdd1de711d06ed Mon Sep 17 00:00:00 2001 From: toxydose Date: Fri, 29 Sep 2017 13:31:40 +0300 Subject: [PATCH 045/284] parse reports defined --- core/functions/profile.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/core/functions/profile.py b/core/functions/profile.py index f9c601d..b18e3ec 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -1,7 +1,7 @@ from telegram import Update, Bot from core.functions.inline_keyboard_handling import generate_profile_buttons -from core.regexp import HERO, PROFILE +from core.regexp import HERO, PROFILE, REPORT from core.types import Character, User, admin_allowed, Equip, user_allowed from core.utils import send_async from datetime import timedelta @@ -68,6 +68,25 @@ def parse_hero(profile, user_id, date, session): return char +def parse_reports(profile, user_id, date, session) + parsed_data = re.search(REPORT, profile) + char = session.query(Character).filter_by(user_id=user_id, date=date).first() + if char is None: + char = Character() + char.user_id = user_id + char.date = date + char.castle = str(parsed_data.group(1)) + char.name = str(parsed_data.group(2)) + char.attack = str(parsed_data.group(3)) + char.defence = str(parsed_data.group(4)) + char.level = int(parsed_data.group(5)) + char.level = int(parsed_data.group(5)) + char.level = int(parsed_data.group(5)) + char.earned_exp = int(pased_data.group(6)) + char.earned_gold = int(pased_data.group(7)) + char.earned_stock = int(pased_data.group(8)) + return char + @user_allowed def char_update(bot: Bot, update: Update, session): if update.message.date - update.message.forward_date > timedelta(minutes=1): From 68cf8ba54f5e29847751a289412016a6a2bc4562 Mon Sep 17 00:00:00 2001 From: toxydose Date: Fri, 29 Sep 2017 13:49:31 +0300 Subject: [PATCH 046/284] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=BE=20=D0=B8=D0=BC=D1=8F=20=D0=BF=D0=B5?= =?UTF-8?q?=D1=80=D0=B5=D0=BC=D0=B5=D0=BD=D0=BD=D0=BE=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/profile.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/functions/profile.py b/core/functions/profile.py index b18e3ec..885f9ef 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -68,8 +68,8 @@ def parse_hero(profile, user_id, date, session): return char -def parse_reports(profile, user_id, date, session) - parsed_data = re.search(REPORT, profile) +def parse_reports(report, user_id, date, session) + parsed_data = re.search(REPORT, report) char = session.query(Character).filter_by(user_id=user_id, date=date).first() if char is None: char = Character() From 2ec6a1711f529c6072d9a8eafb0746d763425f72 Mon Sep 17 00:00:00 2001 From: toxydose Date: Fri, 29 Sep 2017 13:53:20 +0300 Subject: [PATCH 047/284] =?UTF-8?q?=D0=BE=D0=BF=D0=B5=D1=87=D0=B0=D1=82?= =?UTF-8?q?=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/profile.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/core/functions/profile.py b/core/functions/profile.py index 885f9ef..d10f1dc 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -68,7 +68,7 @@ def parse_hero(profile, user_id, date, session): return char -def parse_reports(report, user_id, date, session) +def parse_reports(report, user_id, date, session): parsed_data = re.search(REPORT, report) char = session.query(Character).filter_by(user_id=user_id, date=date).first() if char is None: @@ -82,9 +82,9 @@ def parse_reports(report, user_id, date, session) char.level = int(parsed_data.group(5)) char.level = int(parsed_data.group(5)) char.level = int(parsed_data.group(5)) - char.earned_exp = int(pased_data.group(6)) - char.earned_gold = int(pased_data.group(7)) - char.earned_stock = int(pased_data.group(8)) + char.earned_exp = int(parsed_data.group(6)) + char.earned_gold = int(parsed_data.group(7)) + char.earned_stock = int(parsed_data.group(8)) return char @user_allowed From 94ac19eed688a1ce1112aa64a9cdabdea5e9d80d Mon Sep 17 00:00:00 2001 From: toxydose Date: Fri, 29 Sep 2017 13:58:17 +0300 Subject: [PATCH 048/284] session --- core/functions/profile.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core/functions/profile.py b/core/functions/profile.py index d10f1dc..b216976 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -85,6 +85,8 @@ def parse_reports(report, user_id, date, session): char.earned_exp = int(parsed_data.group(6)) char.earned_gold = int(parsed_data.group(7)) char.earned_stock = int(parsed_data.group(8)) + session.add(char) + session.commit() return char @user_allowed From 69484a783404170ab8a009006c6d9e5d635fd429 Mon Sep 17 00:00:00 2001 From: toxydose Date: Fri, 29 Sep 2017 14:26:21 +0300 Subject: [PATCH 049/284] =?UTF-8?q?=D1=83=D1=87=D1=82=D0=B5=D0=BD=D1=8B=20?= =?UTF-8?q?=D0=BE=D1=82=D1=80=D0=B8=D1=86=D0=B0=D1=82=D0=B5=D0=BB=D1=8C?= =?UTF-8?q?=D0=BD=D1=8B=D0=B5=20=D0=B7=D0=BD=D0=B0=D1=87=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/regexp.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/regexp.py b/core/regexp.py index 61efca7..d3f2a30 100644 --- a/core/regexp.py +++ b/core/regexp.py @@ -6,7 +6,7 @@ '🔥Опыт: ([0-9]+)/([0-9]+)\n' \ '🔋Выносливость: ([0-9]+)/([0-9]+)\n' \ '(?:💧Мана: [0-9]+/[0-9]+\n)?' \ - '💰([0-9]+) 💠([0-9]+)\n\n' \ + '💰(-?[0-9]+) 💠([0-9]+)\n\n' \ '🎽Экипировка (.+)\n' \ '🎒Рюкзак: ([0-9]+)/([0-9]+) /inv' \ '(?:\n\nПомощник:\n(.+?) (?:.+?) (.+)? \(([0-9]+) ур\.\) (.+) /pet)?' @@ -28,5 +28,5 @@ REPORT = '(🇬🇵|🇮🇲|🇨🇾|🇻🇦|🇪🇺|🇲🇴|🇰🇮)(.+) ⚔️:([0-9]+) 🛡:([0-9]+) \(([0-9]+) ур.\)\n' \ 'Твои результаты в бою:\n' \ '🔥Опыт: ([0-9]+) ед\n' \ - '💰Золото: ([0-9]+)\n' \ - '📦Склад: ([0-9]+)' + '💰Золото: (-?[0-9]+)\n' \ + '📦Склад: (-?[0-9]+)' From 1bb21d9c359390731f9f3583d93b47edd5f4d847 Mon Sep 17 00:00:00 2001 From: toxydose Date: Fri, 29 Sep 2017 14:27:42 +0300 Subject: [PATCH 050/284] =?UTF-8?q?=D1=83=D1=87=D1=82=D0=B5=D0=BD=D1=8B=20?= =?UTF-8?q?=D0=BE=D1=82=D1=80=D0=B8=D1=86=D0=B0=D1=82=D0=B5=D0=BB=D1=8C?= =?UTF-8?q?=D0=BD=D1=8B=D0=B5=20=D0=B7=D0=BD=D0=B0=D1=87=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/regexp.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/regexp.py b/core/regexp.py index d3f2a30..f9257be 100644 --- a/core/regexp.py +++ b/core/regexp.py @@ -17,7 +17,7 @@ '🔥Опыт: ([0-9]+)/([0-9]+)\n' \ '🔋Выносливость: ([0-9]+)/([0-9]+)\n' \ '(?:💧Мана: [0-9]+/[0-9]+\n)?' \ - '💰([0-9]+) 💠([0-9]+)\n' \ + '💰(-?[0-9]+) 💠([0-9]+)\n' \ '🤺Побед: ([0-9]+)\n\n' \ '🎽Экипировка(?:(.+)(?:\n)?((?:.|\n)+)?)\n\n' \ '🎒Рюкзак: ([0-9]+)/([0-9]+) /inv\n' \ From 42a25da457957832aec461c1e8f69b60bcf26485 Mon Sep 17 00:00:00 2001 From: toxydose Date: Fri, 29 Sep 2017 14:34:11 +0300 Subject: [PATCH 051/284] Reports --- core/functions/profile.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/functions/profile.py b/core/functions/profile.py index b216976..a3e9429 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -2,7 +2,7 @@ from core.functions.inline_keyboard_handling import generate_profile_buttons from core.regexp import HERO, PROFILE, REPORT -from core.types import Character, User, admin_allowed, Equip, user_allowed +from core.types import Character, Reports, User, admin_allowed, Equip, user_allowed from core.utils import send_async from datetime import timedelta import re @@ -70,9 +70,9 @@ def parse_hero(profile, user_id, date, session): def parse_reports(report, user_id, date, session): parsed_data = re.search(REPORT, report) - char = session.query(Character).filter_by(user_id=user_id, date=date).first() + char = session.query(Reports).filter_by(user_id=user_id, date=date).first() if char is None: - char = Character() + char = Reports() char.user_id = user_id char.date = date char.castle = str(parsed_data.group(1)) From 07114dd7c036f221cbbab365e98d0a1c106b3ef9 Mon Sep 17 00:00:00 2001 From: toxydose Date: Fri, 29 Sep 2017 14:38:30 +0300 Subject: [PATCH 052/284] =?UTF-8?q?=D0=BF=D0=B5=D1=80=D0=B5=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D0=BD=D1=8B=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/main.py b/main.py index a5a9b80..2898cde 100644 --- a/main.py +++ b/main.py @@ -63,8 +63,8 @@ from sqlalchemy.exc import SQLAlchemyError # -----constants---- -chatwars_id = 265204902 -tradebot_id = 278525885 +CWBOT_ID = 265204902 +TRADEBOT_ID = 278525885 # ------------------- logging.basicConfig( @@ -163,7 +163,7 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): elif text == 'свали': delete_user(bot, update) elif 'твои результаты в бою:' in text: - if update.message.forward_from.id == chatwars_id: + if update.message.forward_from.id == CWBOT_ID: job_queue.run_once(del_msg, 2, (update.message.chat.id, update.message.message_id)) elif update.message.text: @@ -193,13 +193,13 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): elif update.message.forward_from: from_id = update.message.forward_from.id - if from_id == chatwars_id: + if from_id == CWBOT_ID: if text.startswith('📦содержимое склада'): stock_compare(bot, update, chat_data) elif re.search(PROFILE, text) or re.search(HERO, text): char_update(bot, update) - elif from_id == tradebot_id: + elif from_id == TRADEBOT_ID: if '📦твой склад с материалами:' in text: trade_compare(bot, update, chat_data) else: From 56503b9a200dead0abb253ca8ac1a94a820286ce Mon Sep 17 00:00:00 2001 From: toxydose Date: Fri, 29 Sep 2017 14:46:54 +0300 Subject: [PATCH 053/284] typos fixed --- core/functions/profile.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/core/functions/profile.py b/core/functions/profile.py index a3e9429..3cc81a5 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -80,8 +80,6 @@ def parse_reports(report, user_id, date, session): char.attack = str(parsed_data.group(3)) char.defence = str(parsed_data.group(4)) char.level = int(parsed_data.group(5)) - char.level = int(parsed_data.group(5)) - char.level = int(parsed_data.group(5)) char.earned_exp = int(parsed_data.group(6)) char.earned_gold = int(parsed_data.group(7)) char.earned_stock = int(parsed_data.group(8)) From c4af08b17941d79d120be00eb05e31d68c85cab2 Mon Sep 17 00:00:00 2001 From: toxydose Date: Fri, 29 Sep 2017 15:04:49 +0300 Subject: [PATCH 054/284] new class Reports --- core/types.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/core/types.py b/core/types.py index 8864528..d2970df 100644 --- a/core/types.py +++ b/core/types.py @@ -92,6 +92,11 @@ class User(Base): order_by='Stock.date.desc()', uselist=False) + reports = relationship('reports', + back_populates='user', + order_by='Character.date.desc()') + + def __repr__(self): user = '' if self.first_name: @@ -219,6 +224,22 @@ class Character(Base): user = relationship('User', back_populates='character') +class Reports(Base): + __tablename__ = 'reports' + + user_id = Column(BigInteger, ForeignKey(User.id), primary_key=True) + date = Column(DATETIME(fsp=6), primary_key=True) + name = Column(UnicodeText(250)) + level = Column(Integer) + attack = Column(Integer) + defence = Column(Integer) + castle = Column(UnicodeText(100)) + earned_exp = Column(Integer) + earned_gold = Column(Integer) + earned_stock = Column(Integer) + + user = relationship('User', back_populates='reports') + class Squad(Base): __tablename__ = 'squads' From c6689857236c95dbf9ac87d547257d37c31daeb5 Mon Sep 17 00:00:00 2001 From: toxydose Date: Fri, 29 Sep 2017 15:15:25 +0300 Subject: [PATCH 055/284] new Reports class --- core/types.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/types.py b/core/types.py index d2970df..dc00731 100644 --- a/core/types.py +++ b/core/types.py @@ -93,10 +93,9 @@ class User(Base): uselist=False) reports = relationship('reports', - back_populates='user', - order_by='Character.date.desc()') + back_populates='user', + order_by='Character.date.desc()') - def __repr__(self): user = '' if self.first_name: @@ -240,6 +239,7 @@ class Reports(Base): user = relationship('User', back_populates='reports') + class Squad(Base): __tablename__ = 'squads' From 501074d43649ab5a91f2756149cb6c3ce436819a Mon Sep 17 00:00:00 2001 From: toxydose Date: Fri, 29 Sep 2017 16:27:05 +0300 Subject: [PATCH 056/284] =?UTF-8?q?=D1=84=D0=B8=D0=BA=D1=81=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config.py.sample | 3 ++- core/functions/profile.py | 4 ++-- core/types.py | 8 ++++---- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/config.py.sample b/config.py.sample index 49c82c5..e89935f 100644 --- a/config.py.sample +++ b/config.py.sample @@ -3,4 +3,5 @@ TOKEN = '' # Токен телеграмбота (получается у @BotFather) DB = 'mysql+pymysql://:@/?charset=utf8mb4' # Строчка подключения к базе данных (поддерживается только MySql, о формате можно прочитать тут http://docs.sqlalchemy.org/en/latest/dialects/mysql.html) API_PORT = 88 # Порт, по которому будет доступен внешний апи бота (REST) -GOVERNMENT_CHAT = -1001149271906 # Чат, в который бот будет слать отчёты \ No newline at end of file +GOVERNMENT_CHAT = -1001149271906 # Чат, в который бот будет слать отчёты +SUPER_ADMIN_ID = #id супер админа \ No newline at end of file diff --git a/core/functions/profile.py b/core/functions/profile.py index 3cc81a5..6b963bd 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -2,7 +2,7 @@ from core.functions.inline_keyboard_handling import generate_profile_buttons from core.regexp import HERO, PROFILE, REPORT -from core.types import Character, Reports, User, admin_allowed, Equip, user_allowed +from core.types import Character, Report, User, admin_allowed, Equip, user_allowed from core.utils import send_async from datetime import timedelta import re @@ -72,7 +72,7 @@ def parse_reports(report, user_id, date, session): parsed_data = re.search(REPORT, report) char = session.query(Reports).filter_by(user_id=user_id, date=date).first() if char is None: - char = Reports() + char = Report() char.user_id = user_id char.date = date char.castle = str(parsed_data.group(1)) diff --git a/core/types.py b/core/types.py index dc00731..8ec9ad6 100644 --- a/core/types.py +++ b/core/types.py @@ -92,9 +92,9 @@ class User(Base): order_by='Stock.date.desc()', uselist=False) - reports = relationship('reports', + report = relationship('Report', back_populates='user', - order_by='Character.date.desc()') + order_by='Report.date.desc()') def __repr__(self): user = '' @@ -223,7 +223,7 @@ class Character(Base): user = relationship('User', back_populates='character') -class Reports(Base): +class Report(Base): __tablename__ = 'reports' user_id = Column(BigInteger, ForeignKey(User.id), primary_key=True) @@ -237,7 +237,7 @@ class Reports(Base): earned_gold = Column(Integer) earned_stock = Column(Integer) - user = relationship('User', back_populates='reports') + user = relationship('User', back_populates='report') class Squad(Base): From a47a5b50d8fa06040f8a9d7bce99c9d96fee2dc0 Mon Sep 17 00:00:00 2001 From: Alexander Bridges Date: Fri, 29 Sep 2017 16:28:14 +0300 Subject: [PATCH 057/284] Update config.py.sample --- config.py.sample | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config.py.sample b/config.py.sample index e89935f..399b584 100644 --- a/config.py.sample +++ b/config.py.sample @@ -4,4 +4,4 @@ TOKEN = '' # Токен телеграмбота (получаетс DB = 'mysql+pymysql://:@/?charset=utf8mb4' # Строчка подключения к базе данных (поддерживается только MySql, о формате можно прочитать тут http://docs.sqlalchemy.org/en/latest/dialects/mysql.html) API_PORT = 88 # Порт, по которому будет доступен внешний апи бота (REST) GOVERNMENT_CHAT = -1001149271906 # Чат, в который бот будет слать отчёты -SUPER_ADMIN_ID = #id супер админа \ No newline at end of file +SUPER_ADMIN_ID = #id супер админа From 30177b350f046e65873bba2db642c4f097194927 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Fri, 29 Sep 2017 17:12:16 +0300 Subject: [PATCH 058/284] =?UTF-8?q?=D0=9D=D0=B0=D1=87=D0=B8=D0=BD=D0=B0?= =?UTF-8?q?=D0=B5=D0=BC=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D1=8F=D1=82?= =?UTF-8?q?=D1=8C=20=D0=BA=D0=BD=D0=BE=D0=BF=D0=BE=D1=87=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/common.py | 14 +++++++++++++- core/functions/reply_markup.py | 8 ++++++++ main.py | 5 +++-- 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/core/functions/common.py b/core/functions/common.py index 58cef5b..c10ceb4 100644 --- a/core/functions/common.py +++ b/core/functions/common.py @@ -5,7 +5,7 @@ from telegram import Update, Bot, ParseMode from core.functions.triggers import trigger_decorator -from core.functions.reply_markup import generate_admin_markup +from core.functions.reply_markup import generate_admin_markup, generate_user_markup from core.texts import * from core.types import AdminType, Admin, Stock, admin_allowed, user_allowed from core.utils import send_async, add_user @@ -47,6 +47,18 @@ def admin_panel(bot: Bot, update: Update, session): reply_markup=generate_admin_markup(full_adm, grp_adm)) +@user_allowed +def user_panel(bot: Bot, update: Update, session): + if update.message.chat.type == 'private': + admin = session.query(Admin).filter_by(user_id=update.message.from_user.id).all() + is_admin = False + for _ in admin: + is_admin = True + break + send_async(bot, chat_id=update.message.chat.id, text=MSG_START_WELCOME, + reply_markup=generate_user_markup(is_admin)) + + @admin_allowed() def kick(bot: Bot, update: Update, session): bot.leave_chat(update.message.chat.id) diff --git a/core/functions/reply_markup.py b/core/functions/reply_markup.py index df5b2fd..c5b7345 100644 --- a/core/functions/reply_markup.py +++ b/core/functions/reply_markup.py @@ -9,3 +9,11 @@ def generate_admin_markup(full=False, grp=False): buttons.append([KeyboardButton('Заявки в отряд'), KeyboardButton('Чистка отряда')]) buttons.append([KeyboardButton('Список отряда')]) return ReplyKeyboardMarkup(buttons, True) + + +def generate_user_markup(is_admin=False): + buttons = [[KeyboardButton('Герой'), KeyboardButton('Топ')], + [KeyboardButton('Отряд'), KeyboardButton('Статистика')], + [KeyboardButton('Стройка'), KeyboardButton('Связь')]] + if is_admin: + buttons.append([KeyboardButton('/admin')]) diff --git a/main.py b/main.py index 4ce14c1..207fa58 100644 --- a/main.py +++ b/main.py @@ -31,8 +31,8 @@ from core.functions.common import ( help_msg, ping, start, error, kick, admin_panel, stock_compare, trade_compare, - delete_msg, delete_user -) + delete_msg, delete_user, + user_panel) from core.functions.inline_keyboard_handling import ( callback_query, send_status, send_order, QueryType ) @@ -199,6 +199,7 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): if '📦твой склад с материалами:' in text: trade_compare(bot, update, chat_data) else: + user_panel(bot, update) order(bot, update, chat_data) else: order(bot, update, chat_data) From d694af4e84ea4bd9ff165e1f0dda49897a9a98b2 Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Fri, 29 Sep 2017 21:10:27 +0300 Subject: [PATCH 059/284] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20=D0=BA=D0=BE=D1=81=D1=8F=D0=BA=20=D1=81=20?= =?UTF-8?q?=D0=BF=D1=80=D0=B8=D0=BD=D1=8F=D1=82=D0=B8=D0=B5=D0=BC=20=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D1=84=D0=B8=D0=BB=D0=B5=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index 4ce14c1..2b5f4b5 100644 --- a/main.py +++ b/main.py @@ -192,7 +192,7 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): if from_id == 265204902: if text.startswith('📦содержимое склада'): stock_compare(bot, update, chat_data) - elif re.search(PROFILE, text) or re.search(HERO, text): + elif re.search(PROFILE, update.message.text) or re.search(HERO, update.message.text): char_update(bot, update) elif from_id == 278525885: From 0a124b64478965cea71cdfe2690d01159330dc30 Mon Sep 17 00:00:00 2001 From: toxydose Date: Sat, 30 Sep 2017 09:31:07 +0300 Subject: [PATCH 060/284] removed hardcoded admin id --- core/functions/admins.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/functions/admins.py b/core/functions/admins.py index 69ae4b5..a53c7da 100644 --- a/core/functions/admins.py +++ b/core/functions/admins.py @@ -12,7 +12,7 @@ ) from core.types import User, AdminType, Admin, admin_allowed, user_allowed from core.utils import send_async - +from config import SUPER_ADMIN_ID @admin_allowed() def set_admin(bot: Bot, update: Update, session): @@ -165,7 +165,7 @@ def set_super_admin(bot: Bot, update: Update, session): text=MSG_USER_UNKNOWN) else: - if user.id == 79612802 and update.message.from_user.id == 79612802: + if user.id == SUPER_ADMIN_ID and update.message.from_user.id == SUPER_ADMIN_ID: adm = session.query(Admin).filter_by(user_id=user.id, admin_group=0).first() if adm is not None: if adm.admin_type == AdminType.SUPER.value: From ab9694e77bcdc6af1c0fa0eab20244416beba406 Mon Sep 17 00:00:00 2001 From: toxydose Date: Sat, 30 Sep 2017 09:52:22 +0300 Subject: [PATCH 061/284] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D1=80=D0=B0=D0=B7=D0=BD=D0=B8=D1=86=D1=83=20?= =?UTF-8?q?=D1=81=20=D1=82=D0=B5=D1=81=D1=82=D0=BE=D0=B2=D1=8B=D0=BC=20?= =?UTF-8?q?=D1=80=D0=B5=D0=BF=D0=BE=D0=B7=D0=B8=D1=82=D0=BE=D1=80=D0=B8?= =?UTF-8?q?=D0=B5=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index 2898cde..2d962e9 100644 --- a/main.py +++ b/main.py @@ -196,7 +196,7 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): if from_id == CWBOT_ID: if text.startswith('📦содержимое склада'): stock_compare(bot, update, chat_data) - elif re.search(PROFILE, text) or re.search(HERO, text): + elif re.search(PROFILE, update.message.text) or re.search(HERO, update.message.text): char_update(bot, update) elif from_id == TRADEBOT_ID: From 6b54e9d972b58f0ad8372257896358fa94e687d7 Mon Sep 17 00:00:00 2001 From: toxydose Date: Sat, 30 Sep 2017 15:23:05 +0300 Subject: [PATCH 062/284] =?UTF-8?q?newbies=20=D1=85=D0=B0=D1=80=D0=B4?= =?UTF-8?q?=D0=BA=D0=BE=D0=B4=D1=8B=20=D0=B8=20=D0=B2=D0=BA=D0=BB/=D0=B2?= =?UTF-8?q?=D1=8B=D0=BA=D0=BB=20=D1=84=D1=83=D0=BD=D0=BA=D1=86=D0=B8=D0=BE?= =?UTF-8?q?=D0=BD=D0=B0=D0=BB=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config.py.sample | 5 ++++- core/functions/newbies.py | 23 ++++++++++++----------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/config.py.sample b/config.py.sample index 399b584..ea9681e 100644 --- a/config.py.sample +++ b/config.py.sample @@ -4,4 +4,7 @@ TOKEN = '' # Токен телеграмбота (получаетс DB = 'mysql+pymysql://:@/?charset=utf8mb4' # Строчка подключения к базе данных (поддерживается только MySql, о формате можно прочитать тут http://docs.sqlalchemy.org/en/latest/dialects/mysql.html) API_PORT = 88 # Порт, по которому будет доступен внешний апи бота (REST) GOVERNMENT_CHAT = -1001149271906 # Чат, в который бот будет слать отчёты -SUPER_ADMIN_ID = #id супер админа +SUPER_ADMIN_ID = # id супер админа +# вербовочный функционал: +CASTLE_CHAT_ID = # id замкового чата (для поиска новых игроков в замке) +ACADEM_CHAT_ID = # id чата академии (для уведомления о новых игроках в замке) \ No newline at end of file diff --git a/core/functions/newbies.py b/core/functions/newbies.py index 08104f1..ede236c 100644 --- a/core/functions/newbies.py +++ b/core/functions/newbies.py @@ -3,15 +3,16 @@ from core.template import fill_template from core.utils import send_async from core.texts import * +from config import ACADEM_CHAT_ID, CASTLE_CHAT_ID - -@user_allowed -def newbie(bot: Bot, update: Update, session): - if update.message.chat.id in [-1001045426965]: - if update.message.new_chat_member is not None: - user = session.query(User).filter(User.id == update.message.new_chat_member.id).first() - if user is None: - group = session.query(Group).filter(Group.id == -1001146975451).first() - if group is not None: - send_async(bot, chat_id=group.id, - text=fill_template(MSG_NEWBIE, update.message.new_chat_member)) +if ACADEM_CHAT_ID and CASTLE_CHAT_ID: + @user_allowed + def newbie(bot: Bot, update: Update, session): + if update.message.chat.id in [CASTLE_CHAT_ID]: + if update.message.new_chat_member is not None: + user = session.query(User).filter(User.id == update.message.new_chat_member.id).first() + if user is None: + group = session.query(Group).filter(Group.id == ACADEM_CHAT_ID).first() + if group is not None: + send_async(bot, chat_id=group.id, + text=fill_template(MSG_NEWBIE, update.message.new_chat_member)) From 0dbee7af5d8554af35a00fbe4bc2ddaa2787c9ab Mon Sep 17 00:00:00 2001 From: toxydose Date: Sat, 30 Sep 2017 15:26:14 +0300 Subject: [PATCH 063/284] edited --- config.py.sample | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/config.py.sample b/config.py.sample index ea9681e..9c8811a 100644 --- a/config.py.sample +++ b/config.py.sample @@ -6,5 +6,5 @@ API_PORT = 88 # Порт, по которому будет доступен вн GOVERNMENT_CHAT = -1001149271906 # Чат, в который бот будет слать отчёты SUPER_ADMIN_ID = # id супер админа # вербовочный функционал: -CASTLE_CHAT_ID = # id замкового чата (для поиска новых игроков в замке) -ACADEM_CHAT_ID = # id чата академии (для уведомления о новых игроках в замке) \ No newline at end of file +CASTLE_CHAT_ID = None # id замкового чата (для поиска новых игроков в замке - если None - функционал отключен) +ACADEM_CHAT_ID = None # id чата академии (для уведомления о новых игроках в замке - если None - функционал отключен) From 7f34696b29cbcfe02b01801bad1065532c57c4c7 Mon Sep 17 00:00:00 2001 From: toxydose Date: Sat, 30 Sep 2017 16:58:46 +0300 Subject: [PATCH 064/284] =?UTF-8?q?=D0=B2=D1=8B=D0=BD=D0=B5=D1=81=20=D1=81?= =?UTF-8?q?=D0=BE=D0=BE=D0=B1=D1=89=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BE=20?= =?UTF-8?q?=D0=BF=D0=B8=D1=82=D0=BE=D0=BC=D1=86=D0=B5=20=D0=B2=20texts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/template.py | 4 ++-- core/texts.py | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/core/template.py b/core/template.py index eeeec22..fc1e9f8 100644 --- a/core/template.py +++ b/core/template.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -from core.texts import MSG_NO_SQUAD, MSG_WANTS_TO_JOIN +from core.texts import MSG_NO_SQUAD, MSG_WANTS_TO_JOIN, MSG_NO_PET from core.types import User, Character @@ -36,7 +36,7 @@ def fill_char_template(msg: str, user: User, char: Character, squad_request=Fals msg = msg.replace('%pet%', '{} {} lvl'.format(str(char.pet), str(char.petLevel))) else: - msg = msg.replace('%pet%', 'Животины нет') + msg = msg.replace('%pet%', MSG_NO_PET) if squad_request: msg += MSG_WANTS_TO_JOIN.format(user.member.squad.squad_name) return msg diff --git a/core/texts.py b/core/texts.py index c2b913c..ce54084 100644 --- a/core/texts.py +++ b/core/texts.py @@ -180,6 +180,7 @@ нагрузкой от постоянного обновления' MSG_NO_SQUAD = 'Безотрядный тунеядец' +MSG_NO_PET = 'Животины нет' MSG_WANTS_TO_JOIN = '\n\nХочет вступить в отряд {}' MSG_CLEARED = 'Выполнено' From 6735de8615f5cacd5e2a5a12c59af8a17436a303 Mon Sep 17 00:00:00 2001 From: toxydose Date: Sat, 30 Sep 2017 17:09:01 +0300 Subject: [PATCH 065/284] . --- core/functions/newbies.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/functions/newbies.py b/core/functions/newbies.py index ede236c..a82f1de 100644 --- a/core/functions/newbies.py +++ b/core/functions/newbies.py @@ -5,9 +5,10 @@ from core.texts import * from config import ACADEM_CHAT_ID, CASTLE_CHAT_ID -if ACADEM_CHAT_ID and CASTLE_CHAT_ID: @user_allowed + def newbie(bot: Bot, update: Update, session): + if ACADEM_CHAT_ID and CASTLE_CHAT_ID: if update.message.chat.id in [CASTLE_CHAT_ID]: if update.message.new_chat_member is not None: user = session.query(User).filter(User.id == update.message.new_chat_member.id).first() From 659618782aef87c5b13e25b75b99bed8242b88d9 Mon Sep 17 00:00:00 2001 From: toxydose Date: Sat, 30 Sep 2017 17:10:51 +0300 Subject: [PATCH 066/284] // --- core/functions/newbies.py | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/core/functions/newbies.py b/core/functions/newbies.py index a82f1de..03d4008 100644 --- a/core/functions/newbies.py +++ b/core/functions/newbies.py @@ -5,15 +5,14 @@ from core.texts import * from config import ACADEM_CHAT_ID, CASTLE_CHAT_ID - @user_allowed - - def newbie(bot: Bot, update: Update, session): - if ACADEM_CHAT_ID and CASTLE_CHAT_ID: - if update.message.chat.id in [CASTLE_CHAT_ID]: - if update.message.new_chat_member is not None: - user = session.query(User).filter(User.id == update.message.new_chat_member.id).first() - if user is None: - group = session.query(Group).filter(Group.id == ACADEM_CHAT_ID).first() - if group is not None: - send_async(bot, chat_id=group.id, - text=fill_template(MSG_NEWBIE, update.message.new_chat_member)) +@user_allowed +def newbie(bot: Bot, update: Update, session): + if ACADEM_CHAT_ID and CASTLE_CHAT_ID: + if update.message.chat.id in [CASTLE_CHAT_ID]: + if update.message.new_chat_member is not None: + user = session.query(User).filter(User.id == update.message.new_chat_member.id).first() + if user is None: + group = session.query(Group).filter(Group.id == ACADEM_CHAT_ID).first() + if group is not None: + send_async(bot, chat_id=group.id, + text=fill_template(MSG_NEWBIE, update.message.new_chat_member)) From 6a24c7fe2327a7b27391aaefe0950e5dcf70a8d6 Mon Sep 17 00:00:00 2001 From: toxydose Date: Sat, 30 Sep 2017 17:11:30 +0300 Subject: [PATCH 067/284] // --- core/functions/newbies.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/core/functions/newbies.py b/core/functions/newbies.py index 03d4008..f8f9c04 100644 --- a/core/functions/newbies.py +++ b/core/functions/newbies.py @@ -8,11 +8,11 @@ @user_allowed def newbie(bot: Bot, update: Update, session): if ACADEM_CHAT_ID and CASTLE_CHAT_ID: - if update.message.chat.id in [CASTLE_CHAT_ID]: - if update.message.new_chat_member is not None: - user = session.query(User).filter(User.id == update.message.new_chat_member.id).first() - if user is None: - group = session.query(Group).filter(Group.id == ACADEM_CHAT_ID).first() - if group is not None: - send_async(bot, chat_id=group.id, - text=fill_template(MSG_NEWBIE, update.message.new_chat_member)) + if update.message.chat.id in [CASTLE_CHAT_ID]: + if update.message.new_chat_member is not None: + user = session.query(User).filter(User.id == update.message.new_chat_member.id).first() + if user is None: + group = session.query(Group).filter(Group.id == ACADEM_CHAT_ID).first() + if group is not None: + send_async(bot, chat_id=group.id, + text=fill_template(MSG_NEWBIE, update.message.new_chat_member)) From e3406fdce16ea9ee7cb43c72e99d150e0fbd70f6 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Mon, 2 Oct 2017 11:52:53 +0300 Subject: [PATCH 068/284] =?UTF-8?q?=D0=9D=D0=B5=D0=B1=D0=BE=D0=BB=D1=8C?= =?UTF-8?q?=D1=88=D0=B8=D0=B5=20=D0=BF=D0=BE=D0=BF=D1=80=D0=B0=D0=B2=D0=BE?= =?UTF-8?q?=D1=87=D0=BA=D0=B8=20=D0=BF=D0=BE=20=D0=BF=D1=83=D0=BB=D0=BB?= =?UTF-8?q?=D1=80=D0=B5=D0=BA=D0=B2=D0=B5=D1=81=D1=82=D0=B0=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config.py.sample | 2 +- core/functions/profile.py | 31 ++++++++++++++++--------------- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/config.py.sample b/config.py.sample index 9c8811a..6bedde4 100644 --- a/config.py.sample +++ b/config.py.sample @@ -4,7 +4,7 @@ TOKEN = '' # Токен телеграмбота (получаетс DB = 'mysql+pymysql://:@/?charset=utf8mb4' # Строчка подключения к базе данных (поддерживается только MySql, о формате можно прочитать тут http://docs.sqlalchemy.org/en/latest/dialects/mysql.html) API_PORT = 88 # Порт, по которому будет доступен внешний апи бота (REST) GOVERNMENT_CHAT = -1001149271906 # Чат, в который бот будет слать отчёты -SUPER_ADMIN_ID = # id супер админа +SUPER_ADMIN_ID = 0 # id супер админа # вербовочный функционал: CASTLE_CHAT_ID = None # id замкового чата (для поиска новых игроков в замке - если None - функционал отключен) ACADEM_CHAT_ID = None # id чата академии (для уведомления о новых игроках в замке - если None - функционал отключен) diff --git a/core/functions/profile.py b/core/functions/profile.py index 6b963bd..c00b3dd 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -70,22 +70,23 @@ def parse_hero(profile, user_id, date, session): def parse_reports(report, user_id, date, session): parsed_data = re.search(REPORT, report) - char = session.query(Reports).filter_by(user_id=user_id, date=date).first() - if char is None: - char = Report() - char.user_id = user_id - char.date = date - char.castle = str(parsed_data.group(1)) - char.name = str(parsed_data.group(2)) - char.attack = str(parsed_data.group(3)) - char.defence = str(parsed_data.group(4)) - char.level = int(parsed_data.group(5)) - char.earned_exp = int(parsed_data.group(6)) - char.earned_gold = int(parsed_data.group(7)) - char.earned_stock = int(parsed_data.group(8)) - session.add(char) + report = session.query(Report).filter_by(user_id=user_id, date=date).first() + if report is None: + report = Report() + report.user_id = user_id + report.date = date + report.castle = str(parsed_data.group(1)) + report.name = str(parsed_data.group(2)) + report.attack = str(parsed_data.group(3)) + report.defence = str(parsed_data.group(4)) + report.level = int(parsed_data.group(5)) + report.earned_exp = int(parsed_data.group(6)) + report.earned_gold = int(parsed_data.group(7)) + report.earned_stock = int(parsed_data.group(8)) + session.add(report) session.commit() - return char + return report + @user_allowed def char_update(bot: Bot, update: Update, session): From d11057665ac2ac723f81624607e73bd8b81fac48 Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Mon, 2 Oct 2017 22:16:22 +0300 Subject: [PATCH 069/284] =?UTF-8?q?=D0=A7=D1=83=D1=82=D1=8C=20=D0=BE=D0=B1?= =?UTF-8?q?=D0=BC=D0=B0=D0=BD=D1=83=D0=BB=D1=81=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index 5ab1c3c..13056bf 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -14,8 +14,8 @@ from core.types import ( User, Group, Admin, admin_allowed, Order, OrderGroup, OrderGroupItem, OrderCleared, Squad, user_allowed, - Character, SquadMember, MessageType, AdminType -) + Character, SquadMember, MessageType, AdminType, + Session) from core.texts import * from core.utils import send_async, update_group, add_user @@ -205,15 +205,12 @@ def generate_profile_buttons(user): return InlineKeyboardMarkup(inline_keys) -def generate_squad_list_key(squad, session): +def generate_squad_list_key(squad): attack = 0 defence = 0 - members = session.query(SquadMember).filter_by(squad_id=squad.chat_id).all() + members = squad.members for member in members: - character = session.query(Character).\ - filter_by(user_id=member.user_id).\ - order_by(Character.date.desc()).\ - limit(1).first() + character = member.user.character attack += character.attack defence += character.defence return [InlineKeyboardButton( @@ -228,12 +225,8 @@ def generate_squad_list_key(squad, session): def generate_squad_list(squads): inline_keys = [] - pool = ThreadPool(processes=10) - threads = [] for squad in squads: - threads.append(pool.apply_async(generate_squad_list_key, (squad,))) - for thread in threads: - inline_keys.append(thread.get()) + inline_keys.append(generate_squad_list_key(squad)) return InlineKeyboardMarkup(inline_keys) From 7195f2e829c7b16c613d9c0574e542152b17c7e3 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 3 Oct 2017 11:40:23 +0300 Subject: [PATCH 070/284] =?UTF-8?q?=D0=9F=D0=BE=D0=BF=D1=8B=D1=82=D0=BA?= =?UTF-8?q?=D0=B0=20=D0=BE=D0=BF=D1=82=D0=B8=D0=BC=D0=B8=D0=B7=D0=B0=D1=86?= =?UTF-8?q?=D0=B8=D0=B8,=20=D0=BD=D1=83=D0=B6=D0=B5=D0=BD=20=D1=82=D0=B5?= =?UTF-8?q?=D1=81=D1=82.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 18 +++++++++++------- core/functions/squad.py | 9 ++++----- main.py | 3 +-- 3 files changed, 16 insertions(+), 14 deletions(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index 13056bf..b4b0e61 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -3,7 +3,6 @@ import json from json import loads import logging -from multiprocessing.pool import ThreadPool from telegram import Bot, Update, InlineKeyboardButton, InlineKeyboardMarkup, TelegramError from telegram.ext.dispatcher import run_async @@ -14,11 +13,12 @@ from core.types import ( User, Group, Admin, admin_allowed, Order, OrderGroup, OrderGroupItem, OrderCleared, Squad, user_allowed, - Character, SquadMember, MessageType, AdminType, - Session) + Character, SquadMember, MessageType, AdminType) from core.texts import * from core.utils import send_async, update_group, add_user +from sqlalchemy import func + LOGGER = logging.getLogger('MyApp') @@ -205,12 +205,16 @@ def generate_profile_buttons(user): return InlineKeyboardMarkup(inline_keys) -def generate_squad_list_key(squad): +def generate_squad_list_key(squad, session): attack = 0 defence = 0 members = squad.members + user_ids = [] for member in members: - character = member.user.character + user_ids.append(member.user_id) + characters = session.query(Character).filter(Character.user_id in user_ids).\ + group_by(Character.user_id).having(func.max(Character.date)).all() + for character in characters: attack += character.attack defence += character.defence return [InlineKeyboardButton( @@ -223,10 +227,10 @@ def generate_squad_list_key(squad): callback_data=json.dumps({'t': QueryType.MemberList.value, 'id': squad.chat_id}))] -def generate_squad_list(squads): +def generate_squad_list(squads, session): inline_keys = [] for squad in squads: - inline_keys.append(generate_squad_list_key(squad)) + inline_keys.append(generate_squad_list_key(squad, session)) return InlineKeyboardMarkup(inline_keys) diff --git a/core/functions/squad.py b/core/functions/squad.py index 343a996..8491baa 100644 --- a/core/functions/squad.py +++ b/core/functions/squad.py @@ -91,15 +91,14 @@ def squad_list(bot: Bot, update: Update, session): if adm.admin_type <= AdminType.FULL.value: global_adm = True break - squads = [] if global_adm: squads = session.query(Squad).all() else: + group_ids = [] for adm in admin: - group = session.query(Group).filter_by(id=adm.admin_group).first() - if len(group.squad) and group.squad[0]: - squads.append(group.squad[0]) - markup = generate_squad_list(squads) + group_ids.append(adm.admin_group) + squads = session.query(Squad).filter(Squad.chat_id in group_ids).all() + markup = generate_squad_list(squads, session) send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_LIST, reply_markup=markup) diff --git a/main.py b/main.py index 2d962e9..3ce0ddb 100644 --- a/main.py +++ b/main.py @@ -4,7 +4,6 @@ import json import logging import re -from threading import Thread from telegram import ( Bot, Update, InlineKeyboardButton, InlineKeyboardMarkup, ParseMode @@ -182,7 +181,7 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): elif text in ['приказы', 'пин']: orders(bot, update, chat_data) elif text in ['список отряда', 'список']: - Thread(target=squad_list, args=(bot, update)).start() + squad_list(bot, update) elif text == 'группы': group_list(bot, update) elif text == 'чистка отряда': From c6ddb0d365c76b094e47b4e25c0c327f172d1013 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 3 Oct 2017 11:55:05 +0300 Subject: [PATCH 071/284] =?UTF-8?q?=D0=A2=D0=B5=D0=BF=D0=B5=D1=80=D1=8C=20?= =?UTF-8?q?=D1=81=D0=BF=D0=B8=D1=81=D0=BE=D0=BA=20=D0=B3=D1=80=D1=83=D0=BF?= =?UTF-8?q?=D0=BF=20=D0=B4=D0=BE=D0=BB=D0=B6=D0=B5=D0=BD=20=D1=80=D0=B0?= =?UTF-8?q?=D0=B1=D0=BE=D1=82=D0=B0=D1=82=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index b4b0e61..6940a44 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -212,8 +212,10 @@ def generate_squad_list_key(squad, session): user_ids = [] for member in members: user_ids.append(member.user_id) - characters = session.query(Character).filter(Character.user_id in user_ids).\ - group_by(Character.user_id).having(func.max(Character.date)).all() + characters = session.query(Character).filter((Character.user_id, Character.date) in + session.query(Character.user_id, func.max(Character.date)). + filter(Character.user_id in user_ids). + group_by(Character.user_id).all()).all() for character in characters: attack += character.attack defence += character.defence From 6a662faf844f29e0460639e1a9011c1478249161 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 3 Oct 2017 12:21:03 +0300 Subject: [PATCH 072/284] =?UTF-8?q?=D0=A1=D0=BF=D0=B8=D1=81=D0=BE=D0=BA=20?= =?UTF-8?q?=D0=B3=D1=80=D1=83=D0=BF=D0=BF=20=D0=B8=20=D1=81=D0=BF=D0=B8?= =?UTF-8?q?=D1=81=D0=BE=D0=BA=20=D0=B3=D1=80=D1=83=D0=BF=D0=BF=D1=8B=20?= =?UTF-8?q?=D0=B4=D0=BE=D0=BB=D0=B6=D0=B5=D0=BD=20=D1=82=D0=B5=D0=BF=D0=B5?= =?UTF-8?q?=D1=80=D1=8C=20=D0=B3=D0=B5=D0=BD=D0=B5=D1=80=D0=B8=D1=80=D0=BE?= =?UTF-8?q?=D0=B2=D0=B0=D1=82=D1=8C=D1=81=D1=8F=20=D1=81=D1=83=D1=89=D0=B5?= =?UTF-8?q?=D1=81=D1=82=D0=B2=D0=B5=D0=BD=D0=BD=D0=BE=20=D0=B1=D1=8B=D1=81?= =?UTF-8?q?=D1=82=D1=80=D0=B5=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 27 ++++++++++++++-------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index 6940a44..a751477 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -212,10 +212,11 @@ def generate_squad_list_key(squad, session): user_ids = [] for member in members: user_ids.append(member.user_id) - characters = session.query(Character).filter((Character.user_id, Character.date) in - session.query(Character.user_id, func.max(Character.date)). - filter(Character.user_id in user_ids). - group_by(Character.user_id).all()).all() + actual_profiles = session.query(Character.user_id, func.max(Character.date)).\ + filter(Character.user_id.in_(user_ids)).\ + group_by(Character.user_id).all() + characters = session.query(Character).filter(Character.user_id.in_([a[0] for a in actual_profiles]), + Character.date.in_([a[1] for a in actual_profiles])).all() for character in characters: attack += character.attack defence += character.defence @@ -253,19 +254,25 @@ def generate_squad_request(session): return InlineKeyboardMarkup(inline_keys) -def generate_squad_members(members): +def generate_squad_members(members, session): inline_keys = [] + user_ids = [] for member in members: - user = member.user - character = user.character + user_ids.append(member.user_id) + actual_profiles = session.query(Character.user_id, func.max(Character.date)). \ + filter(Character.user_id.in_(user_ids)). \ + group_by(Character.user_id).all() + characters = session.query(Character).filter(Character.user_id.in_([a[0] for a in actual_profiles]), + Character.date.in_([a[1] for a in actual_profiles])).all() + for character in characters: inline_keys.append( [InlineKeyboardButton('{}: {}⚔ {}🛡'. - format(user, + format(character.name, character.attack, character.defence), callback_data=json.dumps( {'t': QueryType.ShowHero.value, - 'id': member.user_id} + 'id': character.user_id} ))]) return InlineKeyboardMarkup(inline_keys) @@ -554,7 +561,7 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): reply_markup=generate_profile_buttons(user)) elif data['t'] == QueryType.MemberList.value: squad = session.query(Squad).filter_by(chat_id=data['id']).first() - markup = generate_squad_members(squad.members) + markup = generate_squad_members(squad.members, session) bot.editMessageText(squad.squad_name, update.callback_query.message.chat.id, update.callback_query.message.message_id, From f8295de3c03c8ea3bba267815e3fd85e924b6835 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 3 Oct 2017 12:43:44 +0300 Subject: [PATCH 073/284] =?UTF-8?q?=D0=98=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D1=82=D0=B5=D0=BA=D1=81=D1=82=D0=B0=20?= =?UTF-8?q?=D0=B2=20=D0=BF=D1=80=D0=BE=D1=86=D0=B5=D1=81=D1=81=D0=B5=20?= =?UTF-8?q?=D1=80=D0=B0=D1=81=D1=81=D1=8B=D0=BB=D0=BA=D0=B8=20=D0=B1=D0=BE?= =?UTF-8?q?=D0=BB=D1=8C=D1=88=D0=B5=20=D0=BD=D0=B5=D0=B2=D0=BE=D0=B7=D0=BC?= =?UTF-8?q?=D0=BE=D0=B6=D0=BD=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index a751477..163afca 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -377,9 +377,12 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): bot.editMessageText(msg, update.callback_query.message.chat.id, update.callback_query.message.message_id, reply_markup=inline_markup) elif data['t'] == QueryType.Order.value: + order_text = chat_data['order'] + order_type = chat_data['order_type'] + order_pin = True if 'pin' in chat_data and chat_data['pin'] or 'pin' not in chat_data else False if not data['g']: order = Order() - order.text = chat_data['order'] + order.text = order_text order.chat_id = data['id'] order.date = datetime.now() msg = send_async(bot, chat_id=order.chat_id, text=MSG_ORDER_CLEARED_BY_HEADER + MSG_EMPTY).result() @@ -390,8 +393,8 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): session.add(order) session.commit() markup = generate_ok_markup(order.id, 0) - msg = send_order(bot, order.text, chat_data['order_type'], order.chat_id, markup).result().result() - if 'pin' in chat_data and chat_data['pin'] or 'pin' not in chat_data: + msg = send_order(bot, order.text, order_type, order.chat_id, markup).result().result() + if order_pin and msg: try: bot.request.post(bot.base_url + '/pinChatMessage', {'chat_id': order.chat_id, 'message_id': msg.message_id, @@ -402,7 +405,7 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): group = session.query(OrderGroup).filter_by(id=data['id']).first() for item in group.items: order = Order() - order.text = chat_data['order'] + order.text = order_text order.chat_id = item.chat_id order.date = datetime.now() msg = send_async(bot, chat_id=order.chat_id, text=MSG_ORDER_CLEARED_BY_HEADER + MSG_EMPTY).result() @@ -413,8 +416,8 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): session.add(order) session.commit() markup = generate_ok_markup(order.id, 0) - msg = send_order(bot, order.text, chat_data['order_type'], order.chat_id, markup).result().result() - if 'pin' in chat_data and chat_data['pin'] or 'pin' not in chat_data: + msg = send_order(bot, order.text, order_type, order.chat_id, markup).result().result() + if order_pin and msg: try: bot.request.post(bot.base_url + '/pinChatMessage', {'chat_id': order.chat_id, 'message_id': msg.message_id, From f630de037f9a621ccb932a8cc8f30412bb822991 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 3 Oct 2017 12:48:18 +0300 Subject: [PATCH 074/284] =?UTF-8?q?=D0=92=20=D0=BB=D0=BE=D0=B3=20=D0=B1?= =?UTF-8?q?=D0=BE=D0=BB=D1=8C=D1=88=D0=B5=20=D0=BD=D0=B5=20=D1=82=D0=B5?= =?UTF-8?q?=D0=BA=D1=83=D1=82=20=D1=82=D1=8B=D0=BA=D0=B8=20=D0=BA=D0=BD?= =?UTF-8?q?=D0=BE=D0=BF=D0=BE=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 1 - 1 file changed, 1 deletion(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index 163afca..96a55c2 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -353,7 +353,6 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): update_group(update.callback_query.message.chat, session) user = add_user(update.callback_query.from_user, session) data = json.loads(update.callback_query.data) - LOGGER.warning(data) if data['t'] == QueryType.GroupList.value: msg = MSG_GROUP_STATUS_CHOOSE_CHAT squads = session.query(Squad).all() From fb0a2b472239e3a3f8173c7cbb1763518bc21257 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 3 Oct 2017 13:15:30 +0300 Subject: [PATCH 075/284] =?UTF-8?q?=D0=92=20=D1=81=D0=BF=D0=B8=D1=81=D0=BE?= =?UTF-8?q?=D0=BA=20=D0=BE=D1=82=D1=80=D1=8F=D0=B4=D0=B0=20=D0=B4=D0=BE?= =?UTF-8?q?=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D1=8B=20=D0=BA=D0=BD=D0=BE?= =?UTF-8?q?=D0=BF=D0=BA=D0=B8=20"=D0=9D=D0=B0=D0=B7=D0=B0=D0=B4"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 56 ++++++++++++++++++---- 1 file changed, 47 insertions(+), 9 deletions(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index 96a55c2..6a5ff3c 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -4,7 +4,7 @@ from json import loads import logging -from telegram import Bot, Update, InlineKeyboardButton, InlineKeyboardMarkup, TelegramError +from telegram import Bot, Update, InlineKeyboardButton, InlineKeyboardMarkup, TelegramError, Message from telegram.ext.dispatcher import run_async from core.enums import Castle, Icons @@ -47,6 +47,7 @@ class QueryType(Enum): InviteSquadAccept = 20 InviteSquadDecline = 21 TriggerOrderPin = 22 + SquadList = 23 @admin_allowed() @@ -193,15 +194,21 @@ def generate_group_manage(group_id, session): return InlineKeyboardMarkup(inline_keys) -def generate_profile_buttons(user): +def generate_profile_buttons(user, back_key=False): inline_keys = [[InlineKeyboardButton('🏅Герой', callback_data=json.dumps( - {'t': QueryType.ShowHero.value, 'id': user.id}))]] + {'t': QueryType.ShowHero.value, 'id': user.id, 'b': back_key}))]] if user.stock: inline_keys.append([InlineKeyboardButton('📦Склад', callback_data=json.dumps( - {'t': QueryType.ShowStock.value, 'id': user.id}))]) + {'t': QueryType.ShowStock.value, 'id': user.id, 'b': back_key}))]) if user.equip: inline_keys.append([InlineKeyboardButton('🎽Экипировка', callback_data=json.dumps( - {'t': QueryType.ShowEquip.value, 'id': user.id}))]) + {'t': QueryType.ShowEquip.value, 'id': user.id, 'b': back_key}))]) + if back_key: + inline_keys.append( + [InlineKeyboardButton(MSG_BACK, + callback_data=json.dumps( + {'t': QueryType.MemberList.value, 'id': user.member.squad_id} + ))]) return InlineKeyboardMarkup(inline_keys) @@ -272,8 +279,14 @@ def generate_squad_members(members, session): character.defence), callback_data=json.dumps( {'t': QueryType.ShowHero.value, - 'id': character.user_id} + 'id': character.user_id, + 'b': True} ))]) + inline_keys.append( + [InlineKeyboardButton(MSG_BACK, + callback_data=json.dumps( + {'t': QueryType.SquadList.value} + ))]) return InlineKeyboardMarkup(inline_keys) @@ -541,26 +554,32 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): elif data['t'] == QueryType.ShowEquip.value: user = session.query(User).filter_by(id=data['id']).first() update.callback_query.answer(text=MSG_CLEARED) + back = data['b'] if 'b' in data else False bot.editMessageText('{}\n🕑 Последнее обновление {}'.format(user.equip.equip, user.equip.date), update.callback_query.message.chat.id, update.callback_query.message.message_id, - reply_markup=generate_profile_buttons(user)) + reply_markup=generate_profile_buttons(user, back) + ) elif data['t'] == QueryType.ShowStock.value: user = session.query(User).filter_by(id=data['id']).first() update.callback_query.answer(text=MSG_CLEARED) + back = data['b'] if 'b' in data else False bot.editMessageText('{}\n🕑 Последнее обновление {}'. format(user.stock.stock, user.stock.date.strftime("%Y-%m-%d %H:%M:%S")), update.callback_query.message.chat.id, update.callback_query.message.message_id, - reply_markup=generate_profile_buttons(user)) + reply_markup=generate_profile_buttons(user, back) + ) elif data['t'] == QueryType.ShowHero.value: user = session.query(User).filter_by(id=data['id']).first() update.callback_query.answer(text=MSG_CLEARED) + back = data['b'] if 'b' in data else False bot.editMessageText(fill_char_template(MSG_PROFILE_SHOW_FORMAT, user, user.character), update.callback_query.message.chat.id, update.callback_query.message.message_id, - reply_markup=generate_profile_buttons(user)) + reply_markup=generate_profile_buttons(user, back) + ) elif data['t'] == QueryType.MemberList.value: squad = session.query(Squad).filter_by(chat_id=data['id']).first() markup = generate_squad_members(squad.members, session) @@ -681,3 +700,22 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): update.callback_query.message.chat.id, update.callback_query.message.message_id, reply_markup=markup) + elif data['t'] == QueryType.SquadList.value: + admin = session.query(Admin).filter_by(user_id=update.callback_query.from_user.id).all() + global_adm = False + for adm in admin: + if adm.admin_type <= AdminType.FULL.value: + global_adm = True + break + if global_adm: + squads = session.query(Squad).all() + else: + group_ids = [] + for adm in admin: + group_ids.append(adm.admin_group) + squads = session.query(Squad).filter(Squad.chat_id in group_ids).all() + markup = generate_squad_list(squads, session) + bot.editMessageText(MSG_SQUAD_LIST, + update.callback_query.message.chat.id, + update.callback_query.message.message_id, + reply_markup=markup) From 95dc135d05d258a939292a90e86f8eb1d6d47eae Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 3 Oct 2017 13:16:36 +0300 Subject: [PATCH 076/284] PY-2017.2.3 + \ No newline at end of file From 8c5995f5ac9ef768e82493e562e9b23f9c49399f Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 3 Oct 2017 13:35:38 +0300 Subject: [PATCH 077/284] =?UTF-8?q?=D0=9B=D0=B2=D0=BB=20=D0=B2=20=D1=81?= =?UTF-8?q?=D0=BA=D0=BF=D0=B8=D1=81=D0=BA=D0=B5=20=D0=BE=D1=82=D1=80=D1=8F?= =?UTF-8?q?=D0=B4=D0=B0=20=D0=B8=20=D1=81=D0=BE=D1=80=D1=82=D0=B8=D1=80?= =?UTF-8?q?=D0=BE=D0=B2=D0=BA=D0=B0=20=D0=BF=D0=BE=20=D0=BB=D0=B2=D0=BB?= =?UTF-8?q?=D1=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index 6a5ff3c..b903483 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -270,13 +270,15 @@ def generate_squad_members(members, session): filter(Character.user_id.in_(user_ids)). \ group_by(Character.user_id).all() characters = session.query(Character).filter(Character.user_id.in_([a[0] for a in actual_profiles]), - Character.date.in_([a[1] for a in actual_profiles])).all() + Character.date.in_([a[1] for a in actual_profiles]))\ + .order_by(Character.level.desc()).all() for character in characters: inline_keys.append( - [InlineKeyboardButton('{}: {}⚔ {}🛡'. + [InlineKeyboardButton('{}: {}⚔ {}🛡 {}🏅'. format(character.name, character.attack, - character.defence), + character.defence, + character.level), callback_data=json.dumps( {'t': QueryType.ShowHero.value, 'id': character.user_id, From 7bc1065a09e27694a05dc70aac703977ccfddbcc Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 3 Oct 2017 14:22:28 +0300 Subject: [PATCH 078/284] =?UTF-8?q?=D0=A4=D0=B8=D0=BA=D1=81=20=D0=BA=D0=BD?= =?UTF-8?q?=D0=BE=D0=BF=D0=BE=D0=BA=20=D0=B0=D0=B4=D0=BC=D0=B8=D0=BD=D0=B0?= =?UTF-8?q?=D0=BC=20=D0=B3=D1=80=D1=83=D0=BF=D0=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/squad.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/functions/squad.py b/core/functions/squad.py index 8491baa..82b15d8 100644 --- a/core/functions/squad.py +++ b/core/functions/squad.py @@ -97,7 +97,7 @@ def squad_list(bot: Bot, update: Update, session): group_ids = [] for adm in admin: group_ids.append(adm.admin_group) - squads = session.query(Squad).filter(Squad.chat_id in group_ids).all() + squads = session.query(Squad).filter(Squad.chat_id.in_(group_ids)).all() markup = generate_squad_list(squads, session) send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_LIST, reply_markup=markup) From 2cc0bf3084a457d9e708430ebecd76a6e4df557f Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 3 Oct 2017 14:32:08 +0300 Subject: [PATCH 079/284] =?UTF-8?q?=D0=A3=D0=B1=D1=80=D0=B0=D0=BB=D0=B8=20?= =?UTF-8?q?=D1=85=D0=B0=D1=80=D0=B4=D0=BA=D0=BE=D0=B4=20id=20=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/welcome.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/functions/welcome.py b/core/functions/welcome.py index fce1ae7..e38b522 100644 --- a/core/functions/welcome.py +++ b/core/functions/welcome.py @@ -23,7 +23,7 @@ def welcome(bot: Bot, update: Update, session): if adm.admin_type == AdminType.FULL.value: allow_anywhere = True break - if len(group.squad) == 1 and group.squad[0].thorns_enabled and user.id != 386494081 and \ + if len(group.squad) == 1 and group.squad[0].thorns_enabled and user.id != bot.id and \ (user.member or user.member not in group.squad[0].members) and not allow_anywhere: send_async(bot, chat_id=update.message.chat.id, text=MSG_THORNS.format(str(user))) From a6c98d5fac6c97695caad07344a59e1b02189f9e Mon Sep 17 00:00:00 2001 From: toxydose Date: Tue, 3 Oct 2017 14:45:43 +0300 Subject: [PATCH 080/284] =?UTF-8?q?=D0=BF=D0=B5=D1=80=D0=B5=D0=BD=D0=BE?= =?UTF-8?q?=D1=81=20=D1=82=D0=B5=D0=BA=D1=81=D1=82=D0=BE=D0=B2=20=D0=B2=20?= =?UTF-8?q?texts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/api.py | 6 +++--- core/functions/inline_keyboard_handling.py | 4 ++-- core/functions/reply_markup.py | 10 ++++----- core/functions/squad.py | 8 ++++---- core/functions/triggers.py | 4 ++-- core/texts.py | 24 ++++++++++++++++++++++ main.py | 8 ++++---- 7 files changed, 44 insertions(+), 20 deletions(-) diff --git a/core/functions/api.py b/core/functions/api.py index f37ffed..c19c008 100644 --- a/core/functions/api.py +++ b/core/functions/api.py @@ -3,7 +3,7 @@ import flask from werkzeug.routing import IntegerConverter as BaseIntegerConverter - +from core.texts import MSG_READY_FOR_BATTLE from core.types import Order, Session, Squad, SquadMember, OrderCleared from sqlalchemy.exc import SQLAlchemyError @@ -26,13 +26,13 @@ def new_ready_to_battle(chat_id): order = Order() order.chat_id = chat_id order.confirmed_msg = 0 - order.text = 'К битве готовсь!' + order.text = MSG_READY_FOR_BATTLE order.date = datetime.now() session.add(order) session.commit() order = session.query(Order).filter_by(chat_id=chat_id, date=order.date, - text='К битве готовсь!').first() + text=MSG_READY_FOR_BATTLE).first() return flask.Response(status=200, mimetype="application/json", diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index b903483..dc94b04 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -303,10 +303,10 @@ def generate_squad_request_answer(user_id): def generate_squad_invite_answer(user_id): - inline_keys = [InlineKeyboardButton('✅Зелёное Да', + inline_keys = [InlineKeyboardButton(MSG_SQUAD_GREEN_INLINE_BUTTON, callback_data=json.dumps( {'t': QueryType.InviteSquadAccept.value, 'id': user_id})), - InlineKeyboardButton('❌Красное Да', + InlineKeyboardButton(MSG_SQUAD_RED_INLINE_BUTTON, callback_data=json.dumps( {'t': QueryType.InviteSquadDecline.value, 'id': user_id}))] return InlineKeyboardMarkup([inline_keys]) diff --git a/core/functions/reply_markup.py b/core/functions/reply_markup.py index df5b2fd..a603caa 100644 --- a/core/functions/reply_markup.py +++ b/core/functions/reply_markup.py @@ -1,11 +1,11 @@ from telegram import ReplyKeyboardMarkup, KeyboardButton - +from core.texts import * def generate_admin_markup(full=False, grp=False): - buttons = [[KeyboardButton('Приказы')]] + buttons = [[KeyboardButton(MSG_ORDER_BUTTON)]] if full: - buttons.append([KeyboardButton('Статус'), KeyboardButton('Группы')]) + buttons.append([KeyboardButton(MSG_STATUS_BUTTON), KeyboardButton(MSG_GROUP_BUTTON)]) if grp: - buttons.append([KeyboardButton('Заявки в отряд'), KeyboardButton('Чистка отряда')]) - buttons.append([KeyboardButton('Список отряда')]) + buttons.append([KeyboardButton(MSG_CLAIM_BUTTON), KeyboardButton(MSG_CLEAN_BUTTON)]) + buttons.append([KeyboardButton(MSG_SQUAD_LIST_BUTTON)]) return ReplyKeyboardMarkup(buttons, True) diff --git a/core/functions/squad.py b/core/functions/squad.py index 8491baa..b18730b 100644 --- a/core/functions/squad.py +++ b/core/functions/squad.py @@ -114,7 +114,7 @@ def squad_request(bot: Bot, update: Update, session): markup = generate_squad_request(session) send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_REQUEST, reply_markup=markup) else: - send_async(bot, chat_id=update.message.chat.id, text='Сначала дай мне профиль!') + send_async(bot, chat_id=update.message.chat.id, text=MSG_NO_PROFILE_IN_BOT) @admin_allowed(AdminType.GROUP) @@ -145,7 +145,7 @@ def open_hiring(bot: Bot, update: Update, session): squad.hiring = True session.add(squad) session.commit() - send_async(bot, chat_id=update.message.chat.id, text='Набор открыт') + send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_RECRUITING_ENABLED) @admin_allowed(AdminType.GROUP) @@ -155,7 +155,7 @@ def close_hiring(bot: Bot, update: Update, session): squad.hiring = False session.add(squad) session.commit() - send_async(bot, chat_id=update.message.chat.id, text='Набор закрыт') + send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_RECRUITING_DISABLED) @admin_allowed(AdminType.GROUP) @@ -192,4 +192,4 @@ def add_to_squad(bot: Bot, update: Update, session): send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_ADD_IN_SQUAD.format('@' + username)) elif user.character is None: - send_async(bot, chat_id=update.message.chat.id, text='Сначала пусть даст профиль!') + send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_NO_PROFILE) diff --git a/core/functions/triggers.py b/core/functions/triggers.py index 60f8e95..2c8ddf5 100644 --- a/core/functions/triggers.py +++ b/core/functions/triggers.py @@ -161,8 +161,8 @@ def list_triggers(bot: Bot, update: Update, session): triggers = session.query(Trigger).all() local_triggers = session.query(LocalTrigger).filter_by(chat_id=update.message.chat.id).all() msg = MSG_TRIGGER_LIST_HEADER + \ - 'Глобальные:\n' + ('\n'.join([trigger.trigger for trigger in triggers]) or MSG_EMPTY) + \ - '\nЛокальные:\n' + ('\n'.join([trigger.trigger for trigger in local_triggers]) or MSG_EMPTY) + MSG_TRIGGER_GLOBAL + ('\n'.join([trigger.trigger for trigger in triggers]) or MSG_EMPTY) + \ + MSG_TRIGGER_LOCAL + ('\n'.join([trigger.trigger for trigger in local_triggers]) or MSG_EMPTY) send_async(bot, chat_id=update.message.chat.id, text=msg, parse_mode=ParseMode.HTML) diff --git a/core/texts.py b/core/texts.py index ce54084..b2a881b 100644 --- a/core/texts.py +++ b/core/texts.py @@ -143,9 +143,31 @@ %pet% 🕑 Последнее обновление %date%""" +# main.py texts +MSG_MAIN_INLINE_BATTLE = 'ГРАБЬНАСИЛУЙУБИВАЙ!' +MSG_MAIN_READY_TO_BATTLE = 'К битве готовсь!' +# ----------------------- + +# reply_markup buttons +MSG_ORDER_BUTTON = 'Приказы' +MSG_STATUS_BUTTON = 'Статус' +MSG_GROUP_BUTTON = 'Группы' +MSG_CLAIM_BUTTON = 'Заявки в отряд' +MSG_CLEAN_BUTTON = 'Чистка отряда' +MSG_SQUAD_LIST_BUTTON = 'Список отряда' +# ------------------------ + MSG_PROFILE_NOT_FOUND = 'В мятных записях ещё нет данных об этом герое' MSG_SQUAD_REQUEST_EMPTY = 'На данный момент к вам никто не хочет.' +MSG_READY_FOR_BATTLE = 'К битве готовсь!' + +MSG_NO_PROFILE_IN_BOT = 'Сначала дай мне профиль!' +MSG_SQUAD_RECRUITING_ENABLED = 'Набор открыт!' +MSG_SQUAD_RECRUITING_DISABLED = 'Набор закрыт!' +MSG_SQUAD_NO_PROFILE = 'Сначала пусть даст профиль!' +MSG_SQUAD_GREEN_INLINE_BUTTON ='✅Зелёное Да' +MSG_SQUAD_RED_INLINE_BUTTON = '❌Красное Да' MSG_SQUAD_NEW = """Теперь здесь будет обитать отряд {}! Не забудьте задать ссылку для приглашения новых участников.""" MSG_SQUAD_LINK_SAVED = """Ссылка приглашений сохранена! @@ -157,6 +179,8 @@ теперь каждый может видеть происходящее' MSG_TRIGGER_NEW = 'Триггер на фразу "{}" установлен.' +MSG_TRIGGER_GLOBAL = 'Глобальные:\n' +MSG_TRIGGER_LOCAL = '\nЛокальные:\n' MSG_TRIGGER_NEW_ERROR = 'Какие-то у тебя несвежие мысли, попробуй ещё раз.' MSG_TRIGGER_EXISTS = 'Триггер "{}" уже существует, выбери другой.' MSG_TRIGGER_ALL_ENABLED = 'Теперь триггерить могут все.' diff --git a/main.py b/main.py index 3ce0ddb..03fd078 100644 --- a/main.py +++ b/main.py @@ -54,8 +54,8 @@ ) from core.regexp import PROFILE, HERO from core.texts import ( - MSG_SQUAD_READY, MSG_FULL_TEXT_LINE, MSG_FULL_TEXT_TOTAL -) + MSG_SQUAD_READY, MSG_FULL_TEXT_LINE, MSG_FULL_TEXT_TOTAL, + MSG_MAIN_INLINE_BATTLE, MSG_MAIN_READY_TO_BATTLE) from core.types import Session, Order, Squad, Admin, user_allowed from core.utils import add_user, send_async @@ -214,7 +214,7 @@ def ready_to_battle(bot: Bot, job_queue): group = session.query(Squad).all() for item in group: new_order = Order() - new_order.text = 'К битве готовсь!' + new_order.text = MSG_MAIN_READY_TO_BATTLE new_order.chat_id = item.chat_id new_order.date = datetime.now() new_order.confirmed_msg = 0 @@ -224,7 +224,7 @@ def ready_to_battle(bot: Bot, job_queue): callback_data = json.dumps( {'t': QueryType.OrderOk.value, 'id': new_order.id}) markup = InlineKeyboardMarkup([ - [InlineKeyboardButton('ГРАБЬНАСИЛУЙУБИВАЙ!', + [InlineKeyboardButton(MSG_MAIN_INLINE_BATTLE, callback_data=callback_data)]]) msg = send_order(bot, new_order.text, 0, new_order.chat_id, markup) From db325109fb1cea5894f3e117a4d9b82f80283b99 Mon Sep 17 00:00:00 2001 From: toxydose Date: Tue, 3 Oct 2017 15:13:43 +0300 Subject: [PATCH 081/284] .. --- core/functions/api.py | 6 +++--- core/texts.py | 2 -- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/core/functions/api.py b/core/functions/api.py index c19c008..e9bf3ac 100644 --- a/core/functions/api.py +++ b/core/functions/api.py @@ -3,7 +3,7 @@ import flask from werkzeug.routing import IntegerConverter as BaseIntegerConverter -from core.texts import MSG_READY_FOR_BATTLE +from core.texts import MSG_MAIN_READY_TO_BATTLE from core.types import Order, Session, Squad, SquadMember, OrderCleared from sqlalchemy.exc import SQLAlchemyError @@ -26,13 +26,13 @@ def new_ready_to_battle(chat_id): order = Order() order.chat_id = chat_id order.confirmed_msg = 0 - order.text = MSG_READY_FOR_BATTLE + order.text = MSG_MAIN_READY_TO_BATTLE order.date = datetime.now() session.add(order) session.commit() order = session.query(Order).filter_by(chat_id=chat_id, date=order.date, - text=MSG_READY_FOR_BATTLE).first() + text=MSG_MAIN_READY_TO_BATTLE).first() return flask.Response(status=200, mimetype="application/json", diff --git a/core/texts.py b/core/texts.py index b2a881b..30eb0b4 100644 --- a/core/texts.py +++ b/core/texts.py @@ -160,8 +160,6 @@ MSG_PROFILE_NOT_FOUND = 'В мятных записях ещё нет данных об этом герое' MSG_SQUAD_REQUEST_EMPTY = 'На данный момент к вам никто не хочет.' -MSG_READY_FOR_BATTLE = 'К битве готовсь!' - MSG_NO_PROFILE_IN_BOT = 'Сначала дай мне профиль!' MSG_SQUAD_RECRUITING_ENABLED = 'Набор открыт!' MSG_SQUAD_RECRUITING_DISABLED = 'Набор закрыт!' From 8f56835cd60939f8943692329a87c1c8bd66aa2e Mon Sep 17 00:00:00 2001 From: toxydose Date: Tue, 3 Oct 2017 15:22:05 +0300 Subject: [PATCH 082/284] =?UTF-8?q?=D0=B2=D0=B5=D1=80=D0=BD=D1=83=D0=BB=20?= =?UTF-8?q?=D0=BD=D0=B0=D0=B7=D0=B0=D0=B4=20=D0=BD=D0=B5=D0=B8=D0=BD=D0=BB?= =?UTF-8?q?=D0=B0=D0=B9=D0=BD=20=D0=BA=D0=BD=D0=BE=D0=BF=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/reply_markup.py | 10 +++++----- core/texts.py | 10 +--------- 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/core/functions/reply_markup.py b/core/functions/reply_markup.py index a603caa..df5b2fd 100644 --- a/core/functions/reply_markup.py +++ b/core/functions/reply_markup.py @@ -1,11 +1,11 @@ from telegram import ReplyKeyboardMarkup, KeyboardButton -from core.texts import * + def generate_admin_markup(full=False, grp=False): - buttons = [[KeyboardButton(MSG_ORDER_BUTTON)]] + buttons = [[KeyboardButton('Приказы')]] if full: - buttons.append([KeyboardButton(MSG_STATUS_BUTTON), KeyboardButton(MSG_GROUP_BUTTON)]) + buttons.append([KeyboardButton('Статус'), KeyboardButton('Группы')]) if grp: - buttons.append([KeyboardButton(MSG_CLAIM_BUTTON), KeyboardButton(MSG_CLEAN_BUTTON)]) - buttons.append([KeyboardButton(MSG_SQUAD_LIST_BUTTON)]) + buttons.append([KeyboardButton('Заявки в отряд'), KeyboardButton('Чистка отряда')]) + buttons.append([KeyboardButton('Список отряда')]) return ReplyKeyboardMarkup(buttons, True) diff --git a/core/texts.py b/core/texts.py index 30eb0b4..bb2b6ba 100644 --- a/core/texts.py +++ b/core/texts.py @@ -148,14 +148,6 @@ MSG_MAIN_READY_TO_BATTLE = 'К битве готовсь!' # ----------------------- -# reply_markup buttons -MSG_ORDER_BUTTON = 'Приказы' -MSG_STATUS_BUTTON = 'Статус' -MSG_GROUP_BUTTON = 'Группы' -MSG_CLAIM_BUTTON = 'Заявки в отряд' -MSG_CLEAN_BUTTON = 'Чистка отряда' -MSG_SQUAD_LIST_BUTTON = 'Список отряда' -# ------------------------ MSG_PROFILE_NOT_FOUND = 'В мятных записях ещё нет данных об этом герое' MSG_SQUAD_REQUEST_EMPTY = 'На данный момент к вам никто не хочет.' @@ -164,7 +156,7 @@ MSG_SQUAD_RECRUITING_ENABLED = 'Набор открыт!' MSG_SQUAD_RECRUITING_DISABLED = 'Набор закрыт!' MSG_SQUAD_NO_PROFILE = 'Сначала пусть даст профиль!' -MSG_SQUAD_GREEN_INLINE_BUTTON ='✅Зелёное Да' +MSG_SQUAD_GREEN_INLINE_BUTTON = '✅Зелёное Да' MSG_SQUAD_RED_INLINE_BUTTON = '❌Красное Да' MSG_SQUAD_NEW = """Теперь здесь будет обитать отряд {}! Не забудьте задать ссылку для приглашения новых участников.""" From f67c77553cc6861f875d0f10fd64bd386e115c93 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 3 Oct 2017 18:20:56 +0300 Subject: [PATCH 083/284] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B4=D0=B5?= =?UTF-8?q?=D0=BB=D0=B0=D0=BD=D0=B0=20=D1=81=D0=B8=D1=81=D1=82=D0=B5=D0=BC?= =?UTF-8?q?=D0=B0=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4=20=D0=B8=20=D0=BF?= =?UTF-8?q?=D1=80=D0=B8=D0=BA=D0=B0=D0=B7=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/commands.py | 14 ++++ core/functions/inline_keyboard_handling.py | 79 ++++++++++++---------- core/functions/orders.py | 1 + core/functions/reply_markup.py | 21 +++--- core/texts.py | 2 +- main.py | 24 ++++--- 6 files changed, 86 insertions(+), 55 deletions(-) create mode 100644 core/commands.py diff --git a/core/commands.py b/core/commands.py new file mode 100644 index 0000000..30d3bc1 --- /dev/null +++ b/core/commands.py @@ -0,0 +1,14 @@ +ADMIN_COMMAND_ORDER = 'Приказы' +ADMIN_COMMAND_STATUS = 'Статус' +ADMIN_COMMAND_GROUPS = 'Группы' +ADMIN_COMMAND_RECRUIT = 'Заявки в отряд' +ADMIN_COMMAND_FIRE_UP = 'Чистка отряда' +ADMIN_COMMAND_SQUAD_LIST = 'Список отряда' +ADMIN_COMMAND_ADMINPANNEL = '/admin' + +USER_COMMAND_ME = 'Герой' +USER_COMMAND_TOP = 'Топ' +USER_COMMAND_SQUAD = 'Отряд' +USER_COMMAND_STATISTICS = 'Статистика' +USER_COMMAND_BUILD = 'Стройка' +USER_COMMAND_CONTACTS = 'Связь' diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index dc94b04..a9d9a7a 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -324,42 +324,46 @@ def generate_fire_up(members): @run_async def send_order(bot, order, order_type, chat_id, markup): - msg_sent = None - if order_type == MessageType.AUDIO.value: - msg_sent = bot.send_audio(chat_id, order, reply_markup=markup) - elif order_type == MessageType.DOCUMENT.value: - msg_sent = bot.send_document(chat_id, order, reply_markup=markup) - elif order_type == MessageType.VOICE.value: - msg_sent = bot.send_voice(chat_id, order, reply_markup=markup) - elif order_type == MessageType.STICKER.value: - msg_sent = bot.send_sticker(chat_id, order, reply_markup=markup) - elif order_type == MessageType.CONTACT.value: - msg = order.replace('\'', '"') - contact = loads(msg) - if 'phone_number' not in contact.keys(): - contact['phone_number'] = None - if 'first_name' not in contact.keys(): - contact['first_name'] = None - if 'last_name' not in contact.keys(): - contact['last_name'] = None - msg_sent = bot.send_contact(chat_id, - contact['phone_number'], - contact['first_name'], - contact['last_name'], - reply_markup=markup) - elif order_type == MessageType.VIDEO.value: - msg_sent = bot.send_video(chat_id, order, reply_markup=markup) - elif order_type == MessageType.VIDEO_NOTE.value: - msg_sent = bot.send_video_note(chat_id, order, reply_markup=markup) - elif order_type == MessageType.LOCATION.value: - msg = order.replace('\'', '"') - location = loads(msg) - msg_sent = bot.send_location(chat_id, location['latitude'], location['longitude'], reply_markup=markup) - elif order_type == MessageType.PHOTO.value: - msg_sent = bot.send_photo(chat_id, order, reply_markup=markup) - else: - msg_sent = send_async(bot, chat_id=chat_id, text=order, disable_web_page_preview=True, reply_markup=markup) - return msg_sent + try: + msg_sent = None + if order_type == MessageType.AUDIO.value: + msg_sent = bot.send_audio(chat_id, order, reply_markup=markup) + elif order_type == MessageType.DOCUMENT.value: + msg_sent = bot.send_document(chat_id, order, reply_markup=markup) + elif order_type == MessageType.VOICE.value: + msg_sent = bot.send_voice(chat_id, order, reply_markup=markup) + elif order_type == MessageType.STICKER.value: + msg_sent = bot.send_sticker(chat_id, order, reply_markup=markup) + elif order_type == MessageType.CONTACT.value: + msg = order.replace('\'', '"') + contact = loads(msg) + if 'phone_number' not in contact.keys(): + contact['phone_number'] = None + if 'first_name' not in contact.keys(): + contact['first_name'] = None + if 'last_name' not in contact.keys(): + contact['last_name'] = None + msg_sent = bot.send_contact(chat_id, + contact['phone_number'], + contact['first_name'], + contact['last_name'], + reply_markup=markup) + elif order_type == MessageType.VIDEO.value: + msg_sent = bot.send_video(chat_id, order, reply_markup=markup) + elif order_type == MessageType.VIDEO_NOTE.value: + msg_sent = bot.send_video_note(chat_id, order, reply_markup=markup) + elif order_type == MessageType.LOCATION.value: + msg = order.replace('\'', '"') + location = loads(msg) + msg_sent = bot.send_location(chat_id, location['latitude'], location['longitude'], reply_markup=markup) + elif order_type == MessageType.PHOTO.value: + msg_sent = bot.send_photo(chat_id, order, reply_markup=markup) + else: + msg_sent = send_async(bot, chat_id=chat_id, text=order, disable_web_page_preview=True, reply_markup=markup) + return msg_sent + except TelegramError as err: + bot.logger.error(err.message) + return None @run_async @@ -407,7 +411,7 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): session.add(order) session.commit() markup = generate_ok_markup(order.id, 0) - msg = send_order(bot, order.text, order_type, order.chat_id, markup).result().result() + msg = send_order(bot, order.text, order_type, order.chat_id, markup).result() if order_pin and msg: try: bot.request.post(bot.base_url + '/pinChatMessage', {'chat_id': order.chat_id, @@ -494,6 +498,7 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): update.callback_query.message.message_id, reply_markup=markup) elif data['t'] == QueryType.OrderGroup.value: + chat_data['order_wait'] = False if 'txt' in data and len(data['txt']): chat_data['order_type'] = MessageType.TEXT if data['txt'] == Icons.LES.value: diff --git a/core/functions/orders.py b/core/functions/orders.py index b6cc52f..ba8a8fc 100644 --- a/core/functions/orders.py +++ b/core/functions/orders.py @@ -47,4 +47,5 @@ def order(bot: Bot, update: Update, session, chat_data): @admin_allowed(adm_type=AdminType.GROUP) def orders(bot: Bot, update: Update, session, chat_data): markup = generate_flag_orders() + chat_data['order_wait'] = True send_async(bot, chat_id=update.message.chat.id, text=MSG_FLAG_CHOOSE_HEADER, reply_markup=markup) diff --git a/core/functions/reply_markup.py b/core/functions/reply_markup.py index c5b7345..d4a5730 100644 --- a/core/functions/reply_markup.py +++ b/core/functions/reply_markup.py @@ -1,19 +1,24 @@ from telegram import ReplyKeyboardMarkup, KeyboardButton +from core.commands import ADMIN_COMMAND_ORDER, ADMIN_COMMAND_STATUS, ADMIN_COMMAND_GROUPS, ADMIN_COMMAND_RECRUIT, \ + ADMIN_COMMAND_FIRE_UP, ADMIN_COMMAND_SQUAD_LIST, USER_COMMAND_ME, USER_COMMAND_TOP, USER_COMMAND_SQUAD, \ + USER_COMMAND_STATISTICS, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, ADMIN_COMMAND_ADMINPANNEL + def generate_admin_markup(full=False, grp=False): - buttons = [[KeyboardButton('Приказы')]] + buttons = [[KeyboardButton(ADMIN_COMMAND_ORDER)]] if full: - buttons.append([KeyboardButton('Статус'), KeyboardButton('Группы')]) + buttons.append([KeyboardButton(ADMIN_COMMAND_STATUS), KeyboardButton(ADMIN_COMMAND_GROUPS)]) if grp: - buttons.append([KeyboardButton('Заявки в отряд'), KeyboardButton('Чистка отряда')]) - buttons.append([KeyboardButton('Список отряда')]) + buttons.append([KeyboardButton(ADMIN_COMMAND_RECRUIT), KeyboardButton(ADMIN_COMMAND_FIRE_UP)]) + buttons.append([KeyboardButton(ADMIN_COMMAND_SQUAD_LIST)]) return ReplyKeyboardMarkup(buttons, True) def generate_user_markup(is_admin=False): - buttons = [[KeyboardButton('Герой'), KeyboardButton('Топ')], - [KeyboardButton('Отряд'), KeyboardButton('Статистика')], - [KeyboardButton('Стройка'), KeyboardButton('Связь')]] + buttons = [[KeyboardButton(USER_COMMAND_ME), KeyboardButton(USER_COMMAND_TOP)], + [KeyboardButton(USER_COMMAND_SQUAD), KeyboardButton(USER_COMMAND_STATISTICS)], + [KeyboardButton(USER_COMMAND_BUILD), KeyboardButton(USER_COMMAND_CONTACTS)]] if is_admin: - buttons.append([KeyboardButton('/admin')]) + buttons.append([KeyboardButton(ADMIN_COMMAND_ADMINPANNEL)]) + return ReplyKeyboardMarkup(buttons, True) diff --git a/core/texts.py b/core/texts.py index bb2b6ba..c0abf5e 100644 --- a/core/texts.py +++ b/core/texts.py @@ -123,7 +123,7 @@ MSG_NEWBIE = """Новый игрок в замке!\n Все на вербовку %username%!""" -MSG_FLAG_CHOOSE_HEADER = 'Выбирай' +MSG_FLAG_CHOOSE_HEADER = 'Выбери флаг из списка или отправь мне любой другой приказ' MSG_PROFILE_OLD = 'Твой профиль завял, нужно что-то посвежей...' MSG_PROFILE_SAVED = """Располагайся в зарослях мяты, {}! diff --git a/main.py b/main.py index a99769f..11c5caf 100644 --- a/main.py +++ b/main.py @@ -16,6 +16,8 @@ from telegram.error import TelegramError from config import TOKEN, GOVERNMENT_CHAT +from core.commands import ADMIN_COMMAND_STATUS, ADMIN_COMMAND_RECRUIT, ADMIN_COMMAND_ORDER, ADMIN_COMMAND_SQUAD_LIST, \ + ADMIN_COMMAND_GROUPS, ADMIN_COMMAND_FIRE_UP, USER_COMMAND_ME from core.functions.activity import ( day_activity, week_activity, battle_activity ) @@ -169,23 +171,28 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): trigger_show(bot, update) elif update.message.chat.type == 'private': - if update.message.text: + if 'order_wait' in chat_data and chat_data['order_wait']: + order(bot, update, chat_data) + + elif update.message.text: text = update.message.text.lower() - if text == 'статус': + if text == ADMIN_COMMAND_STATUS.lower(): send_status(bot, update) elif text == 'хочу в отряд': squad_request(bot, update) - elif text == 'заявки в отряд': + elif text == ADMIN_COMMAND_RECRUIT.lower(): list_squad_requests(bot, update) - elif text in ['приказы', 'пин']: + elif text == ADMIN_COMMAND_ORDER.lower(): orders(bot, update, chat_data) - elif text in ['список отряда', 'список']: + elif text == ADMIN_COMMAND_SQUAD_LIST.lower(): squad_list(bot, update) - elif text == 'группы': + elif text == ADMIN_COMMAND_GROUPS.lower(): group_list(bot, update) - elif text == 'чистка отряда': + elif text == ADMIN_COMMAND_FIRE_UP.lower(): remove_from_squad(bot, update) + elif text == USER_COMMAND_ME.lower(): + char_show(bot, update) elif 'wait_group_name' in chat_data and chat_data['wait_group_name']: add_group(bot, update, chat_data) @@ -203,9 +210,8 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): trade_compare(bot, update, chat_data) else: user_panel(bot, update) - order(bot, update, chat_data) else: - order(bot, update, chat_data) + user_panel(bot, update) @run_async From cce92ce1c7ae7fe874aba7514d841ded26cdab09 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 3 Oct 2017 18:22:48 +0300 Subject: [PATCH 084/284] =?UTF-8?q?=D0=91=D0=BE=D0=BB=D1=8C=D1=88=D0=B5=20?= =?UTF-8?q?=D0=BD=D0=B5=20=D0=B6=D0=B4=D1=91=D0=BC=20=D0=BF=D0=BE=D0=B2?= =?UTF-8?q?=D1=82=D0=BE=D1=80=D0=BD=D0=BE=D0=B3=D0=BE=20=D0=BF=D1=80=D0=B8?= =?UTF-8?q?=D0=BA=D0=B0=D0=B7=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 1 - core/functions/orders.py | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index a9d9a7a..67b8504 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -498,7 +498,6 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): update.callback_query.message.message_id, reply_markup=markup) elif data['t'] == QueryType.OrderGroup.value: - chat_data['order_wait'] = False if 'txt' in data and len(data['txt']): chat_data['order_type'] = MessageType.TEXT if data['txt'] == Icons.LES.value: diff --git a/core/functions/orders.py b/core/functions/orders.py index ba8a8fc..35be737 100644 --- a/core/functions/orders.py +++ b/core/functions/orders.py @@ -7,6 +7,7 @@ @admin_allowed(adm_type=AdminType.GROUP) def order(bot: Bot, update: Update, session, chat_data): + chat_data['order_wait'] = False admin_user = session.query(Admin).filter(Admin.user_id == update.message.from_user.id).all() markup = generate_order_groups_markup(session, admin_user, chat_data['pin'] if 'pin' in chat_data else True) msg = update.message From f80257256c3b4a8eb315afa1a5eb3464f03941c6 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 3 Oct 2017 18:32:50 +0300 Subject: [PATCH 085/284] =?UTF-8?q?=D0=98=20=D0=BD=D0=B0=20=D1=81=D1=82?= =?UTF-8?q?=D0=B0=D1=80=D1=82=20=D1=82=D0=BE=D0=B6=D0=B5=20=D0=BA=D0=BD?= =?UTF-8?q?=D0=BE=D0=BF=D0=B0=D1=87=D0=BA=D0=B8=20=D0=B2=D1=8B=D0=B4=D0=B0?= =?UTF-8?q?=D1=91=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index 11c5caf..89dbe8f 100644 --- a/main.py +++ b/main.py @@ -314,7 +314,7 @@ def main(): disp = updater.dispatcher # on different commands - answer in Telegram - disp.add_handler(CommandHandler("start", start)) + disp.add_handler(CommandHandler("start", user_panel)) disp.add_handler(CommandHandler("admin", admin_panel)) disp.add_handler(CommandHandler("help", help_msg)) disp.add_handler(CommandHandler("ping", ping)) From 7d26c965231cedecac34b58a7a49b5bd0f44d0d7 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Wed, 4 Oct 2017 15:35:07 +0300 Subject: [PATCH 086/284] =?UTF-8?q?=D0=97=D0=B0=D0=B1=D1=8B=D0=BB=D0=B8=20?= =?UTF-8?q?=D1=81=D1=82=D1=80=D0=BE=D1=87=D0=BA=D1=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index 03fd078..a6998ca 100644 --- a/main.py +++ b/main.py @@ -257,7 +257,7 @@ def ready_to_battle_result(bot: Bot, job_queue): for item in group: ready_order = session.query(Order).filter_by( chat_id=item.chat_id, - text='К битве готовсь!').order_by(Order.date.desc()).first() + text=MSG_MAIN_READY_TO_BATTLE).order_by(Order.date.desc()).first() if ready_order is not None: attack = 0 From c107c6ccd99a375ad27555680a95a4af616096e6 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Wed, 4 Oct 2017 15:40:08 +0300 Subject: [PATCH 087/284] =?UTF-8?q?=D0=A7=D1=83=D1=82=D1=8C=20=D1=81=20?= =?UTF-8?q?=D0=BB=D0=BE=D0=B3=D0=B3=D0=B5=D1=80=D0=BE=D0=BC=20=D0=BA=D0=BE?= =?UTF-8?q?=D1=81=D1=8F=D0=BA=D0=BD=D1=83=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/main.py b/main.py index a6998ca..f064cc7 100644 --- a/main.py +++ b/main.py @@ -237,10 +237,10 @@ def ready_to_battle(bot: Bot, job_queue): 'disable_notification': False}) except TelegramError as err: - bot.logger(err.message) + bot.logger.error(err.message) except SQLAlchemyError as err: - bot.logger(str(err)) + bot.logger.error(str(err)) Session.rollback() @@ -295,7 +295,7 @@ def ready_to_battle_result(bot: Bot, job_queue): parse_mode=ParseMode.HTML) except SQLAlchemyError as err: - bot.logger(str(err)) + bot.logger.error(str(err)) Session.rollback() From 2cd10c5dfe3ec5a8130efbd21245cac862c7359b Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Wed, 4 Oct 2017 16:16:55 +0300 Subject: [PATCH 088/284] =?UTF-8?q?=D0=92=D0=BE=D0=B7=D0=BC=D0=BE=D0=B6?= =?UTF-8?q?=D0=BD=D0=BE=D1=81=D1=82=D1=8C=20=D1=83=D0=B4=D0=B0=D0=BB=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20=D0=BE=D1=82=D1=80=D1=8F=D0=B4=20=D0=B8=D0=B7=20?= =?UTF-8?q?=D0=BB=D0=B8=D1=87=D0=BA=D0=B8=20=D0=B1=D0=BE=D1=82=D0=B0=20?= =?UTF-8?q?=D0=B8=20=D1=84=D0=B8=D0=BA=D1=81=20=D0=BF=D0=BE=D0=B4=D0=B3?= =?UTF-8?q?=D0=BE=D1=82=D0=BE=D0=B2=D0=BA=D0=B8=20=D0=BA=20=D0=B1=D0=B8?= =?UTF-8?q?=D1=82=D0=B2=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 21 +++++++++++++++++++++ main.py | 9 +++++---- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index dc94b04..ee6a7a0 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -48,6 +48,7 @@ class QueryType(Enum): InviteSquadDecline = 21 TriggerOrderPin = 22 SquadList = 23 + GroupDelete = 24 @admin_allowed() @@ -82,6 +83,8 @@ def generate_group_info(group_id, session): MSG_ON if group.welcome_enabled else MSG_OFF, MSG_ON if group.allow_trigger_all else MSG_OFF, MSG_ON if len(group.squad) and group.squad[0].thorns_enabled else MSG_OFF) + adm_del_keys.append([InlineKeyboardButton(MSG_ORDER_GROUP_DEL, callback_data=json.dumps( + {'t': QueryType.GroupDelete.value, 'gid': group_id}))]) adm_del_keys.append([InlineKeyboardButton(MSG_BACK, callback_data=json.dumps( {'t': QueryType.GroupList.value}))]) inline_markup = InlineKeyboardMarkup(adm_del_keys) @@ -721,3 +724,21 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): update.callback_query.message.chat.id, update.callback_query.message.message_id, reply_markup=markup) + elif data['t'] == QueryType.GroupDelete.value: + squad = session.query(Squad).filter_by(chat_id=data['gid']).first() + if squad is not None: + for member in squad.members: + session.delete(member) + session.delete(squad) + session.commit() + send_async(bot, chat_id=data['gid'], text=MSG_SQUAD_DELETE) + msg = MSG_GROUP_STATUS_CHOOSE_CHAT + squads = session.query(Squad).all() + inline_keys = [] + for squad in squads: + inline_keys.append(InlineKeyboardButton(squad.squad_name, + callback_data=json.dumps({'t': QueryType.GroupInfo.value, + 'id': squad.chat_id}))) + inline_markup = InlineKeyboardMarkup([[key] for key in inline_keys]) + bot.editMessageText(msg, update.callback_query.message.chat.id, update.callback_query.message.message_id, + reply_markup=inline_markup) diff --git a/main.py b/main.py index f064cc7..bca095e 100644 --- a/main.py +++ b/main.py @@ -231,10 +231,11 @@ def ready_to_battle(bot: Bot, job_queue): try: msg = msg.result().result() - bot.request.post(bot.base_url + '/pinChatMessage', - {'chat_id': new_order.chat_id, - 'message_id': msg.message_id, - 'disable_notification': False}) + if msg is not None: + bot.request.post(bot.base_url + '/pinChatMessage', + {'chat_id': new_order.chat_id, + 'message_id': msg.message_id, + 'disable_notification': False}) except TelegramError as err: bot.logger.error(err.message) From 6fec729f7fce7c41ef45233ab337fde3df8c7515 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Thu, 5 Oct 2017 11:58:33 +0300 Subject: [PATCH 089/284] =?UTF-8?q?=D0=A4=D0=B8=D0=BA=D1=81=20=D0=BF=D0=BE?= =?UTF-8?q?=D0=BA=D0=B0=D0=B7=D0=B0=20=D1=82=D1=80=D0=B8=D0=B3=D0=B3=D0=B5?= =?UTF-8?q?=D1=80=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/main.py b/main.py index bca095e..81ed131 100644 --- a/main.py +++ b/main.py @@ -161,11 +161,13 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): delete_msg(bot, update) elif text == 'свали': delete_user(bot, update) + else: + trigger_show(bot, update) elif 'твои результаты в бою:' in text: if update.message.forward_from.id == CWBOT_ID: job_queue.run_once(del_msg, 2, (update.message.chat.id, update.message.message_id)) - elif update.message.text: + else: trigger_show(bot, update) elif update.message.chat.type == 'private': From 6ca569841ce830529c7db1291bb6ff579b62b17c Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Fri, 6 Oct 2017 11:57:17 +0300 Subject: [PATCH 090/284] =?UTF-8?q?=D0=9A=D0=BD=D0=BE=D0=BF=D0=BA=D0=B8=20?= =?UTF-8?q?=D1=8E=D0=B7=D0=B5=D1=80=D0=B0=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/texts.py | 2 ++ main.py | 44 ++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/core/texts.py b/core/texts.py index c0abf5e..f44a305 100644 --- a/core/texts.py +++ b/core/texts.py @@ -222,3 +222,5 @@ MSG_SQUAD_READY = '{} бойцов отряда {} к битве готовы!\n{}⚔ {}🛡' MSG_FULL_TEXT_LINE = '{}: {}👥 {}⚔ {}🛡\n' MSG_FULL_TEXT_TOTAL = '\nВсего: {}👥 {}⚔ {}🛡' + +MSG_IN_DEV = 'Функция находится в разработке =(' diff --git a/main.py b/main.py index 5b33f98..e8dfab1 100644 --- a/main.py +++ b/main.py @@ -17,7 +17,8 @@ from config import TOKEN, GOVERNMENT_CHAT from core.commands import ADMIN_COMMAND_STATUS, ADMIN_COMMAND_RECRUIT, ADMIN_COMMAND_ORDER, ADMIN_COMMAND_SQUAD_LIST, \ - ADMIN_COMMAND_GROUPS, ADMIN_COMMAND_FIRE_UP, USER_COMMAND_ME + ADMIN_COMMAND_GROUPS, ADMIN_COMMAND_FIRE_UP, USER_COMMAND_ME, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS,\ + USER_COMMAND_SQUAD, USER_COMMAND_STATISTICS, USER_COMMAND_TOP from core.functions.activity import ( day_activity, week_activity, battle_activity ) @@ -57,7 +58,7 @@ from core.regexp import PROFILE, HERO from core.texts import ( MSG_SQUAD_READY, MSG_FULL_TEXT_LINE, MSG_FULL_TEXT_TOTAL, - MSG_MAIN_INLINE_BATTLE, MSG_MAIN_READY_TO_BATTLE) + MSG_MAIN_INLINE_BATTLE, MSG_MAIN_READY_TO_BATTLE, MSG_IN_DEV) from core.types import Session, Order, Squad, Admin, user_allowed from core.utils import add_user, send_async @@ -173,6 +174,12 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): trigger_show(bot, update) elif update.message.chat.type == 'private': + admin = session.query(Admin).filter_by(user_id=update.message.from_user.id).all() + is_admin = False + for _ in admin: + is_admin = True + break + if 'order_wait' in chat_data and chat_data['order_wait']: order(bot, update, chat_data) @@ -195,6 +202,31 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): remove_from_squad(bot, update) elif text == USER_COMMAND_ME.lower(): char_show(bot, update) + elif text == USER_COMMAND_BUILD.lower(): + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_IN_DEV, + parse_mode=ParseMode.HTML) + elif text == USER_COMMAND_TOP.lower(): + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_IN_DEV, + parse_mode=ParseMode.HTML) + elif text == USER_COMMAND_STATISTICS.lower(): + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_IN_DEV, + parse_mode=ParseMode.HTML) + elif text == USER_COMMAND_SQUAD.lower(): + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_IN_DEV, + parse_mode=ParseMode.HTML) + elif text == USER_COMMAND_CONTACTS.lower(): + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_IN_DEV, + parse_mode=ParseMode.HTML) elif 'wait_group_name' in chat_data and chat_data['wait_group_name']: add_group(bot, update, chat_data) @@ -210,10 +242,14 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): elif from_id == TRADEBOT_ID: if '📦твой склад с материалами:' in text: trade_compare(bot, update, chat_data) - else: + elif not is_admin: user_panel(bot, update) - else: + else: + order(bot, update, chat_data) + elif not is_admin: user_panel(bot, update) + else: + order(bot, update, chat_data) @run_async From 1c9168a547ea92c2e6bd8db21eb0e0364b27f25f Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Fri, 6 Oct 2017 12:03:50 +0300 Subject: [PATCH 091/284] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D1=85=D0=BE?= =?UTF-8?q?=D0=B4=20=D0=B8=D0=B7=20=D0=B0=D0=B4=D0=BC=D0=B8=D0=BD=D0=BA?= =?UTF-8?q?=D0=B8=20=D0=B2=20=D1=8E=D0=B7=D0=B5=D1=80=D0=BF=D0=B0=D0=BD?= =?UTF-8?q?=D0=B5=D0=BB=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/commands.py | 3 ++- core/functions/reply_markup.py | 6 ++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/core/commands.py b/core/commands.py index 30d3bc1..a0bb5dc 100644 --- a/core/commands.py +++ b/core/commands.py @@ -4,7 +4,8 @@ ADMIN_COMMAND_RECRUIT = 'Заявки в отряд' ADMIN_COMMAND_FIRE_UP = 'Чистка отряда' ADMIN_COMMAND_SQUAD_LIST = 'Список отряда' -ADMIN_COMMAND_ADMINPANNEL = '/admin' +ADMIN_COMMAND_ADMINPANEL = '/admin' +ADMIN_COMMAND_TO_USER_PANEL = '/start' USER_COMMAND_ME = 'Герой' USER_COMMAND_TOP = 'Топ' diff --git a/core/functions/reply_markup.py b/core/functions/reply_markup.py index d4a5730..dea6c4d 100644 --- a/core/functions/reply_markup.py +++ b/core/functions/reply_markup.py @@ -2,7 +2,8 @@ from core.commands import ADMIN_COMMAND_ORDER, ADMIN_COMMAND_STATUS, ADMIN_COMMAND_GROUPS, ADMIN_COMMAND_RECRUIT, \ ADMIN_COMMAND_FIRE_UP, ADMIN_COMMAND_SQUAD_LIST, USER_COMMAND_ME, USER_COMMAND_TOP, USER_COMMAND_SQUAD, \ - USER_COMMAND_STATISTICS, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, ADMIN_COMMAND_ADMINPANNEL + USER_COMMAND_STATISTICS, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, ADMIN_COMMAND_ADMINPANEL,\ + ADMIN_COMMAND_TO_USER_PANEL def generate_admin_markup(full=False, grp=False): @@ -12,6 +13,7 @@ def generate_admin_markup(full=False, grp=False): if grp: buttons.append([KeyboardButton(ADMIN_COMMAND_RECRUIT), KeyboardButton(ADMIN_COMMAND_FIRE_UP)]) buttons.append([KeyboardButton(ADMIN_COMMAND_SQUAD_LIST)]) + buttons.append([KeyboardButton(ADMIN_COMMAND_TO_USER_PANEL)]) return ReplyKeyboardMarkup(buttons, True) @@ -20,5 +22,5 @@ def generate_user_markup(is_admin=False): [KeyboardButton(USER_COMMAND_SQUAD), KeyboardButton(USER_COMMAND_STATISTICS)], [KeyboardButton(USER_COMMAND_BUILD), KeyboardButton(USER_COMMAND_CONTACTS)]] if is_admin: - buttons.append([KeyboardButton(ADMIN_COMMAND_ADMINPANNEL)]) + buttons.append([KeyboardButton(ADMIN_COMMAND_ADMINPANEL)]) return ReplyKeyboardMarkup(buttons, True) From 79f031de4739b1d426c2661aa3bee55b1949bacf Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Fri, 6 Oct 2017 12:30:19 +0300 Subject: [PATCH 092/284] =?UTF-8?q?=D0=A7=D1=83=D1=82=D1=8C=20=D0=BF=D0=B5?= =?UTF-8?q?=D1=80=D0=B5=D0=B4=D0=B5=D0=BB=D0=B0=D0=BD=D0=B0=20=D0=BA=D0=BD?= =?UTF-8?q?=D0=BE=D0=BF=D0=BA=D0=B0=20=D0=BE=D1=82=D1=80=D1=8F=D0=B4=D0=B0?= =?UTF-8?q?=20=D0=B8=20=D0=BF=D0=B5=D1=80=D0=B5=D1=85=D0=BE=D0=B4=20=D0=B8?= =?UTF-8?q?=D0=B7=20=D0=B0=D0=B4=D0=BC=D0=B8=D0=BD=D0=BA=D0=B8=20=D0=B2=20?= =?UTF-8?q?=D1=8E=D0=B7=D0=B5=D1=80=D0=BF=D0=B0=D0=BD=D0=B5=D0=BB=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/commands.py | 4 +++- core/functions/common.py | 5 +++-- core/functions/reply_markup.py | 17 ++++++++++------- main.py | 8 +++++--- 4 files changed, 21 insertions(+), 13 deletions(-) diff --git a/core/commands.py b/core/commands.py index a0bb5dc..294b1fa 100644 --- a/core/commands.py +++ b/core/commands.py @@ -5,7 +5,6 @@ ADMIN_COMMAND_FIRE_UP = 'Чистка отряда' ADMIN_COMMAND_SQUAD_LIST = 'Список отряда' ADMIN_COMMAND_ADMINPANEL = '/admin' -ADMIN_COMMAND_TO_USER_PANEL = '/start' USER_COMMAND_ME = 'Герой' USER_COMMAND_TOP = 'Топ' @@ -13,3 +12,6 @@ USER_COMMAND_STATISTICS = 'Статистика' USER_COMMAND_BUILD = 'Стройка' USER_COMMAND_CONTACTS = 'Связь' +USER_COMMAND_SQUAD_REQUEST = 'Хочу в отряд' + +USER_COMMAND_BACK = '🔙Назад' diff --git a/core/functions/common.py b/core/functions/common.py index c10ceb4..3cc74dc 100644 --- a/core/functions/common.py +++ b/core/functions/common.py @@ -7,7 +7,7 @@ from core.functions.triggers import trigger_decorator from core.functions.reply_markup import generate_admin_markup, generate_user_markup from core.texts import * -from core.types import AdminType, Admin, Stock, admin_allowed, user_allowed +from core.types import AdminType, Admin, Stock, admin_allowed, user_allowed, SquadMember from core.utils import send_async, add_user @@ -55,8 +55,9 @@ def user_panel(bot: Bot, update: Update, session): for _ in admin: is_admin = True break + squad_member = session.query(SquadMember).filter_by(user_id=update.message.from_user.id).first() send_async(bot, chat_id=update.message.chat.id, text=MSG_START_WELCOME, - reply_markup=generate_user_markup(is_admin)) + reply_markup=generate_user_markup(is_admin, True if squad_member else False)) @admin_allowed() diff --git a/core/functions/reply_markup.py b/core/functions/reply_markup.py index dea6c4d..7dfc185 100644 --- a/core/functions/reply_markup.py +++ b/core/functions/reply_markup.py @@ -2,8 +2,8 @@ from core.commands import ADMIN_COMMAND_ORDER, ADMIN_COMMAND_STATUS, ADMIN_COMMAND_GROUPS, ADMIN_COMMAND_RECRUIT, \ ADMIN_COMMAND_FIRE_UP, ADMIN_COMMAND_SQUAD_LIST, USER_COMMAND_ME, USER_COMMAND_TOP, USER_COMMAND_SQUAD, \ - USER_COMMAND_STATISTICS, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, ADMIN_COMMAND_ADMINPANEL,\ - ADMIN_COMMAND_TO_USER_PANEL + USER_COMMAND_STATISTICS, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, ADMIN_COMMAND_ADMINPANEL, \ + USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK def generate_admin_markup(full=False, grp=False): @@ -13,14 +13,17 @@ def generate_admin_markup(full=False, grp=False): if grp: buttons.append([KeyboardButton(ADMIN_COMMAND_RECRUIT), KeyboardButton(ADMIN_COMMAND_FIRE_UP)]) buttons.append([KeyboardButton(ADMIN_COMMAND_SQUAD_LIST)]) - buttons.append([KeyboardButton(ADMIN_COMMAND_TO_USER_PANEL)]) + buttons.append([KeyboardButton(USER_COMMAND_BACK)]) return ReplyKeyboardMarkup(buttons, True) -def generate_user_markup(is_admin=False): - buttons = [[KeyboardButton(USER_COMMAND_ME), KeyboardButton(USER_COMMAND_TOP)], - [KeyboardButton(USER_COMMAND_SQUAD), KeyboardButton(USER_COMMAND_STATISTICS)], - [KeyboardButton(USER_COMMAND_BUILD), KeyboardButton(USER_COMMAND_CONTACTS)]] +def generate_user_markup(is_admin=False, in_squad=False): + buttons = [[KeyboardButton(USER_COMMAND_ME), KeyboardButton(USER_COMMAND_TOP)]] + if not in_squad: + buttons.append([KeyboardButton(USER_COMMAND_SQUAD_REQUEST), KeyboardButton(USER_COMMAND_STATISTICS)]) + else: + buttons.append([KeyboardButton(USER_COMMAND_SQUAD), KeyboardButton(USER_COMMAND_STATISTICS)]) + buttons.append([KeyboardButton(USER_COMMAND_BUILD), KeyboardButton(USER_COMMAND_CONTACTS)]) if is_admin: buttons.append([KeyboardButton(ADMIN_COMMAND_ADMINPANEL)]) return ReplyKeyboardMarkup(buttons, True) diff --git a/main.py b/main.py index e8dfab1..0995bc0 100644 --- a/main.py +++ b/main.py @@ -17,8 +17,8 @@ from config import TOKEN, GOVERNMENT_CHAT from core.commands import ADMIN_COMMAND_STATUS, ADMIN_COMMAND_RECRUIT, ADMIN_COMMAND_ORDER, ADMIN_COMMAND_SQUAD_LIST, \ - ADMIN_COMMAND_GROUPS, ADMIN_COMMAND_FIRE_UP, USER_COMMAND_ME, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS,\ - USER_COMMAND_SQUAD, USER_COMMAND_STATISTICS, USER_COMMAND_TOP + ADMIN_COMMAND_GROUPS, ADMIN_COMMAND_FIRE_UP, USER_COMMAND_ME, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, \ + USER_COMMAND_SQUAD, USER_COMMAND_STATISTICS, USER_COMMAND_TOP, USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK from core.functions.activity import ( day_activity, week_activity, battle_activity ) @@ -188,7 +188,9 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): if text == ADMIN_COMMAND_STATUS.lower(): send_status(bot, update) - elif text == 'хочу в отряд': + elif text == USER_COMMAND_BACK.lower(): + user_panel(bot, update) + elif text == USER_COMMAND_SQUAD_REQUEST.lower(): squad_request(bot, update) elif text == ADMIN_COMMAND_RECRUIT.lower(): list_squad_requests(bot, update) From d8730bed6d86de542383b4564ad1c04b861af030 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Mon, 9 Oct 2017 11:47:29 +0300 Subject: [PATCH 093/284] =?UTF-8?q?=D0=9E=D1=82=D0=BC=D0=B5=D1=87=D0=B0?= =?UTF-8?q?=D0=B5=D0=BC=20outdated=20=D0=BF=D1=80=D0=BE=D1=84=D0=B8=D0=BB?= =?UTF-8?q?=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index 2d1d723..5687117 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -276,9 +276,20 @@ def generate_squad_members(members, session): Character.date.in_([a[1] for a in actual_profiles]))\ .order_by(Character.level.desc()).all() for character in characters: + time_passed = datetime.now() - character.date + status_emoji = '' + if time_passed > timedelta(days=7): + status_emoji = '⁉' + if time_passed > timedelta(days=4): + status_emoji = '‼' + if time_passed > timedelta(days=3): + status_emoji = '❗' + elif time_passed < timedelta(days=1): + status_emoji = '🕐' inline_keys.append( - [InlineKeyboardButton('{}: {}⚔ {}🛡 {}🏅'. - format(character.name, + [InlineKeyboardButton('{}{}: {}⚔ {}🛡 {}🏅'. + format(status_emoji, + character.name, character.attack, character.defence, character.level), From dd3b38aadfd102600f7d2f8b96dd70c87db55744 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Mon, 9 Oct 2017 12:00:25 +0300 Subject: [PATCH 094/284] =?UTF-8?q?=D0=91=D1=8B=D1=81=D1=82=D1=80=D0=BE?= =?UTF-8?q?=D1=84=D0=B8=D0=BA=D1=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index 5687117..50ad563 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -280,9 +280,9 @@ def generate_squad_members(members, session): status_emoji = '' if time_passed > timedelta(days=7): status_emoji = '⁉' - if time_passed > timedelta(days=4): + elif time_passed > timedelta(days=4): status_emoji = '‼' - if time_passed > timedelta(days=3): + elif time_passed > timedelta(days=3): status_emoji = '❗' elif time_passed < timedelta(days=1): status_emoji = '🕐' From 261ea0a5c7122248d97c9b29ea1cfac8857b8db5 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Mon, 9 Oct 2017 12:12:17 +0300 Subject: [PATCH 095/284] =?UTF-8?q?=D0=A2=D0=B5=D0=BF=D0=B5=D1=80=D1=8C=20?= =?UTF-8?q?=D0=B7=D0=B5=D0=BB=D1=91=D0=BD=D0=B5=D0=BD=D1=8C=D0=BA=D0=B8?= =?UTF-8?q?=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index 50ad563..fff75c1 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -277,7 +277,7 @@ def generate_squad_members(members, session): .order_by(Character.level.desc()).all() for character in characters: time_passed = datetime.now() - character.date - status_emoji = '' + status_emoji = '❇' if time_passed > timedelta(days=7): status_emoji = '⁉' elif time_passed > timedelta(days=4): From 6b762e4a99407af326a01ada1284188e3ad408fa Mon Sep 17 00:00:00 2001 From: toxydose Date: Mon, 9 Oct 2017 20:56:00 +0300 Subject: [PATCH 096/284] =?UTF-8?q?=D0=B5=D1=89=D0=B5=20=D0=BD=D0=B5=D0=BC?= =?UTF-8?q?=D0=BD=D0=BE=D0=B3=D0=BE=20=D0=BF=D0=BE=20=D1=80=D0=B5=D0=BF?= =?UTF-8?q?=D0=BE=D1=80=D1=82=D0=B0=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/profile.py | 10 +++++++++- core/texts.py | 1 + main.py | 7 +++++-- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/core/functions/profile.py b/core/functions/profile.py index c00b3dd..7d7dbce 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -4,7 +4,7 @@ from core.regexp import HERO, PROFILE, REPORT from core.types import Character, Report, User, admin_allowed, Equip, user_allowed from core.utils import send_async -from datetime import timedelta +from datetime import timedelta, datetime import re from core.template import fill_char_template from core.texts import * @@ -88,6 +88,14 @@ def parse_reports(report, user_id, date, session): return report +@user_allowed +def report_recieved(bot: Bot, update: Update, session): + if datetime.now() - update.message.forward_date > timedelta(minutes=1): + send_async(bot, chat_id=update.message.chat.id, text=MSG_REPORT_OLD) + else: + if re.search(REPORT, update.message.text): + print('success') + @user_allowed def char_update(bot: Bot, update: Update, session): if update.message.date - update.message.forward_date > timedelta(minutes=1): diff --git a/core/texts.py b/core/texts.py index f44a305..89e4de4 100644 --- a/core/texts.py +++ b/core/texts.py @@ -148,6 +148,7 @@ MSG_MAIN_READY_TO_BATTLE = 'К битве готовсь!' # ----------------------- +MSG_REPORT_OLD = 'Твой репорт уже попахивает, в следующий раз постарайся прислать его в течении минуты после получения.' MSG_PROFILE_NOT_FOUND = 'В мятных записях ещё нет данных об этом герое' MSG_SQUAD_REQUEST_EMPTY = 'На данный момент к вам никто не хочет.' diff --git a/main.py b/main.py index 0995bc0..9b9f485 100644 --- a/main.py +++ b/main.py @@ -40,7 +40,7 @@ ) from core.functions.order_groups import group_list, add_group from core.functions.pin import pin, not_pin_all, pin_all, silent_pin -from core.functions.profile import char_update, char_show, find_by_username +from core.functions.profile import char_update, char_show, find_by_username, report_recieved from core.functions.squad import ( add_squad, del_squad, set_invite_link, set_squad_name, enable_thorns, disable_thorns, @@ -55,7 +55,7 @@ from core.functions.welcome import ( welcome, set_welcome, show_welcome, enable_welcome, disable_welcome ) -from core.regexp import PROFILE, HERO +from core.regexp import PROFILE, HERO, REPORT from core.texts import ( MSG_SQUAD_READY, MSG_FULL_TEXT_LINE, MSG_FULL_TEXT_TOTAL, MSG_MAIN_INLINE_BATTLE, MSG_MAIN_READY_TO_BATTLE, MSG_IN_DEV) @@ -168,6 +168,7 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): trigger_show(bot, update) elif 'твои результаты в бою:' in text: if update.message.forward_from.id == CWBOT_ID: + report_recieved(bot, update) job_queue.run_once(del_msg, 2, (update.message.chat.id, update.message.message_id)) else: @@ -240,6 +241,8 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): stock_compare(bot, update, chat_data) elif re.search(PROFILE, update.message.text) or re.search(HERO, update.message.text): char_update(bot, update) + elif re.search(REPORT, update.message.text): + report_recieved(bot, update) elif from_id == TRADEBOT_ID: if '📦твой склад с материалами:' in text: From a347b1b64232777ad28a385aa4fc1c590ef31e40 Mon Sep 17 00:00:00 2001 From: toxydose Date: Mon, 9 Oct 2017 21:11:57 +0300 Subject: [PATCH 097/284] =?UTF-8?q?=D0=BE=D0=BF=D0=B5=D1=87=D0=B0=D1=82?= =?UTF-8?q?=D0=BA=D0=B0=20=D0=B2=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4?= =?UTF-8?q?=D0=B5=20"=D1=81=D1=82=D0=B0=D1=82=D0=B8=D1=81=D1=82=D0=B8?= =?UTF-8?q?=D0=BA=D0=B0=20=D0=B7=D0=B0=20=D0=BD=D0=B5=D0=B4=D0=B5=D0=BB?= =?UTF-8?q?=D1=8E"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index 9b9f485..7a31dd4 100644 --- a/main.py +++ b/main.py @@ -129,7 +129,7 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): ping(bot, update) elif text == 'статистика за день': day_activity(bot, update) - elif text == 'cтатистика за неделю': + elif text == 'статистика за неделю': week_activity(bot, update) elif text == 'cтатистика за бой': battle_activity(bot, update) From 6081fa5a3f1e9332d006720d1fa838577a0a7e56 Mon Sep 17 00:00:00 2001 From: toxydose Date: Mon, 9 Oct 2017 21:14:22 +0300 Subject: [PATCH 098/284] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BE=D0=BF=D0=B5=D1=87=D0=B0=D1=82=D0=BA=D1=83?= =?UTF-8?q?=20=D0=B2=20"=D1=81=D1=82=D0=B0=D1=82=D0=B8=D1=81=D1=82=D0=B8?= =?UTF-8?q?=D0=BA=D0=B0=20=D0=B7=D0=B0=20=D0=B1=D0=BE=D0=B9"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index 7a31dd4..f52847e 100644 --- a/main.py +++ b/main.py @@ -131,7 +131,7 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): day_activity(bot, update) elif text == 'статистика за неделю': week_activity(bot, update) - elif text == 'cтатистика за бой': + elif text == 'статистика за бой': battle_activity(bot, update) elif text == 'разрешить триггерить всем': enable_trigger_all(bot, update) From 760700253b15800f9fb89fbb40740520a559fcfa Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Mon, 9 Oct 2017 21:29:45 +0300 Subject: [PATCH 099/284] =?UTF-8?q?=D0=94=D0=BE=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D0=BA=D0=B8=20=D0=BF=D0=BE=20=D1=80=D0=B5=D0=BF=D0=BE?= =?UTF-8?q?=D1=80=D1=82=D0=B0=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/profile.py | 22 ++++++++++++++++++---- core/texts.py | 2 ++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/core/functions/profile.py b/core/functions/profile.py index 7d7dbce..146e8e2 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -90,11 +90,25 @@ def parse_reports(report, user_id, date, session): @user_allowed def report_recieved(bot: Bot, update: Update, session): - if datetime.now() - update.message.forward_date > timedelta(minutes=1): - send_async(bot, chat_id=update.message.chat.id, text=MSG_REPORT_OLD) - else: - if re.search(REPORT, update.message.text): + # if datetime.now() - update.message.forward_date > timedelta(minutes=1): + # send_async(bot, chat_id=update.message.chat.id, text=MSG_REPORT_OLD) + # else: + report = re.search(REPORT, update.message.text) + user = session.query(User).filter_by(id=update.message.from_user.id).first() + if report and user.character and str(report.group(2)) == user.character.name: + time_from = datetime(update.message.forward_date.year, update.message.forward_date.month, + update.message.forward_date.day, int(update.message.forward_date.hour / 4) * 4, 0, 0) + time_to = datetime(update.message.forward_date.year, update.message.forward_date.month, + update.message.forward_date.day + (1 if update.message.forward_date.hour >= 20 else 0), + int(update.message.forward_date.hour / 4 + 1) * 4 % 24, 0, 0) + report = session.query(Report).filter(Report.date > time_from, Report.date < time_to).all() + if len(report) == 0: print('success') + parse_reports(update.message.text, update.message.from_user.id, update.message.forward_date, session) + send_async(bot, chat_id=update.message.from_user.id, text=MSG_REPORT_OK) + else: + send_async(bot, chat_id=update.message.from_user.id, text=MSG_REPORT_EXISTS) + @user_allowed def char_update(bot: Bot, update: Update, session): diff --git a/core/texts.py b/core/texts.py index 89e4de4..83a9fb1 100644 --- a/core/texts.py +++ b/core/texts.py @@ -149,6 +149,8 @@ # ----------------------- MSG_REPORT_OLD = 'Твой репорт уже попахивает, в следующий раз постарайся прислать его в течении минуты после получения.' +MSG_REPORT_EXISTS = 'Репорт за эту битву уже внесён.' +MSG_REPORT_OK = 'Спасибо. Не забывай кидать репорты каждую битву.' MSG_PROFILE_NOT_FOUND = 'В мятных записях ещё нет данных об этом герое' MSG_SQUAD_REQUEST_EMPTY = 'На данный момент к вам никто не хочет.' From e1f5b0621465c246efe8f85f0bc1b4b9909022db Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Mon, 9 Oct 2017 21:31:30 +0300 Subject: [PATCH 100/284] =?UTF-8?q?=D0=9E=D0=B1=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D0=B0=D0=BB=D0=B8=20=D0=B8=D1=81=D0=BA=D0=BB=D1=8E=D1=87?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BD=D0=B0=20=D1=83=D0=B4=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/main.py b/main.py index f52847e..67c0c8d 100644 --- a/main.py +++ b/main.py @@ -84,7 +84,10 @@ def battle_time(): def del_msg(bot, job): - bot.delete_message(job.context[0], job.context[1]) + try: + bot.delete_message(job.context[0], job.context[1]) + except TelegramError: + pass @run_async From b45a4ccc64c8df97b0ee24452841c5f0c52fb039 Mon Sep 17 00:00:00 2001 From: toxydose Date: Mon, 9 Oct 2017 21:51:54 +0300 Subject: [PATCH 101/284] deleted debug print --- core/functions/profile.py | 1 - 1 file changed, 1 deletion(-) diff --git a/core/functions/profile.py b/core/functions/profile.py index 146e8e2..8a68c23 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -103,7 +103,6 @@ def report_recieved(bot: Bot, update: Update, session): int(update.message.forward_date.hour / 4 + 1) * 4 % 24, 0, 0) report = session.query(Report).filter(Report.date > time_from, Report.date < time_to).all() if len(report) == 0: - print('success') parse_reports(update.message.text, update.message.from_user.id, update.message.forward_date, session) send_async(bot, chat_id=update.message.from_user.id, text=MSG_REPORT_OK) else: From fabda53e2338306c5e186becf948ae8e2f37cc5a Mon Sep 17 00:00:00 2001 From: toxydose Date: Mon, 9 Oct 2017 22:01:13 +0300 Subject: [PATCH 102/284] typos fixed --- core/functions/profile.py | 2 +- main.py | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/core/functions/profile.py b/core/functions/profile.py index 8a68c23..92276a7 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -89,7 +89,7 @@ def parse_reports(report, user_id, date, session): @user_allowed -def report_recieved(bot: Bot, update: Update, session): +def report_received(bot: Bot, update: Update, session): # if datetime.now() - update.message.forward_date > timedelta(minutes=1): # send_async(bot, chat_id=update.message.chat.id, text=MSG_REPORT_OLD) # else: diff --git a/main.py b/main.py index 67c0c8d..df4ea66 100644 --- a/main.py +++ b/main.py @@ -40,7 +40,7 @@ ) from core.functions.order_groups import group_list, add_group from core.functions.pin import pin, not_pin_all, pin_all, silent_pin -from core.functions.profile import char_update, char_show, find_by_username, report_recieved +from core.functions.profile import char_update, char_show, find_by_username, report_received from core.functions.squad import ( add_squad, del_squad, set_invite_link, set_squad_name, enable_thorns, disable_thorns, @@ -171,7 +171,7 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): trigger_show(bot, update) elif 'твои результаты в бою:' in text: if update.message.forward_from.id == CWBOT_ID: - report_recieved(bot, update) + report_received(bot, update) job_queue.run_once(del_msg, 2, (update.message.chat.id, update.message.message_id)) else: @@ -245,7 +245,7 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): elif re.search(PROFILE, update.message.text) or re.search(HERO, update.message.text): char_update(bot, update) elif re.search(REPORT, update.message.text): - report_recieved(bot, update) + report_received(bot, update) elif from_id == TRADEBOT_ID: if '📦твой склад с материалами:' in text: From 868943c4174dc33e4fe444578786b010ca54e9eb Mon Sep 17 00:00:00 2001 From: toxydose Date: Mon, 9 Oct 2017 23:33:59 +0300 Subject: [PATCH 103/284] =?UTF-8?q?=D1=8D=D0=BC=D0=BE=D0=B4=D0=B7=D0=B8=20?= =?UTF-8?q?=D0=BD=D0=B0=20=D0=BA=D0=BD=D0=BE=D0=BF=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/commands.py | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/core/commands.py b/core/commands.py index 294b1fa..f39c891 100644 --- a/core/commands.py +++ b/core/commands.py @@ -1,17 +1,17 @@ -ADMIN_COMMAND_ORDER = 'Приказы' -ADMIN_COMMAND_STATUS = 'Статус' -ADMIN_COMMAND_GROUPS = 'Группы' -ADMIN_COMMAND_RECRUIT = 'Заявки в отряд' -ADMIN_COMMAND_FIRE_UP = 'Чистка отряда' -ADMIN_COMMAND_SQUAD_LIST = 'Список отряда' +ADMIN_COMMAND_ORDER = '⚔️Приказы' +ADMIN_COMMAND_STATUS = '🔎Статус' +ADMIN_COMMAND_GROUPS = '👥Группы' +ADMIN_COMMAND_RECRUIT = '📬Заявки в отряд' +ADMIN_COMMAND_FIRE_UP = '🔥Алтарь' +ADMIN_COMMAND_SQUAD_LIST = '🗂Список отряда' ADMIN_COMMAND_ADMINPANEL = '/admin' -USER_COMMAND_ME = 'Герой' -USER_COMMAND_TOP = 'Топ' -USER_COMMAND_SQUAD = 'Отряд' -USER_COMMAND_STATISTICS = 'Статистика' -USER_COMMAND_BUILD = 'Стройка' -USER_COMMAND_CONTACTS = 'Связь' -USER_COMMAND_SQUAD_REQUEST = 'Хочу в отряд' +USER_COMMAND_ME = '🏅Герой' +USER_COMMAND_TOP = '🌟Топ' +USER_COMMAND_SQUAD = '️Отряд' +USER_COMMAND_STATISTICS = '📊Статистика' +USER_COMMAND_BUILD = '🚧Стройка' +USER_COMMAND_CONTACTS = '💬Связь' +USER_COMMAND_SQUAD_REQUEST = '⚜Хочу в отряд' USER_COMMAND_BACK = '🔙Назад' From f02e89b2b1bf8406cc3c6bfbe9db3344d6928f7f Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Mon, 9 Oct 2017 23:49:45 +0300 Subject: [PATCH 104/284] =?UTF-8?q?=D0=A4=D0=B8=D0=BA=D1=81=20=D1=8D=D0=BC?= =?UTF-8?q?=D0=BE=D0=B4=D0=B6=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/commands.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/commands.py b/core/commands.py index f39c891..af38d5a 100644 --- a/core/commands.py +++ b/core/commands.py @@ -1,4 +1,4 @@ -ADMIN_COMMAND_ORDER = '⚔️Приказы' +ADMIN_COMMAND_ORDER = '⚔Приказы' ADMIN_COMMAND_STATUS = '🔎Статус' ADMIN_COMMAND_GROUPS = '👥Группы' ADMIN_COMMAND_RECRUIT = '📬Заявки в отряд' @@ -8,7 +8,7 @@ USER_COMMAND_ME = '🏅Герой' USER_COMMAND_TOP = '🌟Топ' -USER_COMMAND_SQUAD = '️Отряд' +USER_COMMAND_SQUAD = '⚜Отряд' USER_COMMAND_STATISTICS = '📊Статистика' USER_COMMAND_BUILD = '🚧Стройка' USER_COMMAND_CONTACTS = '💬Связь' From 4adadb0317f519561065c646b2dd1ba0783a3fbe Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 10 Oct 2017 10:57:25 +0300 Subject: [PATCH 105/284] =?UTF-8?q?=D0=A4=D0=B8=D0=BA=D1=81=20=D1=80=D0=B5?= =?UTF-8?q?=D0=BF=D0=BE=D1=80=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/profile.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/functions/profile.py b/core/functions/profile.py index 92276a7..12b57e5 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -101,7 +101,8 @@ def report_received(bot: Bot, update: Update, session): time_to = datetime(update.message.forward_date.year, update.message.forward_date.month, update.message.forward_date.day + (1 if update.message.forward_date.hour >= 20 else 0), int(update.message.forward_date.hour / 4 + 1) * 4 % 24, 0, 0) - report = session.query(Report).filter(Report.date > time_from, Report.date < time_to).all() + report = session.query(Report).filter(Report.date > time_from, Report.date < time_to, + Report.user_id == update.message.from_user.id).all() if len(report) == 0: parse_reports(update.message.text, update.message.from_user.id, update.message.forward_date, session) send_async(bot, chat_id=update.message.from_user.id, text=MSG_REPORT_OK) From 7607104d6a73801058d064e6607c2fa60f63a8cf Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 10 Oct 2017 12:57:45 +0300 Subject: [PATCH 106/284] =?UTF-8?q?=D0=9D=D0=B5=D0=BC=D0=BD=D0=BE=D0=B3?= =?UTF-8?q?=D0=BE=20=D1=82=D0=BE=D0=BF=D0=BE=D0=B2=20=D0=B8=20=D1=84=D0=B8?= =?UTF-8?q?=D0=BA=D1=81=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/commands.py | 4 ++ core/functions/inline_keyboard_handling.py | 10 +++- core/functions/reply_markup.py | 9 ++- core/functions/top.py | 68 ++++++++++++++++++++++ core/texts.py | 2 + main.py | 17 ++++-- 6 files changed, 102 insertions(+), 8 deletions(-) create mode 100644 core/functions/top.py diff --git a/core/commands.py b/core/commands.py index af38d5a..4e9bb97 100644 --- a/core/commands.py +++ b/core/commands.py @@ -15,3 +15,7 @@ USER_COMMAND_SQUAD_REQUEST = '⚜Хочу в отряд' USER_COMMAND_BACK = '🔙Назад' + +TOP_COMMAND_ATTACK = '⚔' +TOP_COMMAND_DEFENCE = '🛡' +TOP_COMMAND_EXP = '🔥' diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index fff75c1..36802b1 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -9,6 +9,7 @@ from core.enums import Castle, Icons from core.functions.admins import del_adm +from core.functions.reply_markup import generate_user_markup from core.template import fill_char_template from core.types import ( User, Group, Admin, admin_allowed, Order, OrderGroup, @@ -666,7 +667,14 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): bot.editMessageText(MSG_SQUAD_REQUEST_ACCEPTED.format('@'+member.user.username), update.callback_query.message.chat.id, update.callback_query.message.message_id) - send_async(bot, chat_id=member.user_id, text=MSG_SQUAD_REQUEST_ACCEPTED_ANSWER) + admin = session.query(Admin).filter_by(user_id=update.message.from_user.id).all() + is_admin = False + for _ in admin: + is_admin = True + break + squad_member = session.query(SquadMember).filter_by(user_id=update.message.from_user.id).first() + send_async(bot, chat_id=member.user_id, text=MSG_SQUAD_REQUEST_ACCEPTED_ANSWER, + reply_markup=generate_user_markup(is_admin, True if squad_member else False)) send_async(bot, chat_id=member.squad_id, text=MSG_SQUAD_REQUEST_ACCEPTED.format('@'+member.user.username)) elif data['t'] == QueryType.RequestSquadDecline.value: member = session.query(SquadMember).filter_by(user_id=data['id']).first() diff --git a/core/functions/reply_markup.py b/core/functions/reply_markup.py index 7dfc185..c174615 100644 --- a/core/functions/reply_markup.py +++ b/core/functions/reply_markup.py @@ -3,7 +3,7 @@ from core.commands import ADMIN_COMMAND_ORDER, ADMIN_COMMAND_STATUS, ADMIN_COMMAND_GROUPS, ADMIN_COMMAND_RECRUIT, \ ADMIN_COMMAND_FIRE_UP, ADMIN_COMMAND_SQUAD_LIST, USER_COMMAND_ME, USER_COMMAND_TOP, USER_COMMAND_SQUAD, \ USER_COMMAND_STATISTICS, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, ADMIN_COMMAND_ADMINPANEL, \ - USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK + USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK, TOP_COMMAND_ATTACK, TOP_COMMAND_DEFENCE, TOP_COMMAND_EXP def generate_admin_markup(full=False, grp=False): @@ -27,3 +27,10 @@ def generate_user_markup(is_admin=False, in_squad=False): if is_admin: buttons.append([KeyboardButton(ADMIN_COMMAND_ADMINPANEL)]) return ReplyKeyboardMarkup(buttons, True) + + +def generate_top_markup(): + buttons = [[KeyboardButton(TOP_COMMAND_ATTACK), KeyboardButton(TOP_COMMAND_DEFENCE), + KeyboardButton(TOP_COMMAND_EXP)], + [KeyboardButton(USER_COMMAND_BACK)]] + return ReplyKeyboardMarkup(buttons, True) diff --git a/core/functions/top.py b/core/functions/top.py new file mode 100644 index 0000000..d33c50a --- /dev/null +++ b/core/functions/top.py @@ -0,0 +1,68 @@ +from sqlalchemy import func, text as text_ +from telegram import Update, Bot + +from core.functions.reply_markup import generate_top_markup +from core.texts import MSG_TOP_ABOUT +from core.types import user_allowed, Character, SquadMember +from core.utils import send_async + + +@user_allowed +def top_about(bot: Bot, update: Update, session): + markup = generate_top_markup() + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_TOP_ABOUT, + reply_markup=markup) + + +def get_top(condition, session, header, field_name, icon, user_id, additional_filter=text_('')): + actual_profiles = session.query(Character.user_id, func.max(Character.date)). \ + group_by(Character.user_id).all() + characters = session.query(Character).filter(Character.user_id.in_([a[0] for a in actual_profiles]), + Character.date.in_([a[1] for a in actual_profiles]), + additional_filter)\ + .order_by(condition).all() + text = header + str_format = '{}. {} ({}🌟) - {}{}\n' + for i in range(min(10, len(characters))): + text += str_format.format(i + 1, characters[i].name, characters[i].level, + getattr(characters[i], field_name), icon) + if user_id in [character.user_id for character in characters]: + if user_id not in [character.user_id for character in characters[:10]]: + for i in range(10, len(characters)): + if characters[i].user_id == user_id: + text += '...\n' + text += str_format.format(i, characters[i - 1].name, characters[i-1].level, + getattr(characters[i-1], field_name), icon) + text += str_format.format(i + 1, characters[i].name, characters[i].level, + getattr(characters[i], field_name), icon) + if i != len(characters) - 1: + text += str_format.format(i + 2, characters[i + 1].name, characters[i+1].level, + getattr(characters[i+1], field_name), icon) + break + return text + + +@user_allowed +def attack_top(bot: Bot, update: Update, session): + text = get_top(Character.attack.desc(), session, '⚔Топ атакеры:\n', 'attack', '⚔', update.message.from_user.id) + send_async(bot, + chat_id=update.message.chat.id, + text=text) + + +@user_allowed +def def_top(bot: Bot, update: Update, session): + text = get_top(Character.defence.desc(), session, '🛡Топ дэферы:\n', 'defence', '🛡', update.message.from_user.id) + send_async(bot, + chat_id=update.message.chat.id, + text=text) + + +@user_allowed +def exp_top(bot: Bot, update: Update, session): + text = get_top(Character.exp.desc(), session, '🔥Топ качки:\n', 'exp', '🔥', update.message.from_user.id) + send_async(bot, + chat_id=update.message.chat.id, + text=text) diff --git a/core/texts.py b/core/texts.py index 83a9fb1..daea967 100644 --- a/core/texts.py +++ b/core/texts.py @@ -227,3 +227,5 @@ MSG_FULL_TEXT_TOTAL = '\nВсего: {}👥 {}⚔ {}🛡' MSG_IN_DEV = 'Функция находится в разработке =(' + +MSG_TOP_ABOUT = '🏆 Топы 🏆' diff --git a/main.py b/main.py index df4ea66..c0005be 100644 --- a/main.py +++ b/main.py @@ -18,7 +18,8 @@ from config import TOKEN, GOVERNMENT_CHAT from core.commands import ADMIN_COMMAND_STATUS, ADMIN_COMMAND_RECRUIT, ADMIN_COMMAND_ORDER, ADMIN_COMMAND_SQUAD_LIST, \ ADMIN_COMMAND_GROUPS, ADMIN_COMMAND_FIRE_UP, USER_COMMAND_ME, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, \ - USER_COMMAND_SQUAD, USER_COMMAND_STATISTICS, USER_COMMAND_TOP, USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK + USER_COMMAND_SQUAD, USER_COMMAND_STATISTICS, USER_COMMAND_TOP, USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK, \ + TOP_COMMAND_ATTACK, TOP_COMMAND_DEFENCE, TOP_COMMAND_EXP from core.functions.activity import ( day_activity, week_activity, battle_activity ) @@ -47,6 +48,7 @@ squad_list, squad_request, list_squad_requests, open_hiring, close_hiring, remove_from_squad, add_to_squad ) +from core.functions.top import top_about, attack_top, exp_top, def_top from core.functions.triggers import ( set_trigger, add_trigger, del_trigger, list_triggers, enable_trigger_all, disable_trigger_all, trigger_show, @@ -208,12 +210,15 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): remove_from_squad(bot, update) elif text == USER_COMMAND_ME.lower(): char_show(bot, update) - elif text == USER_COMMAND_BUILD.lower(): - send_async(bot, - chat_id=update.message.chat.id, - text=MSG_IN_DEV, - parse_mode=ParseMode.HTML) elif text == USER_COMMAND_TOP.lower(): + top_about(bot, update) + elif text == TOP_COMMAND_ATTACK.lower(): + attack_top(bot, update) + elif text == TOP_COMMAND_DEFENCE.lower(): + def_top(bot, update) + elif text == TOP_COMMAND_EXP.lower(): + exp_top(bot, update) + elif text == USER_COMMAND_BUILD.lower(): send_async(bot, chat_id=update.message.chat.id, text=MSG_IN_DEV, From 105e2e062cd97bfb10147c265c95a23c46dfdb54 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 10 Oct 2017 13:01:56 +0300 Subject: [PATCH 107/284] =?UTF-8?q?=D0=A3=D0=BF=D1=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index 36802b1..4df9a6a 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -667,12 +667,12 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): bot.editMessageText(MSG_SQUAD_REQUEST_ACCEPTED.format('@'+member.user.username), update.callback_query.message.chat.id, update.callback_query.message.message_id) - admin = session.query(Admin).filter_by(user_id=update.message.from_user.id).all() + admin = session.query(Admin).filter_by(user_id=member.user_id).all() is_admin = False for _ in admin: is_admin = True break - squad_member = session.query(SquadMember).filter_by(user_id=update.message.from_user.id).first() + squad_member = session.query(SquadMember).filter_by(user_id=member.user_id).first() send_async(bot, chat_id=member.user_id, text=MSG_SQUAD_REQUEST_ACCEPTED_ANSWER, reply_markup=generate_user_markup(is_admin, True if squad_member else False)) send_async(bot, chat_id=member.squad_id, text=MSG_SQUAD_REQUEST_ACCEPTED.format('@'+member.user.username)) From ce59dc28eb8fe4d960ff8614cefc386e4c14d805 Mon Sep 17 00:00:00 2001 From: toxydose Date: Tue, 10 Oct 2017 17:30:46 +0300 Subject: [PATCH 108/284] =?UTF-8?q?=D1=84=D0=B8=D0=BA=D1=81=D1=8B=20=D1=80?= =?UTF-8?q?=D0=B5=D0=BF=D0=BE=D1=80=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/profile.py | 15 ++++++++++++--- core/regexp.py | 7 +++---- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/core/functions/profile.py b/core/functions/profile.py index 12b57e5..7ad3211 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -80,9 +80,18 @@ def parse_reports(report, user_id, date, session): report.attack = str(parsed_data.group(3)) report.defence = str(parsed_data.group(4)) report.level = int(parsed_data.group(5)) - report.earned_exp = int(parsed_data.group(6)) - report.earned_gold = int(parsed_data.group(7)) - report.earned_stock = int(parsed_data.group(8)) + if parsed_data.group(6): + report.earned_exp = int(parsed_data.group(6)) + else: + report.earned_exp = 0 + if parsed_data.group(7): + report.earned_gold = int(parsed_data.group(7)) + else: + report.earned_gold = 0 + if parsed_data.group(8): + report.earned_stock = int(parsed_data.group(8)) + else: + report.earned_stock = 0 session.add(report) session.commit() return report diff --git a/core/regexp.py b/core/regexp.py index f9257be..9b2b23a 100644 --- a/core/regexp.py +++ b/core/regexp.py @@ -26,7 +26,6 @@ '(.+?) (?:.+?) (.+)? \(([0-9]+) ур\.\) (.+) /pet)?' REPORT = '(🇬🇵|🇮🇲|🇨🇾|🇻🇦|🇪🇺|🇲🇴|🇰🇮)(.+) ⚔️:([0-9]+) 🛡:([0-9]+) \(([0-9]+) ур.\)\n' \ - 'Твои результаты в бою:\n' \ - '🔥Опыт: ([0-9]+) ед\n' \ - '💰Золото: (-?[0-9]+)\n' \ - '📦Склад: (-?[0-9]+)' + 'Твои результаты в бою:(?:\n' \ + '🔥Опыт: ([0-9]+) ед)?(?:\n' \ + '💰Золото: (-?[0-9]+))?(?:\n📦Склад: (-?[0-9]+))?' From 8087c79a7dfcb0f5158d00d43c35b7d9fd63477b Mon Sep 17 00:00:00 2001 From: toxydose Date: Tue, 10 Oct 2017 17:39:05 +0300 Subject: [PATCH 109/284] 11 --- core/commands.py | 4 ++ core/functions/reply_markup.py | 9 ++++- core/functions/top.py | 68 ++++++++++++++++++++++++++++++++++ core/texts.py | 2 + main.py | 17 ++++++--- 5 files changed, 93 insertions(+), 7 deletions(-) create mode 100644 core/functions/top.py diff --git a/core/commands.py b/core/commands.py index af38d5a..4e9bb97 100644 --- a/core/commands.py +++ b/core/commands.py @@ -15,3 +15,7 @@ USER_COMMAND_SQUAD_REQUEST = '⚜Хочу в отряд' USER_COMMAND_BACK = '🔙Назад' + +TOP_COMMAND_ATTACK = '⚔' +TOP_COMMAND_DEFENCE = '🛡' +TOP_COMMAND_EXP = '🔥' diff --git a/core/functions/reply_markup.py b/core/functions/reply_markup.py index 7dfc185..c174615 100644 --- a/core/functions/reply_markup.py +++ b/core/functions/reply_markup.py @@ -3,7 +3,7 @@ from core.commands import ADMIN_COMMAND_ORDER, ADMIN_COMMAND_STATUS, ADMIN_COMMAND_GROUPS, ADMIN_COMMAND_RECRUIT, \ ADMIN_COMMAND_FIRE_UP, ADMIN_COMMAND_SQUAD_LIST, USER_COMMAND_ME, USER_COMMAND_TOP, USER_COMMAND_SQUAD, \ USER_COMMAND_STATISTICS, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, ADMIN_COMMAND_ADMINPANEL, \ - USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK + USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK, TOP_COMMAND_ATTACK, TOP_COMMAND_DEFENCE, TOP_COMMAND_EXP def generate_admin_markup(full=False, grp=False): @@ -27,3 +27,10 @@ def generate_user_markup(is_admin=False, in_squad=False): if is_admin: buttons.append([KeyboardButton(ADMIN_COMMAND_ADMINPANEL)]) return ReplyKeyboardMarkup(buttons, True) + + +def generate_top_markup(): + buttons = [[KeyboardButton(TOP_COMMAND_ATTACK), KeyboardButton(TOP_COMMAND_DEFENCE), + KeyboardButton(TOP_COMMAND_EXP)], + [KeyboardButton(USER_COMMAND_BACK)]] + return ReplyKeyboardMarkup(buttons, True) diff --git a/core/functions/top.py b/core/functions/top.py new file mode 100644 index 0000000..d33c50a --- /dev/null +++ b/core/functions/top.py @@ -0,0 +1,68 @@ +from sqlalchemy import func, text as text_ +from telegram import Update, Bot + +from core.functions.reply_markup import generate_top_markup +from core.texts import MSG_TOP_ABOUT +from core.types import user_allowed, Character, SquadMember +from core.utils import send_async + + +@user_allowed +def top_about(bot: Bot, update: Update, session): + markup = generate_top_markup() + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_TOP_ABOUT, + reply_markup=markup) + + +def get_top(condition, session, header, field_name, icon, user_id, additional_filter=text_('')): + actual_profiles = session.query(Character.user_id, func.max(Character.date)). \ + group_by(Character.user_id).all() + characters = session.query(Character).filter(Character.user_id.in_([a[0] for a in actual_profiles]), + Character.date.in_([a[1] for a in actual_profiles]), + additional_filter)\ + .order_by(condition).all() + text = header + str_format = '{}. {} ({}🌟) - {}{}\n' + for i in range(min(10, len(characters))): + text += str_format.format(i + 1, characters[i].name, characters[i].level, + getattr(characters[i], field_name), icon) + if user_id in [character.user_id for character in characters]: + if user_id not in [character.user_id for character in characters[:10]]: + for i in range(10, len(characters)): + if characters[i].user_id == user_id: + text += '...\n' + text += str_format.format(i, characters[i - 1].name, characters[i-1].level, + getattr(characters[i-1], field_name), icon) + text += str_format.format(i + 1, characters[i].name, characters[i].level, + getattr(characters[i], field_name), icon) + if i != len(characters) - 1: + text += str_format.format(i + 2, characters[i + 1].name, characters[i+1].level, + getattr(characters[i+1], field_name), icon) + break + return text + + +@user_allowed +def attack_top(bot: Bot, update: Update, session): + text = get_top(Character.attack.desc(), session, '⚔Топ атакеры:\n', 'attack', '⚔', update.message.from_user.id) + send_async(bot, + chat_id=update.message.chat.id, + text=text) + + +@user_allowed +def def_top(bot: Bot, update: Update, session): + text = get_top(Character.defence.desc(), session, '🛡Топ дэферы:\n', 'defence', '🛡', update.message.from_user.id) + send_async(bot, + chat_id=update.message.chat.id, + text=text) + + +@user_allowed +def exp_top(bot: Bot, update: Update, session): + text = get_top(Character.exp.desc(), session, '🔥Топ качки:\n', 'exp', '🔥', update.message.from_user.id) + send_async(bot, + chat_id=update.message.chat.id, + text=text) diff --git a/core/texts.py b/core/texts.py index 83a9fb1..daea967 100644 --- a/core/texts.py +++ b/core/texts.py @@ -227,3 +227,5 @@ MSG_FULL_TEXT_TOTAL = '\nВсего: {}👥 {}⚔ {}🛡' MSG_IN_DEV = 'Функция находится в разработке =(' + +MSG_TOP_ABOUT = '🏆 Топы 🏆' diff --git a/main.py b/main.py index df4ea66..c0005be 100644 --- a/main.py +++ b/main.py @@ -18,7 +18,8 @@ from config import TOKEN, GOVERNMENT_CHAT from core.commands import ADMIN_COMMAND_STATUS, ADMIN_COMMAND_RECRUIT, ADMIN_COMMAND_ORDER, ADMIN_COMMAND_SQUAD_LIST, \ ADMIN_COMMAND_GROUPS, ADMIN_COMMAND_FIRE_UP, USER_COMMAND_ME, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, \ - USER_COMMAND_SQUAD, USER_COMMAND_STATISTICS, USER_COMMAND_TOP, USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK + USER_COMMAND_SQUAD, USER_COMMAND_STATISTICS, USER_COMMAND_TOP, USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK, \ + TOP_COMMAND_ATTACK, TOP_COMMAND_DEFENCE, TOP_COMMAND_EXP from core.functions.activity import ( day_activity, week_activity, battle_activity ) @@ -47,6 +48,7 @@ squad_list, squad_request, list_squad_requests, open_hiring, close_hiring, remove_from_squad, add_to_squad ) +from core.functions.top import top_about, attack_top, exp_top, def_top from core.functions.triggers import ( set_trigger, add_trigger, del_trigger, list_triggers, enable_trigger_all, disable_trigger_all, trigger_show, @@ -208,12 +210,15 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): remove_from_squad(bot, update) elif text == USER_COMMAND_ME.lower(): char_show(bot, update) - elif text == USER_COMMAND_BUILD.lower(): - send_async(bot, - chat_id=update.message.chat.id, - text=MSG_IN_DEV, - parse_mode=ParseMode.HTML) elif text == USER_COMMAND_TOP.lower(): + top_about(bot, update) + elif text == TOP_COMMAND_ATTACK.lower(): + attack_top(bot, update) + elif text == TOP_COMMAND_DEFENCE.lower(): + def_top(bot, update) + elif text == TOP_COMMAND_EXP.lower(): + exp_top(bot, update) + elif text == USER_COMMAND_BUILD.lower(): send_async(bot, chat_id=update.message.chat.id, text=MSG_IN_DEV, From c10c20aaceaf2a0c3f44145e9911a70c03991472 Mon Sep 17 00:00:00 2001 From: toxydose Date: Tue, 10 Oct 2017 17:52:42 +0300 Subject: [PATCH 110/284] =?UTF-8?q?=D1=82=D0=B5=D0=BF=D0=B5=D1=80=D1=8C=20?= =?UTF-8?q?=D0=BA=D1=80=D0=B0=D1=81=D0=B8=D0=B2=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/regexp.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/regexp.py b/core/regexp.py index 9b2b23a..3b6fa68 100644 --- a/core/regexp.py +++ b/core/regexp.py @@ -28,4 +28,5 @@ REPORT = '(🇬🇵|🇮🇲|🇨🇾|🇻🇦|🇪🇺|🇲🇴|🇰🇮)(.+) ⚔️:([0-9]+) 🛡:([0-9]+) \(([0-9]+) ур.\)\n' \ 'Твои результаты в бою:(?:\n' \ '🔥Опыт: ([0-9]+) ед)?(?:\n' \ - '💰Золото: (-?[0-9]+))?(?:\n📦Склад: (-?[0-9]+))?' + '💰Золото: (-?[0-9]+))?(?:\n' \ + '📦Склад: (-?[0-9]+))?' From b15cc6b637d3c875c6b989f91ebaa970d09df437 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 10 Oct 2017 18:01:19 +0300 Subject: [PATCH 111/284] =?UTF-8?q?=D0=9D=D0=B5=D0=BC=D0=BD=D0=BE=D0=B3?= =?UTF-8?q?=D0=BE=20=D1=81=D1=82=D0=B0=D1=82=D0=B8=D1=81=D1=82=D0=B8=D0=BA?= =?UTF-8?q?=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/commands.py | 2 ++ core/functions/reply_markup.py | 9 ++++++- core/functions/statistics.py | 44 ++++++++++++++++++++++++++++++++++ core/functions/top.py | 2 +- core/texts.py | 1 + main.py | 10 ++++---- requirements.txt | 1 + 7 files changed, 62 insertions(+), 7 deletions(-) create mode 100644 core/functions/statistics.py diff --git a/core/commands.py b/core/commands.py index 4e9bb97..ede4637 100644 --- a/core/commands.py +++ b/core/commands.py @@ -19,3 +19,5 @@ TOP_COMMAND_ATTACK = '⚔' TOP_COMMAND_DEFENCE = '🛡' TOP_COMMAND_EXP = '🔥' + +STATISTICS_COMMAND_EXP = '🔥Опыт' diff --git a/core/functions/reply_markup.py b/core/functions/reply_markup.py index c174615..651ce0c 100644 --- a/core/functions/reply_markup.py +++ b/core/functions/reply_markup.py @@ -3,7 +3,8 @@ from core.commands import ADMIN_COMMAND_ORDER, ADMIN_COMMAND_STATUS, ADMIN_COMMAND_GROUPS, ADMIN_COMMAND_RECRUIT, \ ADMIN_COMMAND_FIRE_UP, ADMIN_COMMAND_SQUAD_LIST, USER_COMMAND_ME, USER_COMMAND_TOP, USER_COMMAND_SQUAD, \ USER_COMMAND_STATISTICS, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, ADMIN_COMMAND_ADMINPANEL, \ - USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK, TOP_COMMAND_ATTACK, TOP_COMMAND_DEFENCE, TOP_COMMAND_EXP + USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK, TOP_COMMAND_ATTACK, TOP_COMMAND_DEFENCE, TOP_COMMAND_EXP, \ + STATISTICS_COMMAND_EXP def generate_admin_markup(full=False, grp=False): @@ -34,3 +35,9 @@ def generate_top_markup(): KeyboardButton(TOP_COMMAND_EXP)], [KeyboardButton(USER_COMMAND_BACK)]] return ReplyKeyboardMarkup(buttons, True) + + +def generate_statistics_markup(): + buttons = [[KeyboardButton(STATISTICS_COMMAND_EXP)], + [KeyboardButton(USER_COMMAND_BACK)]] + return ReplyKeyboardMarkup(buttons, True) diff --git a/core/functions/statistics.py b/core/functions/statistics.py new file mode 100644 index 0000000..9cbb65a --- /dev/null +++ b/core/functions/statistics.py @@ -0,0 +1,44 @@ +from telegram import Update, Bot + +from core.functions.reply_markup import generate_statistics_markup +from core.texts import MSG_STATISTICS_ABOUT +from core.types import user_allowed, Character +from core.utils import send_async + +import matplotlib.pyplot as plot + +from datetime import datetime + +import os + + +@user_allowed +def statistic_about(bot: Bot, update: Update, session): + markup = generate_statistics_markup() + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_STATISTICS_ABOUT, + reply_markup=markup) + + +@user_allowed +def exp_statistic(bot: Bot, update: Update, session): + profiles = session.query(Character).filter_by(user_id=update.message.from_user.id)\ + .order_by(Character.date).all() + plot.switch_backend('ps') + plot.xlabel('Дата') + plot.ylabel('Опыт') + x = [profile.date for profile in profiles] + y = [profile.exp for profile in profiles] + x.append(datetime.now()) + y.append(y[-1]) + plot.plot(x, y) + plot.gcf().autofmt_xdate() + filename = str(datetime.now()).replace(':', '').replace(' ', '').replace('-', '') + '.png' + with open(filename, 'wb') as file: + plot.savefig(file, format='png') + with open(filename, 'rb') as file: + bot.sendPhoto(update.message.chat.id, file, 'В среднем {} опыта в день' + .format(int((y[-1] - y[0])/(x[-1] - x[0]).days))) + plot.clf() + os.remove(filename) diff --git a/core/functions/top.py b/core/functions/top.py index d33c50a..71b6210 100644 --- a/core/functions/top.py +++ b/core/functions/top.py @@ -3,7 +3,7 @@ from core.functions.reply_markup import generate_top_markup from core.texts import MSG_TOP_ABOUT -from core.types import user_allowed, Character, SquadMember +from core.types import user_allowed, Character from core.utils import send_async diff --git a/core/texts.py b/core/texts.py index daea967..b60fa53 100644 --- a/core/texts.py +++ b/core/texts.py @@ -229,3 +229,4 @@ MSG_IN_DEV = 'Функция находится в разработке =(' MSG_TOP_ABOUT = '🏆 Топы 🏆' +MSG_STATISTICS_ABOUT = '📈Статистика📈' diff --git a/main.py b/main.py index c0005be..89ed5b8 100644 --- a/main.py +++ b/main.py @@ -19,7 +19,7 @@ from core.commands import ADMIN_COMMAND_STATUS, ADMIN_COMMAND_RECRUIT, ADMIN_COMMAND_ORDER, ADMIN_COMMAND_SQUAD_LIST, \ ADMIN_COMMAND_GROUPS, ADMIN_COMMAND_FIRE_UP, USER_COMMAND_ME, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, \ USER_COMMAND_SQUAD, USER_COMMAND_STATISTICS, USER_COMMAND_TOP, USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK, \ - TOP_COMMAND_ATTACK, TOP_COMMAND_DEFENCE, TOP_COMMAND_EXP + TOP_COMMAND_ATTACK, TOP_COMMAND_DEFENCE, TOP_COMMAND_EXP, STATISTICS_COMMAND_EXP from core.functions.activity import ( day_activity, week_activity, battle_activity ) @@ -48,6 +48,7 @@ squad_list, squad_request, list_squad_requests, open_hiring, close_hiring, remove_from_squad, add_to_squad ) +from core.functions.statistics import statistic_about, exp_statistic from core.functions.top import top_about, attack_top, exp_top, def_top from core.functions.triggers import ( set_trigger, add_trigger, del_trigger, list_triggers, enable_trigger_all, @@ -224,10 +225,9 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): text=MSG_IN_DEV, parse_mode=ParseMode.HTML) elif text == USER_COMMAND_STATISTICS.lower(): - send_async(bot, - chat_id=update.message.chat.id, - text=MSG_IN_DEV, - parse_mode=ParseMode.HTML) + statistic_about(bot, update) + elif text == STATISTICS_COMMAND_EXP.lower(): + exp_statistic(bot, update) elif text == USER_COMMAND_SQUAD.lower(): send_async(bot, chat_id=update.message.chat.id, diff --git a/requirements.txt b/requirements.txt index 37a8ebb..01baf8c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,4 @@ +matplotlib certifi==2017.7.27.1 chardet==3.0.4 click==6.7 From 92e30bf9ff4b6981494305ff77c708cbfc97317a Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 10 Oct 2017 18:05:53 +0300 Subject: [PATCH 112/284] =?UTF-8?q?=D0=9A=D0=BE=D1=81=D1=8F=D0=BA=20=D0=B7?= =?UTF-8?q?=D0=B0=D0=B2=D0=B8=D1=81=D0=B8=D0=BC=D0=BE=D1=81=D1=82=D0=B5?= =?UTF-8?q?=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- requirements.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 01baf8c..32e048f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -8,7 +8,6 @@ idna==2.6 itsdangerous==0.24 Jinja2==2.9.6 MarkupSafe==1.0 -pkg-resources==0.0.0 PyMySQL==0.7.11 python-telegram-bot==8.0 requests==2.18.4 From f969d264be397be65073573d06f16794b7eede4a Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Wed, 11 Oct 2017 12:41:50 +0300 Subject: [PATCH 113/284] =?UTF-8?q?=D0=9A=D0=BE=D0=BD=D1=84=D0=B8=D0=B3=20?= =?UTF-8?q?=D0=B7=D0=B0=D0=BC=D0=BA=D0=B0=20=D0=B8=20=D1=84=D0=B8=D0=BA?= =?UTF-8?q?=D1=81=D1=8B=20=D1=82=D0=BE=D0=BF=D0=BE=D0=B2=20=D0=B8=20=D1=81?= =?UTF-8?q?=D0=BF=D0=B8=D1=81=D0=BA=D0=B0=20=D0=BE=D1=82=D1=80=D1=8F=D0=B4?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config.py.sample | 1 + core/functions/inline_keyboard_handling.py | 12 +++++------ core/functions/profile.py | 23 ++++++++++++++++++---- core/functions/top.py | 16 ++++++++++----- 4 files changed, 37 insertions(+), 15 deletions(-) diff --git a/config.py.sample b/config.py.sample index 6bedde4..6754acd 100644 --- a/config.py.sample +++ b/config.py.sample @@ -8,3 +8,4 @@ SUPER_ADMIN_ID = 0 # id супер админа # вербовочный функционал: CASTLE_CHAT_ID = None # id замкового чата (для поиска новых игроков в замке - если None - функционал отключен) ACADEM_CHAT_ID = None # id чата академии (для уведомления о новых игроках в замке - если None - функционал отключен) +CASTLE = None # Флаг замка, который вы хотите обслуживать (например '🇮🇲'), оставьте None, чтобы не было ограничений diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index 4df9a6a..b34062f 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -4,7 +4,7 @@ from json import loads import logging -from telegram import Bot, Update, InlineKeyboardButton, InlineKeyboardMarkup, TelegramError, Message +from telegram import Bot, Update, InlineKeyboardButton, InlineKeyboardMarkup, TelegramError from telegram.ext.dispatcher import run_async from core.enums import Castle, Icons @@ -18,7 +18,7 @@ from core.texts import * from core.utils import send_async, update_group, add_user -from sqlalchemy import func +from sqlalchemy import func, tuple_ LOGGER = logging.getLogger('MyApp') @@ -226,8 +226,8 @@ def generate_squad_list_key(squad, session): actual_profiles = session.query(Character.user_id, func.max(Character.date)).\ filter(Character.user_id.in_(user_ids)).\ group_by(Character.user_id).all() - characters = session.query(Character).filter(Character.user_id.in_([a[0] for a in actual_profiles]), - Character.date.in_([a[1] for a in actual_profiles])).all() + characters = session.query(Character).filter(tuple_(Character.user_id, Character.date) + .in_([(a[0], a[1]) for a in actual_profiles])).all() for character in characters: attack += character.attack defence += character.defence @@ -273,8 +273,8 @@ def generate_squad_members(members, session): actual_profiles = session.query(Character.user_id, func.max(Character.date)). \ filter(Character.user_id.in_(user_ids)). \ group_by(Character.user_id).all() - characters = session.query(Character).filter(Character.user_id.in_([a[0] for a in actual_profiles]), - Character.date.in_([a[1] for a in actual_profiles]))\ + characters = session.query(Character).filter(tuple_(Character.user_id, Character.date) + .in_([(a[0], a[1]) for a in actual_profiles]))\ .order_by(Character.level.desc()).all() for character in characters: time_passed = datetime.now() - character.date diff --git a/core/functions/profile.py b/core/functions/profile.py index 7ad3211..770fde9 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -9,6 +9,8 @@ from core.template import fill_char_template from core.texts import * +from config import CASTLE + def parse_profile(profile, user_id, date, session): parsed_data = re.search(PROFILE, profile) @@ -135,7 +137,14 @@ def char_update(bot: Bot, update: Update, session): update.message.from_user.id, update.message.forward_date, session) - send_async(bot, chat_id=update.message.chat.id, text=MSG_PROFILE_SAVED.format(char.name)) + if CASTLE: + if char and char.castle == CASTLE: + send_async(bot, chat_id=update.message.chat.id, text=MSG_PROFILE_SAVED.format(char.name)) + else: + send_async(bot, chat_id=update.message.chat.id, + text=MSG_PROFILE_CASTLE_MISTAKE) + else: + send_async(bot, chat_id=update.message.chat.id, text=MSG_PROFILE_SAVED.format(char.name)) @user_allowed @@ -144,9 +153,15 @@ def char_show(bot: Bot, update: Update, session): user = session.query(User).filter_by(id=update.message.from_user.id).first() if user is not None and user.character is not None: char = user.character - text = fill_char_template(MSG_PROFILE_SHOW_FORMAT, user, char) - btns = generate_profile_buttons(user) - send_async(bot, chat_id=update.message.chat.id, text=text, reply_markup=btns) + if CASTLE: + if char.castle == CASTLE: + text = fill_char_template(MSG_PROFILE_SHOW_FORMAT, user, char) + btns = generate_profile_buttons(user) + send_async(bot, chat_id=update.message.chat.id, text=text, reply_markup=btns) + else: + text = fill_char_template(MSG_PROFILE_SHOW_FORMAT, user, char) + btns = generate_profile_buttons(user) + send_async(bot, chat_id=update.message.chat.id, text=text, reply_markup=btns) @admin_allowed() diff --git a/core/functions/top.py b/core/functions/top.py index 71b6210..938a9a9 100644 --- a/core/functions/top.py +++ b/core/functions/top.py @@ -1,4 +1,4 @@ -from sqlalchemy import func, text as text_ +from sqlalchemy import func, text as text_, tuple_ from telegram import Update, Bot from core.functions.reply_markup import generate_top_markup @@ -6,6 +6,8 @@ from core.types import user_allowed, Character from core.utils import send_async +from config import CASTLE + @user_allowed def top_about(bot: Bot, update: Update, session): @@ -18,11 +20,15 @@ def top_about(bot: Bot, update: Update, session): def get_top(condition, session, header, field_name, icon, user_id, additional_filter=text_('')): actual_profiles = session.query(Character.user_id, func.max(Character.date)). \ - group_by(Character.user_id).all() - characters = session.query(Character).filter(Character.user_id.in_([a[0] for a in actual_profiles]), - Character.date.in_([a[1] for a in actual_profiles]), + group_by(Character.user_id) + actual_profiles = actual_profiles.all() + characters = session.query(Character).filter(tuple_(Character.user_id, Character.date) + .in_([(a[0], a[1]) for a in actual_profiles]), additional_filter)\ - .order_by(condition).all() + .order_by(condition) + if CASTLE: + characters = characters.filter_by(castle=CASTLE) + characters = characters.all() text = header str_format = '{}. {} ({}🌟) - {}{}\n' for i in range(min(10, len(characters))): From fe31fcee2f06b72f8dc9dcce395f49764d5dd3f3 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Wed, 11 Oct 2017 13:01:51 +0300 Subject: [PATCH 114/284] =?UTF-8?q?=D0=92=20=D1=82=D0=BE=D0=BF=D0=B0=D1=85?= =?UTF-8?q?=20=D1=82=D0=B5=D0=BF=D0=B5=D1=80=D1=8C=20=D1=82=D0=BE=D0=BB?= =?UTF-8?q?=D1=8C=D0=BA=D0=BE=20=D1=81=D0=BE=20=D1=81=D0=B2=D0=B5=D0=B6?= =?UTF-8?q?=D0=B8=D0=BC=20=D0=BF=D1=80=D0=BE=D1=84=D0=B8=D0=BB=D0=B5=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/top.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core/functions/top.py b/core/functions/top.py index 938a9a9..bac3557 100644 --- a/core/functions/top.py +++ b/core/functions/top.py @@ -8,6 +8,8 @@ from config import CASTLE +from datetime import datetime, timedelta + @user_allowed def top_about(bot: Bot, update: Update, session): @@ -24,6 +26,7 @@ def get_top(condition, session, header, field_name, icon, user_id, additional_fi actual_profiles = actual_profiles.all() characters = session.query(Character).filter(tuple_(Character.user_id, Character.date) .in_([(a[0], a[1]) for a in actual_profiles]), + Character.date > datetime.now() - timedelta(days=7), additional_filter)\ .order_by(condition) if CASTLE: From 4f355a5b8495363da2ca157505fb18d0782c85d4 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Wed, 11 Oct 2017 15:02:33 +0300 Subject: [PATCH 115/284] =?UTF-8?q?=D0=9A=D0=B0=D0=BA=D0=BE=D0=B9-=D1=82?= =?UTF-8?q?=D0=BE=20=D1=84=D0=B8=D0=BA=D1=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index b34062f..19ad24b 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -426,7 +426,7 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): session.add(order) session.commit() markup = generate_ok_markup(order.id, 0) - msg = send_order(bot, order.text, order_type, order.chat_id, markup).result() + msg = send_order(bot, order.text, order_type, order.chat_id, markup).result().result() if order_pin and msg: try: bot.request.post(bot.base_url + '/pinChatMessage', {'chat_id': order.chat_id, From 7be003083f3e624c25da235ec92691e2ba699e0f Mon Sep 17 00:00:00 2001 From: toxydose Date: Wed, 11 Oct 2017 15:37:22 +0300 Subject: [PATCH 116/284] =?UTF-8?q?=D0=BA=D0=BE=D1=81=D1=8F=D0=BA=20=D1=81?= =?UTF-8?q?=20=D0=B7=D0=B0=D0=B2=D0=B8=D1=81=D0=B8=D0=BC=D0=BE=D1=81=D1=82?= =?UTF-8?q?=D1=8F=D0=BC=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8f49164..16adb45 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,12 @@ exit ``` 9)open the file 'config.py.sample', enter your new database user's credentials, database name and your telegram bot API token -10)launch the bot: +10)You have to install python3-tk (if not yet installed) to properly run matplotlib requirement. +``` +sudo apt-get install python3-tk +``` + +11)launch the bot: ``` python3 main.py ``` From 53050d6dfac2bd180b0a46d474f7999e26cef93a Mon Sep 17 00:00:00 2001 From: toxydose Date: Thu, 12 Oct 2017 01:18:16 +0300 Subject: [PATCH 117/284] TOP refactoring --- core/functions/top.py | 10 +++++----- core/texts.py | 5 +++++ 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/core/functions/top.py b/core/functions/top.py index bac3557..ab73a11 100644 --- a/core/functions/top.py +++ b/core/functions/top.py @@ -2,7 +2,7 @@ from telegram import Update, Bot from core.functions.reply_markup import generate_top_markup -from core.texts import MSG_TOP_ABOUT +from core.texts import MSG_TOP_ABOUT, MSG_TOP_FORMAT,MSG_TOP_ATTACK, MSG_TOP_DEFENCE, MSG_TOP_EXPERIENCE from core.types import user_allowed, Character from core.utils import send_async @@ -33,7 +33,7 @@ def get_top(condition, session, header, field_name, icon, user_id, additional_fi characters = characters.filter_by(castle=CASTLE) characters = characters.all() text = header - str_format = '{}. {} ({}🌟) - {}{}\n' + str_format = MSG_TOP_FORMAT for i in range(min(10, len(characters))): text += str_format.format(i + 1, characters[i].name, characters[i].level, getattr(characters[i], field_name), icon) @@ -55,7 +55,7 @@ def get_top(condition, session, header, field_name, icon, user_id, additional_fi @user_allowed def attack_top(bot: Bot, update: Update, session): - text = get_top(Character.attack.desc(), session, '⚔Топ атакеры:\n', 'attack', '⚔', update.message.from_user.id) + text = get_top(Character.attack.desc(), session, MSG_TOP_ATTACK, 'attack', '⚔', update.message.from_user.id) send_async(bot, chat_id=update.message.chat.id, text=text) @@ -63,7 +63,7 @@ def attack_top(bot: Bot, update: Update, session): @user_allowed def def_top(bot: Bot, update: Update, session): - text = get_top(Character.defence.desc(), session, '🛡Топ дэферы:\n', 'defence', '🛡', update.message.from_user.id) + text = get_top(Character.defence.desc(), session, MSG_TOP_DEFENCE, 'defence', '🛡', update.message.from_user.id) send_async(bot, chat_id=update.message.chat.id, text=text) @@ -71,7 +71,7 @@ def def_top(bot: Bot, update: Update, session): @user_allowed def exp_top(bot: Bot, update: Update, session): - text = get_top(Character.exp.desc(), session, '🔥Топ качки:\n', 'exp', '🔥', update.message.from_user.id) + text = get_top(Character.exp.desc(), session, MSG_TOP_EXPERIENCE, 'exp', '🔥', update.message.from_user.id) send_async(bot, chat_id=update.message.chat.id, text=text) diff --git a/core/texts.py b/core/texts.py index b60fa53..793b98d 100644 --- a/core/texts.py +++ b/core/texts.py @@ -230,3 +230,8 @@ MSG_TOP_ABOUT = '🏆 Топы 🏆' MSG_STATISTICS_ABOUT = '📈Статистика📈' + +MSG_TOP_FORMAT = '{}. {} ({}🌟) - {}{}\n' +MSG_TOP_DEFENCE = '🛡Топ дэферы:\n' +MSG_TOP_ATTACK = '⚔Топ атакеры:\n' +MSG_TOP_EXPERIENCE = '🔥Топ качки:\n' From 15a10763a81765cb7acc75187fceb5017909ab93 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Fri, 13 Oct 2017 14:53:21 +0300 Subject: [PATCH 118/284] =?UTF-8?q?=D0=9F=D0=B0=D1=80=D1=81=D0=B8=D0=BD?= =?UTF-8?q?=D0=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/common.py | 8 ++++---- core/functions/inline_keyboard_handling.py | 12 ++++++------ core/functions/profile.py | 12 +++++++----- core/functions/squad.py | 10 ++++++---- core/texts.py | 2 ++ 5 files changed, 25 insertions(+), 19 deletions(-) diff --git a/core/functions/common.py b/core/functions/common.py index 3cc74dc..6761848 100644 --- a/core/functions/common.py +++ b/core/functions/common.py @@ -29,7 +29,7 @@ def error(bot: Bot, update, error, **kwargs): def start(bot: Bot, update: Update, session): add_user(update.message.from_user, session) if update.message.chat.type == 'private': - send_async(bot, chat_id=update.message.chat.id, text=MSG_START_WELCOME) + send_async(bot, chat_id=update.message.chat.id, text=MSG_START_WELCOME, parse_mode=ParseMode.HTML) @admin_allowed(adm_type=AdminType.GROUP) @@ -56,7 +56,7 @@ def user_panel(bot: Bot, update: Update, session): is_admin = True break squad_member = session.query(SquadMember).filter_by(user_id=update.message.from_user.id).first() - send_async(bot, chat_id=update.message.chat.id, text=MSG_START_WELCOME, + send_async(bot, chat_id=update.message.chat.id, text=MSG_START_WELCOME, parse_mode=ParseMode.HTML, reply_markup=generate_user_markup(is_admin, True if squad_member else False)) @@ -145,7 +145,7 @@ def stock_compare(bot: Bot, update: Update, session, chat_data: dict): msg += MSG_EMPTY send_async(bot, chat_id=update.message.chat.id, text=msg, parse_mode=ParseMode.HTML) else: - send_async(bot, chat_id=update.message.chat.id, text=MSG_STOCK_COMPARE_WAIT) + send_async(bot, chat_id=update.message.chat.id, text=MSG_STOCK_COMPARE_WAIT, parse_mode=ParseMode.HTML) @admin_allowed(adm_type=AdminType.GROUP) @@ -201,4 +201,4 @@ def trade_compare(bot: Bot, update: Update, session, chat_data: dict): msg += MSG_EMPTY send_async(bot, chat_id=update.message.chat.id, text=msg, parse_mode=ParseMode.HTML) else: - send_async(bot, chat_id=update.message.chat.id, text=MSG_STOCK_COMPARE_WAIT) + send_async(bot, chat_id=update.message.chat.id, text=MSG_STOCK_COMPARE_WAIT, parse_mode=ParseMode.HTML) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index 19ad24b..53f221e 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -4,7 +4,7 @@ from json import loads import logging -from telegram import Bot, Update, InlineKeyboardButton, InlineKeyboardMarkup, TelegramError +from telegram import Bot, Update, InlineKeyboardButton, InlineKeyboardMarkup, TelegramError, ParseMode from telegram.ext.dispatcher import run_async from core.enums import Castle, Icons @@ -621,13 +621,13 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): send_async(bot, chat_id=adm.user_id, text=MSG_SQUAD_LEAVED.format(user.character.name, squad.squad_name)) send_async(bot, chat_id=member.squad_id, - text=MSG_SQUAD_LEAVED.format(user.character.name, squad.squad_name)) + text=MSG_SQUAD_LEAVED.format(user.character.name, squad.squad_name), parse_mode=ParseMode.HTML) send_async(bot, chat_id=member.user_id, - text=MSG_SQUAD_LEAVED.format(user.character.name, squad.squad_name)) + text=MSG_SQUAD_LEAVED.format(user.character.name, squad.squad_name), parse_mode=ParseMode.HTML) if data['id'] == update.callback_query.from_user.id: bot.editMessageText(MSG_SQUAD_LEAVED.format(user.character.name, squad.squad_name), update.callback_query.message.chat.id, - update.callback_query.message.message_id) + update.callback_query.message.message_id, parse_mode=ParseMode.HTML) else: members = session.query(SquadMember).filter_by(squad_id=member.squad_id).all() bot.editMessageText(update.callback_query.message.text, @@ -635,7 +635,7 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): update.callback_query.message.message_id, reply_markup=generate_fire_up(members)) else: - update.callback_query.answer(text='Этот пользователь уже выпилен из отряда, кнопка больше не работает =(') + update.callback_query.answer(text=MSG_SQUAD_ALREADY_DELETED) elif data['t'] == QueryType.RequestSquad.value: member = session.query(SquadMember).filter_by(user_id=update.callback_query.from_user.id).first() if member is None: @@ -648,7 +648,7 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): usernames = ['@' + session.query(User).filter_by(id=admin.user_id).first().username for admin in admins] bot.editMessageText(MSG_SQUAD_REQUESTED.format(member.squad.squad_name, ', '.join(usernames)), update.callback_query.message.chat.id, - update.callback_query.message.message_id) + update.callback_query.message.message_id, parse_mode=ParseMode.HTML) admins = session.query(Admin).filter_by(admin_group=member.squad.chat_id).all() for adm in admins: send_async(bot, chat_id=adm.user_id, text=MSG_SQUAD_REQUEST_NEW) diff --git a/core/functions/profile.py b/core/functions/profile.py index 770fde9..1cc0505 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -1,4 +1,4 @@ -from telegram import Update, Bot +from telegram import Update, Bot, ParseMode from core.functions.inline_keyboard_handling import generate_profile_buttons from core.regexp import HERO, PROFILE, REPORT @@ -139,12 +139,14 @@ def char_update(bot: Bot, update: Update, session): session) if CASTLE: if char and char.castle == CASTLE: - send_async(bot, chat_id=update.message.chat.id, text=MSG_PROFILE_SAVED.format(char.name)) + send_async(bot, chat_id=update.message.chat.id, text=MSG_PROFILE_SAVED.format(char.name), + parse_mode=ParseMode.HTML) else: send_async(bot, chat_id=update.message.chat.id, - text=MSG_PROFILE_CASTLE_MISTAKE) + text=MSG_PROFILE_CASTLE_MISTAKE, parse_mode=ParseMode.HTML) else: - send_async(bot, chat_id=update.message.chat.id, text=MSG_PROFILE_SAVED.format(char.name)) + send_async(bot, chat_id=update.message.chat.id, text=MSG_PROFILE_SAVED.format(char.name), + parse_mode=ParseMode.HTML) @user_allowed @@ -177,4 +179,4 @@ def find_by_username(bot: Bot, update: Update, session): btns = generate_profile_buttons(user) send_async(bot, chat_id=update.message.chat.id, text=text, reply_markup=btns) else: - send_async(bot, chat_id=update.message.chat.id, text=MSG_PROFILE_NOT_FOUND) + send_async(bot, chat_id=update.message.chat.id, text=MSG_PROFILE_NOT_FOUND, parse_mode=ParseMode.HTML) diff --git a/core/functions/squad.py b/core/functions/squad.py index 64823f2..9cd7b1b 100644 --- a/core/functions/squad.py +++ b/core/functions/squad.py @@ -1,4 +1,4 @@ -from telegram import Update, Bot +from telegram import Update, Bot, ParseMode from core.template import fill_char_template from core.types import User, AdminType, Admin, admin_allowed, Group, Squad, SquadMember, user_allowed @@ -25,7 +25,8 @@ def add_squad(bot: Bot, update: Update, session): squad.squad_name = group.title session.add(squad) session.commit() - send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_NEW.format(squad.squad_name)) + send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_NEW.format(squad.squad_name), + parse_mode=ParseMode.HTML) @admin_allowed() @@ -49,7 +50,8 @@ def set_squad_name(bot: Bot, update: Update, session): squad.squad_name = msg[1] session.add(squad) session.commit() - send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_RENAMED.format(squad.squad_name)) + send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_RENAMED.format(squad.squad_name), + parse_mode=ParseMode.HTML) @admin_allowed() @@ -172,7 +174,7 @@ def remove_from_squad(bot: Bot, update: Update, session): squad = session.query(Squad).filter_by(chat_id=adm.admin_group).first() send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_CLEAN.format(squad.squad_name), - reply_markup=markup) + reply_markup=markup, parse_mode=ParseMode.HTML) @admin_allowed(AdminType.GROUP) diff --git a/core/texts.py b/core/texts.py index 793b98d..124ceab 100644 --- a/core/texts.py +++ b/core/texts.py @@ -170,6 +170,7 @@ MSG_SQUAD_THORNS_ENABLED = 'Непроходимые тернии выросли вокруг' MSG_SQUAD_THORNS_DISABLED = 'Тернии завяли, \ теперь каждый может видеть происходящее' +MSG_SQUAD_ALREADY_DELETED = 'Этот пользователь уже выпилен из отряда, кнопка больше не работает =(' MSG_TRIGGER_NEW = 'Триггер на фразу "{}" установлен.' MSG_TRIGGER_GLOBAL = 'Глобальные:\n' @@ -225,6 +226,7 @@ MSG_SQUAD_READY = '{} бойцов отряда {} к битве готовы!\n{}⚔ {}🛡' MSG_FULL_TEXT_LINE = '{}: {}👥 {}⚔ {}🛡\n' MSG_FULL_TEXT_TOTAL = '\nВсего: {}👥 {}⚔ {}🛡' +MSG_WANTS_TO_JOIN = '\n\nХочет вступить в отряд {}' MSG_IN_DEV = 'Функция находится в разработке =(' From 532b35a6143883cfe814aeb7e9024927bce38f3b Mon Sep 17 00:00:00 2001 From: toxydose Date: Mon, 16 Oct 2017 13:57:27 +0300 Subject: [PATCH 119/284] =?UTF-8?q?=D1=83=D0=B1=D1=80=D0=B0=D0=BB=20=D0=B4?= =?UTF-8?q?=D1=83=D0=B1=D0=BB=D0=B8=D0=BA=D0=B0=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/texts.py | 1 - 1 file changed, 1 deletion(-) diff --git a/core/texts.py b/core/texts.py index 124ceab..1e7fbf5 100644 --- a/core/texts.py +++ b/core/texts.py @@ -226,7 +226,6 @@ MSG_SQUAD_READY = '{} бойцов отряда {} к битве готовы!\n{}⚔ {}🛡' MSG_FULL_TEXT_LINE = '{}: {}👥 {}⚔ {}🛡\n' MSG_FULL_TEXT_TOTAL = '\nВсего: {}👥 {}⚔ {}🛡' -MSG_WANTS_TO_JOIN = '\n\nХочет вступить в отряд {}' MSG_IN_DEV = 'Функция находится в разработке =(' From 6af6f8f96aff2939ca249c5de3da6ba02268b0ed Mon Sep 17 00:00:00 2001 From: toxydose Date: Mon, 16 Oct 2017 14:22:10 +0300 Subject: [PATCH 120/284] =?UTF-8?q?=D1=84=D0=B8=D0=BA=D1=81=20=D1=80=D0=B0?= =?UTF-8?q?=D0=B7=D0=BC=D0=B5=D1=82=D0=BA=D0=B8=20(=D0=BF=D0=B0=D1=80?= =?UTF-8?q?=D1=81=D0=B8=D0=BD=D0=B3)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index 53f221e..dba7135 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -619,7 +619,7 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): for adm in admins: if adm.user_id != update.callback_query.from_user.id: send_async(bot, chat_id=adm.user_id, - text=MSG_SQUAD_LEAVED.format(user.character.name, squad.squad_name)) + text=MSG_SQUAD_LEAVED.format(user.character.name, squad.squad_name), parse_mode=ParseMode.HTML) send_async(bot, chat_id=member.squad_id, text=MSG_SQUAD_LEAVED.format(user.character.name, squad.squad_name), parse_mode=ParseMode.HTML) send_async(bot, chat_id=member.user_id, From c2e57ee470bd88d71bdbef59055ba97af93a8ace Mon Sep 17 00:00:00 2001 From: toxydose Date: Tue, 17 Oct 2017 13:45:28 +0300 Subject: [PATCH 121/284] =?UTF-8?q?=D1=80=D0=B5=D0=B3=D1=83=D0=BB=D1=8F?= =?UTF-8?q?=D1=80=D0=BA=D0=B0=20=D0=B4=D0=BB=D1=8F=20=D1=81=D1=82=D1=80?= =?UTF-8?q?=D0=BE=D0=B9=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/regexp.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core/regexp.py b/core/regexp.py index 3b6fa68..6011fd0 100644 --- a/core/regexp.py +++ b/core/regexp.py @@ -30,3 +30,5 @@ '🔥Опыт: ([0-9]+) ед)?(?:\n' \ '💰Золото: (-?[0-9]+))?(?:\n' \ '📦Склад: (-?[0-9]+))?' + +BUILD_REPORT = 'Ты вернулся со стройки: (.+), прогресс работ: ([0-9]+)%' From 7359fd9af550246334561bdb55dc96e08fcda0ce Mon Sep 17 00:00:00 2001 From: toxydose Date: Tue, 17 Oct 2017 15:37:32 +0300 Subject: [PATCH 122/284] =?UTF-8?q?=D1=80=D0=B5=D0=B3=D1=83=D0=BB=D1=8F?= =?UTF-8?q?=D1=80=D0=BA=D0=B0=20=D0=B4=D0=BB=D1=8F=20=D1=81=D1=82=D1=80?= =?UTF-8?q?=D0=BE=D0=B9=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/regexp.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core/regexp.py b/core/regexp.py index 6011fd0..19e60ec 100644 --- a/core/regexp.py +++ b/core/regexp.py @@ -32,3 +32,5 @@ '📦Склад: (-?[0-9]+))?' BUILD_REPORT = 'Ты вернулся со стройки: (.+), прогресс работ: ([0-9]+)%' + +REPAIR_REPORT = 'Здание отремонтировано: (.+)' From 252e9260ce6d7fc913715409bae653ea9f0f52f6 Mon Sep 17 00:00:00 2001 From: toxydose Date: Tue, 17 Oct 2017 15:46:31 +0300 Subject: [PATCH 123/284] =?UTF-8?q?BuildType=20class=20(=D1=84=D0=BB=D0=B0?= =?UTF-8?q?=D0=B3=20=D0=BF=D0=BE=D1=81=D1=82=D1=80=D0=BE=D0=B9=D0=BA=D0=B0?= =?UTF-8?q?/=D1=80=D0=B5=D0=BC=D0=BE=D0=BD=D1=82)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/common.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core/functions/common.py b/core/functions/common.py index 6761848..372d799 100644 --- a/core/functions/common.py +++ b/core/functions/common.py @@ -18,6 +18,9 @@ class StockType(Enum): Stock = 0 TradeBot = 1 +class BuildType(Enum): + Build = 1 + Repair = 0 def error(bot: Bot, update, error, **kwargs): """ Error handling """ From ccecf70c577ceb081caab4c641ad261416b52a9e Mon Sep 17 00:00:00 2001 From: toxydose Date: Tue, 17 Oct 2017 15:48:46 +0300 Subject: [PATCH 124/284] =?UTF-8?q?=D1=81=D0=BE=D0=B1=D0=BB=D1=8E=D0=B4?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BE=D0=B1=D1=89=D0=B5=D0=B3=D0=BE?= =?UTF-8?q?=20=D1=81=D1=82=D0=B8=D0=BB=D1=8F=20=D0=BF=D1=80=D0=BE=D1=8D?= =?UTF-8?q?=D0=BA=D1=82=D0=B0=20(2=20=D0=BF=D0=B5=D1=80=D0=B5=D0=BD=D0=BE?= =?UTF-8?q?=D1=81=D0=B0=20=D1=81=D1=82=D1=80=D0=BE=D0=BA=D0=B8=20=D0=BC?= =?UTF-8?q?=D0=B5=D0=B6=D0=B4=D1=83=20=D1=84=D1=83=D0=BD=D0=BA=D1=86=D0=B8?= =?UTF-8?q?=D1=8F=D0=BC=D0=B8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/common.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core/functions/common.py b/core/functions/common.py index 372d799..450ae00 100644 --- a/core/functions/common.py +++ b/core/functions/common.py @@ -18,10 +18,12 @@ class StockType(Enum): Stock = 0 TradeBot = 1 + class BuildType(Enum): Build = 1 Repair = 0 + def error(bot: Bot, update, error, **kwargs): """ Error handling """ LOGGER.error("An error (%s) occurred: %s" From 24e157d8bc0bd8111fad6d84b799b4aaa4b342e1 Mon Sep 17 00:00:00 2001 From: toxydose Date: Wed, 18 Oct 2017 12:45:26 +0300 Subject: [PATCH 125/284] add TradeReport class in types.py --- core/types.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/core/types.py b/core/types.py index 8ec9ad6..6d46113 100644 --- a/core/types.py +++ b/core/types.py @@ -223,6 +223,18 @@ class Character(Base): user = relationship('User', back_populates='character') +class TradeReport(Base): + __tablename__ = 'trade_reports' + + user_id = Column(BigInteger, ForeignKey(User.id), primary_key=True) + date = Column(DATETIME(fsp=6), primary_key=True) + name = Column(UnicodeText(250)) + building = Column(UnicodeText(250)) + progress_percent = Column(Integer) + report_count = Column(Integer) + report_type = Column(Integer) + + class Report(Base): __tablename__ = 'reports' From 79566423561f71dc475963745adca38fe6c30ae3 Mon Sep 17 00:00:00 2001 From: toxydose Date: Wed, 18 Oct 2017 13:17:27 +0300 Subject: [PATCH 126/284] =?UTF-8?q?=D0=BF=D0=B5=D1=80=D0=B5=D0=BD=D0=BE?= =?UTF-8?q?=D1=81=20Enum=20=D1=82=D0=B8=D0=BF=D0=B0=20=D1=81=D1=82=D1=80?= =?UTF-8?q?=D0=BE=D0=B9=D0=BA=D0=B8,=20relationships=20=D1=82=D0=B0=D0=B1?= =?UTF-8?q?=D0=BB=D0=B8=D1=86,=20=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=BE=20=D0=B7=D0=B0=D1=82=D1=83=D0=BF=D0=B8?= =?UTF-8?q?=D0=BB=D0=BE=D0=B2=D0=BE=20=D1=81=20=D0=B8=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D0=B5=D0=BC=20=D0=BA=D0=BB=D0=B0=D1=81=D1=81=D0=B0.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/common.py | 5 ----- core/types.py | 15 +++++++++++++-- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/core/functions/common.py b/core/functions/common.py index 450ae00..6761848 100644 --- a/core/functions/common.py +++ b/core/functions/common.py @@ -19,11 +19,6 @@ class StockType(Enum): TradeBot = 1 -class BuildType(Enum): - Build = 1 - Repair = 0 - - def error(bot: Bot, update, error, **kwargs): """ Error handling """ LOGGER.error("An error (%s) occurred: %s" diff --git a/core/types.py b/core/types.py index 6d46113..2138336 100644 --- a/core/types.py +++ b/core/types.py @@ -38,6 +38,11 @@ class MessageType(Enum): PHOTO = 9 +class BuildType(Enum): + Build = 1 + Repair = 0 + + ENGINE = create_engine(DB, echo=False, pool_size=200, @@ -96,6 +101,11 @@ class User(Base): back_populates='user', order_by='Report.date.desc()') + build_report = relationship('BuildReport', + back_populates='user', + order_by='BuildReport.date.desc()') + + def __repr__(self): user = '' if self.first_name: @@ -223,8 +233,8 @@ class Character(Base): user = relationship('User', back_populates='character') -class TradeReport(Base): - __tablename__ = 'trade_reports' +class BuildReport(Base): + __tablename__ = 'build_reports' user_id = Column(BigInteger, ForeignKey(User.id), primary_key=True) date = Column(DATETIME(fsp=6), primary_key=True) @@ -234,6 +244,7 @@ class TradeReport(Base): report_count = Column(Integer) report_type = Column(Integer) + user = relationship('User', back_populates='build_report') class Report(Base): __tablename__ = 'reports' From 62b92664cddedcec9556ec5d88ba53c3e44fa854 Mon Sep 17 00:00:00 2001 From: toxydose Date: Wed, 18 Oct 2017 13:33:56 +0300 Subject: [PATCH 127/284] =?UTF-8?q?=D1=80=D0=B5=D1=84=D0=BE=D1=80=D0=BC?= =?UTF-8?q?=D0=B0=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/types.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/types.py b/core/types.py index 2138336..939771b 100644 --- a/core/types.py +++ b/core/types.py @@ -98,14 +98,13 @@ class User(Base): uselist=False) report = relationship('Report', - back_populates='user', - order_by='Report.date.desc()') + back_populates='user', + order_by='Report.date.desc()') build_report = relationship('BuildReport', back_populates='user', order_by='BuildReport.date.desc()') - def __repr__(self): user = '' if self.first_name: @@ -246,6 +245,7 @@ class BuildReport(Base): user = relationship('User', back_populates='build_report') + class Report(Base): __tablename__ = 'reports' From c4ef2fe4cea4438fcb3ebe8a6101924b21aea931 Mon Sep 17 00:00:00 2001 From: toxydose Date: Wed, 18 Oct 2017 13:43:46 +0300 Subject: [PATCH 128/284] =?UTF-8?q?=D1=83=D0=B1=D1=80=D0=B0=D0=BB=20=D0=BD?= =?UTF-8?q?=D0=B5=D0=BD=D1=83=D0=B6=D0=BD=D1=8B=D0=B5=20=D0=BA=D0=BE=D0=BB?= =?UTF-8?q?=D0=BE=D0=BD=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/types.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/core/types.py b/core/types.py index 939771b..535e71e 100644 --- a/core/types.py +++ b/core/types.py @@ -237,10 +237,8 @@ class BuildReport(Base): user_id = Column(BigInteger, ForeignKey(User.id), primary_key=True) date = Column(DATETIME(fsp=6), primary_key=True) - name = Column(UnicodeText(250)) building = Column(UnicodeText(250)) progress_percent = Column(Integer) - report_count = Column(Integer) report_type = Column(Integer) user = relationship('User', back_populates='build_report') From 1a35cb851c3a21b0ad05e1a7efb656167ea5f10e Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Fri, 20 Oct 2017 18:51:41 +0300 Subject: [PATCH 129/284] =?UTF-8?q?=D0=92=D1=8B=D1=85=D0=BE=D0=B4=20=D1=81?= =?UTF-8?q?=20=D0=BE=D1=82=D1=80=D1=8F=D0=B4=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/commands.py | 1 + core/functions/reply_markup.py | 8 +++++++- core/functions/squad.py | 33 +++++++++++++++++++++++++++++++++ core/texts.py | 2 ++ main.py | 18 +++++++++++++++--- 5 files changed, 58 insertions(+), 4 deletions(-) diff --git a/core/commands.py b/core/commands.py index ede4637..1e7989a 100644 --- a/core/commands.py +++ b/core/commands.py @@ -13,6 +13,7 @@ USER_COMMAND_BUILD = '🚧Стройка' USER_COMMAND_CONTACTS = '💬Связь' USER_COMMAND_SQUAD_REQUEST = '⚜Хочу в отряд' +USER_COMMAND_SQUAD_LEAVE = '☄Покинуть отряд' USER_COMMAND_BACK = '🔙Назад' diff --git a/core/functions/reply_markup.py b/core/functions/reply_markup.py index 651ce0c..487d921 100644 --- a/core/functions/reply_markup.py +++ b/core/functions/reply_markup.py @@ -4,7 +4,7 @@ ADMIN_COMMAND_FIRE_UP, ADMIN_COMMAND_SQUAD_LIST, USER_COMMAND_ME, USER_COMMAND_TOP, USER_COMMAND_SQUAD, \ USER_COMMAND_STATISTICS, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, ADMIN_COMMAND_ADMINPANEL, \ USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK, TOP_COMMAND_ATTACK, TOP_COMMAND_DEFENCE, TOP_COMMAND_EXP, \ - STATISTICS_COMMAND_EXP + STATISTICS_COMMAND_EXP, USER_COMMAND_SQUAD_LEAVE def generate_admin_markup(full=False, grp=False): @@ -41,3 +41,9 @@ def generate_statistics_markup(): buttons = [[KeyboardButton(STATISTICS_COMMAND_EXP)], [KeyboardButton(USER_COMMAND_BACK)]] return ReplyKeyboardMarkup(buttons, True) + + +def generate_squad_markup(): + buttons = [[KeyboardButton(USER_COMMAND_SQUAD_LEAVE)], + [KeyboardButton(USER_COMMAND_BACK)]] + return ReplyKeyboardMarkup(buttons, True) diff --git a/core/functions/squad.py b/core/functions/squad.py index 9cd7b1b..7e8c5aa 100644 --- a/core/functions/squad.py +++ b/core/functions/squad.py @@ -1,5 +1,6 @@ from telegram import Update, Bot, ParseMode +from core.functions.reply_markup import generate_squad_markup from core.template import fill_char_template from core.types import User, AdminType, Admin, admin_allowed, Group, Squad, SquadMember, user_allowed from core.utils import send_async @@ -9,6 +10,15 @@ from core.texts import * +@user_allowed +def squad_about(bot: Bot, update: Update, session): + markup = generate_squad_markup() + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_SQUAD_ABOUT, + reply_markup=markup) + + @admin_allowed() def add_squad(bot: Bot, update: Update, session): if update.message.chat.type == 'supergroup': @@ -177,6 +187,29 @@ def remove_from_squad(bot: Bot, update: Update, session): reply_markup=markup, parse_mode=ParseMode.HTML) +@user_allowed +def leave_squad(bot: Bot, update: Update, session): + member = session.query(SquadMember).filter_by(user_id=update.message.from_user.id).first() + user = session.query(User).filter_by(id=update.message.from_user.id).first() + if member: + squad = member.squad + session.delete(member) + session.commit() + admins = session.query(Admin).filter_by(admin_group=squad.chat_id).all() + for adm in admins: + if adm.user_id != update.callback_query.from_user.id: + send_async(bot, chat_id=adm.user_id, + text=MSG_SQUAD_LEAVED.format(user.character.name, squad.squad_name), + parse_mode=ParseMode.HTML) + send_async(bot, chat_id=member.squad_id, + text=MSG_SQUAD_LEAVED.format(user.character.name, squad.squad_name), parse_mode=ParseMode.HTML) + send_async(bot, chat_id=member.user_id, + text=MSG_SQUAD_LEAVED.format(user.character.name, squad.squad_name), parse_mode=ParseMode.HTML) + else: + send_async(bot, chat_id=user.id, + text=MSG_SQUAD_NONE, parse_mode=ParseMode.HTML) + + @admin_allowed(AdminType.GROUP) def add_to_squad(bot: Bot, update: Update, session): squad = session.query(Squad).filter_by(chat_id=update.message.chat.id).first() diff --git a/core/texts.py b/core/texts.py index 1e7fbf5..743543c 100644 --- a/core/texts.py +++ b/core/texts.py @@ -222,6 +222,7 @@ MSG_SQUAD_ADD_IN_SQUAD = '{} уже в отряде (возможно не в вашем).' MSG_SQUAD_ADD_ACCEPTED = '{} принял предложение.' MSG_SQUAD_ADD_DECLINED = '{} бесполезен и никто ему не поможет.' +MSG_SQUAD_NONE = 'Похоже ты не в отряде' MSG_SQUAD_READY = '{} бойцов отряда {} к битве готовы!\n{}⚔ {}🛡' MSG_FULL_TEXT_LINE = '{}: {}👥 {}⚔ {}🛡\n' @@ -231,6 +232,7 @@ MSG_TOP_ABOUT = '🏆 Топы 🏆' MSG_STATISTICS_ABOUT = '📈Статистика📈' +MSG_SQUAD_ABOUT = '⚜Отряд⚜' MSG_TOP_FORMAT = '{}. {} ({}🌟) - {}{}\n' MSG_TOP_DEFENCE = '🛡Топ дэферы:\n' diff --git a/main.py b/main.py index 89ed5b8..06a35cb 100644 --- a/main.py +++ b/main.py @@ -19,7 +19,7 @@ from core.commands import ADMIN_COMMAND_STATUS, ADMIN_COMMAND_RECRUIT, ADMIN_COMMAND_ORDER, ADMIN_COMMAND_SQUAD_LIST, \ ADMIN_COMMAND_GROUPS, ADMIN_COMMAND_FIRE_UP, USER_COMMAND_ME, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, \ USER_COMMAND_SQUAD, USER_COMMAND_STATISTICS, USER_COMMAND_TOP, USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK, \ - TOP_COMMAND_ATTACK, TOP_COMMAND_DEFENCE, TOP_COMMAND_EXP, STATISTICS_COMMAND_EXP + TOP_COMMAND_ATTACK, TOP_COMMAND_DEFENCE, TOP_COMMAND_EXP, STATISTICS_COMMAND_EXP, USER_COMMAND_SQUAD_LEAVE from core.functions.activity import ( day_activity, week_activity, battle_activity ) @@ -46,8 +46,8 @@ add_squad, del_squad, set_invite_link, set_squad_name, enable_thorns, disable_thorns, squad_list, squad_request, list_squad_requests, - open_hiring, close_hiring, remove_from_squad, add_to_squad -) + open_hiring, close_hiring, remove_from_squad, add_to_squad, + leave_squad) from core.functions.statistics import statistic_about, exp_statistic from core.functions.top import top_about, attack_top, exp_top, def_top from core.functions.triggers import ( @@ -233,6 +233,8 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): chat_id=update.message.chat.id, text=MSG_IN_DEV, parse_mode=ParseMode.HTML) + elif text == USER_COMMAND_SQUAD_LEAVE.lower: + leave_squad(bot, update) elif text == USER_COMMAND_CONTACTS.lower(): send_async(bot, chat_id=update.message.chat.id, @@ -358,6 +360,16 @@ def ready_to_battle_result(bot: Bot, job_queue): Session.rollback() +@run_async +def fresh_profiles(bot: Bot, job_queue): + session = Session() + try: + pass + except SQLAlchemyError as err: + bot.logger.error(str(err)) + Session.rollback() + + def main(): # Create the EventHandler and pass it your bot's token. updater = Updater(TOKEN) From 7de1f3c8b489055ae3effa5eaebde9db93572164 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Fri, 20 Oct 2017 18:56:15 +0300 Subject: [PATCH 130/284] =?UTF-8?q?=D0=97=D0=B0=D0=B1=D1=8B=D0=BB=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/main.py b/main.py index 06a35cb..1c08651 100644 --- a/main.py +++ b/main.py @@ -47,7 +47,7 @@ enable_thorns, disable_thorns, squad_list, squad_request, list_squad_requests, open_hiring, close_hiring, remove_from_squad, add_to_squad, - leave_squad) + leave_squad, squad_about) from core.functions.statistics import statistic_about, exp_statistic from core.functions.top import top_about, attack_top, exp_top, def_top from core.functions.triggers import ( @@ -229,10 +229,7 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): elif text == STATISTICS_COMMAND_EXP.lower(): exp_statistic(bot, update) elif text == USER_COMMAND_SQUAD.lower(): - send_async(bot, - chat_id=update.message.chat.id, - text=MSG_IN_DEV, - parse_mode=ParseMode.HTML) + squad_about(bot, update) elif text == USER_COMMAND_SQUAD_LEAVE.lower: leave_squad(bot, update) elif text == USER_COMMAND_CONTACTS.lower(): From 52fade990e46199cf4b07337375be8b6187576ce Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Fri, 20 Oct 2017 18:59:14 +0300 Subject: [PATCH 131/284] =?UTF-8?q?=D0=9A=D0=BE=D1=81=D1=8F=D1=87=D1=91?= =?UTF-8?q?=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index 1c08651..e5e9249 100644 --- a/main.py +++ b/main.py @@ -230,7 +230,7 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): exp_statistic(bot, update) elif text == USER_COMMAND_SQUAD.lower(): squad_about(bot, update) - elif text == USER_COMMAND_SQUAD_LEAVE.lower: + elif text == USER_COMMAND_SQUAD_LEAVE.lower(): leave_squad(bot, update) elif text == USER_COMMAND_CONTACTS.lower(): send_async(bot, From dba9fe304d26994b6f90c48e607d694ee15cfe0a Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Fri, 20 Oct 2017 21:53:37 +0300 Subject: [PATCH 132/284] =?UTF-8?q?=D0=A4=D0=B8=D0=BA=D1=81=20=D0=BE=D1=82?= =?UTF-8?q?=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B8=20=D1=81=D0=BE=D0=BE=D0=B1?= =?UTF-8?q?=D1=89=D0=B5=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/squad.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/functions/squad.py b/core/functions/squad.py index 7e8c5aa..b108326 100644 --- a/core/functions/squad.py +++ b/core/functions/squad.py @@ -197,7 +197,7 @@ def leave_squad(bot: Bot, update: Update, session): session.commit() admins = session.query(Admin).filter_by(admin_group=squad.chat_id).all() for adm in admins: - if adm.user_id != update.callback_query.from_user.id: + if adm.user_id != update.message.from_user.id: send_async(bot, chat_id=adm.user_id, text=MSG_SQUAD_LEAVED.format(user.character.name, squad.squad_name), parse_mode=ParseMode.HTML) From de954fe9b4b7da2f485ebb9d5d9f858d7e9969b2 Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Fri, 20 Oct 2017 23:03:24 +0300 Subject: [PATCH 133/284] =?UTF-8?q?=D0=9D=D0=B0=D0=BF=D0=BE=D0=BC=D0=B8?= =?UTF-8?q?=D0=BD=D0=B0=D0=BD=D0=B8=D1=8F=20=D0=BE=D0=B1=20=D0=BE=D0=B1?= =?UTF-8?q?=D0=BD=D0=BE=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D0=B8=20=D0=BF=D1=80?= =?UTF-8?q?=D0=BE=D1=84=D0=B8=D0=BB=D1=8F=20=D0=B8=20=D0=B8=D0=B7=D0=B3?= =?UTF-8?q?=D0=BD=D0=B0=D0=BD=D0=B8=D0=B5=20=D0=B8=D0=B7=20=D0=BE=D1=82?= =?UTF-8?q?=D1=80=D1=8F=D0=B4=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/texts.py | 3 +++ main.py | 46 +++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/core/texts.py b/core/texts.py index 743543c..f1e8d2f 100644 --- a/core/texts.py +++ b/core/texts.py @@ -238,3 +238,6 @@ MSG_TOP_DEFENCE = '🛡Топ дэферы:\n' MSG_TOP_ATTACK = '⚔Топ атакеры:\n' MSG_TOP_EXPERIENCE = '🔥Топ качки:\n' + +MSG_UPDATE_PROFILE = 'Пришли свежий игровой профиль (🏅 команда "/hero"), пока я не выгнал тебя с отряда.' +MSG_SQUAD_DELETE_OUTDATED = 'Ты был изгнан из отряда за то, что давно не обновлял свой профиль.' diff --git a/main.py b/main.py index e5e9249..57706b3 100644 --- a/main.py +++ b/main.py @@ -1,10 +1,11 @@ # -*- coding: utf-8 -*- -from datetime import datetime, time +from datetime import datetime, time, timedelta import json import logging import re +from sqlalchemy import func, tuple_ from telegram import ( Bot, Update, InlineKeyboardButton, InlineKeyboardMarkup, ParseMode ) @@ -15,7 +16,7 @@ from telegram.ext.dispatcher import run_async from telegram.error import TelegramError -from config import TOKEN, GOVERNMENT_CHAT +from config import TOKEN, GOVERNMENT_CHAT, CASTLE from core.commands import ADMIN_COMMAND_STATUS, ADMIN_COMMAND_RECRUIT, ADMIN_COMMAND_ORDER, ADMIN_COMMAND_SQUAD_LIST, \ ADMIN_COMMAND_GROUPS, ADMIN_COMMAND_FIRE_UP, USER_COMMAND_ME, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, \ USER_COMMAND_SQUAD, USER_COMMAND_STATISTICS, USER_COMMAND_TOP, USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK, \ @@ -61,8 +62,8 @@ from core.regexp import PROFILE, HERO, REPORT from core.texts import ( MSG_SQUAD_READY, MSG_FULL_TEXT_LINE, MSG_FULL_TEXT_TOTAL, - MSG_MAIN_INLINE_BATTLE, MSG_MAIN_READY_TO_BATTLE, MSG_IN_DEV) -from core.types import Session, Order, Squad, Admin, user_allowed + MSG_MAIN_INLINE_BATTLE, MSG_MAIN_READY_TO_BATTLE, MSG_IN_DEV, MSG_UPDATE_PROFILE, MSG_SQUAD_DELETE_OUTDATED) +from core.types import Session, Order, Squad, Admin, user_allowed, Character, SquadMember from core.utils import add_user, send_async from sqlalchemy.exc import SQLAlchemyError @@ -361,7 +362,32 @@ def ready_to_battle_result(bot: Bot, job_queue): def fresh_profiles(bot: Bot, job_queue): session = Session() try: - pass + actual_profiles = session.query(Character.user_id, func.max(Character.date)). \ + group_by(Character.user_id) + actual_profiles = actual_profiles.all() + characters = session.query(Character).filter(tuple_(Character.user_id, Character.date) + .in_([(a[0], a[1]) for a in actual_profiles]), + datetime.now() - timedelta(days=3) > Character.date + > datetime.now() - timedelta(days=14)) + if CASTLE: + characters = characters.filter_by(castle=CASTLE) + characters = characters.all() + for character in characters: + send_async(bot, + chat_id=character.user_id, + text=MSG_UPDATE_PROFILE, + parse_mode=ParseMode.HTML) + characters = session.query(Character).filter(tuple_(Character.user_id, Character.date) + .in_([(a[0], a[1]) for a in actual_profiles]), + Character.date < datetime.now() - timedelta(days=14)).all() + members = session.query(SquadMember).filter(SquadMember.user_id in + [character.user_id for character in characters]).all() + for member in members: + session.delete(member) + send_async(bot, + chat_id=member.user_id, + text=MSG_SQUAD_DELETE_OUTDATED, + parse_mode=ParseMode.HTML) except SQLAlchemyError as err: bot.logger.error(str(err)) Session.rollback() @@ -437,6 +463,16 @@ def main(): updater.job_queue.run_daily(ready_to_battle, time(hour=23, minute=50)) updater.job_queue.run_daily(ready_to_battle_result, time(hour=23, minute=55)) + updater.job_queue.run_daily(fresh_profiles, + time(hour=7, minute=40)) + updater.job_queue.run_daily(fresh_profiles, + time(hour=11, minute=40)) + updater.job_queue.run_daily(fresh_profiles, + time(hour=15, minute=40)) + updater.job_queue.run_daily(fresh_profiles, + time(hour=19, minute=40)) + updater.job_queue.run_daily(fresh_profiles, + time(hour=23, minute=40)) # Start the Bot updater.start_polling() From c17294f7dd3c37149dca0f8b910d649d35b56715 Mon Sep 17 00:00:00 2001 From: toxydose Date: Sun, 22 Oct 2017 15:02:14 +0300 Subject: [PATCH 134/284] =?UTF-8?q?=D1=81=D1=82=D1=80=D0=BE=D0=B8=D1=82?= =?UTF-8?q?=D0=B5=D0=BB=D1=8C=D0=BD=D1=8B=D0=B5=20=D1=80=D0=B5=D0=BF=D0=BE?= =?UTF-8?q?=D1=80=D1=82=D1=8B=20=D0=B1=D0=B5=D0=B7=20=D0=BB=D0=BE=D0=B3?= =?UTF-8?q?=D0=B8=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/profile.py | 51 +++++++++++++++++++++++++++++++++++++-- core/texts.py | 3 +++ main.py | 16 +++++++++--- 3 files changed, 65 insertions(+), 5 deletions(-) diff --git a/core/functions/profile.py b/core/functions/profile.py index 1cc0505..856d6ac 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -1,8 +1,8 @@ from telegram import Update, Bot, ParseMode from core.functions.inline_keyboard_handling import generate_profile_buttons -from core.regexp import HERO, PROFILE, REPORT -from core.types import Character, Report, User, admin_allowed, Equip, user_allowed +from core.regexp import HERO, PROFILE, REPORT, BUILD_REPORT, REPAIR_REPORT +from core.types import Character, Report, User, admin_allowed, Equip, user_allowed, BuildReport from core.utils import send_async from datetime import timedelta, datetime import re @@ -99,6 +99,53 @@ def parse_reports(report, user_id, date, session): return report +def parse_build_reports(report, user_id, date, session): + parsed_data = re.search(BUILD_REPORT, report) + report = session.query(BuildReport).filter_by(user_id=user_id, date=date).first() + if report is None: + report = BuildReport() + report.user_id = user_id + report.date = date + report.building = str(parsed_data.group(1)) + report.progress_percent = str(parsed_data.group(2)) + report.report_type = 1 + session.add(report) + session.commit() + +def parse_repair_reports(report, user_id, date, session): + parsed_data = re.search(REPAIR_REPORT, report) + report = session.query(BuildReport).filter_by(user_id=user_id, date=date).first() + if report is None: + report = BuildReport() + report.user_id = user_id + report.date = date + report.building = str(parsed_data.group(1)) + report.report_type = 0 + session.add(report) + session.commit() + +@user_allowed +def build_report_received(bot: Bot, update: Update, session): + report = re.search(BUILD_REPORT, update.message.text) + user = session.query(User).filter_by(id=update.message.from_user.id).first() + if report: + parse_build_reports(update.message.text, update.message.from_user.id, update.message.forward_date, session) + send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_OK) + else: + send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_EXISTS) + + +@user_allowed +def repair_report_received(bot: Bot, update: Update, session): + report = re.search(REPAIR_REPORT, update.message.text) + user = session.query(User).filter_by(id=update.message.from_user.id).first() + if report: + parse_repair_reports(update.message.text, update.message.from_user.id, update.message.forward_date, session) + send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_OK) + else: + send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_EXISTS) + + @user_allowed def report_received(bot: Bot, update: Update, session): # if datetime.now() - update.message.forward_date > timedelta(minutes=1): diff --git a/core/texts.py b/core/texts.py index 1e7fbf5..f8fca14 100644 --- a/core/texts.py +++ b/core/texts.py @@ -147,6 +147,9 @@ MSG_MAIN_INLINE_BATTLE = 'ГРАБЬНАСИЛУЙУБИВАЙ!' MSG_MAIN_READY_TO_BATTLE = 'К битве готовсь!' # ----------------------- +MSG_BUILD_REPORT_EXISTS = 'Ты уже кидал этот репорт!' +MSG_BUILD_REPORT_OK = 'Спасибо за помощь на стройке! Это твой {} репорт.' +MSG_BUILD_REPORT_FORWARDED = 'Больше не присылай мне репорты с твинков!!!' MSG_REPORT_OLD = 'Твой репорт уже попахивает, в следующий раз постарайся прислать его в течении минуты после получения.' MSG_REPORT_EXISTS = 'Репорт за эту битву уже внесён.' diff --git a/main.py b/main.py index 89ed5b8..ca216cd 100644 --- a/main.py +++ b/main.py @@ -41,7 +41,8 @@ ) from core.functions.order_groups import group_list, add_group from core.functions.pin import pin, not_pin_all, pin_all, silent_pin -from core.functions.profile import char_update, char_show, find_by_username, report_received +from core.functions.profile import char_update, char_show, find_by_username, report_received, build_report_received, \ + repair_report_received from core.functions.squad import ( add_squad, del_squad, set_invite_link, set_squad_name, enable_thorns, disable_thorns, @@ -58,7 +59,7 @@ from core.functions.welcome import ( welcome, set_welcome, show_welcome, enable_welcome, disable_welcome ) -from core.regexp import PROFILE, HERO, REPORT +from core.regexp import PROFILE, HERO, REPORT, BUILD_REPORT, REPAIR_REPORT from core.texts import ( MSG_SQUAD_READY, MSG_FULL_TEXT_LINE, MSG_FULL_TEXT_TOTAL, MSG_MAIN_INLINE_BATTLE, MSG_MAIN_READY_TO_BATTLE, MSG_IN_DEV) @@ -177,6 +178,12 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): report_received(bot, update) job_queue.run_once(del_msg, 2, (update.message.chat.id, update.message.message_id)) + elif 'Ты вернулся со стройки:' in text: + if update.message.forward_from.id == CWBOT_ID: + build_report_received(bot, update) + elif 'Здание отремонтировано:' in text: + if update.message.forward_from.id == CWBOT_ID: + repair_report_received(bot, update) else: trigger_show(bot, update) @@ -251,7 +258,10 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): char_update(bot, update) elif re.search(REPORT, update.message.text): report_received(bot, update) - + elif re.search(BUILD_REPORT, update.message.text): + build_report_received(bot, update) + elif re.search(REPAIR_REPORT, update.message.text): + repair_report_received(bot, update) elif from_id == TRADEBOT_ID: if '📦твой склад с материалами:' in text: trade_compare(bot, update, chat_data) From b0ea31aad5997718c1cf5a6180de77845f098c5f Mon Sep 17 00:00:00 2001 From: toxydose Date: Sun, 22 Oct 2017 15:04:12 +0300 Subject: [PATCH 135/284] Merge branch 'master' of https://github.com/DuskDev/HelperBot into origin/toxydose_dusk --- core/commands.py | 1 + core/functions/reply_markup.py | 8 +++- core/functions/squad.py | 33 +++++++++++++++++ core/texts.py | 5 +++ main.py | 67 ++++++++++++++++++++++++++++------ 5 files changed, 102 insertions(+), 12 deletions(-) diff --git a/core/commands.py b/core/commands.py index ede4637..1e7989a 100644 --- a/core/commands.py +++ b/core/commands.py @@ -13,6 +13,7 @@ USER_COMMAND_BUILD = '🚧Стройка' USER_COMMAND_CONTACTS = '💬Связь' USER_COMMAND_SQUAD_REQUEST = '⚜Хочу в отряд' +USER_COMMAND_SQUAD_LEAVE = '☄Покинуть отряд' USER_COMMAND_BACK = '🔙Назад' diff --git a/core/functions/reply_markup.py b/core/functions/reply_markup.py index 651ce0c..487d921 100644 --- a/core/functions/reply_markup.py +++ b/core/functions/reply_markup.py @@ -4,7 +4,7 @@ ADMIN_COMMAND_FIRE_UP, ADMIN_COMMAND_SQUAD_LIST, USER_COMMAND_ME, USER_COMMAND_TOP, USER_COMMAND_SQUAD, \ USER_COMMAND_STATISTICS, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, ADMIN_COMMAND_ADMINPANEL, \ USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK, TOP_COMMAND_ATTACK, TOP_COMMAND_DEFENCE, TOP_COMMAND_EXP, \ - STATISTICS_COMMAND_EXP + STATISTICS_COMMAND_EXP, USER_COMMAND_SQUAD_LEAVE def generate_admin_markup(full=False, grp=False): @@ -41,3 +41,9 @@ def generate_statistics_markup(): buttons = [[KeyboardButton(STATISTICS_COMMAND_EXP)], [KeyboardButton(USER_COMMAND_BACK)]] return ReplyKeyboardMarkup(buttons, True) + + +def generate_squad_markup(): + buttons = [[KeyboardButton(USER_COMMAND_SQUAD_LEAVE)], + [KeyboardButton(USER_COMMAND_BACK)]] + return ReplyKeyboardMarkup(buttons, True) diff --git a/core/functions/squad.py b/core/functions/squad.py index 9cd7b1b..b108326 100644 --- a/core/functions/squad.py +++ b/core/functions/squad.py @@ -1,5 +1,6 @@ from telegram import Update, Bot, ParseMode +from core.functions.reply_markup import generate_squad_markup from core.template import fill_char_template from core.types import User, AdminType, Admin, admin_allowed, Group, Squad, SquadMember, user_allowed from core.utils import send_async @@ -9,6 +10,15 @@ from core.texts import * +@user_allowed +def squad_about(bot: Bot, update: Update, session): + markup = generate_squad_markup() + send_async(bot, + chat_id=update.message.chat.id, + text=MSG_SQUAD_ABOUT, + reply_markup=markup) + + @admin_allowed() def add_squad(bot: Bot, update: Update, session): if update.message.chat.type == 'supergroup': @@ -177,6 +187,29 @@ def remove_from_squad(bot: Bot, update: Update, session): reply_markup=markup, parse_mode=ParseMode.HTML) +@user_allowed +def leave_squad(bot: Bot, update: Update, session): + member = session.query(SquadMember).filter_by(user_id=update.message.from_user.id).first() + user = session.query(User).filter_by(id=update.message.from_user.id).first() + if member: + squad = member.squad + session.delete(member) + session.commit() + admins = session.query(Admin).filter_by(admin_group=squad.chat_id).all() + for adm in admins: + if adm.user_id != update.message.from_user.id: + send_async(bot, chat_id=adm.user_id, + text=MSG_SQUAD_LEAVED.format(user.character.name, squad.squad_name), + parse_mode=ParseMode.HTML) + send_async(bot, chat_id=member.squad_id, + text=MSG_SQUAD_LEAVED.format(user.character.name, squad.squad_name), parse_mode=ParseMode.HTML) + send_async(bot, chat_id=member.user_id, + text=MSG_SQUAD_LEAVED.format(user.character.name, squad.squad_name), parse_mode=ParseMode.HTML) + else: + send_async(bot, chat_id=user.id, + text=MSG_SQUAD_NONE, parse_mode=ParseMode.HTML) + + @admin_allowed(AdminType.GROUP) def add_to_squad(bot: Bot, update: Update, session): squad = session.query(Squad).filter_by(chat_id=update.message.chat.id).first() diff --git a/core/texts.py b/core/texts.py index f8fca14..5053aea 100644 --- a/core/texts.py +++ b/core/texts.py @@ -225,6 +225,7 @@ MSG_SQUAD_ADD_IN_SQUAD = '{} уже в отряде (возможно не в вашем).' MSG_SQUAD_ADD_ACCEPTED = '{} принял предложение.' MSG_SQUAD_ADD_DECLINED = '{} бесполезен и никто ему не поможет.' +MSG_SQUAD_NONE = 'Похоже ты не в отряде' MSG_SQUAD_READY = '{} бойцов отряда {} к битве готовы!\n{}⚔ {}🛡' MSG_FULL_TEXT_LINE = '{}: {}👥 {}⚔ {}🛡\n' @@ -234,8 +235,12 @@ MSG_TOP_ABOUT = '🏆 Топы 🏆' MSG_STATISTICS_ABOUT = '📈Статистика📈' +MSG_SQUAD_ABOUT = '⚜Отряд⚜' MSG_TOP_FORMAT = '{}. {} ({}🌟) - {}{}\n' MSG_TOP_DEFENCE = '🛡Топ дэферы:\n' MSG_TOP_ATTACK = '⚔Топ атакеры:\n' MSG_TOP_EXPERIENCE = '🔥Топ качки:\n' + +MSG_UPDATE_PROFILE = 'Пришли свежий игровой профиль (🏅 команда "/hero"), пока я не выгнал тебя с отряда.' +MSG_SQUAD_DELETE_OUTDATED = 'Ты был изгнан из отряда за то, что давно не обновлял свой профиль.' diff --git a/main.py b/main.py index ca216cd..6cf1ed3 100644 --- a/main.py +++ b/main.py @@ -1,10 +1,11 @@ # -*- coding: utf-8 -*- -from datetime import datetime, time +from datetime import datetime, time, timedelta import json import logging import re +from sqlalchemy import func, tuple_ from telegram import ( Bot, Update, InlineKeyboardButton, InlineKeyboardMarkup, ParseMode ) @@ -15,11 +16,11 @@ from telegram.ext.dispatcher import run_async from telegram.error import TelegramError -from config import TOKEN, GOVERNMENT_CHAT +from config import TOKEN, GOVERNMENT_CHAT, CASTLE from core.commands import ADMIN_COMMAND_STATUS, ADMIN_COMMAND_RECRUIT, ADMIN_COMMAND_ORDER, ADMIN_COMMAND_SQUAD_LIST, \ ADMIN_COMMAND_GROUPS, ADMIN_COMMAND_FIRE_UP, USER_COMMAND_ME, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, \ USER_COMMAND_SQUAD, USER_COMMAND_STATISTICS, USER_COMMAND_TOP, USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK, \ - TOP_COMMAND_ATTACK, TOP_COMMAND_DEFENCE, TOP_COMMAND_EXP, STATISTICS_COMMAND_EXP + TOP_COMMAND_ATTACK, TOP_COMMAND_DEFENCE, TOP_COMMAND_EXP, STATISTICS_COMMAND_EXP, USER_COMMAND_SQUAD_LEAVE from core.functions.activity import ( day_activity, week_activity, battle_activity ) @@ -47,8 +48,8 @@ add_squad, del_squad, set_invite_link, set_squad_name, enable_thorns, disable_thorns, squad_list, squad_request, list_squad_requests, - open_hiring, close_hiring, remove_from_squad, add_to_squad -) + open_hiring, close_hiring, remove_from_squad, add_to_squad, + leave_squad, squad_about) from core.functions.statistics import statistic_about, exp_statistic from core.functions.top import top_about, attack_top, exp_top, def_top from core.functions.triggers import ( @@ -62,8 +63,8 @@ from core.regexp import PROFILE, HERO, REPORT, BUILD_REPORT, REPAIR_REPORT from core.texts import ( MSG_SQUAD_READY, MSG_FULL_TEXT_LINE, MSG_FULL_TEXT_TOTAL, - MSG_MAIN_INLINE_BATTLE, MSG_MAIN_READY_TO_BATTLE, MSG_IN_DEV) -from core.types import Session, Order, Squad, Admin, user_allowed + MSG_MAIN_INLINE_BATTLE, MSG_MAIN_READY_TO_BATTLE, MSG_IN_DEV, MSG_UPDATE_PROFILE, MSG_SQUAD_DELETE_OUTDATED) +from core.types import Session, Order, Squad, Admin, user_allowed, Character, SquadMember from core.utils import add_user, send_async from sqlalchemy.exc import SQLAlchemyError @@ -236,10 +237,9 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): elif text == STATISTICS_COMMAND_EXP.lower(): exp_statistic(bot, update) elif text == USER_COMMAND_SQUAD.lower(): - send_async(bot, - chat_id=update.message.chat.id, - text=MSG_IN_DEV, - parse_mode=ParseMode.HTML) + squad_about(bot, update) + elif text == USER_COMMAND_SQUAD_LEAVE.lower(): + leave_squad(bot, update) elif text == USER_COMMAND_CONTACTS.lower(): send_async(bot, chat_id=update.message.chat.id, @@ -368,6 +368,41 @@ def ready_to_battle_result(bot: Bot, job_queue): Session.rollback() +@run_async +def fresh_profiles(bot: Bot, job_queue): + session = Session() + try: + actual_profiles = session.query(Character.user_id, func.max(Character.date)). \ + group_by(Character.user_id) + actual_profiles = actual_profiles.all() + characters = session.query(Character).filter(tuple_(Character.user_id, Character.date) + .in_([(a[0], a[1]) for a in actual_profiles]), + datetime.now() - timedelta(days=3) > Character.date + > datetime.now() - timedelta(days=14)) + if CASTLE: + characters = characters.filter_by(castle=CASTLE) + characters = characters.all() + for character in characters: + send_async(bot, + chat_id=character.user_id, + text=MSG_UPDATE_PROFILE, + parse_mode=ParseMode.HTML) + characters = session.query(Character).filter(tuple_(Character.user_id, Character.date) + .in_([(a[0], a[1]) for a in actual_profiles]), + Character.date < datetime.now() - timedelta(days=14)).all() + members = session.query(SquadMember).filter(SquadMember.user_id in + [character.user_id for character in characters]).all() + for member in members: + session.delete(member) + send_async(bot, + chat_id=member.user_id, + text=MSG_SQUAD_DELETE_OUTDATED, + parse_mode=ParseMode.HTML) + except SQLAlchemyError as err: + bot.logger.error(str(err)) + Session.rollback() + + def main(): # Create the EventHandler and pass it your bot's token. updater = Updater(TOKEN) @@ -438,6 +473,16 @@ def main(): updater.job_queue.run_daily(ready_to_battle, time(hour=23, minute=50)) updater.job_queue.run_daily(ready_to_battle_result, time(hour=23, minute=55)) + updater.job_queue.run_daily(fresh_profiles, + time(hour=7, minute=40)) + updater.job_queue.run_daily(fresh_profiles, + time(hour=11, minute=40)) + updater.job_queue.run_daily(fresh_profiles, + time(hour=15, minute=40)) + updater.job_queue.run_daily(fresh_profiles, + time(hour=19, minute=40)) + updater.job_queue.run_daily(fresh_profiles, + time(hour=23, minute=40)) # Start the Bot updater.start_polling() From 7b89b1ca19784ba2319f7568c7ace8ca928bdc90 Mon Sep 17 00:00:00 2001 From: toxydose Date: Sun, 22 Oct 2017 15:25:48 +0300 Subject: [PATCH 136/284] =?UTF-8?q?=D0=B5=D1=89=D0=B5=20=D1=81=D1=82=D1=80?= =?UTF-8?q?=D0=BE=D0=B9=20=D1=80=D0=B5=D0=BF=D0=BE=D1=80=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/profile.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/core/functions/profile.py b/core/functions/profile.py index 856d6ac..c9923ce 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -109,8 +109,10 @@ def parse_build_reports(report, user_id, date, session): report.building = str(parsed_data.group(1)) report.progress_percent = str(parsed_data.group(2)) report.report_type = 1 - session.add(report) - session.commit() + session.add(report) + session.commit() + return report + def parse_repair_reports(report, user_id, date, session): parsed_data = re.search(REPAIR_REPORT, report) @@ -121,8 +123,10 @@ def parse_repair_reports(report, user_id, date, session): report.date = date report.building = str(parsed_data.group(1)) report.report_type = 0 - session.add(report) - session.commit() + session.add(report) + session.commit() + return report + @user_allowed def build_report_received(bot: Bot, update: Update, session): From eef1013fc5330329c8142bbd1d24a984b4785bb8 Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Sun, 22 Oct 2017 15:30:15 +0300 Subject: [PATCH 137/284] =?UTF-8?q?=D0=9F=D0=BE=D0=B4=D1=83=D1=87=D0=B8?= =?UTF-8?q?=D0=BB=D0=B8=20=D0=B0=D0=BB=D1=85=D0=B8=D0=BC=D0=B8=D1=8E=20:/?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/main.py b/main.py index 57706b3..b999a29 100644 --- a/main.py +++ b/main.py @@ -367,8 +367,8 @@ def fresh_profiles(bot: Bot, job_queue): actual_profiles = actual_profiles.all() characters = session.query(Character).filter(tuple_(Character.user_id, Character.date) .in_([(a[0], a[1]) for a in actual_profiles]), - datetime.now() - timedelta(days=3) > Character.date - > datetime.now() - timedelta(days=14)) + datetime.now() - timedelta(days=3) > Character.date, + Character.date > datetime.now() - timedelta(days=14)) if CASTLE: characters = characters.filter_by(castle=CASTLE) characters = characters.all() @@ -472,7 +472,7 @@ def main(): updater.job_queue.run_daily(fresh_profiles, time(hour=19, minute=40)) updater.job_queue.run_daily(fresh_profiles, - time(hour=23, minute=40)) + time(hour=15, minute=28)) # Start the Bot updater.start_polling() From 228877b35cf8856e2bbd68eae7df6e1993e6e520 Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Sun, 22 Oct 2017 15:40:51 +0300 Subject: [PATCH 138/284] =?UTF-8?q?=D0=97=D0=B0=D0=B1=D1=8B=D0=BB=20=D0=BD?= =?UTF-8?q?=D0=B0=D0=B7=D0=B0=D0=B4=20=D0=BF=D0=BE=D0=BC=D0=B5=D0=BD=D1=8F?= =?UTF-8?q?=D1=82=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index b999a29..4dd7d36 100644 --- a/main.py +++ b/main.py @@ -472,7 +472,7 @@ def main(): updater.job_queue.run_daily(fresh_profiles, time(hour=19, minute=40)) updater.job_queue.run_daily(fresh_profiles, - time(hour=15, minute=28)) + time(hour=23, minute=40)) # Start the Bot updater.start_polling() From d9fd9beed30300d997cc47c07e51c0c07fd22d71 Mon Sep 17 00:00:00 2001 From: toxydose Date: Sun, 22 Oct 2017 15:52:20 +0300 Subject: [PATCH 139/284] =?UTF-8?q?=D0=B5=D1=89=D0=B5=20=D1=81=D1=82=D1=80?= =?UTF-8?q?=D0=BE=D0=B9=D1=80=D0=B5=D0=BF=D0=BE=D1=80=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/profile.py | 14 ++++++++++---- core/types.py | 5 ----- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/core/functions/profile.py b/core/functions/profile.py index c9923ce..68ab3d7 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -8,10 +8,16 @@ import re from core.template import fill_char_template from core.texts import * +from enum import Enum from config import CASTLE +class BuildType(Enum): + Build = 1 + Repair = 0 + + def parse_profile(profile, user_id, date, session): parsed_data = re.search(PROFILE, profile) char = session.query(Character).filter_by(user_id=user_id, date=date).first() @@ -108,7 +114,7 @@ def parse_build_reports(report, user_id, date, session): report.date = date report.building = str(parsed_data.group(1)) report.progress_percent = str(parsed_data.group(2)) - report.report_type = 1 + report.report_type = BuildType.Build.value session.add(report) session.commit() return report @@ -122,7 +128,7 @@ def parse_repair_reports(report, user_id, date, session): report.user_id = user_id report.date = date report.building = str(parsed_data.group(1)) - report.report_type = 0 + report.report_type = BuildType.Repair.value session.add(report) session.commit() return report @@ -132,7 +138,7 @@ def parse_repair_reports(report, user_id, date, session): def build_report_received(bot: Bot, update: Update, session): report = re.search(BUILD_REPORT, update.message.text) user = session.query(User).filter_by(id=update.message.from_user.id).first() - if report: + if report and user.character: parse_build_reports(update.message.text, update.message.from_user.id, update.message.forward_date, session) send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_OK) else: @@ -143,7 +149,7 @@ def build_report_received(bot: Bot, update: Update, session): def repair_report_received(bot: Bot, update: Update, session): report = re.search(REPAIR_REPORT, update.message.text) user = session.query(User).filter_by(id=update.message.from_user.id).first() - if report: + if report and user.character: parse_repair_reports(update.message.text, update.message.from_user.id, update.message.forward_date, session) send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_OK) else: diff --git a/core/types.py b/core/types.py index 535e71e..916d744 100644 --- a/core/types.py +++ b/core/types.py @@ -38,11 +38,6 @@ class MessageType(Enum): PHOTO = 9 -class BuildType(Enum): - Build = 1 - Repair = 0 - - ENGINE = create_engine(DB, echo=False, pool_size=200, From 97cc30d892bdf9fb06c37d0d1f04cb5f93ffb96f Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Sun, 22 Oct 2017 21:41:13 +0300 Subject: [PATCH 140/284] =?UTF-8?q?=D0=A1=D1=80=D0=B5=D0=B4=D0=BD=D0=B8?= =?UTF-8?q?=D0=B9=20=D1=83=D1=80=D0=BE=D0=B2=D0=B5=D0=BD=D1=8C=20=D0=BD?= =?UTF-8?q?=D0=B0=20=D0=BA=D0=BD=D0=BE=D0=BF=D0=BA=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index dba7135..e29d3b6 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -219,6 +219,7 @@ def generate_profile_buttons(user, back_key=False): def generate_squad_list_key(squad, session): attack = 0 defence = 0 + level = 0 members = squad.members user_ids = [] for member in members: @@ -231,12 +232,14 @@ def generate_squad_list_key(squad, session): for character in characters: attack += character.attack defence += character.defence + level += character.level return [InlineKeyboardButton( - '{} : {}⚔ {}🛡 {}👥'.format( + '{} : {}⚔ {}🛡 {}👥 {}🏅'.format( squad.squad_name, attack, defence, - len(members) + len(members), + int(level/len(members)) ), callback_data=json.dumps({'t': QueryType.MemberList.value, 'id': squad.chat_id}))] From e4e9b42ad0ff32714a046eb56dc4dd5337215bef Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Sun, 22 Oct 2017 21:44:51 +0300 Subject: [PATCH 141/284] =?UTF-8?q?=D0=A4=D0=B0=D1=81=D1=82=D1=84=D0=B8?= =?UTF-8?q?=D0=BA=D1=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index e29d3b6..550fb32 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -239,7 +239,7 @@ def generate_squad_list_key(squad, session): attack, defence, len(members), - int(level/len(members)) + int(level/(len(members) or 1)) ), callback_data=json.dumps({'t': QueryType.MemberList.value, 'id': squad.chat_id}))] From cf5ebc0d301f6fe50b740411de0431729a55e484 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Wed, 25 Oct 2017 18:30:40 +0300 Subject: [PATCH 142/284] =?UTF-8?q?=D0=91=D0=B0=D0=BD=D1=8C=D1=87=D0=B8?= =?UTF-8?q?=D0=BA=D0=B8-=D0=B1=D0=B0=D0=BD=D0=B0=D0=BD=D1=8C=D1=87=D0=B8?= =?UTF-8?q?=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/admins.py | 2 +- core/functions/ban.py | 59 +++++++++++++++++++++++++++++++++++++++ core/functions/common.py | 4 +-- core/functions/profile.py | 4 +-- core/texts.py | 8 ++++++ core/types.py | 30 ++++++++++++++++++-- main.py | 3 ++ 7 files changed, 102 insertions(+), 8 deletions(-) create mode 100644 core/functions/ban.py diff --git a/core/functions/admins.py b/core/functions/admins.py index a53c7da..c87f693 100644 --- a/core/functions/admins.py +++ b/core/functions/admins.py @@ -153,7 +153,7 @@ def set_global_admin(bot: Bot, update: Update, session): text=MSG_NEW_GLOBAL_ADMIN_EXISTS.format(user.username)) -@user_allowed +@user_allowed(False) def set_super_admin(bot: Bot, update: Update, session): msg = update.message.text.split(' ', 1)[1] msg = msg.replace('@', '') diff --git a/core/functions/ban.py b/core/functions/ban.py new file mode 100644 index 0000000..a1c82dd --- /dev/null +++ b/core/functions/ban.py @@ -0,0 +1,59 @@ +from datetime import datetime + +from telegram import Bot, Update + +from core.texts import MSG_USER_UNKNOWN, MSG_USER_BANNED, MSG_YOU_BANNED, MSG_BAN_COMPLETE, MSG_ALREADY_BANNED, \ + MSG_USER_NOT_BANNED, MSG_USER_UNBANNED, MSG_YOU_UNBANNED +from core.types import admin_allowed, Ban, User, Squad, SquadMember, Admin +from core.utils import send_async + + +@admin_allowed() +def ban(bot: Bot, update: Update, session): + username, reason = update.message.text.split(' ', 2)[1:] + username = username.replace('@', '') + user = session.query(User).filter_by(username=username).first() + if user: + banned = session.query(Ban).filter_by(user_id=user.id).first() + if banned: + send_async(bot, chat_id=update.message.chat.id, + text=MSG_ALREADY_BANNED.format(banned.to_date, banned.reason)) + else: + banned = Ban() + banned.user_id = user.id + banned.from_date = datetime.now() + banned.to_date = datetime.max + banned.reason = reason or 'Причина не указана' + member = session.query(SquadMember).filter_by(user_id=user.id).first() + if member: + session.delete(member) + admins = session.query(Admin).filter_by(user_id=user.id).all() + for admin in admins: + session.delete(admin) + session.add(banned) + session.commit() + squads = session.query(Squad).all() + for squad in squads: + send_async(bot, chat_id=squad.chat_id, text=MSG_USER_BANNED.format('@' + username)) + send_async(bot, chat_id=user.id, text=MSG_YOU_BANNED.format(banned.reason)) + send_async(bot, chat_id=update.message.chat.id, text=MSG_BAN_COMPLETE) + else: + send_async(bot, chat_id=update.message.chat.id, text=MSG_USER_UNKNOWN) + + +@admin_allowed() +def unban(bot: Bot, update: Update, session): + username = update.message.text.split(' ', 1)[1] + username = username.replace('@', '') + user = session.query(User).filter_by(username=username).first() + if user: + banned = session.query(Ban).filter_by(user_id=user.id).first() + if banned: + session.delete(banned) + session.commit() + send_async(bot, chat_id=user.id, text=MSG_YOU_UNBANNED) + send_async(bot, chat_id=update.message.chat.id, text=MSG_USER_UNBANNED.format('@' + user.username)) + else: + send_async(bot, chat_id=update.message.chat.id, text=MSG_USER_NOT_BANNED) + else: + send_async(bot, chat_id=update.message.chat.id, text=MSG_USER_UNKNOWN) diff --git a/core/functions/common.py b/core/functions/common.py index 6761848..1fa745f 100644 --- a/core/functions/common.py +++ b/core/functions/common.py @@ -106,7 +106,7 @@ def get_diff(dict_one, dict_two): return resource_diff_add, resource_diff_del -@user_allowed +@user_allowed(False) def stock_compare(bot: Bot, update: Update, session, chat_data: dict): old_stock = session.query(Stock).filter_by(user_id=update.message.from_user.id, stock_type=StockType.Stock.value).order_by(Stock.date.desc()).first() @@ -160,7 +160,7 @@ def delete_user(bot: Bot, update: Update, session): bot.unbanChatMember(update.message.reply_to_message.chat_id, update.message.reply_to_message.from_user.id) -@user_allowed +@user_allowed(False) def trade_compare(bot: Bot, update: Update, session, chat_data: dict): old_stock = session.query(Stock).filter_by(user_id=update.message.from_user.id, stock_type=StockType.TradeBot.value).order_by(Stock.date.desc()).first() diff --git a/core/functions/profile.py b/core/functions/profile.py index 1cc0505..4f14c56 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -99,7 +99,7 @@ def parse_reports(report, user_id, date, session): return report -@user_allowed +@user_allowed(False) def report_received(bot: Bot, update: Update, session): # if datetime.now() - update.message.forward_date > timedelta(minutes=1): # send_async(bot, chat_id=update.message.chat.id, text=MSG_REPORT_OLD) @@ -121,7 +121,7 @@ def report_received(bot: Bot, update: Update, session): send_async(bot, chat_id=update.message.from_user.id, text=MSG_REPORT_EXISTS) -@user_allowed +@user_allowed(False) def char_update(bot: Bot, update: Update, session): if update.message.date - update.message.forward_date > timedelta(minutes=1): send_async(bot, chat_id=update.message.chat.id, text=MSG_PROFILE_OLD) diff --git a/core/texts.py b/core/texts.py index f1e8d2f..703db3e 100644 --- a/core/texts.py +++ b/core/texts.py @@ -241,3 +241,11 @@ MSG_UPDATE_PROFILE = 'Пришли свежий игровой профиль (🏅 команда "/hero"), пока я не выгнал тебя с отряда.' MSG_SQUAD_DELETE_OUTDATED = 'Ты был изгнан из отряда за то, что давно не обновлял свой профиль.' + +MSG_ALREADY_BANNED = 'Пользователь уже забанен. Причина: {2}.' +MSG_USER_BANNED = 'Член нашего ордена {} был замечен в нарушении правил и был с позором изгнан из замка!' +MSG_YOU_BANNED = 'Вас изгнали по причине {}' +MSG_BAN_COMPLETE = 'Изгнание завершено.' +MSG_USER_NOT_BANNED = 'Мы не изгоняли этого господина.' +MSG_USER_UNBANNED = '{} больше не изгнан.' +MSG_YOU_UNBANNED = 'Мы снова можем пообщаться 🌚' diff --git a/core/types.py b/core/types.py index 8ec9ad6..a677459 100644 --- a/core/types.py +++ b/core/types.py @@ -285,6 +285,15 @@ class LocalTrigger(Base): message_type = Column(Integer, default=0) +class Ban(Base): + __tablename__ = 'banned_users' + + user_id = Column(BigInteger, ForeignKey(User.id), primary_key=True) + reason = Column(UnicodeText(2500)) + from_date = Column(DATETIME(fsp=6)) + to_date = Column(DATETIME(fsp=6)) + + def check_admin(update, session, adm_type): allowed = False if adm_type == AdminType.NOT_ADMIN: @@ -306,12 +315,22 @@ def check_admin(update, session, adm_type): return allowed -def admin_allowed(adm_type=AdminType.FULL): +def check_ban(update, session): + ban = session.query(Ban).filter_by(user_id=update.message.from_user.id).first() + if ban is None or ban.to_date < datetime.now(): + return True + else: + return False + + +def admin_allowed(adm_type=AdminType.FULL, ban_enable=True): def decorate(func): def wrapper(bot: Bot, update, *args, **kwargs): session = Session() try: allowed = check_admin(update, session, adm_type) + if ban_enable: + allowed &= check_ban(update, session) if allowed: func(bot, update, session, *args, **kwargs) except SQLAlchemyError as err: @@ -321,8 +340,13 @@ def wrapper(bot: Bot, update, *args, **kwargs): return decorate -def user_allowed(func): - return admin_allowed(AdminType.NOT_ADMIN)(func) +def user_allowed(ban_enable=True): + if callable(ban_enable): + return admin_allowed(AdminType.NOT_ADMIN)(ban_enable) + else: + def wrap(func): + return admin_allowed(AdminType.NOT_ADMIN, ban_enable)(func) + return wrap Base.metadata.create_all(ENGINE) diff --git a/main.py b/main.py index 4dd7d36..4fbfa51 100644 --- a/main.py +++ b/main.py @@ -28,6 +28,7 @@ list_admins, admins_for_users, set_admin, del_admin, set_global_admin, set_super_admin, del_global_admin ) +from core.functions.ban import unban, ban from core.functions.bosses import ( boss_leader, boss_zhalo, boss_monoeye, boss_hydra) from core.functions.orders import order, orders @@ -435,6 +436,8 @@ def main(): disp.add_handler(CommandHandler("set_invite_link", set_invite_link)) disp.add_handler(CommandHandler("find", find_by_username)) disp.add_handler(CommandHandler("add", add_to_squad)) + disp.add_handler(CommandHandler("ban", ban)) + disp.add_handler(CommandHandler("unban", unban)) disp.add_handler(CallbackQueryHandler(callback_query, pass_chat_data=True)) From 5e228a344a6fba3d4264a531e48be9dfb449129f Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Thu, 26 Oct 2017 15:44:57 +0300 Subject: [PATCH 143/284] =?UTF-8?q?=D0=91=D1=8B=D1=81=D1=82=D1=80=D0=BE?= =?UTF-8?q?=D1=84=D0=B8=D0=BA=D1=81=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/types.py | 3 ++- main.py | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/core/types.py b/core/types.py index a677459..3517011 100644 --- a/core/types.py +++ b/core/types.py @@ -316,7 +316,8 @@ def check_admin(update, session, adm_type): def check_ban(update, session): - ban = session.query(Ban).filter_by(user_id=update.message.from_user.id).first() + ban = session.query(Ban).filter_by(user_id=update.message.from_user.id + if update.message else update.callback_query.from_user).first() if ban is None or ban.to_date < datetime.now(): return True else: diff --git a/main.py b/main.py index 4fbfa51..5bfefc5 100644 --- a/main.py +++ b/main.py @@ -381,8 +381,8 @@ def fresh_profiles(bot: Bot, job_queue): characters = session.query(Character).filter(tuple_(Character.user_id, Character.date) .in_([(a[0], a[1]) for a in actual_profiles]), Character.date < datetime.now() - timedelta(days=14)).all() - members = session.query(SquadMember).filter(SquadMember.user_id in - [character.user_id for character in characters]).all() + members = session.query(SquadMember).filter(SquadMember.user_id + .in_([character.user_id for character in characters])).all() for member in members: session.delete(member) send_async(bot, From 47e60e9823949c4a4079d20c1bd4ce4b50c4eb36 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Thu, 26 Oct 2017 16:48:57 +0300 Subject: [PATCH 144/284] =?UTF-8?q?=D0=A3=D0=BF=D1=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/types.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/types.py b/core/types.py index 3517011..9ebe71e 100644 --- a/core/types.py +++ b/core/types.py @@ -317,7 +317,7 @@ def check_admin(update, session, adm_type): def check_ban(update, session): ban = session.query(Ban).filter_by(user_id=update.message.from_user.id - if update.message else update.callback_query.from_user).first() + if update.message else update.callback_query.from_user.id).first() if ban is None or ban.to_date < datetime.now(): return True else: From 1380358bc856dc4107c5375525d9eb4107db49b6 Mon Sep 17 00:00:00 2001 From: toxydose Date: Thu, 26 Oct 2017 16:56:28 +0300 Subject: [PATCH 145/284] =?UTF-8?q?=D1=83=D0=B1=D1=80=D0=B0=D0=BB=20=D0=BF?= =?UTF-8?q?=D0=BE=D0=B8=D1=81=D0=BA=20=D1=81=D1=82=D1=80=D0=BE=D0=B8=D1=82?= =?UTF-8?q?=D0=B5=D0=BB=D1=8C=D0=BD=D1=8B=D1=85=20=D1=80=D0=B5=D0=BF=D0=BE?= =?UTF-8?q?=D1=80=D1=82=D0=BE=D0=B2=20=D0=B2=20=D0=B3=D1=80=D1=83=D0=BF?= =?UTF-8?q?=D0=BF=D0=B0=D1=85=20=D0=B8=20=D1=87=D0=B0=D1=82=D0=B0=D1=85.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 6 ------ 1 file changed, 6 deletions(-) diff --git a/main.py b/main.py index ce955ad..544558d 100644 --- a/main.py +++ b/main.py @@ -180,12 +180,6 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): report_received(bot, update) job_queue.run_once(del_msg, 2, (update.message.chat.id, update.message.message_id)) - elif 'Ты вернулся со стройки:' in text: - if update.message.forward_from.id == CWBOT_ID: - build_report_received(bot, update) - elif 'Здание отремонтировано:' in text: - if update.message.forward_from.id == CWBOT_ID: - repair_report_received(bot, update) else: trigger_show(bot, update) From 2e369d1b2a9154097a1328a2a5c43981612e45ce Mon Sep 17 00:00:00 2001 From: toxydose Date: Thu, 26 Oct 2017 19:57:42 +0300 Subject: [PATCH 146/284] =?UTF-8?q?=D0=BF=D1=80=D0=BE=D0=BF=D1=83=D1=89?= =?UTF-8?q?=D0=B5=D0=BD=D0=BD=D1=8B=D0=B9=20=D0=BA=D0=BE=D0=BC=D0=BC=D0=B8?= =?UTF-8?q?=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 1 + 1 file changed, 1 insertion(+) diff --git a/main.py b/main.py index 544558d..2a18ced 100644 --- a/main.py +++ b/main.py @@ -393,6 +393,7 @@ def fresh_profiles(bot: Bot, job_queue): chat_id=member.user_id, text=MSG_SQUAD_DELETE_OUTDATED, parse_mode=ParseMode.HTML) + session.commit() except SQLAlchemyError as err: bot.logger.error(str(err)) Session.rollback() From 077a859242d9d0f328c966f6e11f45e850ade710 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Fri, 27 Oct 2017 13:14:59 +0300 Subject: [PATCH 147/284] =?UTF-8?q?=D0=A1=D0=BE=D0=BE=D0=B1=D1=89=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D1=8F=20=D0=BE=D0=B1=20=D1=83=D0=B4=D0=B0=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B8=20=D0=BF=D0=BE=20=D0=BD=D0=B5=D0=B0?= =?UTF-8?q?=D0=BA=D1=82=D0=B8=D0=B2=D0=BD=D0=BE=D1=81=D1=82=D0=B8=20=D0=B0?= =?UTF-8?q?=D0=B4=D0=BC=D0=B8=D0=BD=D0=B0=D0=BC=20=D0=B8=20=D0=B2=20=D0=BE?= =?UTF-8?q?=D1=82=D1=80=D1=8F=D0=B4,=20=D0=B0=20=D0=B7=D0=B0=D0=BE=D0=B4?= =?UTF-8?q?=D0=BD=D0=BE=20=D0=BE=D1=82=D0=BA=D0=BB=D1=8E=D1=87=D0=B8=D0=BB?= =?UTF-8?q?=20=D1=83=D0=B4=D0=B0=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=80?= =?UTF-8?q?=D0=B5=D0=BF=D0=BE=D1=80=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/texts.py | 1 + main.py | 14 +++++++++++--- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/core/texts.py b/core/texts.py index abe91f9..9ca2515 100644 --- a/core/texts.py +++ b/core/texts.py @@ -244,6 +244,7 @@ MSG_UPDATE_PROFILE = 'Пришли свежий игровой профиль (🏅 команда "/hero"), пока я не выгнал тебя с отряда.' MSG_SQUAD_DELETE_OUTDATED = 'Ты был изгнан из отряда за то, что давно не обновлял свой профиль.' +MSG_SQUAD_DELETE_OUTDATED_EXT = '{} был изгнан из отряда {} за то, что давно не обновлял свой профиль.' MSG_ALREADY_BANNED = 'Пользователь уже забанен. Причина: {2}.' MSG_USER_BANNED = 'Член нашего ордена {} был замечен в нарушении правил и был с позором изгнан из замка!' diff --git a/main.py b/main.py index 2a18ced..98947fd 100644 --- a/main.py +++ b/main.py @@ -64,7 +64,8 @@ from core.regexp import PROFILE, HERO, REPORT, BUILD_REPORT, REPAIR_REPORT from core.texts import ( MSG_SQUAD_READY, MSG_FULL_TEXT_LINE, MSG_FULL_TEXT_TOTAL, - MSG_MAIN_INLINE_BATTLE, MSG_MAIN_READY_TO_BATTLE, MSG_IN_DEV, MSG_UPDATE_PROFILE, MSG_SQUAD_DELETE_OUTDATED) + MSG_MAIN_INLINE_BATTLE, MSG_MAIN_READY_TO_BATTLE, MSG_IN_DEV, MSG_UPDATE_PROFILE, MSG_SQUAD_DELETE_OUTDATED, + MSG_SQUAD_DELETE_OUTDATED_EXT) from core.types import Session, Order, Squad, Admin, user_allowed, Character, SquadMember from core.utils import add_user, send_async @@ -178,8 +179,6 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): elif 'твои результаты в бою:' in text: if update.message.forward_from.id == CWBOT_ID: report_received(bot, update) - job_queue.run_once(del_msg, 2, (update.message.chat.id, - update.message.message_id)) else: trigger_show(bot, update) @@ -389,6 +388,15 @@ def fresh_profiles(bot: Bot, job_queue): .in_([character.user_id for character in characters])).all() for member in members: session.delete(member) + admins = session.query(Admin).filter_by(admin_group=member.squad_id).all() + for adm in admins: + send_async(bot, chat_id=adm.user_id, + text=MSG_SQUAD_DELETE_OUTDATED_EXT + .format(member.user.character.name, member.squad.squad_name), + parse_mode=ParseMode.HTML) + send_async(bot, chat_id=member.squad_id, + text=MSG_SQUAD_DELETE_OUTDATED_EXT.format(member.user.character.name, member.squad.squad_name), + parse_mode=ParseMode.HTML) send_async(bot, chat_id=member.user_id, text=MSG_SQUAD_DELETE_OUTDATED, From ad2b248bb5dcf1fff7b21f83c7e56effd60e68b7 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Fri, 27 Oct 2017 13:28:32 +0300 Subject: [PATCH 148/284] =?UTF-8?q?=D0=9F=D1=80=D0=B8=20=D1=83=D0=B4=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D0=B8=20=D0=BE=D1=82=D1=80=D1=8F=D0=B4?= =?UTF-8?q?=D0=B0=20=D0=B2=D1=8B=D1=87=D0=B8=D1=89=D0=B0=D0=B5=D0=BC=20?= =?UTF-8?q?=D0=B5=D0=B3=D0=BE=20=D0=B8=D0=B7=20=D1=81=D0=BF=D0=B8=D1=81?= =?UTF-8?q?=D0=BA=D0=BE=D0=B2=20=D1=80=D0=B0=D1=81=D1=81=D1=8B=D0=BB=D0=BA?= =?UTF-8?q?=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/squad.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core/functions/squad.py b/core/functions/squad.py index b108326..0a56eb8 100644 --- a/core/functions/squad.py +++ b/core/functions/squad.py @@ -70,6 +70,8 @@ def del_squad(bot: Bot, update: Update, session): if update.message.chat.type == 'supergroup' and squad is not None: for member in squad.members: session.delete(member) + for order_group_item in squad.chat.group_items: + session.delete(order_group_item) session.delete(squad) session.commit() send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_DELETE) From 95826d1b338dd01145fa08d66c5217852a2aaf20 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Fri, 27 Oct 2017 13:52:01 +0300 Subject: [PATCH 149/284] =?UTF-8?q?=D0=A4=D0=B8=D0=BA=D1=81=D1=8B=20=D0=BF?= =?UTF-8?q?=D0=BE=20=D1=81=D1=82=D1=80=D0=BE=D0=B9=D0=BA=D0=B0=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/profile.py | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/core/functions/profile.py b/core/functions/profile.py index 77c4df4..6a37a65 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -139,10 +139,15 @@ def build_report_received(bot: Bot, update: Update, session): report = re.search(BUILD_REPORT, update.message.text) user = session.query(User).filter_by(id=update.message.from_user.id).first() if report and user.character: - parse_build_reports(update.message.text, update.message.from_user.id, update.message.forward_date, session) - send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_OK) - else: - send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_EXISTS) + old_report = session.query(BuildReport) \ + .filter(BuildReport.user_id == user.id, + BuildReport.date > update.message.forward_date - timedelta(minutes=5), + BuildReport.date < update.message.forward_date + timedelta(minutes=5)).first() + if old_report is None: + parse_build_reports(update.message.text, update.message.from_user.id, update.message.forward_date, session) + send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_OK) + else: + send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_EXISTS) @user_allowed(False) @@ -150,10 +155,15 @@ def repair_report_received(bot: Bot, update: Update, session): report = re.search(REPAIR_REPORT, update.message.text) user = session.query(User).filter_by(id=update.message.from_user.id).first() if report and user.character: - parse_repair_reports(update.message.text, update.message.from_user.id, update.message.forward_date, session) - send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_OK) - else: - send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_EXISTS) + old_report = session.query(BuildReport) \ + .filter(BuildReport.user_id == user.id, + BuildReport.date > update.message.forward_date - timedelta(minutes=5), + BuildReport.date < update.message.forward_date + timedelta(minutes=5)).first() + if old_report is None: + parse_repair_reports(update.message.text, update.message.from_user.id, update.message.forward_date, session) + send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_OK) + else: + send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_EXISTS) @user_allowed(False) From 38af0eae270aa13909c2ae519df7b9f9aacc419f Mon Sep 17 00:00:00 2001 From: toxydose Date: Tue, 31 Oct 2017 10:35:43 +0200 Subject: [PATCH 150/284] =?UTF-8?q?=D1=81=D1=87=D0=B5=D1=82=D1=87=D0=B8?= =?UTF-8?q?=D0=BA=20=D1=81=D1=82=D1=80=D0=BE=D0=B9=20=D1=80=D0=B5=D0=BF?= =?UTF-8?q?=D0=BE=D1=80=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/profile.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/core/functions/profile.py b/core/functions/profile.py index 6a37a65..135c55c 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -145,7 +145,8 @@ def build_report_received(bot: Bot, update: Update, session): BuildReport.date < update.message.forward_date + timedelta(minutes=5)).first() if old_report is None: parse_build_reports(update.message.text, update.message.from_user.id, update.message.forward_date, session) - send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_OK) + user_builds = session.query(BuildReport).filter_by(user_id=user.id).count() + send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_OK.format(user_builds)) else: send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_EXISTS) @@ -161,7 +162,8 @@ def repair_report_received(bot: Bot, update: Update, session): BuildReport.date < update.message.forward_date + timedelta(minutes=5)).first() if old_report is None: parse_repair_reports(update.message.text, update.message.from_user.id, update.message.forward_date, session) - send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_OK) + user_builds = session.query(BuildReport).filter_by(user_id=user.id).count() + send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_OK.format(user_builds)) else: send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_EXISTS) From d60a5c4ec767489ca79b96e848274f44bd2b6e88 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 31 Oct 2017 11:58:40 +0300 Subject: [PATCH 151/284] =?UTF-8?q?=D0=A4=D0=B8=D0=BA=D1=81=20=D1=81=D1=82?= =?UTF-8?q?=D0=B0=D1=82=D0=B8=D1=81=D1=82=D0=B8=D0=BA=D0=B8=20=D0=B8=20?= =?UTF-8?q?=D1=83=D0=B4=D0=B0=D0=BB=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=BA=D0=B0?= =?UTF-8?q?=D1=80=D1=82=D0=B8=D0=BD=D0=BE=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/statistics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/functions/statistics.py b/core/functions/statistics.py index 9cbb65a..fcfdaeb 100644 --- a/core/functions/statistics.py +++ b/core/functions/statistics.py @@ -39,6 +39,6 @@ def exp_statistic(bot: Bot, update: Update, session): plot.savefig(file, format='png') with open(filename, 'rb') as file: bot.sendPhoto(update.message.chat.id, file, 'В среднем {} опыта в день' - .format(int((y[-1] - y[0])/(x[-1] - x[0]).days))) + .format(int((y[-1] - y[0])/((x[-1] - x[0]) or 1).days))) plot.clf() os.remove(filename) From ebe17d6beb3891111ee54eef27a9f62eb8ebd5da Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 31 Oct 2017 12:00:09 +0300 Subject: [PATCH 152/284] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=B2=D0=B8=D0=BB?= =?UTF-8?q?=D1=8C=D0=BD=D1=8B=D0=B9=20=D1=84=D0=B8=D0=BA=D1=81=20=D1=81?= =?UTF-8?q?=D1=82=D0=B0=D1=82=D0=B8=D1=81=D1=82=D0=B8=D0=BA=D0=B8=20=D0=B8?= =?UTF-8?q?=20=D1=83=D0=B4=D0=B0=D0=BB=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=BA?= =?UTF-8?q?=D0=B0=D1=80=D1=82=D0=B8=D0=BD=D0=BE=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/statistics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/functions/statistics.py b/core/functions/statistics.py index fcfdaeb..517783a 100644 --- a/core/functions/statistics.py +++ b/core/functions/statistics.py @@ -39,6 +39,6 @@ def exp_statistic(bot: Bot, update: Update, session): plot.savefig(file, format='png') with open(filename, 'rb') as file: bot.sendPhoto(update.message.chat.id, file, 'В среднем {} опыта в день' - .format(int((y[-1] - y[0])/((x[-1] - x[0]) or 1).days))) + .format(int((y[-1] - y[0])/((x[-1] - x[0]).days or 1)))) plot.clf() os.remove(filename) From eae432c2e0e3eb0d9da60d96d11197dec3de400b Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Thu, 2 Nov 2017 15:16:34 +0300 Subject: [PATCH 153/284] PY-2017.2.3 + + + + \ No newline at end of file From 6a1093753cb9348d5a26ce395e6b90facc37ec02 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Thu, 2 Nov 2017 15:33:02 +0300 Subject: [PATCH 154/284] PY-2017.2.3 + + + \ No newline at end of file diff --git a/_windows/laf.xml b/_windows/laf.xml new file mode 100644 index 0000000..c1f98d9 --- /dev/null +++ b/_windows/laf.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/codestyles/Default.xml b/codestyles/Default.xml new file mode 100644 index 0000000..e598e06 --- /dev/null +++ b/codestyles/Default.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/colors.scheme.xml b/colors.scheme.xml new file mode 100644 index 0000000..39308cd --- /dev/null +++ b/colors.scheme.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/debugger.xml b/debugger.xml new file mode 100644 index 0000000..544ab15 --- /dev/null +++ b/debugger.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/editor.codeinsight.xml b/editor.codeinsight.xml new file mode 100644 index 0000000..b43f2d4 --- /dev/null +++ b/editor.codeinsight.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/editor.xml b/editor.xml new file mode 100644 index 0000000..19bd26a --- /dev/null +++ b/editor.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/filetypes.xml b/filetypes.xml new file mode 100644 index 0000000..324c956 --- /dev/null +++ b/filetypes.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/ide.general.xml b/ide.general.xml new file mode 100644 index 0000000..8329a5d --- /dev/null +++ b/ide.general.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/ignore.xml b/ignore.xml new file mode 100644 index 0000000..b26bee8 --- /dev/null +++ b/ignore.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From 5c074206ae98f65efdcfb2a2454d0417e34ae78a Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Thu, 2 Nov 2017 16:27:37 +0300 Subject: [PATCH 155/284] =?UTF-8?q?=D0=A4=D1=83=D0=BD=D0=BA=D1=86=D0=B8?= =?UTF-8?q?=D1=8F=20=D1=81=D0=BE=D0=B7=D1=8B=D0=B2=D0=B0=20=D0=BE=D1=82?= =?UTF-8?q?=D1=80=D1=8F=D0=B4=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/squad.py | 12 ++++++++++++ main.py | 4 +++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/core/functions/squad.py b/core/functions/squad.py index 0a56eb8..9688f17 100644 --- a/core/functions/squad.py +++ b/core/functions/squad.py @@ -230,3 +230,15 @@ def add_to_squad(bot: Bot, update: Update, session): text=MSG_SQUAD_ADD_IN_SQUAD.format('@' + username)) elif user.character is None: send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_NO_PROFILE) + + +@admin_allowed(AdminType.GROUP) +def call_squad(bot: Bot, update: Update, session): + squad = session.query(Squad).filter_by(chat_id=update.message.chat.id).first() + if squad is not None: + users = session.query(User).join(SquadMember).filter(User.id == SquadMember.user_id)\ + .filter(SquadMember.squad_id == squad.chat_id).all() + msg = 'Все сюда!\n' + for user in users: + msg += '@' + user.username + ' ' + send_async(bot, chat_id=update.message.chat.id, text=msg) diff --git a/main.py b/main.py index 98947fd..7c0d2e7 100644 --- a/main.py +++ b/main.py @@ -50,7 +50,7 @@ enable_thorns, disable_thorns, squad_list, squad_request, list_squad_requests, open_hiring, close_hiring, remove_from_squad, add_to_squad, - leave_squad, squad_about) + leave_squad, squad_about, call_squad) from core.functions.statistics import statistic_about, exp_statistic from core.functions.top import top_about, attack_top, exp_top, def_top from core.functions.triggers import ( @@ -121,6 +121,8 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): set_welcome(bot, update) elif text == 'помощь': help_msg(bot, update) + elif text == 'отряд': + call_squad(bot, update) elif text == 'покажи приветствие': show_welcome(bot, update) elif text == 'включи приветствие': From a19ca1756e2b371686cbfdc3dc0f46a8b61524c1 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Thu, 2 Nov 2017 17:02:56 +0300 Subject: [PATCH 156/284] =?UTF-8?q?=D0=9F=D0=BE=D0=BA=D0=B0=D0=B7=20=D1=80?= =?UTF-8?q?=D0=B5=D0=BF=D0=BE=D1=80=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/commands.py | 3 ++- core/functions/reply_markup.py | 10 ++++++---- core/functions/squad.py | 31 ++++++++++++++++++++++++++++++- main.py | 7 +++++-- 4 files changed, 43 insertions(+), 8 deletions(-) diff --git a/core/commands.py b/core/commands.py index 1e7989a..b50db1b 100644 --- a/core/commands.py +++ b/core/commands.py @@ -4,7 +4,8 @@ ADMIN_COMMAND_RECRUIT = '📬Заявки в отряд' ADMIN_COMMAND_FIRE_UP = '🔥Алтарь' ADMIN_COMMAND_SQUAD_LIST = '🗂Список отряда' -ADMIN_COMMAND_ADMINPANEL = '/admin' +ADMIN_COMMAND_ADMINPANEL = '🌚Админочка🌚' +ADMIN_COMMAND_REPORTS = '📜Репорты' USER_COMMAND_ME = '🏅Герой' USER_COMMAND_TOP = '🌟Топ' diff --git a/core/functions/reply_markup.py b/core/functions/reply_markup.py index 487d921..efd34ea 100644 --- a/core/functions/reply_markup.py +++ b/core/functions/reply_markup.py @@ -4,7 +4,7 @@ ADMIN_COMMAND_FIRE_UP, ADMIN_COMMAND_SQUAD_LIST, USER_COMMAND_ME, USER_COMMAND_TOP, USER_COMMAND_SQUAD, \ USER_COMMAND_STATISTICS, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, ADMIN_COMMAND_ADMINPANEL, \ USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK, TOP_COMMAND_ATTACK, TOP_COMMAND_DEFENCE, TOP_COMMAND_EXP, \ - STATISTICS_COMMAND_EXP, USER_COMMAND_SQUAD_LEAVE + STATISTICS_COMMAND_EXP, USER_COMMAND_SQUAD_LEAVE, ADMIN_COMMAND_REPORTS def generate_admin_markup(full=False, grp=False): @@ -43,7 +43,9 @@ def generate_statistics_markup(): return ReplyKeyboardMarkup(buttons, True) -def generate_squad_markup(): - buttons = [[KeyboardButton(USER_COMMAND_SQUAD_LEAVE)], - [KeyboardButton(USER_COMMAND_BACK)]] +def generate_squad_markup(is_group_admin=False): + buttons = [[KeyboardButton(USER_COMMAND_SQUAD_LEAVE)]] + if is_group_admin: + buttons.append([KeyboardButton(ADMIN_COMMAND_REPORTS)]) + buttons.append([KeyboardButton(USER_COMMAND_BACK)]) return ReplyKeyboardMarkup(buttons, True) diff --git a/core/functions/squad.py b/core/functions/squad.py index 9688f17..f2b4d51 100644 --- a/core/functions/squad.py +++ b/core/functions/squad.py @@ -1,8 +1,10 @@ +from datetime import datetime + from telegram import Update, Bot, ParseMode from core.functions.reply_markup import generate_squad_markup from core.template import fill_char_template -from core.types import User, AdminType, Admin, admin_allowed, Group, Squad, SquadMember, user_allowed +from core.types import User, AdminType, Admin, admin_allowed, Group, Squad, SquadMember, user_allowed, Report, Character from core.utils import send_async from core.functions.inline_keyboard_handling import generate_squad_list, \ generate_leave_squad, generate_squad_request, generate_squad_request_answer, generate_fire_up, \ @@ -242,3 +244,30 @@ def call_squad(bot: Bot, update: Update, session): for user in users: msg += '@' + user.username + ' ' send_async(bot, chat_id=update.message.chat.id, text=msg) + + +@admin_allowed(AdminType.GROUP) +def battle_reports_show(bot: Bot, update: Update, session): + admin = session.query(Admin, Squad).filter(Admin.user_id == update.message.from_user.id, + Squad.chat_id == Admin.admin_group).all() + group_admin = [] + for adm, squad in admin: + if squad is not None: + group_admin.append([adm, squad]) + for adm, squad in group_admin: + now = datetime.now() + time_from = datetime(now.year, now.month, + now.day, int(now.hour / 4) * 4, 0, 0) + reports = session.query(Report, User).join(SquadMember)\ + .filter(SquadMember.squad_id == adm.admin_group, + User.id == SquadMember.user_id, + Report.user_id == SquadMember.user_id, + Report.date > time_from).all() + text = 'Репорты отряда {} за битву {}\n'.format(squad.squad_name, time_from) + for report, user in reports: + if report: + text += '{} ({}): 🔥{} 💰{} 📦{}\n'.format(report.name, user.username, + report.earned_exp, report.earned_gold, report.earned_stock) + else: + text += '{} ({}): проспал\n'.format(user.character.name, user.username) + send_async(bot, chat_id=update.message.chat.id, text=text) diff --git a/main.py b/main.py index 7c0d2e7..0358d75 100644 --- a/main.py +++ b/main.py @@ -20,7 +20,8 @@ from core.commands import ADMIN_COMMAND_STATUS, ADMIN_COMMAND_RECRUIT, ADMIN_COMMAND_ORDER, ADMIN_COMMAND_SQUAD_LIST, \ ADMIN_COMMAND_GROUPS, ADMIN_COMMAND_FIRE_UP, USER_COMMAND_ME, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, \ USER_COMMAND_SQUAD, USER_COMMAND_STATISTICS, USER_COMMAND_TOP, USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK, \ - TOP_COMMAND_ATTACK, TOP_COMMAND_DEFENCE, TOP_COMMAND_EXP, STATISTICS_COMMAND_EXP, USER_COMMAND_SQUAD_LEAVE + TOP_COMMAND_ATTACK, TOP_COMMAND_DEFENCE, TOP_COMMAND_EXP, STATISTICS_COMMAND_EXP, USER_COMMAND_SQUAD_LEAVE, \ + ADMIN_COMMAND_REPORTS from core.functions.activity import ( day_activity, week_activity, battle_activity ) @@ -50,7 +51,7 @@ enable_thorns, disable_thorns, squad_list, squad_request, list_squad_requests, open_hiring, close_hiring, remove_from_squad, add_to_squad, - leave_squad, squad_about, call_squad) + leave_squad, squad_about, call_squad, battle_reports_show) from core.functions.statistics import statistic_about, exp_statistic from core.functions.top import top_about, attack_top, exp_top, def_top from core.functions.triggers import ( @@ -211,6 +212,8 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): squad_list(bot, update) elif text == ADMIN_COMMAND_GROUPS.lower(): group_list(bot, update) + elif text == ADMIN_COMMAND_REPORTS.lower(): + battle_reports_show(bot, update) elif text == ADMIN_COMMAND_FIRE_UP.lower(): remove_from_squad(bot, update) elif text == USER_COMMAND_ME.lower(): From f2a8b59db29f3b6d883cffbc61c27b0d69a33062 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Thu, 2 Nov 2017 17:08:17 +0300 Subject: [PATCH 157/284] =?UTF-8?q?=D0=9D=D0=B5=D0=B1=D0=BE=D0=BB=D1=8C?= =?UTF-8?q?=D1=88=D0=B0=D1=8F=20=D0=BF=D0=BE=D0=BF=D1=80=D0=B0=D0=B2=D0=BE?= =?UTF-8?q?=D1=87=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/squad.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core/functions/squad.py b/core/functions/squad.py index f2b4d51..21c59fe 100644 --- a/core/functions/squad.py +++ b/core/functions/squad.py @@ -14,7 +14,9 @@ @user_allowed def squad_about(bot: Bot, update: Update, session): - markup = generate_squad_markup() + admin = session.query(Admin).filter(Admin.user_id == update.message.from_user.id, + Admin.admin_group != 0).first() + markup = generate_squad_markup(is_group_admin=admin is not None) send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_ABOUT, From b77b093e43eec2a950da030d91a924c260980355 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Thu, 2 Nov 2017 17:10:30 +0300 Subject: [PATCH 158/284] =?UTF-8?q?=D0=98=20=D0=B0=D0=B4=D0=BC=D0=B8=D0=BD?= =?UTF-8?q?=D0=BF=D0=B0=D0=BD=D0=B5=D0=BB=D1=8C=D0=BA=D1=83=20=D0=B2=D0=B5?= =?UTF-8?q?=D1=80=D0=BD=D1=91=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/main.py b/main.py index 0358d75..ed96c9e 100644 --- a/main.py +++ b/main.py @@ -21,7 +21,7 @@ ADMIN_COMMAND_GROUPS, ADMIN_COMMAND_FIRE_UP, USER_COMMAND_ME, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, \ USER_COMMAND_SQUAD, USER_COMMAND_STATISTICS, USER_COMMAND_TOP, USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK, \ TOP_COMMAND_ATTACK, TOP_COMMAND_DEFENCE, TOP_COMMAND_EXP, STATISTICS_COMMAND_EXP, USER_COMMAND_SQUAD_LEAVE, \ - ADMIN_COMMAND_REPORTS + ADMIN_COMMAND_REPORTS, ADMIN_COMMAND_ADMINPANEL from core.functions.activity import ( day_activity, week_activity, battle_activity ) @@ -244,6 +244,8 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): chat_id=update.message.chat.id, text=MSG_IN_DEV, parse_mode=ParseMode.HTML) + elif text == ADMIN_COMMAND_ADMINPANEL.lower(): + admin_panel(bot, update) elif 'wait_group_name' in chat_data and chat_data['wait_group_name']: add_group(bot, update, chat_data) From 85ebd2c3e066c93bbcc195c3cb2e5e3857c14152 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Thu, 2 Nov 2017 17:19:34 +0300 Subject: [PATCH 159/284] =?UTF-8?q?=D0=9D=D0=B5=D0=BF=D0=BE=D0=BD=D1=8F?= =?UTF-8?q?=D1=82=D0=BE=D1=87=D0=BA=D0=B0=20=D1=81=20join=20=D0=B2=D1=8B?= =?UTF-8?q?=D1=88=D0=BB=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/squad.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/functions/squad.py b/core/functions/squad.py index 21c59fe..fb65161 100644 --- a/core/functions/squad.py +++ b/core/functions/squad.py @@ -260,7 +260,7 @@ def battle_reports_show(bot: Bot, update: Update, session): now = datetime.now() time_from = datetime(now.year, now.month, now.day, int(now.hour / 4) * 4, 0, 0) - reports = session.query(Report, User).join(SquadMember)\ + reports = session.query(Report, User).join(SquadMember, Report.user_id == SquadMember.user_id)\ .filter(SquadMember.squad_id == adm.admin_group, User.id == SquadMember.user_id, Report.user_id == SquadMember.user_id, From 231f84ace02cc4b8f5641d56d3f2b64c84eb51db Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Thu, 2 Nov 2017 17:24:52 +0300 Subject: [PATCH 160/284] =?UTF-8?q?=D0=95=D1=89=D1=91=20=D0=BD=D0=B5=D0=B1?= =?UTF-8?q?=D0=BE=D0=BB=D1=8C=D1=88=D0=B0=D1=8F=20=D0=BF=D0=BE=D0=BF=D1=80?= =?UTF-8?q?=D0=B0=D0=B2=D0=BE=D1=87=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/squad.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/functions/squad.py b/core/functions/squad.py index fb65161..dbefd39 100644 --- a/core/functions/squad.py +++ b/core/functions/squad.py @@ -260,13 +260,13 @@ def battle_reports_show(bot: Bot, update: Update, session): now = datetime.now() time_from = datetime(now.year, now.month, now.day, int(now.hour / 4) * 4, 0, 0) - reports = session.query(Report, User).join(SquadMember, Report.user_id == SquadMember.user_id)\ + reports = session.query(User, Report).outerjoin(Report).join(SquadMember, Report.user_id == SquadMember.user_id)\ .filter(SquadMember.squad_id == adm.admin_group, User.id == SquadMember.user_id, Report.user_id == SquadMember.user_id, Report.date > time_from).all() text = 'Репорты отряда {} за битву {}\n'.format(squad.squad_name, time_from) - for report, user in reports: + for user, report in reports: if report: text += '{} ({}): 🔥{} 💰{} 📦{}\n'.format(report.name, user.username, report.earned_exp, report.earned_gold, report.earned_stock) From 7bab4f9b20a90abe2036a37fb3ab4aa0c317a427 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Thu, 2 Nov 2017 18:00:41 +0300 Subject: [PATCH 161/284] =?UTF-8?q?=D0=A2=D0=B5=D0=BF=D0=B5=D1=80=D1=8C=20?= =?UTF-8?q?=D0=B2=D1=81=D1=91=20=D0=BA=D0=B0=D0=BA=20=D0=B4=D0=BE=D0=BB?= =?UTF-8?q?=D0=B6=D0=BD=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/squad.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/core/functions/squad.py b/core/functions/squad.py index dbefd39..6709780 100644 --- a/core/functions/squad.py +++ b/core/functions/squad.py @@ -1,5 +1,6 @@ from datetime import datetime +from sqlalchemy import or_, and_ from telegram import Update, Bot, ParseMode from core.functions.reply_markup import generate_squad_markup @@ -260,16 +261,15 @@ def battle_reports_show(bot: Bot, update: Update, session): now = datetime.now() time_from = datetime(now.year, now.month, now.day, int(now.hour / 4) * 4, 0, 0) - reports = session.query(User, Report).outerjoin(Report).join(SquadMember, Report.user_id == SquadMember.user_id)\ - .filter(SquadMember.squad_id == adm.admin_group, - User.id == SquadMember.user_id, - Report.user_id == SquadMember.user_id, - Report.date > time_from).all() + reports = session.query(User, Report) \ + .join(SquadMember) \ + .outerjoin(Report, and_(User.id == Report.user_id, Report.date > time_from)) \ + .filter(SquadMember.squad_id == adm.admin_group).all() text = 'Репорты отряда {} за битву {}\n'.format(squad.squad_name, time_from) for user, report in reports: if report: - text += '{} ({}): 🔥{} 💰{} 📦{}\n'.format(report.name, user.username, + text += '{} (@{}): 🔥{} 💰{} 📦{}\n'.format(report.name, user.username, report.earned_exp, report.earned_gold, report.earned_stock) else: - text += '{} ({}): проспал\n'.format(user.character.name, user.username) + text += '{} (@{}): проспал\n'.format(user.character.name, user.username) send_async(bot, chat_id=update.message.chat.id, text=text) From 215354067756e8be66d05193715b06c16a7aad9d Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 7 Nov 2017 15:28:27 +0300 Subject: [PATCH 162/284] =?UTF-8?q?=D0=A4=D0=B8=D0=BA=D1=81=20=D0=BD=D0=B5?= =?UTF-8?q?=D0=BE=D0=B1=D1=85=D0=BE=D0=B4=D0=B8=D0=BC=D0=BE=D1=81=D1=82?= =?UTF-8?q?=D0=B8=20=D0=B4=D0=B2=D1=83=D1=85=20=D0=BA=D0=BB=D0=B8=D0=BA?= =?UTF-8?q?=D0=BE=D0=B2=20=D0=BF=D0=BE=20=D0=BF=D1=80=D0=B8=D0=BA=D0=B0?= =?UTF-8?q?=D0=B7=D1=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 1 + 1 file changed, 1 insertion(+) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index 550fb32..9f69b64 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -501,6 +501,7 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): else: update.callback_query.answer(text=MSG_ORDER_CLEARED_ERROR) elif data['t'] == QueryType.Orders.value: + chat_data['order_wait'] = False if 'txt' in data and len(data['txt']): if data['txt'] == Icons.LES.value: chat_data['order'] = Castle.LES.value From 6c20b400c9373bcc6aa5c95a4bcb6e0cb1715e4b Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 7 Nov 2017 15:38:09 +0300 Subject: [PATCH 163/284] PY-2017.2.3 + + + \ No newline at end of file From 3bc931ac17826a41021770e30eeef33026c0b0db Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 7 Nov 2017 15:59:44 +0300 Subject: [PATCH 164/284] =?UTF-8?q?=D0=9F=D1=80=D0=B8=D0=BA=D0=B0=D0=B7?= =?UTF-8?q?=D1=8B=20=D0=B1=D0=B5=D0=B7=20=D0=BA=D0=BD=D0=BE=D0=BF=D0=BA?= =?UTF-8?q?=D0=B8.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 134 ++++++++++++++------- core/functions/orders.py | 3 +- core/texts.py | 2 + 3 files changed, 92 insertions(+), 47 deletions(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index 9f69b64..9afcf6a 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -50,6 +50,7 @@ class QueryType(Enum): TriggerOrderPin = 22 SquadList = 23 GroupDelete = 24 + TriggerOrderButton = 25 @admin_allowed() @@ -117,7 +118,7 @@ def generate_flag_orders(): return inline_markup -def generate_order_chats_markup(session, pin=True): +def generate_order_chats_markup(session, pin=True, btn=True): squads = session.query(Squad).all() inline_keys = [] for squad in squads: @@ -125,11 +126,13 @@ def generate_order_chats_markup(session, pin=True): {'t': QueryType.Order.value, 'g': False, 'id': squad.chat_id}))]) inline_keys.append([InlineKeyboardButton(MSG_ORDER_PIN if pin else MSG_ORDER_NO_PIN, callback_data=json.dumps( {'t': QueryType.TriggerOrderPin.value, 'g': False}))]) + inline_keys.append([InlineKeyboardButton(MSG_ORDER_BUTTON if btn else MSG_ORDER_NO_BUTTON, callback_data=json.dumps( + {'t': QueryType.TriggerOrderButton.value, 'g': False}))]) inline_markup = InlineKeyboardMarkup(inline_keys) return inline_markup -def generate_order_groups_markup(session, admin_user: list=None, pin: bool=True): +def generate_order_groups_markup(session, admin_user: list=None, pin: bool=True, btn=True): if admin_user: group_adm = True for adm in admin_user: @@ -143,22 +146,30 @@ def generate_order_groups_markup(session, admin_user: list=None, pin: bool=True) if group: inline_keys.append([InlineKeyboardButton(group.title, callback_data=json.dumps( {'t': QueryType.Order.value, 'g': False, 'id': group.id}))]) - inline_keys.append( - [InlineKeyboardButton(MSG_ORDER_PIN if pin else MSG_ORDER_NO_PIN, callback_data=json.dumps( - {'t': QueryType.TriggerOrderPin.value, 'g': True}))]) + inline_keys.append( + [InlineKeyboardButton(MSG_ORDER_PIN if pin else MSG_ORDER_NO_PIN, callback_data=json.dumps( + {'t': QueryType.TriggerOrderPin.value, 'g': True}))]) + inline_keys.append( + [InlineKeyboardButton(MSG_ORDER_BUTTON if btn else MSG_ORDER_NO_BUTTON, callback_data=json.dumps( + {'t': QueryType.TriggerOrderButton.value, 'g': True}))]) + inline_markup = InlineKeyboardMarkup(inline_keys) + return inline_markup + else: + groups = session.query(OrderGroup).all() + inline_keys = [] + for group in groups: + inline_keys.append([InlineKeyboardButton(group.name, callback_data=json.dumps( + {'t': QueryType.Order.value, 'g': True, 'id': group.id}))]) + inline_keys.append([InlineKeyboardButton(MSG_ORDER_TO_SQUADS, callback_data=json.dumps( + {'t': QueryType.Orders.value}))]) + inline_keys.append([InlineKeyboardButton(MSG_ORDER_PIN if pin else MSG_ORDER_NO_PIN, + callback_data=json.dumps( + {'t': QueryType.TriggerOrderPin.value, 'g': True}))]) + inline_keys.append([InlineKeyboardButton(MSG_ORDER_BUTTON if btn else MSG_ORDER_NO_BUTTON, + callback_data=json.dumps( + {'t': QueryType.TriggerOrderButton.value, 'g': True}))]) inline_markup = InlineKeyboardMarkup(inline_keys) return inline_markup - groups = session.query(OrderGroup).all() - inline_keys = [] - for group in groups: - inline_keys.append([InlineKeyboardButton(group.name, callback_data=json.dumps( - {'t': QueryType.Order.value, 'g': True, 'id': group.id}))]) - inline_keys.append([InlineKeyboardButton(MSG_ORDER_TO_SQUADS, callback_data=json.dumps( - {'t': QueryType.Orders.value}))]) - inline_keys.append([InlineKeyboardButton(MSG_ORDER_PIN if pin else MSG_ORDER_NO_PIN, callback_data=json.dumps( - {'t': QueryType.TriggerOrderPin.value, 'g': True}))]) - inline_markup = InlineKeyboardMarkup(inline_keys) - return inline_markup def generate_ok_markup(order_id, count): @@ -415,34 +426,13 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): elif data['t'] == QueryType.Order.value: order_text = chat_data['order'] order_type = chat_data['order_type'] - order_pin = True if 'pin' in chat_data and chat_data['pin'] or 'pin' not in chat_data else False + order_pin = chat_data['pin'] if 'pin' in chat_data else True + order_btn = chat_data['btn'] if 'btn' in chat_data else True if not data['g']: - order = Order() - order.text = order_text - order.chat_id = data['id'] - order.date = datetime.now() - msg = send_async(bot, chat_id=order.chat_id, text=MSG_ORDER_CLEARED_BY_HEADER + MSG_EMPTY).result() - if msg: - order.confirmed_msg = msg.message_id - else: - order.confirmed_msg = 0 - session.add(order) - session.commit() - markup = generate_ok_markup(order.id, 0) - msg = send_order(bot, order.text, order_type, order.chat_id, markup).result().result() - if order_pin and msg: - try: - bot.request.post(bot.base_url + '/pinChatMessage', {'chat_id': order.chat_id, - 'message_id': msg.message_id, - 'disable_notification': False}) - except TelegramError as err: - bot.logger.error(err.message) - else: - group = session.query(OrderGroup).filter_by(id=data['id']).first() - for item in group.items: + if order_btn: order = Order() order.text = order_text - order.chat_id = item.chat_id + order.chat_id = data['id'] order.date = datetime.now() msg = send_async(bot, chat_id=order.chat_id, text=MSG_ORDER_CLEARED_BY_HEADER + MSG_EMPTY).result() if msg: @@ -453,10 +443,38 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): session.commit() markup = generate_ok_markup(order.id, 0) msg = send_order(bot, order.text, order_type, order.chat_id, markup).result().result() + else: + msg = send_order(bot, order_text, order_type, data['id']).result().result() + if order_pin and msg: + try: + bot.request.post(bot.base_url + '/pinChatMessage', {'chat_id': data['id'], + 'message_id': msg.message_id, + 'disable_notification': False}) + except TelegramError as err: + bot.logger.error(err.message) + else: + group = session.query(OrderGroup).filter_by(id=data['id']).first() + for item in group.items: + if order_btn: + order = Order() + order.text = order_text + order.chat_id = item.chat_id + order.date = datetime.now() + msg = send_async(bot, chat_id=order.chat_id, text=MSG_ORDER_CLEARED_BY_HEADER + MSG_EMPTY).result() + if msg: + order.confirmed_msg = msg.message_id + else: + order.confirmed_msg = 0 + session.add(order) + session.commit() + markup = generate_ok_markup(order.id, 0) + msg = send_order(bot, order.text, order_type, order.chat_id, markup).result().result() + else: + msg = send_order(bot, order_text, order_type, item.chat_id).result().result() if order_pin and msg: try: bot.request.post(bot.base_url + '/pinChatMessage', - {'chat_id': order.chat_id, 'message_id': msg.message_id, + {'chat_id': item.chat_id, 'message_id': msg.message_id, 'disable_notification': False}) except TelegramError as err: bot.logger.error(err.message) @@ -511,7 +529,8 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): chat_data['order'] = Castle.SEA.value else: chat_data['order'] = data['txt'] - markup = generate_order_chats_markup(session, chat_data['pin'] if 'pin' in chat_data else True) + markup = generate_order_chats_markup(session, chat_data['pin'] if 'pin' in chat_data else True, + chat_data['btn'] if 'btn' in chat_data else True) bot.editMessageText(MSG_ORDER_SEND_HEADER.format(chat_data['order']), update.callback_query.message.chat.id, update.callback_query.message.message_id, @@ -528,7 +547,8 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): else: chat_data['order'] = data['txt'] admin_user = session.query(Admin).filter(Admin.user_id == update.callback_query.from_user.id).all() - markup = generate_order_groups_markup(session, admin_user, chat_data['pin'] if 'pin' in chat_data else True) + markup = generate_order_groups_markup(session, admin_user, chat_data['pin'] if 'pin' in chat_data else True, + chat_data['btn'] if 'btn' in chat_data else True) bot.editMessageText(MSG_ORDER_SEND_HEADER.format(chat_data['order']), update.callback_query.message.chat.id, update.callback_query.message.message_id, @@ -721,13 +741,35 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): chat_data['pin'] = False if data['g']: admin_user = session.query(Admin).filter(Admin.user_id == update.callback_query.from_user.id).all() - markup = generate_order_groups_markup(session, admin_user, chat_data['pin'] if 'pin' in chat_data else True) + markup = generate_order_groups_markup(session, admin_user, chat_data['pin'] if 'pin' in chat_data else True, + chat_data['btn'] if 'btn' in chat_data else True) + bot.editMessageText(MSG_ORDER_SEND_HEADER.format(chat_data['order']), + update.callback_query.message.chat.id, + update.callback_query.message.message_id, + reply_markup=markup) + else: + markup = generate_order_chats_markup(session, chat_data['pin'] if 'pin' in chat_data else True, + chat_data['btn'] if 'btn' in chat_data else True) + bot.editMessageText(MSG_ORDER_SEND_HEADER.format(chat_data['order']), + update.callback_query.message.chat.id, + update.callback_query.message.message_id, + reply_markup=markup) + elif data['t'] == QueryType.TriggerOrderButton.value: + if 'btn' in chat_data: + chat_data['btn'] = not chat_data['btn'] + else: + chat_data['btn'] = False + if data['g']: + admin_user = session.query(Admin).filter(Admin.user_id == update.callback_query.from_user.id).all() + markup = generate_order_groups_markup(session, admin_user, chat_data['pin'] if 'pin' in chat_data else True, + chat_data['btn'] if 'btn' in chat_data else True) bot.editMessageText(MSG_ORDER_SEND_HEADER.format(chat_data['order']), update.callback_query.message.chat.id, update.callback_query.message.message_id, reply_markup=markup) else: - markup = generate_order_chats_markup(session, chat_data['pin'] if 'pin' in chat_data else True) + markup = generate_order_chats_markup(session, chat_data['pin'] if 'pin' in chat_data else True, + chat_data['btn'] if 'btn' in chat_data else True) bot.editMessageText(MSG_ORDER_SEND_HEADER.format(chat_data['order']), update.callback_query.message.chat.id, update.callback_query.message.message_id, diff --git a/core/functions/orders.py b/core/functions/orders.py index 35be737..a7775ac 100644 --- a/core/functions/orders.py +++ b/core/functions/orders.py @@ -9,7 +9,8 @@ def order(bot: Bot, update: Update, session, chat_data): chat_data['order_wait'] = False admin_user = session.query(Admin).filter(Admin.user_id == update.message.from_user.id).all() - markup = generate_order_groups_markup(session, admin_user, chat_data['pin'] if 'pin' in chat_data else True) + markup = generate_order_groups_markup(session, admin_user, chat_data['pin'] if 'pin' in chat_data else True, + chat_data['btn'] if 'btn' in chat_data else True) msg = update.message if msg.audio: chat_data['order'] = msg.audio.file_id diff --git a/core/texts.py b/core/texts.py index 9ca2515..50ff546 100644 --- a/core/texts.py +++ b/core/texts.py @@ -104,6 +104,8 @@ MSG_ORDER_ACCEPT = 'Принято!' MSG_ORDER_PIN = '✅Пинить' MSG_ORDER_NO_PIN = '❌Не Пинить' +MSG_ORDER_BUTTON = '✅С кнопкой' +MSG_ORDER_NO_BUTTON = '❌Без кнопки' MSG_ORDER_CLEARED_BY_HEADER = 'Приказ выполнили:\n' From 7359647edf82bde5a62f154f70de923b2b139649 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 7 Nov 2017 16:07:53 +0300 Subject: [PATCH 165/284] =?UTF-8?q?=D0=A4=D0=B0=D1=81=D1=82=D1=84=D0=B8?= =?UTF-8?q?=D0=BA=D1=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index 9afcf6a..89d8e24 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -444,7 +444,7 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): markup = generate_ok_markup(order.id, 0) msg = send_order(bot, order.text, order_type, order.chat_id, markup).result().result() else: - msg = send_order(bot, order_text, order_type, data['id']).result().result() + msg = send_order(bot, order_text, order_type, data['id'], None).result().result() if order_pin and msg: try: bot.request.post(bot.base_url + '/pinChatMessage', {'chat_id': data['id'], @@ -470,7 +470,7 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): markup = generate_ok_markup(order.id, 0) msg = send_order(bot, order.text, order_type, order.chat_id, markup).result().result() else: - msg = send_order(bot, order_text, order_type, item.chat_id).result().result() + msg = send_order(bot, order_text, order_type, item.chat_id, None).result().result() if order_pin and msg: try: bot.request.post(bot.base_url + '/pinChatMessage', From d76ddf9b025eae553afbd359927922e889f14fb8 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 7 Nov 2017 16:11:48 +0300 Subject: [PATCH 166/284] =?UTF-8?q?=D0=A4=D0=B0=D1=81=D1=82=D1=84=D0=B8?= =?UTF-8?q?=D0=BA=D1=812?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 1 + 1 file changed, 1 insertion(+) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index 89d8e24..8ef1601 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -536,6 +536,7 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): update.callback_query.message.message_id, reply_markup=markup) elif data['t'] == QueryType.OrderGroup.value: + chat_data['order_wait'] = False if 'txt' in data and len(data['txt']): chat_data['order_type'] = MessageType.TEXT if data['txt'] == Icons.LES.value: From 266c3e2dd76c6f9db6f4a870ccf54c67286bf9c8 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 7 Nov 2017 16:38:11 +0300 Subject: [PATCH 167/284] =?UTF-8?q?=D0=98=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5?= =?UTF-8?q?=D0=BD=D0=BE=20=D0=BE=D1=82=D0=BE=D0=B1=D1=80=D0=B0=D0=B6=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D1=80=D0=B5=D0=BF=D0=BE=D1=80=D1=82=D0=BE?= =?UTF-8?q?=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 1 + core/functions/squad.py | 10 +++++----- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index 8ef1601..b1cba09 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -51,6 +51,7 @@ class QueryType(Enum): SquadList = 23 GroupDelete = 24 TriggerOrderButton = 25 + OtherReport = 26 @admin_allowed() diff --git a/core/functions/squad.py b/core/functions/squad.py index 6709780..4dd5cd7 100644 --- a/core/functions/squad.py +++ b/core/functions/squad.py @@ -264,12 +264,12 @@ def battle_reports_show(bot: Bot, update: Update, session): reports = session.query(User, Report) \ .join(SquadMember) \ .outerjoin(Report, and_(User.id == Report.user_id, Report.date > time_from)) \ - .filter(SquadMember.squad_id == adm.admin_group).all() + .filter(SquadMember.squad_id == adm.admin_group).order_by(Report.date.desc()).all() text = 'Репорты отряда {} за битву {}\n'.format(squad.squad_name, time_from) for user, report in reports: if report: - text += '{} (@{}): 🔥{} 💰{} 📦{}\n'.format(report.name, user.username, - report.earned_exp, report.earned_gold, report.earned_stock) + text += '{} (@{})\n🔥{} 💰{} 📦{}\n'.format(report.name, user.username, + report.earned_exp, report.earned_gold, report.earned_stock) else: - text += '{} (@{}): проспал\n'.format(user.character.name, user.username) - send_async(bot, chat_id=update.message.chat.id, text=text) + text += '{} (@{}) ❗\n'.format(user.character.name, user.username) + send_async(bot, chat_id=update.message.chat.id, text=text, parse_mode=ParseMode.HTML) From 89c21a5f7aa44a116794db71fee350e231744a6b Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 7 Nov 2017 16:49:38 +0300 Subject: [PATCH 168/284] =?UTF-8?q?=D0=A2=D0=B5=D0=BF=D0=B5=D1=80=D1=8C=20?= =?UTF-8?q?=D1=80=D0=B5=D0=BF=D0=BE=D1=80=D1=82=D1=8B=20=D0=B2=D1=8B=D0=B3?= =?UTF-8?q?=D0=BB=D1=8F=D0=B4=D1=8F=D1=82=20=D0=B5=D1=89=D1=91=20=D0=BA?= =?UTF-8?q?=D1=80=D0=B0=D1=81=D0=B8=D0=B2=D0=B5=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/squad.py | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/core/functions/squad.py b/core/functions/squad.py index 4dd5cd7..d218bc7 100644 --- a/core/functions/squad.py +++ b/core/functions/squad.py @@ -265,11 +265,29 @@ def battle_reports_show(bot: Bot, update: Update, session): .join(SquadMember) \ .outerjoin(Report, and_(User.id == Report.user_id, Report.date > time_from)) \ .filter(SquadMember.squad_id == adm.admin_group).order_by(Report.date.desc()).all() - text = 'Репорты отряда {} за битву {}\n'.format(squad.squad_name, time_from) + text = '' + full_def = 0 + full_atk = 0 + full_exp = 0 + full_gold = 0 + full_stock = 0 for user, report in reports: if report: - text += '{} (@{})\n🔥{} 💰{} 📦{}\n'.format(report.name, user.username, - report.earned_exp, report.earned_gold, report.earned_stock) + text += '{} (@{})\n⚔{} 🛡{} 🔥{} 💰{} 📦{}\n'.format( + report.name, user.username, report.attack, report.defence, + report.earned_exp, report.earned_gold, report.earned_stock) + full_atk += report.attack + full_def += report.defence + full_exp += report.earned_exp + full_gold += report.earned_gold + full_stock += report.earned_stock else: text += '{} (@{}) ❗\n'.format(user.character.name, user.username) + text = 'Репорты отряда {} за битву {}\n' \ + 'Общие\n' \ + 'Атака: ⚔{}\n' \ + 'Защита: 🛡{}\n' \ + 'Профит: 🔥{} 💰{} 📦{}\n\n' \ + 'Личные\n'.format(squad.squad_name, time_from, full_atk, full_def, full_exp, full_gold, + full_stock) + text send_async(bot, chat_id=update.message.chat.id, text=text, parse_mode=ParseMode.HTML) From 4c7804ac70b76520021ca70d84988048786676fa Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 7 Nov 2017 17:13:03 +0300 Subject: [PATCH 169/284] =?UTF-8?q?=D0=A0=D0=B5=D0=BF=D0=BE=D1=80=D1=82?= =?UTF-8?q?=D1=8B=20=D1=82=D0=B5=D0=BF=D0=B5=D1=80=D1=8C=20=D0=BC=D0=BE?= =?UTF-8?q?=D0=B6=D0=BD=D0=BE=20=D0=BF=D0=BE=D0=BB=D0=B8=D1=81=D1=82=D0=B0?= =?UTF-8?q?=D1=82=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 56 ++++++++++++++++++++-- core/functions/squad.py | 5 +- 2 files changed, 56 insertions(+), 5 deletions(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index b1cba09..f701bf3 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -14,12 +14,11 @@ from core.types import ( User, Group, Admin, admin_allowed, Order, OrderGroup, OrderGroupItem, OrderCleared, Squad, user_allowed, - Character, SquadMember, MessageType, AdminType) + Character, SquadMember, MessageType, AdminType, Report) from core.texts import * from core.utils import send_async, update_group, add_user -from sqlalchemy import func, tuple_ - +from sqlalchemy import func, tuple_, and_ LOGGER = logging.getLogger('MyApp') @@ -280,6 +279,21 @@ def generate_squad_request(session): return InlineKeyboardMarkup(inline_keys) +def generate_other_reports(time: datetime, squad_id): + inline_keys = [[InlineKeyboardButton('<< ' + str(time - timedelta(hours=4)), + callback_data=json.dumps( + {'t': QueryType.OtherReport.value, + 'ts': (time - timedelta(hours=4)).timestamp(), + 'c': squad_id}))]] + if time + timedelta(hours=4) < datetime.now(): + inline_keys[0].append(InlineKeyboardButton(str(time + timedelta(hours=4)) + ' >>', + callback_data=json.dumps( + {'t': QueryType.OtherReport.value, + 'ts': (time + timedelta(hours=4)).timestamp(), + 'c': squad_id}))) + return InlineKeyboardMarkup(inline_keys) + + def generate_squad_members(members, session): inline_keys = [] user_ids = [] @@ -813,3 +827,39 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): inline_markup = InlineKeyboardMarkup([[key] for key in inline_keys]) bot.editMessageText(msg, update.callback_query.message.chat.id, update.callback_query.message.message_id, reply_markup=inline_markup) + elif data['t'] == QueryType.OtherReport.value: + squad = session.query(Squad).filter(Squad.chat_id == data['c']).first() + time_from = datetime.fromtimestamp(data['ts']) + time_to = time_from + timedelta(hours=4) + reports = session.query(User, Report) \ + .join(SquadMember) \ + .outerjoin(Report, and_(User.id == Report.user_id, Report.date > time_from, Report.date < time_to)) \ + .filter(SquadMember.squad_id == data['c']).order_by(Report.date.desc()).all() + text = '' + full_def = 0 + full_atk = 0 + full_exp = 0 + full_gold = 0 + full_stock = 0 + for user, report in reports: + if report: + text += '{} (@{})\n⚔{} 🛡{} 🔥{} 💰{} 📦{}\n'.format( + report.name, user.username, report.attack, report.defence, + report.earned_exp, report.earned_gold, report.earned_stock) + full_atk += report.attack + full_def += report.defence + full_exp += report.earned_exp + full_gold += report.earned_gold + full_stock += report.earned_stock + else: + text += '{} (@{}) ❗\n'.format(user.character.name, user.username) + text = 'Репорты отряда {} за битву {}\n' \ + 'Общие\n' \ + 'Атака: ⚔{}\n' \ + 'Защита: 🛡{}\n' \ + 'Профит: 🔥{} 💰{} 📦{}\n\n' \ + 'Личные\n'.format(squad.squad_name, time_from, full_atk, full_def, full_exp, full_gold, + full_stock) + text + markup = generate_other_reports(time_from, squad.chat_id) + bot.editMessageText(text, update.callback_query.message.chat.id, update.callback_query.message.message_id, + parse_mode=ParseMode.HTML, reply_markup=markup) diff --git a/core/functions/squad.py b/core/functions/squad.py index d218bc7..2c3ca7b 100644 --- a/core/functions/squad.py +++ b/core/functions/squad.py @@ -9,7 +9,7 @@ from core.utils import send_async from core.functions.inline_keyboard_handling import generate_squad_list, \ generate_leave_squad, generate_squad_request, generate_squad_request_answer, generate_fire_up, \ - generate_squad_invite_answer + generate_squad_invite_answer, generate_other_reports from core.texts import * @@ -290,4 +290,5 @@ def battle_reports_show(bot: Bot, update: Update, session): 'Профит: 🔥{} 💰{} 📦{}\n\n' \ 'Личные\n'.format(squad.squad_name, time_from, full_atk, full_def, full_exp, full_gold, full_stock) + text - send_async(bot, chat_id=update.message.chat.id, text=text, parse_mode=ParseMode.HTML) + markup = generate_other_reports(time_from, squad.chat_id) + send_async(bot, chat_id=update.message.chat.id, text=text, parse_mode=ParseMode.HTML, reply_markup=markup) From 3338f76991d2e05f5fc04e900f4aa4696b1b9aff Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Thu, 9 Nov 2017 13:54:32 +0300 Subject: [PATCH 170/284] PY-2017.2.4 - + @@ -20,12 +20,12 @@ - + - + From 778b06af95b51e4e0ff0b2d741e72bc56a2c21a1 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Fri, 10 Nov 2017 14:10:01 +0300 Subject: [PATCH 171/284] PY-2017.2.4 + + + + + + + + + + + + + + \ No newline at end of file From 3f4bbe638988c09c49bb2ac8db320ba569c9fe7f Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Mon, 13 Nov 2017 12:39:02 +0300 Subject: [PATCH 172/284] PY-2017.2.4 + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From 6c1ae0d4c08ee417e35d872bc2beedba9965e5d4 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Mon, 13 Nov 2017 16:37:36 +0300 Subject: [PATCH 173/284] PY-2017.2.4 + + + + + + + + + + + + + \ No newline at end of file From 13cc720001f0f67422960a32909bd391d453b380 Mon Sep 17 00:00:00 2001 From: eclipse7 Date: Tue, 5 Dec 2017 16:28:59 +0200 Subject: [PATCH 197/284] fix zeroExp --- core/functions/statistics.py | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/core/functions/statistics.py b/core/functions/statistics.py index f3ccf67..454ba55 100644 --- a/core/functions/statistics.py +++ b/core/functions/statistics.py @@ -53,18 +53,21 @@ def exp_statistic(bot: Bot, update: Update, session): interval = (delta.days * 86400 + delta.seconds) or 1 day_exp = (now_exp - prev_exp) * 86400 / interval delta_exp = need_exp - now_exp - delta_days = round((need_exp - now_exp) / (day_exp or 1)) or 1 - if (delta_days % 10 == 0) or (delta_days % 10 >= 5) or ((delta_days % 100) in (11, 12, 13, 14)): - days_text = 'дней' - elif (delta_days % 10) in (2, 3, 4): - days_text = 'дня' - else: - days_text = 'день' + text = '' + if day_exp: + delta_days = round(delta_exp / day_exp) or 1 + if (delta_days % 10 == 0) or (delta_days % 10 >= 5) or ((delta_days % 100) in (11, 12, 13, 14)): + days_text = 'дней' + elif (delta_days % 10) in (2, 3, 4): + days_text = 'дня' + else: + days_text = 'день' + text = ('и {} {}'.format(delta_days, days_text)) with open(filename, 'rb') as file: bot.sendPhoto(update.message.chat.id, file, 'В среднем {} опыта в день. ' - 'До следующего уровня осталось {} опыта и {} {}' - .format(int(day_exp), delta_exp, delta_days, days_text)) + 'До следующего уровня осталось {} опыта {}' + .format(int(day_exp), delta_exp, text)) plot.clf() os.remove(filename) From 74b67b1645d937f49a58baa4093c7f9123b56ad1 Mon Sep 17 00:00:00 2001 From: eclipse7 Date: Tue, 5 Dec 2017 16:53:23 +0200 Subject: [PATCH 198/284] fix endpoint --- core/functions/statistics.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/functions/statistics.py b/core/functions/statistics.py index 454ba55..dd860ec 100644 --- a/core/functions/statistics.py +++ b/core/functions/statistics.py @@ -39,9 +39,9 @@ def exp_statistic(bot: Bot, update: Update, session): with open(filename, 'wb') as file: plot.savefig(file, format='png') - now_date = x[-1] + now_date = x[-2] prev_date = x[0] - now_exp = y[-1] + now_exp = y[-2] prev_exp = y[0] for date, exp in zip(reversed(x), reversed(y)): if date <= datetime.now() - timedelta(days=3): From ea106cadceba32929776ef871bbcbe1cacef1874 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Tue, 5 Dec 2017 18:36:01 +0300 Subject: [PATCH 199/284] =?UTF-8?q?=D0=9D=D0=BE=D0=B2=D1=8B=D0=B5=20=D1=82?= =?UTF-8?q?=D0=BE=D0=BF=D1=8B=20=D1=87=D0=B0=D1=81=D1=82=D1=8C=20=D0=BF?= =?UTF-8?q?=D0=B5=D1=80=D0=B2=D0=B0=D1=8F.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- _windows/git.xml | 5 -- _windows/laf.xml | 5 -- codestyles/Default.xml | 1 - colors.scheme.xml | 5 -- core/commands.py | 3 + core/functions/inline_keyboard_handling.py | 19 +++++ core/functions/reply_markup.py | 4 +- core/functions/statistics.py | 4 +- core/functions/top.py | 87 +++++++++++++++++++++- core/texts.py | 2 + debugger.xml | 13 ---- editor.codeinsight.xml | 6 -- editor.xml | 6 -- filetypes.xml | 9 --- find.xml | 9 --- github_settings.xml | 5 -- ide.general.xml | 5 -- ignore.xml | 32 -------- main.py | 10 ++- markdown.xml | 10 --- vcs.xml | 13 ---- 21 files changed, 121 insertions(+), 132 deletions(-) delete mode 100644 _windows/git.xml delete mode 100644 _windows/laf.xml delete mode 100644 codestyles/Default.xml delete mode 100644 colors.scheme.xml delete mode 100644 debugger.xml delete mode 100644 editor.codeinsight.xml delete mode 100644 editor.xml delete mode 100644 filetypes.xml delete mode 100644 find.xml delete mode 100644 github_settings.xml delete mode 100644 ide.general.xml delete mode 100644 ignore.xml delete mode 100644 markdown.xml delete mode 100644 vcs.xml diff --git a/_windows/git.xml b/_windows/git.xml deleted file mode 100644 index a8092bd..0000000 --- a/_windows/git.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - \ No newline at end of file diff --git a/_windows/laf.xml b/_windows/laf.xml deleted file mode 100644 index c1f98d9..0000000 --- a/_windows/laf.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/codestyles/Default.xml b/codestyles/Default.xml deleted file mode 100644 index e598e06..0000000 --- a/codestyles/Default.xml +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/colors.scheme.xml b/colors.scheme.xml deleted file mode 100644 index 39308cd..0000000 --- a/colors.scheme.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/core/commands.py b/core/commands.py index 1faf2d1..1587c1c 100644 --- a/core/commands.py +++ b/core/commands.py @@ -23,4 +23,7 @@ TOP_COMMAND_EXP = '🔥' TOP_COMMAND_GLOBAL_BUILD = '⚒' +TOP_COMMAND_WEEK_BUILD = '⚒ Неделя стройки ⚒' +TOP_COMMAND_WEEK_BATTLES = '⚔ Неделя битв 🛡' + STATISTICS_COMMAND_EXP = '🔥Опыт' diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index e4738cb..4d54219 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -51,6 +51,13 @@ class QueryType(Enum): GroupDelete = 24 TriggerOrderButton = 25 OtherReport = 26 + GlobalBuildTop = 27 + WeekBuildTop = 28 + SquadGlobalBuildTop = 29 + SquadWeekBuildTop = 30 + BattleGlobalTop = 31 + BattleWeekTop = 32 + @admin_allowed() @@ -863,3 +870,15 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): markup = generate_other_reports(time_from, squad.chat_id) bot.editMessageText(text, update.callback_query.message.chat.id, update.callback_query.message.message_id, parse_mode=ParseMode.HTML, reply_markup=markup) + elif data['t'] == QueryType.GlobalBuildTop.value: + pass + elif data['t'] == QueryType.WeekBuildTop.value: + pass + elif data['t'] == QueryType.SquadGlobalBuildTop.value: + pass + elif data['t'] == QueryType.SquadWeekBuildTop.value: + pass + elif data['t'] == QueryType.BattleGlobalTop.value: + pass + elif data['t'] == QueryType.BattleWeekTop.value: + pass diff --git a/core/functions/reply_markup.py b/core/functions/reply_markup.py index d87dc59..9ee5e5d 100644 --- a/core/functions/reply_markup.py +++ b/core/functions/reply_markup.py @@ -4,7 +4,8 @@ ADMIN_COMMAND_FIRE_UP, ADMIN_COMMAND_SQUAD_LIST, USER_COMMAND_ME, USER_COMMAND_TOP, USER_COMMAND_SQUAD, \ USER_COMMAND_STATISTICS, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, ADMIN_COMMAND_ADMINPANEL, \ USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK, TOP_COMMAND_ATTACK, TOP_COMMAND_DEFENCE, TOP_COMMAND_EXP, \ - STATISTICS_COMMAND_EXP, USER_COMMAND_SQUAD_LEAVE, ADMIN_COMMAND_REPORTS, TOP_COMMAND_GLOBAL_BUILD + STATISTICS_COMMAND_EXP, USER_COMMAND_SQUAD_LEAVE, ADMIN_COMMAND_REPORTS, TOP_COMMAND_GLOBAL_BUILD, \ + TOP_COMMAND_WEEK_BUILD, TOP_COMMAND_WEEK_BATTLES def generate_admin_markup(full=False): @@ -28,6 +29,7 @@ def generate_user_markup(is_admin=False): def generate_top_markup(): buttons = [[KeyboardButton(TOP_COMMAND_ATTACK), KeyboardButton(TOP_COMMAND_DEFENCE), KeyboardButton(TOP_COMMAND_EXP), KeyboardButton(TOP_COMMAND_GLOBAL_BUILD)], + [KeyboardButton(TOP_COMMAND_WEEK_BUILD), KeyboardButton(TOP_COMMAND_WEEK_BATTLES)], [KeyboardButton(USER_COMMAND_BACK)]] return ReplyKeyboardMarkup(buttons, True) diff --git a/core/functions/statistics.py b/core/functions/statistics.py index dd860ec..44d7c54 100644 --- a/core/functions/statistics.py +++ b/core/functions/statistics.py @@ -43,8 +43,8 @@ def exp_statistic(bot: Bot, update: Update, session): prev_date = x[0] now_exp = y[-2] prev_exp = y[0] - for date, exp in zip(reversed(x), reversed(y)): - if date <= datetime.now() - timedelta(days=3): + for date, exp in zip(x[-3::-1], y[-3::-1]): + if date <= now_date - timedelta(days=3): prev_date = date prev_exp = exp break diff --git a/core/functions/top.py b/core/functions/top.py index 117835a..9b3055b 100644 --- a/core/functions/top.py +++ b/core/functions/top.py @@ -3,8 +3,8 @@ from core.functions.reply_markup import generate_top_markup from core.texts import MSG_TOP_ABOUT, MSG_TOP_FORMAT, MSG_TOP_ATTACK, MSG_TOP_DEFENCE, MSG_TOP_EXPERIENCE, \ - MSG_TOP_GLOBAL_BUILDERS -from core.types import user_allowed, Character, BuildReport + MSG_TOP_GLOBAL_BUILDERS, MSG_TOP_WEEK_BUILDERS, MSG_TOP_WEEK_WARRIORS +from core.types import user_allowed, Character, BuildReport, Report from core.utils import send_async from config import CASTLE @@ -87,7 +87,8 @@ def global_build_top(bot: Bot, update: Update, session): .filter(tuple_(Character.user_id, Character.date) .in_([(a[0], a[1]) for a in actual_profiles]), Character.date > datetime.now() - timedelta(days=7))\ - .outerjoin(BuildReport, BuildReport.user_id == Character.user_id).group_by(Character)\ + .outerjoin(BuildReport, BuildReport.user_id == Character.user_id).group_by(Character) \ + .filter(BuildReport.date > datetime(2017, 12, 1))\ .order_by(func.count(BuildReport.user_id).desc()) if CASTLE: builds = builds.filter(Character.castle == CASTLE) @@ -113,3 +114,83 @@ def global_build_top(bot: Bot, update: Update, session): send_async(bot, chat_id=update.message.chat.id, text=text) + + +@user_allowed +def week_build_top(bot: Bot, update: Update, session): + actual_profiles = session.query(Character.user_id, func.max(Character.date)). \ + group_by(Character.user_id) + actual_profiles = actual_profiles.all() + today = datetime.today() + builds = session.query(Character, func.count(BuildReport.user_id))\ + .filter(tuple_(Character.user_id, Character.date) + .in_([(a[0], a[1]) for a in actual_profiles]), + Character.date > datetime.now() - timedelta(days=7))\ + .outerjoin(BuildReport, BuildReport.user_id == Character.user_id).group_by(Character) \ + .filter(BuildReport.date > today - timedelta(days=today.weekday()))\ + .order_by(func.count(BuildReport.user_id).desc()) + if CASTLE: + builds = builds.filter(Character.castle == CASTLE) + builds = builds.all() + text = MSG_TOP_WEEK_BUILDERS + str_format = MSG_TOP_FORMAT + for i in range(min(10, len(builds))): + text += str_format.format(i + 1, builds[i][0].name, builds[i][0].level, + builds[i][1], '⚒') + if update.message.from_user.id in [build[0].user_id for build in builds]: + if update.message.from_user.id not in [build[0].user_id for build in builds[:10]]: + for i in range(10, len(builds)): + if builds[i][0].user_id == update.message.from_user.id: + text += '...\n' + text += str_format.format(i, builds[i - 1][0].name, builds[i-1][0].level, + builds[i - 1][1], '⚒') + text += str_format.format(i + 1, builds[i][0].name, builds[i][0].level, + builds[i][1], '⚒') + if i != len(builds) - 1: + text += str_format.format(i + 2, builds[i + 1][0].name, builds[i+1][0].level, + builds[i + 1][1], '⚒') + break + send_async(bot, + chat_id=update.message.chat.id, + text=text) + + +@user_allowed +def week_battle_top(bot: Bot, update: Update, session): + actual_profiles = session.query(Character.user_id, func.max(Character.date)). \ + group_by(Character.user_id) + actual_profiles = actual_profiles.all() + today = datetime.today() + battles = session.query(Character, func.count(Report.user_id))\ + .filter(tuple_(Character.user_id, Character.date) + .in_([(a[0], a[1]) for a in actual_profiles]), + Character.date > datetime.now() - timedelta(days=7))\ + .outerjoin(Report, Report.user_id == Character.user_id).group_by(Character) \ + .filter(Report.date > today - timedelta(days=today.weekday())) \ + .filter(Report.earned_exp > 1) \ + .order_by(func.count(Report.user_id).desc()) + if CASTLE: + battles = battles.filter(Character.castle == CASTLE) + battles = battles.all() + text = MSG_TOP_WEEK_WARRIORS + str_format = MSG_TOP_FORMAT + for i in range(min(10, len(battles))): + text += str_format.format(i + 1, battles[i][0].name, battles[i][0].level, + battles[i][1], '⚔') + if update.message.from_user.id in [build[0].user_id for build in battles]: + if update.message.from_user.id not in [build[0].user_id for build in battles[:10]]: + for i in range(10, len(battles)): + if battles[i][0].user_id == update.message.from_user.id: + text += '...\n' + text += str_format.format(i, battles[i - 1][0].name, battles[i-1][0].level, + battles[i - 1][1], '⚔') + text += str_format.format(i + 1, battles[i][0].name, battles[i][0].level, + battles[i][1], '⚔') + if i != len(battles) - 1: + text += str_format.format(i + 2, battles[i + 1][0].name, battles[i+1][0].level, + battles[i + 1][1], '⚔') + break + send_async(bot, + chat_id=update.message.chat.id, + text=text) + diff --git a/core/texts.py b/core/texts.py index fe5ada9..de51083 100644 --- a/core/texts.py +++ b/core/texts.py @@ -246,6 +246,8 @@ MSG_TOP_ATTACK = '⚔Топ атакеры:\n' MSG_TOP_EXPERIENCE = '🔥Топ качки:\n' MSG_TOP_GLOBAL_BUILDERS = '⚒Топ строители:\n' +MSG_TOP_WEEK_BUILDERS = '⚒Топ строители недели:\n' +MSG_TOP_WEEK_WARRIORS = '⚔🛡Топ по участию в битвах:\n' MSG_UPDATE_PROFILE = 'Пришли свежий игровой профиль (🏅 команда "/hero"), пока я не выгнал тебя с отряда.' MSG_SQUAD_DELETE_OUTDATED = 'Ты был изгнан из отряда за то, что давно не обновлял свой профиль.' diff --git a/debugger.xml b/debugger.xml deleted file mode 100644 index 544ab15..0000000 --- a/debugger.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/editor.codeinsight.xml b/editor.codeinsight.xml deleted file mode 100644 index b43f2d4..0000000 --- a/editor.codeinsight.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - \ No newline at end of file diff --git a/editor.xml b/editor.xml deleted file mode 100644 index 19bd26a..0000000 --- a/editor.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - \ No newline at end of file diff --git a/filetypes.xml b/filetypes.xml deleted file mode 100644 index 324c956..0000000 --- a/filetypes.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/find.xml b/find.xml deleted file mode 100644 index 4596d19..0000000 --- a/find.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - \ No newline at end of file diff --git a/github_settings.xml b/github_settings.xml deleted file mode 100644 index 0e4cecb..0000000 --- a/github_settings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - \ No newline at end of file diff --git a/ide.general.xml b/ide.general.xml deleted file mode 100644 index 8329a5d..0000000 --- a/ide.general.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/ignore.xml b/ignore.xml deleted file mode 100644 index 9e7f63b..0000000 --- a/ignore.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/main.py b/main.py index 8acd34a..fa1f226 100644 --- a/main.py +++ b/main.py @@ -21,7 +21,8 @@ ADMIN_COMMAND_GROUPS, ADMIN_COMMAND_FIRE_UP, USER_COMMAND_ME, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, \ USER_COMMAND_SQUAD, USER_COMMAND_STATISTICS, USER_COMMAND_TOP, USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK, \ TOP_COMMAND_ATTACK, TOP_COMMAND_DEFENCE, TOP_COMMAND_EXP, STATISTICS_COMMAND_EXP, USER_COMMAND_SQUAD_LEAVE, \ - ADMIN_COMMAND_REPORTS, ADMIN_COMMAND_ADMINPANEL, TOP_COMMAND_GLOBAL_BUILD + ADMIN_COMMAND_REPORTS, ADMIN_COMMAND_ADMINPANEL, TOP_COMMAND_GLOBAL_BUILD, TOP_COMMAND_WEEK_BUILD, \ + TOP_COMMAND_WEEK_BATTLES from core.functions.activity import ( day_activity, week_activity, battle_activity ) @@ -53,7 +54,8 @@ open_hiring, close_hiring, remove_from_squad, add_to_squad, leave_squad, squad_about, call_squad, battle_reports_show) from core.functions.statistics import statistic_about, exp_statistic -from core.functions.top import top_about, attack_top, exp_top, def_top, global_build_top +from core.functions.top import top_about, attack_top, exp_top, def_top, global_build_top, week_build_top, \ + week_battle_top from core.functions.triggers import ( set_trigger, add_trigger, del_trigger, list_triggers, enable_trigger_all, disable_trigger_all, trigger_show, @@ -228,6 +230,10 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): exp_top(bot, update) elif text == TOP_COMMAND_GLOBAL_BUILD.lower(): global_build_top(bot, update) + elif text == TOP_COMMAND_WEEK_BUILD.lower(): + week_build_top(bot, update) + elif text == TOP_COMMAND_WEEK_BATTLES.lower(): + week_battle_top(bot, update) elif text == USER_COMMAND_BUILD.lower(): send_async(bot, chat_id=update.message.chat.id, diff --git a/markdown.xml b/markdown.xml deleted file mode 100644 index 4f846d0..0000000 --- a/markdown.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/vcs.xml b/vcs.xml deleted file mode 100644 index ac8d523..0000000 --- a/vcs.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - \ No newline at end of file From b2aa6499229fbcae308b0206beb7560cc940bbe9 Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Tue, 5 Dec 2017 21:05:33 +0300 Subject: [PATCH 200/284] =?UTF-8?q?=D0=A4=D0=B0=D1=81=D1=82=D1=84=D0=B8?= =?UTF-8?q?=D0=BA=D1=81=20=D0=BB=D0=BE=D0=B3=D0=B8=D0=BD=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/common.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/functions/common.py b/core/functions/common.py index 18a5efd..5bc9769 100644 --- a/core/functions/common.py +++ b/core/functions/common.py @@ -212,4 +212,5 @@ def web_auth(bot: Bot, update: Update, session): session.add(auth) session.commit() link = 'https://dusk.ruckus.dj/?token={}'.format(auth.id) - send_async(bot, chat_id=update.message.chat.id, text=MSG_PERSONAL_SITE_LINK.format(link), parse_mode=ParseMode.HTML) + send_async(bot, chat_id=update.message.chat.id, text=MSG_PERSONAL_SITE_LINK.format(link), + parse_mode=ParseMode.HTML, disable_web_page_preview=True) From 081339ac08be554efbe3cfe1507b03274e6aeb8d Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Wed, 6 Dec 2017 17:10:57 +0300 Subject: [PATCH 201/284] =?UTF-8?q?=D0=9D=D0=BE=D0=B2=D1=8B=D0=B5=20=D1=82?= =?UTF-8?q?=D0=BE=D0=BF=D1=8B=20=D1=87=D0=B0=D1=81=D1=82=D1=8C=20=D0=BF?= =?UTF-8?q?=D0=BE=D1=81=D0=BB=D0=B5=D0=B4=D0=BD=D1=8F=D1=8F.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/commands.py | 5 +- core/functions/inline_keyboard_handling.py | 368 ++------------------ core/functions/inline_markup.py | 375 +++++++++++++++++++++ core/functions/orders.py | 2 +- core/functions/reply_markup.py | 8 +- core/functions/squad.py | 5 +- core/functions/top.py | 248 ++++++++++---- core/texts.py | 1 + main.py | 13 +- 9 files changed, 589 insertions(+), 436 deletions(-) create mode 100644 core/functions/inline_markup.py diff --git a/core/commands.py b/core/commands.py index 1587c1c..3400358 100644 --- a/core/commands.py +++ b/core/commands.py @@ -21,9 +21,8 @@ TOP_COMMAND_ATTACK = '⚔' TOP_COMMAND_DEFENCE = '🛡' TOP_COMMAND_EXP = '🔥' -TOP_COMMAND_GLOBAL_BUILD = '⚒' +TOP_COMMAND_BUILD = '⚒' -TOP_COMMAND_WEEK_BUILD = '⚒ Неделя стройки ⚒' -TOP_COMMAND_WEEK_BATTLES = '⚔ Неделя битв 🛡' +TOP_COMMAND_BATTLES = '⚔🛡' STATISTICS_COMMAND_EXP = '🔥Опыт' diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index 4d54219..bf9ed81 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -1,5 +1,4 @@ from datetime import datetime, timedelta -from enum import Enum import json from json import loads import logging @@ -9,57 +8,26 @@ from core.enums import Castle, Icons from core.functions.admins import del_adm +from core.functions.inline_markup import generate_group_info, generate_order_chats_markup, generate_order_groups_markup, \ + generate_ok_markup, generate_groups_manage, generate_group_manage, generate_profile_buttons, generate_squad_list, \ + generate_leave_squad, generate_other_reports, generate_squad_members, generate_fire_up, generate_build_top, \ + generate_battle_top, QueryType from core.functions.reply_markup import generate_user_markup +from core.functions.top import global_build_top, week_build_top, week_battle_top, global_battle_top, \ + week_squad_build_top, global_squad_build_top from core.template import fill_char_template from core.types import ( - User, Group, Admin, admin_allowed, Order, OrderGroup, + User, Admin, admin_allowed, Order, OrderGroup, OrderGroupItem, OrderCleared, Squad, user_allowed, - Character, SquadMember, MessageType, AdminType, Report) + SquadMember, MessageType, AdminType, Report) from core.texts import * from core.utils import send_async, update_group, add_user -from sqlalchemy import func, tuple_, and_ +from sqlalchemy import and_ LOGGER = logging.getLogger('MyApp') -class QueryType(Enum): - GroupList = 0 - GroupInfo = 1 - DelAdm = 2 - Order = 3 - OrderOk = 4 - Orders = 5 - OrderGroup = 6 - OrderGroupManage = 7 - OrderGroupTriggerChat = 8 - OrderGroupAdd = 9 - OrderGroupDelete = 10 - OrderGroupList = 11 - ShowStock = 12 - ShowEquip = 13 - ShowHero = 14 - MemberList = 15 - LeaveSquad = 16 - RequestSquad = 17 - RequestSquadAccept = 18 - RequestSquadDecline = 19 - InviteSquadAccept = 20 - InviteSquadDecline = 21 - TriggerOrderPin = 22 - SquadList = 23 - GroupDelete = 24 - TriggerOrderButton = 25 - OtherReport = 26 - GlobalBuildTop = 27 - WeekBuildTop = 28 - SquadGlobalBuildTop = 29 - SquadWeekBuildTop = 30 - BattleGlobalTop = 31 - BattleWeekTop = 32 - - - @admin_allowed() def send_status(bot: Bot, update: Update, session): msg = MSG_GROUP_STATUS_CHOOSE_CHAT @@ -73,306 +41,6 @@ def send_status(bot: Bot, update: Update, session): send_async(bot, chat_id=update.message.chat.id, text=msg, reply_markup=inline_markup) -def generate_group_info(group_id, session): - group = session.query(Group).filter(Group.id == group_id).first() - admins = session.query(Admin).filter(Admin.admin_group == group_id).all() - adm_msg = '' - adm_del_keys = [] - for adm in admins: - user = session.query(User).filter_by(id=adm.user_id).first() - adm_msg += MSG_GROUP_STATUS_ADMIN_FORMAT.\ - format(user.id, user.username or '', user.first_name or '', user.last_name or '') - adm_del_keys.append([InlineKeyboardButton(MSG_GROUP_STATUS_DEL_ADMIN. - format(user.first_name or '', user.last_name or ''), - callback_data=json.dumps( - {'t': QueryType.DelAdm.value, 'uid': user.id, - 'gid': group_id}))]) - msg = MSG_GROUP_STATUS.format(group.title, - adm_msg, - MSG_ON if group.welcome_enabled else MSG_OFF, - MSG_ON if group.allow_trigger_all else MSG_OFF, - MSG_ON if len(group.squad) and group.squad[0].thorns_enabled else MSG_OFF) - adm_del_keys.append([InlineKeyboardButton(MSG_ORDER_GROUP_DEL, callback_data=json.dumps( - {'t': QueryType.GroupDelete.value, 'gid': group_id}))]) - adm_del_keys.append([InlineKeyboardButton(MSG_BACK, callback_data=json.dumps( - {'t': QueryType.GroupList.value}))]) - inline_markup = InlineKeyboardMarkup(adm_del_keys) - return msg, inline_markup - - -def generate_flag_orders(): - flag_btns = [[InlineKeyboardButton(Castle.BLACK.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Castle.BLACK.value})), - InlineKeyboardButton(Castle.WHITE.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Castle.WHITE.value})), - InlineKeyboardButton(Castle.BLUE.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Castle.BLUE.value}))], - [InlineKeyboardButton(Castle.YELLOW.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Castle.YELLOW.value})), - InlineKeyboardButton(Castle.RED.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Castle.RED.value})), - InlineKeyboardButton(Castle.DUSK.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Castle.DUSK.value}))], - [InlineKeyboardButton(Castle.MINT.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Castle.MINT.value})), - InlineKeyboardButton(Castle.GORY.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Icons.GORY.value})), - InlineKeyboardButton(Castle.LES.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Icons.LES.value}))], - [InlineKeyboardButton(Castle.SEA.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Icons.SEA.value}))]] - inline_markup = InlineKeyboardMarkup(flag_btns) - return inline_markup - - -def generate_order_chats_markup(session, pin=True, btn=True): - squads = session.query(Squad).all() - inline_keys = [] - for squad in squads: - inline_keys.append([InlineKeyboardButton(squad.squad_name, callback_data=json.dumps( - {'t': QueryType.Order.value, 'g': False, 'id': squad.chat_id}))]) - inline_keys.append([InlineKeyboardButton(MSG_ORDER_PIN if pin else MSG_ORDER_NO_PIN, callback_data=json.dumps( - {'t': QueryType.TriggerOrderPin.value, 'g': False}))]) - inline_keys.append([InlineKeyboardButton(MSG_ORDER_BUTTON if btn else MSG_ORDER_NO_BUTTON, callback_data=json.dumps( - {'t': QueryType.TriggerOrderButton.value, 'g': False}))]) - inline_markup = InlineKeyboardMarkup(inline_keys) - return inline_markup - - -def generate_order_groups_markup(session, admin_user: list=None, pin: bool=True, btn=True): - if admin_user: - group_adm = True - for adm in admin_user: - if adm.admin_type < AdminType.GROUP.value: - group_adm = False - break - if group_adm: - inline_keys = [] - for adm in admin_user: - group = session.query(Group).filter_by(id=adm.admin_group, bot_in_group=True).first() - if group: - inline_keys.append([InlineKeyboardButton(group.title, callback_data=json.dumps( - {'t': QueryType.Order.value, 'g': False, 'id': group.id}))]) - inline_keys.append( - [InlineKeyboardButton(MSG_ORDER_PIN if pin else MSG_ORDER_NO_PIN, callback_data=json.dumps( - {'t': QueryType.TriggerOrderPin.value, 'g': True}))]) - inline_keys.append( - [InlineKeyboardButton(MSG_ORDER_BUTTON if btn else MSG_ORDER_NO_BUTTON, callback_data=json.dumps( - {'t': QueryType.TriggerOrderButton.value, 'g': True}))]) - inline_markup = InlineKeyboardMarkup(inline_keys) - return inline_markup - else: - groups = session.query(OrderGroup).all() - inline_keys = [] - for group in groups: - inline_keys.append([InlineKeyboardButton(group.name, callback_data=json.dumps( - {'t': QueryType.Order.value, 'g': True, 'id': group.id}))]) - inline_keys.append([InlineKeyboardButton(MSG_ORDER_TO_SQUADS, callback_data=json.dumps( - {'t': QueryType.Orders.value}))]) - inline_keys.append([InlineKeyboardButton(MSG_ORDER_PIN if pin else MSG_ORDER_NO_PIN, - callback_data=json.dumps( - {'t': QueryType.TriggerOrderPin.value, 'g': True}))]) - inline_keys.append([InlineKeyboardButton(MSG_ORDER_BUTTON if btn else MSG_ORDER_NO_BUTTON, - callback_data=json.dumps( - {'t': QueryType.TriggerOrderButton.value, 'g': True}))]) - inline_markup = InlineKeyboardMarkup(inline_keys) - return inline_markup - - -def generate_ok_markup(order_id, count): - inline_markup = InlineKeyboardMarkup([[InlineKeyboardButton(MSG_ORDER_ACCEPT.format(count), - callback_data=json.dumps( - {'t': QueryType.OrderOk.value, 'id': order_id}))]]) - return inline_markup - - -def generate_groups_manage(session): - groups = session.query(OrderGroup).all() - inline_keys = [] - for group in groups: - inline_keys.append([InlineKeyboardButton(group.name, callback_data=json.dumps( - {'t': QueryType.OrderGroupManage.value, 'id': group.id}))]) - inline_keys.append([InlineKeyboardButton(MSG_ORDER_GROUP_ADD, callback_data=json.dumps( - {'t': QueryType.OrderGroupAdd.value}))]) - return InlineKeyboardMarkup(inline_keys) - - -def generate_group_manage(group_id, session): - squads = session.query(Squad).all() - inline_keys = [] - for squad in squads: - in_group = False - for item in squad.chat.group_items: - if item.group_id == group_id: - in_group = True - break - inline_keys.append([InlineKeyboardButton((MSG_SYMBOL_ON if in_group else MSG_SYMBOL_OFF) + - squad.squad_name, callback_data=json.dumps( - {'t': QueryType.OrderGroupTriggerChat.value, 'id': group_id, 'c': squad.chat_id}))]) - inline_keys.append([InlineKeyboardButton(MSG_ORDER_GROUP_DEL, callback_data=json.dumps( - {'t': QueryType.OrderGroupDelete.value, 'id': group_id}))]) - inline_keys.append([InlineKeyboardButton(MSG_BACK, callback_data=json.dumps( - {'t': QueryType.OrderGroupList.value}))]) - return InlineKeyboardMarkup(inline_keys) - - -def generate_profile_buttons(user, back_key=False): - inline_keys = [[InlineKeyboardButton('🏅Герой', callback_data=json.dumps( - {'t': QueryType.ShowHero.value, 'id': user.id, 'b': back_key}))]] - if user.stock: - inline_keys.append([InlineKeyboardButton('📦Склад', callback_data=json.dumps( - {'t': QueryType.ShowStock.value, 'id': user.id, 'b': back_key}))]) - if user.equip: - inline_keys.append([InlineKeyboardButton('🎽Экипировка', callback_data=json.dumps( - {'t': QueryType.ShowEquip.value, 'id': user.id, 'b': back_key}))]) - if back_key: - inline_keys.append( - [InlineKeyboardButton(MSG_BACK, - callback_data=json.dumps( - {'t': QueryType.MemberList.value, 'id': user.member.squad_id} - ))]) - return InlineKeyboardMarkup(inline_keys) - - -def generate_squad_list_key(squad, session): - attack = 0 - defence = 0 - level = 0 - members = squad.members - user_ids = [] - for member in members: - user_ids.append(member.user_id) - actual_profiles = session.query(Character.user_id, func.max(Character.date)).\ - filter(Character.user_id.in_(user_ids)).\ - group_by(Character.user_id).all() - characters = session.query(Character).filter(tuple_(Character.user_id, Character.date) - .in_([(a[0], a[1]) for a in actual_profiles])).all() - for character in characters: - attack += character.attack - defence += character.defence - level += character.level - return [InlineKeyboardButton( - '{} : {}⚔ {}🛡 {}👥 {}🏅'.format( - squad.squad_name, - attack, - defence, - len(members), - int(level/(len(members) or 1)) - ), - callback_data=json.dumps({'t': QueryType.MemberList.value, 'id': squad.chat_id}))] - - -def generate_squad_list(squads, session): - inline_keys = [] - for squad in squads: - inline_keys.append(generate_squad_list_key(squad, session)) - return InlineKeyboardMarkup(inline_keys) - - -def generate_leave_squad(user_id): - inline_keys = [[InlineKeyboardButton('Выйти', - callback_data=json.dumps({'t': QueryType.LeaveSquad.value, - 'id': user_id}))]] - return InlineKeyboardMarkup(inline_keys) - - -def generate_squad_request(session): - inline_keys = [] - squads = session.query(Squad).filter_by(hiring=True).all() - for squad in squads: - inline_keys.append([InlineKeyboardButton(squad.squad_name, - callback_data=json.dumps( - {'t': QueryType.RequestSquad.value, 'id': squad.chat_id}))]) - return InlineKeyboardMarkup(inline_keys) - - -def generate_other_reports(time: datetime, squad_id): - inline_keys = [[InlineKeyboardButton('<< ' + str(time - timedelta(hours=4)), - callback_data=json.dumps( - {'t': QueryType.OtherReport.value, - 'ts': (time - timedelta(hours=4)).timestamp(), - 'c': squad_id}))]] - if time + timedelta(hours=4) < datetime.now(): - inline_keys[0].append(InlineKeyboardButton(str(time + timedelta(hours=4)) + ' >>', - callback_data=json.dumps( - {'t': QueryType.OtherReport.value, - 'ts': (time + timedelta(hours=4)).timestamp(), - 'c': squad_id}))) - return InlineKeyboardMarkup(inline_keys) - - -def generate_squad_members(members, session): - inline_keys = [] - user_ids = [] - for member in members: - user_ids.append(member.user_id) - actual_profiles = session.query(Character.user_id, func.max(Character.date)). \ - filter(Character.user_id.in_(user_ids)). \ - group_by(Character.user_id).all() - characters = session.query(Character).filter(tuple_(Character.user_id, Character.date) - .in_([(a[0], a[1]) for a in actual_profiles]))\ - .order_by(Character.level.desc()).all() - for character in characters: - time_passed = datetime.now() - character.date - status_emoji = '❇' - if time_passed > timedelta(days=7): - status_emoji = '⁉' - elif time_passed > timedelta(days=4): - status_emoji = '‼' - elif time_passed > timedelta(days=3): - status_emoji = '❗' - elif time_passed < timedelta(days=1): - status_emoji = '🕐' - inline_keys.append( - [InlineKeyboardButton('{}{}: {}⚔ {}🛡 {}🏅'. - format(status_emoji, - character.name, - character.attack, - character.defence, - character.level), - callback_data=json.dumps( - {'t': QueryType.ShowHero.value, - 'id': character.user_id, - 'b': True} - ))]) - inline_keys.append( - [InlineKeyboardButton(MSG_BACK, - callback_data=json.dumps( - {'t': QueryType.SquadList.value} - ))]) - return InlineKeyboardMarkup(inline_keys) - - -def generate_squad_request_answer(user_id): - inline_keys = [InlineKeyboardButton('✅Принять', - callback_data=json.dumps( - {'t': QueryType.RequestSquadAccept.value, 'id': user_id})), - InlineKeyboardButton('❌Отклонить', - callback_data=json.dumps( - {'t': QueryType.RequestSquadDecline.value, 'id': user_id}))] - return InlineKeyboardMarkup([inline_keys]) - - -def generate_squad_invite_answer(user_id): - inline_keys = [InlineKeyboardButton(MSG_SQUAD_GREEN_INLINE_BUTTON, - callback_data=json.dumps( - {'t': QueryType.InviteSquadAccept.value, 'id': user_id})), - InlineKeyboardButton(MSG_SQUAD_RED_INLINE_BUTTON, - callback_data=json.dumps( - {'t': QueryType.InviteSquadDecline.value, 'id': user_id}))] - return InlineKeyboardMarkup([inline_keys]) - - -def generate_fire_up(members): - inline_keys = [] - for member in members: - inline_keys.append([InlineKeyboardButton('🔥{}: {}⚔ {}🛡'.format(member.user, member.user.character.attack, - member.user.character.defence), - callback_data=json.dumps( - {'t': QueryType.LeaveSquad.value, 'id': member.user_id}))]) - return InlineKeyboardMarkup(inline_keys) - - @run_async def send_order(bot, order, order_type, chat_id, markup): try: @@ -871,14 +539,20 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): bot.editMessageText(text, update.callback_query.message.chat.id, update.callback_query.message.message_id, parse_mode=ParseMode.HTML, reply_markup=markup) elif data['t'] == QueryType.GlobalBuildTop.value: - pass + update.callback_query.answer(text='Генерируем топ') + global_build_top(bot, update) elif data['t'] == QueryType.WeekBuildTop.value: - pass + update.callback_query.answer(text='Генерируем топ') + week_build_top(bot, update) elif data['t'] == QueryType.SquadGlobalBuildTop.value: - pass + update.callback_query.answer(text='Генерируем топ') + global_squad_build_top(bot, update) elif data['t'] == QueryType.SquadWeekBuildTop.value: - pass + update.callback_query.answer(text='Генерируем топ') + week_squad_build_top(bot, update) elif data['t'] == QueryType.BattleGlobalTop.value: - pass + update.callback_query.answer(text='Генерируем топ') + global_battle_top(bot, update) elif data['t'] == QueryType.BattleWeekTop.value: - pass + update.callback_query.answer(text='Генерируем топ') + week_battle_top(bot, update) diff --git a/core/functions/inline_markup.py b/core/functions/inline_markup.py new file mode 100644 index 0000000..e05ecae --- /dev/null +++ b/core/functions/inline_markup.py @@ -0,0 +1,375 @@ +import json +from datetime import datetime, timedelta +from enum import Enum + +from sqlalchemy import func, tuple_ +from telegram import InlineKeyboardButton, InlineKeyboardMarkup + +from core.enums import Castle, Icons +from core.texts import MSG_GROUP_STATUS_ADMIN_FORMAT, MSG_GROUP_STATUS_DEL_ADMIN, MSG_GROUP_STATUS, MSG_ON, MSG_OFF, \ + MSG_ORDER_GROUP_DEL, MSG_BACK, MSG_ORDER_PIN, MSG_ORDER_NO_PIN, MSG_ORDER_BUTTON, MSG_ORDER_NO_BUTTON, \ + MSG_ORDER_TO_SQUADS, MSG_ORDER_ACCEPT, MSG_ORDER_GROUP_ADD, MSG_SYMBOL_ON, MSG_SYMBOL_OFF, \ + MSG_SQUAD_GREEN_INLINE_BUTTON, MSG_SQUAD_RED_INLINE_BUTTON +from core.types import Group, Admin, User, Squad, AdminType, OrderGroup, Character + + +class QueryType(Enum): + GroupList = 0 + GroupInfo = 1 + DelAdm = 2 + Order = 3 + OrderOk = 4 + Orders = 5 + OrderGroup = 6 + OrderGroupManage = 7 + OrderGroupTriggerChat = 8 + OrderGroupAdd = 9 + OrderGroupDelete = 10 + OrderGroupList = 11 + ShowStock = 12 + ShowEquip = 13 + ShowHero = 14 + MemberList = 15 + LeaveSquad = 16 + RequestSquad = 17 + RequestSquadAccept = 18 + RequestSquadDecline = 19 + InviteSquadAccept = 20 + InviteSquadDecline = 21 + TriggerOrderPin = 22 + SquadList = 23 + GroupDelete = 24 + TriggerOrderButton = 25 + OtherReport = 26 + GlobalBuildTop = 27 + WeekBuildTop = 28 + SquadGlobalBuildTop = 29 + SquadWeekBuildTop = 30 + BattleGlobalTop = 31 + BattleWeekTop = 32 + + +def generate_group_info(group_id, session): + group = session.query(Group).filter(Group.id == group_id).first() + admins = session.query(Admin).filter(Admin.admin_group == group_id).all() + adm_msg = '' + adm_del_keys = [] + for adm in admins: + user = session.query(User).filter_by(id=adm.user_id).first() + adm_msg += MSG_GROUP_STATUS_ADMIN_FORMAT.\ + format(user.id, user.username or '', user.first_name or '', user.last_name or '') + adm_del_keys.append([InlineKeyboardButton(MSG_GROUP_STATUS_DEL_ADMIN. + format(user.first_name or '', user.last_name or ''), + callback_data=json.dumps( + {'t': QueryType.DelAdm.value, 'uid': user.id, + 'gid': group_id}))]) + msg = MSG_GROUP_STATUS.format(group.title, + adm_msg, + MSG_ON if group.welcome_enabled else MSG_OFF, + MSG_ON if group.allow_trigger_all else MSG_OFF, + MSG_ON if len(group.squad) and group.squad[0].thorns_enabled else MSG_OFF) + adm_del_keys.append([InlineKeyboardButton(MSG_ORDER_GROUP_DEL, callback_data=json.dumps( + {'t': QueryType.GroupDelete.value, 'gid': group_id}))]) + adm_del_keys.append([InlineKeyboardButton(MSG_BACK, callback_data=json.dumps( + {'t': QueryType.GroupList.value}))]) + inline_markup = InlineKeyboardMarkup(adm_del_keys) + return msg, inline_markup + + +def generate_flag_orders(): + flag_btns = [[InlineKeyboardButton(Castle.BLACK.value, callback_data=json.dumps( + {'t': QueryType.OrderGroup.value, 'txt': Castle.BLACK.value})), + InlineKeyboardButton(Castle.WHITE.value, callback_data=json.dumps( + {'t': QueryType.OrderGroup.value, 'txt': Castle.WHITE.value})), + InlineKeyboardButton(Castle.BLUE.value, callback_data=json.dumps( + {'t': QueryType.OrderGroup.value, 'txt': Castle.BLUE.value}))], + [InlineKeyboardButton(Castle.YELLOW.value, callback_data=json.dumps( + {'t': QueryType.OrderGroup.value, 'txt': Castle.YELLOW.value})), + InlineKeyboardButton(Castle.RED.value, callback_data=json.dumps( + {'t': QueryType.OrderGroup.value, 'txt': Castle.RED.value})), + InlineKeyboardButton(Castle.DUSK.value, callback_data=json.dumps( + {'t': QueryType.OrderGroup.value, 'txt': Castle.DUSK.value}))], + [InlineKeyboardButton(Castle.MINT.value, callback_data=json.dumps( + {'t': QueryType.OrderGroup.value, 'txt': Castle.MINT.value})), + InlineKeyboardButton(Castle.GORY.value, callback_data=json.dumps( + {'t': QueryType.OrderGroup.value, 'txt': Icons.GORY.value})), + InlineKeyboardButton(Castle.LES.value, callback_data=json.dumps( + {'t': QueryType.OrderGroup.value, 'txt': Icons.LES.value}))], + [InlineKeyboardButton(Castle.SEA.value, callback_data=json.dumps( + {'t': QueryType.OrderGroup.value, 'txt': Icons.SEA.value}))]] + inline_markup = InlineKeyboardMarkup(flag_btns) + return inline_markup + + +def generate_order_chats_markup(session, pin=True, btn=True): + squads = session.query(Squad).all() + inline_keys = [] + for squad in squads: + inline_keys.append([InlineKeyboardButton(squad.squad_name, callback_data=json.dumps( + {'t': QueryType.Order.value, 'g': False, 'id': squad.chat_id}))]) + inline_keys.append([InlineKeyboardButton(MSG_ORDER_PIN if pin else MSG_ORDER_NO_PIN, callback_data=json.dumps( + {'t': QueryType.TriggerOrderPin.value, 'g': False}))]) + inline_keys.append([InlineKeyboardButton(MSG_ORDER_BUTTON if btn else MSG_ORDER_NO_BUTTON, callback_data=json.dumps( + {'t': QueryType.TriggerOrderButton.value, 'g': False}))]) + inline_markup = InlineKeyboardMarkup(inline_keys) + return inline_markup + + +def generate_order_groups_markup(session, admin_user: list=None, pin: bool=True, btn=True): + if admin_user: + group_adm = True + for adm in admin_user: + if adm.admin_type < AdminType.GROUP.value: + group_adm = False + break + if group_adm: + inline_keys = [] + for adm in admin_user: + group = session.query(Group).filter_by(id=adm.admin_group, bot_in_group=True).first() + if group: + inline_keys.append([InlineKeyboardButton(group.title, callback_data=json.dumps( + {'t': QueryType.Order.value, 'g': False, 'id': group.id}))]) + inline_keys.append( + [InlineKeyboardButton(MSG_ORDER_PIN if pin else MSG_ORDER_NO_PIN, callback_data=json.dumps( + {'t': QueryType.TriggerOrderPin.value, 'g': True}))]) + inline_keys.append( + [InlineKeyboardButton(MSG_ORDER_BUTTON if btn else MSG_ORDER_NO_BUTTON, callback_data=json.dumps( + {'t': QueryType.TriggerOrderButton.value, 'g': True}))]) + inline_markup = InlineKeyboardMarkup(inline_keys) + return inline_markup + else: + groups = session.query(OrderGroup).all() + inline_keys = [] + for group in groups: + inline_keys.append([InlineKeyboardButton(group.name, callback_data=json.dumps( + {'t': QueryType.Order.value, 'g': True, 'id': group.id}))]) + inline_keys.append([InlineKeyboardButton(MSG_ORDER_TO_SQUADS, callback_data=json.dumps( + {'t': QueryType.Orders.value}))]) + inline_keys.append([InlineKeyboardButton(MSG_ORDER_PIN if pin else MSG_ORDER_NO_PIN, + callback_data=json.dumps( + {'t': QueryType.TriggerOrderPin.value, 'g': True}))]) + inline_keys.append([InlineKeyboardButton(MSG_ORDER_BUTTON if btn else MSG_ORDER_NO_BUTTON, + callback_data=json.dumps( + {'t': QueryType.TriggerOrderButton.value, 'g': True}))]) + inline_markup = InlineKeyboardMarkup(inline_keys) + return inline_markup + + +def generate_ok_markup(order_id, count): + inline_markup = InlineKeyboardMarkup([[InlineKeyboardButton(MSG_ORDER_ACCEPT.format(count), + callback_data=json.dumps( + {'t': QueryType.OrderOk.value, 'id': order_id}))]]) + return inline_markup + + +def generate_groups_manage(session): + groups = session.query(OrderGroup).all() + inline_keys = [] + for group in groups: + inline_keys.append([InlineKeyboardButton(group.name, callback_data=json.dumps( + {'t': QueryType.OrderGroupManage.value, 'id': group.id}))]) + inline_keys.append([InlineKeyboardButton(MSG_ORDER_GROUP_ADD, callback_data=json.dumps( + {'t': QueryType.OrderGroupAdd.value}))]) + return InlineKeyboardMarkup(inline_keys) + + +def generate_group_manage(group_id, session): + squads = session.query(Squad).all() + inline_keys = [] + for squad in squads: + in_group = False + for item in squad.chat.group_items: + if item.group_id == group_id: + in_group = True + break + inline_keys.append([InlineKeyboardButton((MSG_SYMBOL_ON if in_group else MSG_SYMBOL_OFF) + + squad.squad_name, callback_data=json.dumps( + {'t': QueryType.OrderGroupTriggerChat.value, 'id': group_id, 'c': squad.chat_id}))]) + inline_keys.append([InlineKeyboardButton(MSG_ORDER_GROUP_DEL, callback_data=json.dumps( + {'t': QueryType.OrderGroupDelete.value, 'id': group_id}))]) + inline_keys.append([InlineKeyboardButton(MSG_BACK, callback_data=json.dumps( + {'t': QueryType.OrderGroupList.value}))]) + return InlineKeyboardMarkup(inline_keys) + + +def generate_profile_buttons(user, back_key=False): + inline_keys = [[InlineKeyboardButton('🏅Герой', callback_data=json.dumps( + {'t': QueryType.ShowHero.value, 'id': user.id, 'b': back_key}))]] + if user.stock: + inline_keys.append([InlineKeyboardButton('📦Склад', callback_data=json.dumps( + {'t': QueryType.ShowStock.value, 'id': user.id, 'b': back_key}))]) + if user.equip: + inline_keys.append([InlineKeyboardButton('🎽Экипировка', callback_data=json.dumps( + {'t': QueryType.ShowEquip.value, 'id': user.id, 'b': back_key}))]) + if back_key: + inline_keys.append( + [InlineKeyboardButton(MSG_BACK, + callback_data=json.dumps( + {'t': QueryType.MemberList.value, 'id': user.member.squad_id} + ))]) + return InlineKeyboardMarkup(inline_keys) + + +def generate_squad_list_key(squad, session): + attack = 0 + defence = 0 + level = 0 + members = squad.members + user_ids = [] + for member in members: + user_ids.append(member.user_id) + actual_profiles = session.query(Character.user_id, func.max(Character.date)).\ + filter(Character.user_id.in_(user_ids)).\ + group_by(Character.user_id).all() + characters = session.query(Character).filter(tuple_(Character.user_id, Character.date) + .in_([(a[0], a[1]) for a in actual_profiles])).all() + for character in characters: + attack += character.attack + defence += character.defence + level += character.level + return [InlineKeyboardButton( + '{} : {}⚔ {}🛡 {}👥 {}🏅'.format( + squad.squad_name, + attack, + defence, + len(members), + int(level/(len(members) or 1)) + ), + callback_data=json.dumps({'t': QueryType.MemberList.value, 'id': squad.chat_id}))] + + +def generate_squad_list(squads, session): + inline_keys = [] + for squad in squads: + inline_keys.append(generate_squad_list_key(squad, session)) + return InlineKeyboardMarkup(inline_keys) + + +def generate_leave_squad(user_id): + inline_keys = [[InlineKeyboardButton('Выйти', + callback_data=json.dumps({'t': QueryType.LeaveSquad.value, + 'id': user_id}))]] + return InlineKeyboardMarkup(inline_keys) + + +def generate_squad_request(session): + inline_keys = [] + squads = session.query(Squad).filter_by(hiring=True).all() + for squad in squads: + inline_keys.append([InlineKeyboardButton(squad.squad_name, + callback_data=json.dumps( + {'t': QueryType.RequestSquad.value, 'id': squad.chat_id}))]) + return InlineKeyboardMarkup(inline_keys) + + +def generate_other_reports(time: datetime, squad_id): + inline_keys = [[InlineKeyboardButton('<< ' + str(time - timedelta(hours=4)), + callback_data=json.dumps( + {'t': QueryType.OtherReport.value, + 'ts': (time - timedelta(hours=4)).timestamp(), + 'c': squad_id}))]] + if time + timedelta(hours=4) < datetime.now(): + inline_keys[0].append(InlineKeyboardButton(str(time + timedelta(hours=4)) + ' >>', + callback_data=json.dumps( + {'t': QueryType.OtherReport.value, + 'ts': (time + timedelta(hours=4)).timestamp(), + 'c': squad_id}))) + return InlineKeyboardMarkup(inline_keys) + + +def generate_squad_members(members, session): + inline_keys = [] + user_ids = [] + for member in members: + user_ids.append(member.user_id) + actual_profiles = session.query(Character.user_id, func.max(Character.date)). \ + filter(Character.user_id.in_(user_ids)). \ + group_by(Character.user_id).all() + characters = session.query(Character).filter(tuple_(Character.user_id, Character.date) + .in_([(a[0], a[1]) for a in actual_profiles]))\ + .order_by(Character.level.desc()).all() + for character in characters: + time_passed = datetime.now() - character.date + status_emoji = '❇' + if time_passed > timedelta(days=7): + status_emoji = '⁉' + elif time_passed > timedelta(days=4): + status_emoji = '‼' + elif time_passed > timedelta(days=3): + status_emoji = '❗' + elif time_passed < timedelta(days=1): + status_emoji = '🕐' + inline_keys.append( + [InlineKeyboardButton('{}{}: {}⚔ {}🛡 {}🏅'. + format(status_emoji, + character.name, + character.attack, + character.defence, + character.level), + callback_data=json.dumps( + {'t': QueryType.ShowHero.value, + 'id': character.user_id, + 'b': True} + ))]) + inline_keys.append( + [InlineKeyboardButton(MSG_BACK, + callback_data=json.dumps( + {'t': QueryType.SquadList.value} + ))]) + return InlineKeyboardMarkup(inline_keys) + + +def generate_squad_request_answer(user_id): + inline_keys = [InlineKeyboardButton('✅Принять', + callback_data=json.dumps( + {'t': QueryType.RequestSquadAccept.value, 'id': user_id})), + InlineKeyboardButton('❌Отклонить', + callback_data=json.dumps( + {'t': QueryType.RequestSquadDecline.value, 'id': user_id}))] + return InlineKeyboardMarkup([inline_keys]) + + +def generate_squad_invite_answer(user_id): + inline_keys = [InlineKeyboardButton(MSG_SQUAD_GREEN_INLINE_BUTTON, + callback_data=json.dumps( + {'t': QueryType.InviteSquadAccept.value, 'id': user_id})), + InlineKeyboardButton(MSG_SQUAD_RED_INLINE_BUTTON, + callback_data=json.dumps( + {'t': QueryType.InviteSquadDecline.value, 'id': user_id}))] + return InlineKeyboardMarkup([inline_keys]) + + +def generate_fire_up(members): + inline_keys = [] + for member in members: + inline_keys.append([InlineKeyboardButton('🔥{}: {}⚔ {}🛡'.format(member.user, member.user.character.attack, + member.user.character.defence), + callback_data=json.dumps( + {'t': QueryType.LeaveSquad.value, 'id': member.user_id}))]) + return InlineKeyboardMarkup(inline_keys) + + +def generate_build_top(): + inline_keys = [[InlineKeyboardButton("Неделя", + callback_data=json.dumps( + {'t': QueryType.WeekBuildTop.value})), + InlineKeyboardButton("Всё время", + callback_data=json.dumps( + {'t': QueryType.GlobalBuildTop.value}))], + [InlineKeyboardButton("Отряды за неделю", + callback_data=json.dumps( + {'t': QueryType.SquadWeekBuildTop.value})), + InlineKeyboardButton("Отряды за всё время", + callback_data=json.dumps( + {'t': QueryType.SquadGlobalBuildTop.value}))]] + return InlineKeyboardMarkup(inline_keys) + + +def generate_battle_top(): + inline_keys = [[InlineKeyboardButton("Неделя", + callback_data=json.dumps( + {'t': QueryType.BattleWeekTop.value})), + InlineKeyboardButton("Всё время", + callback_data=json.dumps( + {'t': QueryType.BattleGlobalTop.value}))]] + return InlineKeyboardMarkup(inline_keys) diff --git a/core/functions/orders.py b/core/functions/orders.py index a7775ac..a4a8559 100644 --- a/core/functions/orders.py +++ b/core/functions/orders.py @@ -1,7 +1,7 @@ from telegram import Update, Bot from core.types import AdminType, Admin, admin_allowed, MessageType from core.utils import send_async -from core.functions.inline_keyboard_handling import generate_order_groups_markup, generate_flag_orders +from core.functions.inline_markup import generate_order_groups_markup, generate_flag_orders from core.texts import * diff --git a/core/functions/reply_markup.py b/core/functions/reply_markup.py index 9ee5e5d..3ddb46f 100644 --- a/core/functions/reply_markup.py +++ b/core/functions/reply_markup.py @@ -4,8 +4,8 @@ ADMIN_COMMAND_FIRE_UP, ADMIN_COMMAND_SQUAD_LIST, USER_COMMAND_ME, USER_COMMAND_TOP, USER_COMMAND_SQUAD, \ USER_COMMAND_STATISTICS, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, ADMIN_COMMAND_ADMINPANEL, \ USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK, TOP_COMMAND_ATTACK, TOP_COMMAND_DEFENCE, TOP_COMMAND_EXP, \ - STATISTICS_COMMAND_EXP, USER_COMMAND_SQUAD_LEAVE, ADMIN_COMMAND_REPORTS, TOP_COMMAND_GLOBAL_BUILD, \ - TOP_COMMAND_WEEK_BUILD, TOP_COMMAND_WEEK_BATTLES + STATISTICS_COMMAND_EXP, USER_COMMAND_SQUAD_LEAVE, ADMIN_COMMAND_REPORTS, TOP_COMMAND_BUILD, \ + TOP_COMMAND_BATTLES def generate_admin_markup(full=False): @@ -28,8 +28,8 @@ def generate_user_markup(is_admin=False): def generate_top_markup(): buttons = [[KeyboardButton(TOP_COMMAND_ATTACK), KeyboardButton(TOP_COMMAND_DEFENCE), - KeyboardButton(TOP_COMMAND_EXP), KeyboardButton(TOP_COMMAND_GLOBAL_BUILD)], - [KeyboardButton(TOP_COMMAND_WEEK_BUILD), KeyboardButton(TOP_COMMAND_WEEK_BATTLES)], + KeyboardButton(TOP_COMMAND_EXP), KeyboardButton(TOP_COMMAND_BUILD), + KeyboardButton(TOP_COMMAND_BATTLES)], [KeyboardButton(USER_COMMAND_BACK)]] return ReplyKeyboardMarkup(buttons, True) diff --git a/core/functions/squad.py b/core/functions/squad.py index 6f17a81..5b44ac4 100644 --- a/core/functions/squad.py +++ b/core/functions/squad.py @@ -7,9 +7,8 @@ from core.template import fill_char_template from core.types import User, AdminType, Admin, admin_allowed, Group, Squad, SquadMember, user_allowed, Report, Character from core.utils import send_async -from core.functions.inline_keyboard_handling import generate_squad_list, \ - generate_leave_squad, generate_squad_request, generate_squad_request_answer, generate_fire_up, \ - generate_squad_invite_answer, generate_other_reports +from core.functions.inline_markup import generate_squad_list, generate_leave_squad, generate_squad_request, \ + generate_other_reports, generate_squad_request_answer, generate_squad_invite_answer, generate_fire_up from core.texts import * diff --git a/core/functions/top.py b/core/functions/top.py index 9b3055b..aed3a2f 100644 --- a/core/functions/top.py +++ b/core/functions/top.py @@ -1,16 +1,19 @@ from sqlalchemy import func, text as text_, tuple_ from telegram import Update, Bot +from core.functions.inline_markup import generate_build_top, generate_battle_top from core.functions.reply_markup import generate_top_markup from core.texts import MSG_TOP_ABOUT, MSG_TOP_FORMAT, MSG_TOP_ATTACK, MSG_TOP_DEFENCE, MSG_TOP_EXPERIENCE, \ - MSG_TOP_GLOBAL_BUILDERS, MSG_TOP_WEEK_BUILDERS, MSG_TOP_WEEK_WARRIORS -from core.types import user_allowed, Character, BuildReport, Report + MSG_TOP_GLOBAL_BUILDERS, MSG_TOP_WEEK_BUILDERS, MSG_TOP_WEEK_WARRIORS, MSG_SQUAD_TOP_FORMAT +from core.types import user_allowed, Character, BuildReport, Report, Squad, SquadMember from core.utils import send_async from config import CASTLE from datetime import datetime, timedelta +TOP_START_DATE = datetime(2017, 11, 11) + @user_allowed def top_about(bot: Bot, update: Update, session): @@ -78,6 +81,42 @@ def exp_top(bot: Bot, update: Update, session): text=text) +def gen_top_msg(data, user_id, header, icon): + text = header + str_format = MSG_TOP_FORMAT + for i in range(min(10, len(data))): + text += str_format.format(i + 1, data[i][0].name, data[i][0].level, + data[i][1], icon) + if len(data) and hasattr(data[0][0], 'user_id') and user_id in [build[0].user_id for build in data]: + if user_id not in [build[0].user_id for build in data[:10]]: + for i in range(10, len(data)): + if data[i][0].user_id == user_id: + text += '...\n' + text += str_format.format(i, data[i - 1][0].name, data[i - 1][0].level, + data[i - 1][1], icon) + text += str_format.format(i + 1, data[i][0].name, data[i][0].level, + data[i][1], icon) + if i != len(data) - 1: + text += str_format.format(i + 2, data[i + 1][0].name, data[i + 1][0].level, + data[i + 1][1], icon) + break + return text + + +def gen_squad_top_msg(data, counts, header, icon): + text = header + str_format = MSG_SQUAD_TOP_FORMAT + for i in range(min(10, len(data))): + squad_count = 1 + for squad, count in counts: + if squad.chat_id == data[i][0].chat_id: + squad_count = count + break + text += str_format.format(i + 1, data[i][0].squad_name, squad_count, + data[i][1], icon, round(data[i][1]/squad_count, 2), icon) + return text + + @user_allowed def global_build_top(bot: Bot, update: Update, session): actual_profiles = session.query(Character.user_id, func.max(Character.date)). \ @@ -87,33 +126,26 @@ def global_build_top(bot: Bot, update: Update, session): .filter(tuple_(Character.user_id, Character.date) .in_([(a[0], a[1]) for a in actual_profiles]), Character.date > datetime.now() - timedelta(days=7))\ - .outerjoin(BuildReport, BuildReport.user_id == Character.user_id).group_by(Character) \ - .filter(BuildReport.date > datetime(2017, 12, 1))\ + .outerjoin(BuildReport, BuildReport.user_id == Character.user_id) \ + .filter(BuildReport.date > TOP_START_DATE).group_by(Character)\ .order_by(func.count(BuildReport.user_id).desc()) if CASTLE: builds = builds.filter(Character.castle == CASTLE) builds = builds.all() - text = MSG_TOP_GLOBAL_BUILDERS - str_format = MSG_TOP_FORMAT - for i in range(min(10, len(builds))): - text += str_format.format(i + 1, builds[i][0].name, builds[i][0].level, - builds[i][1], '⚒') - if update.message.from_user.id in [build[0].user_id for build in builds]: - if update.message.from_user.id not in [build[0].user_id for build in builds[:10]]: - for i in range(10, len(builds)): - if builds[i][0].user_id == update.message.from_user.id: - text += '...\n' - text += str_format.format(i, builds[i - 1][0].name, builds[i-1][0].level, - builds[i - 1][1], '⚒') - text += str_format.format(i + 1, builds[i][0].name, builds[i][0].level, - builds[i][1], '⚒') - if i != len(builds) - 1: - text += str_format.format(i + 2, builds[i + 1][0].name, builds[i+1][0].level, - builds[i + 1][1], '⚒') - break - send_async(bot, - chat_id=update.message.chat.id, - text=text) + user_id = 0 + if update.message: + user_id = update.message.from_user.id + elif update.callback_query: + user_id = update.callback_query.message.from_user.id + text = gen_top_msg(builds, user_id, MSG_TOP_GLOBAL_BUILDERS, '⚒') + markup = generate_build_top() + if update.message: + send_async(bot, + chat_id=update.message.chat.id, + text=text, reply_markup=markup) + elif update.callback_query: + bot.editMessageText(text, update.callback_query.message.chat.id, update.callback_query.message.message_id, + reply_markup=markup) @user_allowed @@ -126,33 +158,83 @@ def week_build_top(bot: Bot, update: Update, session): .filter(tuple_(Character.user_id, Character.date) .in_([(a[0], a[1]) for a in actual_profiles]), Character.date > datetime.now() - timedelta(days=7))\ - .outerjoin(BuildReport, BuildReport.user_id == Character.user_id).group_by(Character) \ - .filter(BuildReport.date > today - timedelta(days=today.weekday()))\ + .outerjoin(BuildReport, BuildReport.user_id == Character.user_id) \ + .filter(BuildReport.date > today - timedelta(days=today.weekday())).group_by(Character)\ .order_by(func.count(BuildReport.user_id).desc()) if CASTLE: builds = builds.filter(Character.castle == CASTLE) builds = builds.all() - text = MSG_TOP_WEEK_BUILDERS - str_format = MSG_TOP_FORMAT - for i in range(min(10, len(builds))): - text += str_format.format(i + 1, builds[i][0].name, builds[i][0].level, - builds[i][1], '⚒') - if update.message.from_user.id in [build[0].user_id for build in builds]: - if update.message.from_user.id not in [build[0].user_id for build in builds[:10]]: - for i in range(10, len(builds)): - if builds[i][0].user_id == update.message.from_user.id: - text += '...\n' - text += str_format.format(i, builds[i - 1][0].name, builds[i-1][0].level, - builds[i - 1][1], '⚒') - text += str_format.format(i + 1, builds[i][0].name, builds[i][0].level, - builds[i][1], '⚒') - if i != len(builds) - 1: - text += str_format.format(i + 2, builds[i + 1][0].name, builds[i+1][0].level, - builds[i + 1][1], '⚒') - break - send_async(bot, - chat_id=update.message.chat.id, - text=text) + user_id = 0 + if update.message: + user_id = update.message.from_user.id + elif update.callback_query: + user_id = update.callback_query.message.from_user.id + text = gen_top_msg(builds, user_id, MSG_TOP_WEEK_BUILDERS, '⚒') + markup = generate_build_top() + if update.message: + send_async(bot, + chat_id=update.message.chat.id, + text=text, reply_markup=markup) + elif update.callback_query: + bot.editMessageText(text, update.callback_query.message.chat.id, update.callback_query.message.message_id, + reply_markup=markup) + + +@user_allowed +def week_squad_build_top(bot: Bot, update: Update, session): + actual_profiles = session.query(Character.user_id, func.max(Character.date)). \ + group_by(Character.user_id) + actual_profiles = actual_profiles.all() + today = datetime.today() + builds = session.query(Squad, func.count(BuildReport.user_id))\ + .join(SquadMember).join(Character, SquadMember.user_id == Character.user_id)\ + .filter(tuple_(Character.user_id, Character.date) + .in_([(a[0], a[1]) for a in actual_profiles]), + Character.date > datetime.now() - timedelta(days=7))\ + .outerjoin(BuildReport, BuildReport.user_id == Character.user_id) \ + .filter(BuildReport.date > today - timedelta(days=today.weekday()))\ + .order_by(func.count(BuildReport.user_id).desc()) + if CASTLE: + builds = builds.filter(Character.castle == CASTLE) + builds = builds.group_by(Squad).all() + counts = session.query(Squad, func.count(SquadMember.user_id)).join(SquadMember).group_by(Squad) + text = gen_squad_top_msg(builds, counts, MSG_TOP_WEEK_BUILDERS, '⚒') + markup = generate_build_top() + if update.message: + send_async(bot, + chat_id=update.message.chat.id, + text=text, reply_markup=markup) + elif update.callback_query: + bot.editMessageText(text, update.callback_query.message.chat.id, update.callback_query.message.message_id, + reply_markup=markup) + + +@user_allowed +def global_squad_build_top(bot: Bot, update: Update, session): + actual_profiles = session.query(Character.user_id, func.max(Character.date)). \ + group_by(Character.user_id) + actual_profiles = actual_profiles.all() + builds = session.query(Squad, func.count(BuildReport.user_id))\ + .join(SquadMember).join(Character, SquadMember.user_id == Character.user_id)\ + .filter(tuple_(Character.user_id, Character.date) + .in_([(a[0], a[1]) for a in actual_profiles]), + Character.date > datetime.now() - timedelta(days=7))\ + .outerjoin(BuildReport, BuildReport.user_id == Character.user_id) \ + .filter(BuildReport.date > TOP_START_DATE) \ + .order_by(func.count(BuildReport.user_id).desc()) + if CASTLE: + builds = builds.filter(Character.castle == CASTLE) + builds = builds.group_by(Squad).all() + counts = session.query(Squad, func.count(SquadMember.user_id)).join(SquadMember).group_by(Squad) + text = gen_squad_top_msg(builds, counts, MSG_TOP_GLOBAL_BUILDERS, '⚒') + markup = generate_build_top() + if update.message: + send_async(bot, + chat_id=update.message.chat.id, + text=text, reply_markup=markup) + elif update.callback_query: + bot.editMessageText(text, update.callback_query.message.chat.id, update.callback_query.message.message_id, + reply_markup=markup) @user_allowed @@ -165,32 +247,56 @@ def week_battle_top(bot: Bot, update: Update, session): .filter(tuple_(Character.user_id, Character.date) .in_([(a[0], a[1]) for a in actual_profiles]), Character.date > datetime.now() - timedelta(days=7))\ - .outerjoin(Report, Report.user_id == Character.user_id).group_by(Character) \ + .outerjoin(Report, Report.user_id == Character.user_id) \ .filter(Report.date > today - timedelta(days=today.weekday())) \ - .filter(Report.earned_exp > 1) \ + .filter(Report.earned_exp > 1).group_by(Character) \ .order_by(func.count(Report.user_id).desc()) if CASTLE: battles = battles.filter(Character.castle == CASTLE) battles = battles.all() - text = MSG_TOP_WEEK_WARRIORS - str_format = MSG_TOP_FORMAT - for i in range(min(10, len(battles))): - text += str_format.format(i + 1, battles[i][0].name, battles[i][0].level, - battles[i][1], '⚔') - if update.message.from_user.id in [build[0].user_id for build in battles]: - if update.message.from_user.id not in [build[0].user_id for build in battles[:10]]: - for i in range(10, len(battles)): - if battles[i][0].user_id == update.message.from_user.id: - text += '...\n' - text += str_format.format(i, battles[i - 1][0].name, battles[i-1][0].level, - battles[i - 1][1], '⚔') - text += str_format.format(i + 1, battles[i][0].name, battles[i][0].level, - battles[i][1], '⚔') - if i != len(battles) - 1: - text += str_format.format(i + 2, battles[i + 1][0].name, battles[i+1][0].level, - battles[i + 1][1], '⚔') - break - send_async(bot, - chat_id=update.message.chat.id, - text=text) + user_id = 0 + if update.message: + user_id = update.message.from_user.id + elif update.callback_query: + user_id = update.callback_query.message.from_user.id + text = gen_top_msg(battles, user_id, MSG_TOP_WEEK_WARRIORS, '⚔🛡') + markup = generate_battle_top() + if update.message: + send_async(bot, + chat_id=update.message.chat.id, + text=text, reply_markup=markup) + elif update.callback_query: + bot.editMessageText(text, update.callback_query.message.chat.id, update.callback_query.message.message_id, + reply_markup=markup) + +@user_allowed +def global_battle_top(bot: Bot, update: Update, session): + actual_profiles = session.query(Character.user_id, func.max(Character.date)). \ + group_by(Character.user_id) + actual_profiles = actual_profiles.all() + battles = session.query(Character, func.count(Report.user_id))\ + .filter(tuple_(Character.user_id, Character.date) + .in_([(a[0], a[1]) for a in actual_profiles]), + Character.date > datetime.now() - timedelta(days=7))\ + .outerjoin(Report, Report.user_id == Character.user_id) \ + .filter(Report.earned_exp > 1) \ + .filter(Report.date > TOP_START_DATE).group_by(Character) \ + .order_by(func.count(Report.user_id).desc()) + if CASTLE: + battles = battles.filter(Character.castle == CASTLE) + battles = battles.all() + user_id = 0 + if update.message: + user_id = update.message.from_user.id + elif update.callback_query: + user_id = update.callback_query.message.from_user.id + text = gen_top_msg(battles, user_id, MSG_TOP_WEEK_WARRIORS, '⚔🛡') + markup = generate_battle_top() + if update.message: + send_async(bot, + chat_id=update.message.chat.id, + text=text, reply_markup=markup) + elif update.callback_query: + bot.editMessageText(text, update.callback_query.message.chat.id, update.callback_query.message.message_id, + reply_markup=markup) diff --git a/core/texts.py b/core/texts.py index de51083..7e0681c 100644 --- a/core/texts.py +++ b/core/texts.py @@ -242,6 +242,7 @@ MSG_SQUAD_ABOUT = '⚜Отряд⚜' MSG_TOP_FORMAT = '{}. {} ({}🌟) - {}{}\n' +MSG_SQUAD_TOP_FORMAT = '{}. {} ({}👥) - {}{} ({}{}/👤)\n' MSG_TOP_DEFENCE = '🛡Топ дэферы:\n' MSG_TOP_ATTACK = '⚔Топ атакеры:\n' MSG_TOP_EXPERIENCE = '🔥Топ качки:\n' diff --git a/main.py b/main.py index fa1f226..2cf11cc 100644 --- a/main.py +++ b/main.py @@ -21,8 +21,8 @@ ADMIN_COMMAND_GROUPS, ADMIN_COMMAND_FIRE_UP, USER_COMMAND_ME, USER_COMMAND_BUILD, USER_COMMAND_CONTACTS, \ USER_COMMAND_SQUAD, USER_COMMAND_STATISTICS, USER_COMMAND_TOP, USER_COMMAND_SQUAD_REQUEST, USER_COMMAND_BACK, \ TOP_COMMAND_ATTACK, TOP_COMMAND_DEFENCE, TOP_COMMAND_EXP, STATISTICS_COMMAND_EXP, USER_COMMAND_SQUAD_LEAVE, \ - ADMIN_COMMAND_REPORTS, ADMIN_COMMAND_ADMINPANEL, TOP_COMMAND_GLOBAL_BUILD, TOP_COMMAND_WEEK_BUILD, \ - TOP_COMMAND_WEEK_BATTLES + ADMIN_COMMAND_REPORTS, ADMIN_COMMAND_ADMINPANEL, TOP_COMMAND_BUILD, \ + TOP_COMMAND_BATTLES from core.functions.activity import ( day_activity, week_activity, battle_activity ) @@ -41,8 +41,9 @@ delete_msg, delete_user, user_panel, web_auth) from core.functions.inline_keyboard_handling import ( - callback_query, send_status, send_order, QueryType + callback_query, send_status, send_order ) +from core.functions.inline_markup import QueryType from core.functions.order_groups import group_list, add_group from core.functions.pin import pin, not_pin_all, pin_all, silent_pin from core.functions.profile import char_update, char_show, find_by_username, report_received, build_report_received, \ @@ -228,11 +229,9 @@ def manage_all(bot: Bot, update: Update, session, chat_data, job_queue): def_top(bot, update) elif text == TOP_COMMAND_EXP.lower(): exp_top(bot, update) - elif text == TOP_COMMAND_GLOBAL_BUILD.lower(): - global_build_top(bot, update) - elif text == TOP_COMMAND_WEEK_BUILD.lower(): + elif text == TOP_COMMAND_BUILD.lower(): week_build_top(bot, update) - elif text == TOP_COMMAND_WEEK_BATTLES.lower(): + elif text == TOP_COMMAND_BATTLES.lower(): week_battle_top(bot, update) elif text == USER_COMMAND_BUILD.lower(): send_async(bot, From 179778f33bacda40f316ebb9bc2194350dc409dd Mon Sep 17 00:00:00 2001 From: eclipse7 Date: Thu, 7 Dec 2017 18:16:48 +0200 Subject: [PATCH 202/284] Fix db encoding --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 16adb45..b91f1ba 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ exit 7)create a new database ``` CREATE DATABASE 'test'; +ALTER DATABASE 'test' CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci; ``` 8)exit to CLI ``` From 704af7f1b7fc0343ba324868095073e364fe9f21 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Fri, 8 Dec 2017 14:01:11 +0300 Subject: [PATCH 203/284] =?UTF-8?q?=D0=9F=D0=BE=D1=80=D1=8F=D0=B4=D0=BE?= =?UTF-8?q?=D0=BA=20=D0=BA=D0=BD=D0=BE=D0=BF=D0=BE=D0=BA=20=D0=BF=D1=80?= =?UTF-8?q?=D0=B8=D0=BA=D0=B0=D0=B7=D0=BE=D0=B2=20=D0=B8=D0=B7=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D1=91=D0=BD.=20=D0=A2=D0=B5=D0=BF=D0=B5=D1=80=D1=8C=20?= =?UTF-8?q?=D1=84=D0=BB=D0=B0=D0=B3=20=D0=B8=D0=B7=20=D0=BD=D0=B0=D1=81?= =?UTF-8?q?=D1=82=D1=80=D0=BE=D0=B5=D0=BA=20=D0=B2=D1=8B=D0=B2=D0=BE=D0=B4?= =?UTF-8?q?=D0=B8=D1=82=D1=81=D1=8F=20=D0=BF=D0=BE=D1=81=D0=BB=D0=B5=D0=B4?= =?UTF-8?q?=D0=BD=D0=B8=D0=BC.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_markup.py | 60 +++++++++++++++++++++------------ 1 file changed, 39 insertions(+), 21 deletions(-) diff --git a/core/functions/inline_markup.py b/core/functions/inline_markup.py index e05ecae..f8326fc 100644 --- a/core/functions/inline_markup.py +++ b/core/functions/inline_markup.py @@ -5,6 +5,7 @@ from sqlalchemy import func, tuple_ from telegram import InlineKeyboardButton, InlineKeyboardMarkup +from config import CASTLE from core.enums import Castle, Icons from core.texts import MSG_GROUP_STATUS_ADMIN_FORMAT, MSG_GROUP_STATUS_DEL_ADMIN, MSG_GROUP_STATUS, MSG_ON, MSG_OFF, \ MSG_ORDER_GROUP_DEL, MSG_BACK, MSG_ORDER_PIN, MSG_ORDER_NO_PIN, MSG_ORDER_BUTTON, MSG_ORDER_NO_BUTTON, \ @@ -77,27 +78,44 @@ def generate_group_info(group_id, session): def generate_flag_orders(): - flag_btns = [[InlineKeyboardButton(Castle.BLACK.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Castle.BLACK.value})), - InlineKeyboardButton(Castle.WHITE.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Castle.WHITE.value})), - InlineKeyboardButton(Castle.BLUE.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Castle.BLUE.value}))], - [InlineKeyboardButton(Castle.YELLOW.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Castle.YELLOW.value})), - InlineKeyboardButton(Castle.RED.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Castle.RED.value})), - InlineKeyboardButton(Castle.DUSK.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Castle.DUSK.value}))], - [InlineKeyboardButton(Castle.MINT.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Castle.MINT.value})), - InlineKeyboardButton(Castle.GORY.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Icons.GORY.value})), - InlineKeyboardButton(Castle.LES.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Icons.LES.value}))], - [InlineKeyboardButton(Castle.SEA.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Icons.SEA.value}))]] - inline_markup = InlineKeyboardMarkup(flag_btns) + flag_btns = [InlineKeyboardButton(Castle.BLACK.value, callback_data=json.dumps( + {'t': QueryType.OrderGroup.value, 'txt': Castle.BLACK.value})), + InlineKeyboardButton(Castle.WHITE.value, callback_data=json.dumps( + {'t': QueryType.OrderGroup.value, 'txt': Castle.WHITE.value})), + InlineKeyboardButton(Castle.BLUE.value, callback_data=json.dumps( + {'t': QueryType.OrderGroup.value, 'txt': Castle.BLUE.value})), + InlineKeyboardButton(Castle.YELLOW.value, callback_data=json.dumps( + {'t': QueryType.OrderGroup.value, 'txt': Castle.YELLOW.value})), + InlineKeyboardButton(Castle.RED.value, callback_data=json.dumps( + {'t': QueryType.OrderGroup.value, 'txt': Castle.RED.value})), + InlineKeyboardButton(Castle.DUSK.value, callback_data=json.dumps( + {'t': QueryType.OrderGroup.value, 'txt': Castle.DUSK.value})), + InlineKeyboardButton(Castle.MINT.value, callback_data=json.dumps( + {'t': QueryType.OrderGroup.value, 'txt': Castle.MINT.value})), + InlineKeyboardButton(Castle.GORY.value, callback_data=json.dumps( + {'t': QueryType.OrderGroup.value, 'txt': Icons.GORY.value})), + InlineKeyboardButton(Castle.LES.value, callback_data=json.dumps( + {'t': QueryType.OrderGroup.value, 'txt': Icons.LES.value})), + InlineKeyboardButton(Castle.SEA.value, callback_data=json.dumps( + {'t': QueryType.OrderGroup.value, 'txt': Icons.SEA.value}))] + btns = [] + i = 0 + for btn in flag_btns: + if CASTLE: + if btn.text == CASTLE: + continue + if i % 3 == 0: + btns.append([]) + btns[-1].append(btn) + i += 1 + + if CASTLE: + btns.append([]) + for btn in flag_btns: + if btn.text == CASTLE: + btns[-1].append(btn) + + inline_markup = InlineKeyboardMarkup(btns) return inline_markup From c44f3d13e84eccc14d56dfeaf008a9d87a35b7fe Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Fri, 8 Dec 2017 14:06:43 +0300 Subject: [PATCH 204/284] =?UTF-8?q?=D0=A1=D0=BD=D0=BE=D0=B2=D0=B0=20=D0=BB?= =?UTF-8?q?=D0=B5=D0=B2=D1=8B=D0=B5=20xml=20:/?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- _windows/applicationLibraries.xml | 67 ------------------------------- baseRefactoring.xml | 5 --- ui.lnf.xml | 5 --- 3 files changed, 77 deletions(-) delete mode 100644 _windows/applicationLibraries.xml delete mode 100644 baseRefactoring.xml delete mode 100644 ui.lnf.xml diff --git a/_windows/applicationLibraries.xml b/_windows/applicationLibraries.xml deleted file mode 100644 index cda75ff..0000000 --- a/_windows/applicationLibraries.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/baseRefactoring.xml b/baseRefactoring.xml deleted file mode 100644 index dd208be..0000000 --- a/baseRefactoring.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - \ No newline at end of file diff --git a/ui.lnf.xml b/ui.lnf.xml deleted file mode 100644 index 73792a4..0000000 --- a/ui.lnf.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - \ No newline at end of file From ba405f7893ca797859d0b97e5f556c2876188b61 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Fri, 8 Dec 2017 16:08:11 +0300 Subject: [PATCH 205/284] PY-2017.3 + + + + + + + + + + + + + + + + + + + + + + From 257748b3428398ea32755c6defe1acc7933e2db0 Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Sun, 10 Dec 2017 15:44:32 +0300 Subject: [PATCH 206/284] =?UTF-8?q?=D0=A1=D1=82=D1=80=D0=BE=D0=B9=D0=BA?= =?UTF-8?q?=D0=BE=D1=80=D0=B5=D0=BF=D0=BE=D1=80=D1=82=D1=8B=20=D0=BF=D1=80?= =?UTF-8?q?=D0=B8=D0=BD=D0=B8=D0=BC=D0=B0=D1=8E=D1=82=D1=81=D1=8F=20=D1=82?= =?UTF-8?q?=D0=BE=D0=BB=D1=8C=D0=BA=D0=BE=20=D0=B7=D0=B0=20=D0=BF=D0=BE?= =?UTF-8?q?=D1=81=D0=BB=D0=B5=D0=B4=D0=BD=D0=B8=D0=B5=205=20=D0=BC=D0=B8?= =?UTF-8?q?=D0=BD=D1=83=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/profile.py | 6 ++++++ core/texts.py | 1 + 2 files changed, 7 insertions(+) diff --git a/core/functions/profile.py b/core/functions/profile.py index 135c55c..e1e41a4 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -136,6 +136,9 @@ def parse_repair_reports(report, user_id, date, session): @user_allowed(False) def build_report_received(bot: Bot, update: Update, session): + if datetime.now() - update.message.forward_date > timedelta(minutes=5): + send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_TOO_OLD) + return report = re.search(BUILD_REPORT, update.message.text) user = session.query(User).filter_by(id=update.message.from_user.id).first() if report and user.character: @@ -153,6 +156,9 @@ def build_report_received(bot: Bot, update: Update, session): @user_allowed(False) def repair_report_received(bot: Bot, update: Update, session): + if datetime.now() - update.message.forward_date > timedelta(minutes=5): + send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_TOO_OLD) + return report = re.search(REPAIR_REPORT, update.message.text) user = session.query(User).filter_by(id=update.message.from_user.id).first() if report and user.character: diff --git a/core/texts.py b/core/texts.py index 7e0681c..acb2a39 100644 --- a/core/texts.py +++ b/core/texts.py @@ -154,6 +154,7 @@ MSG_BUILD_REPORT_EXISTS = 'Ты уже кидал этот репорт!' MSG_BUILD_REPORT_OK = 'Спасибо за помощь на стройке! Это твой {} репорт.' MSG_BUILD_REPORT_FORWARDED = 'Больше не присылай мне репорты с твинков!!!' +MSG_BUILD_REPORT_TOO_OLD = 'Этот репорт очень стар, я не могу его принять.' MSG_REPORT_OLD = 'Твой репорт уже попахивает, в следующий раз постарайся прислать его в течении минуты после получения.' MSG_REPORT_EXISTS = 'Репорт за эту битву уже внесён.' From e1dd5877a06d4c3d41e9925fe855b8b45464d6c0 Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Sun, 10 Dec 2017 16:24:02 +0300 Subject: [PATCH 207/284] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=82=D1=8B=D0=BA=D0=BD=D1=83=D0=B2?= =?UTF-8?q?=D1=88=D0=B8=D1=85=20=D1=80=D0=B0=D0=B7=20=D0=B2=205=20=D1=81?= =?UTF-8?q?=D0=B5=D0=BA=D1=83=D0=BD=D0=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/inline_keyboard_handling.py | 29 +++++++++++++++++----- main.py | 2 +- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/core/functions/inline_keyboard_handling.py b/core/functions/inline_keyboard_handling.py index bf9ed81..d6b815a 100644 --- a/core/functions/inline_keyboard_handling.py +++ b/core/functions/inline_keyboard_handling.py @@ -4,6 +4,7 @@ import logging from telegram import Bot, Update, InlineKeyboardButton, InlineKeyboardMarkup, TelegramError, ParseMode +from telegram.ext import JobQueue, Job from telegram.ext.dispatcher import run_async from core.enums import Castle, Icons @@ -28,6 +29,9 @@ LOGGER = logging.getLogger('MyApp') +order_updated = {} + + @admin_allowed() def send_status(bot: Bot, update: Update, session): msg = MSG_GROUP_STATUS_CHOOSE_CHAT @@ -85,9 +89,18 @@ def send_order(bot, order, order_type, chat_id, markup): return None +def update_confirmed(bot: Bot, job: Job): + order = job.context + confirmed = order.cleared + msg = MSG_ORDER_CLEARED_BY_HEADER + for confirm in confirmed: + msg += str(confirm.user) + '\n' + bot.editMessageText(msg, order.chat_id, order.confirmed_msg) + + @run_async @user_allowed -def callback_query(bot: Bot, update: Update, session, chat_data: dict): +def callback_query(bot: Bot, update: Update, session, chat_data: dict, job_queue: JobQueue): update_group(update.callback_query.message.chat, session) user = add_user(update.callback_query.from_user, session) data = json.loads(update.callback_query.data) @@ -186,11 +199,10 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): session.add(order_ok) session.commit() if order.confirmed_msg != 0: - confirmed = order.cleared - msg = MSG_ORDER_CLEARED_BY_HEADER - for confirm in confirmed: - msg += str(confirm.user) + '\n' - bot.editMessageText(msg, order.chat_id, order.confirmed_msg) + if order.id not in order_updated or \ + datetime.now() - order_updated[order.id] > timedelta(seconds=4): + order_updated[order.id] = datetime.now() + job_queue.run_once(update_confirmed, 5, order) update.callback_query.answer(text=MSG_ORDER_CLEARED) else: update.callback_query.answer(text=MSG_ORDER_CLEARED_ERROR) @@ -205,6 +217,11 @@ def callback_query(bot: Bot, update: Update, session, chat_data: dict): order_ok.user_id = update.callback_query.from_user.id session.add(order_ok) session.commit() + if order.confirmed_msg != 0: + if order.id not in order_updated or \ + datetime.now() - order_updated[order.id] > timedelta(seconds=4): + order_updated[order.id] = datetime.now() + job_queue.run_once(update_confirmed, 5, order) update.callback_query.answer(text=MSG_ORDER_CLEARED) else: update.callback_query.answer(text=MSG_ORDER_CLEARED_ERROR) diff --git a/main.py b/main.py index 2cf11cc..f4d943c 100644 --- a/main.py +++ b/main.py @@ -465,7 +465,7 @@ def main(): disp.add_handler(CommandHandler("ban", ban)) disp.add_handler(CommandHandler("unban", unban)) - disp.add_handler(CallbackQueryHandler(callback_query, pass_chat_data=True)) + disp.add_handler(CallbackQueryHandler(callback_query, pass_chat_data=True, pass_job_queue=True)) # on noncommand i.e message - echo the message on Telegram disp.add_handler(MessageHandler(Filters.status_update, welcome)) From 3e4c2ec698c17fb94d17169c7c67dc92b430de9c Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Sun, 10 Dec 2017 16:28:55 +0300 Subject: [PATCH 208/284] =?UTF-8?q?=D0=94=D0=B0=D1=82=D0=B0=20=D1=81=D1=82?= =?UTF-8?q?=D1=80=D0=B0=D1=82=D0=B0=20=D1=82=D0=BE=D0=BF=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/top.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/functions/top.py b/core/functions/top.py index aed3a2f..d52691d 100644 --- a/core/functions/top.py +++ b/core/functions/top.py @@ -12,7 +12,7 @@ from datetime import datetime, timedelta -TOP_START_DATE = datetime(2017, 11, 11) +TOP_START_DATE = datetime(2017, 12, 11) @user_allowed From 4138fd92aac63cb24f34f570934dc140c0d6ae79 Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Sun, 10 Dec 2017 17:37:29 +0300 Subject: [PATCH 209/284] =?UTF-8?q?=D0=9E=D1=82=D1=87=D1=91=D1=82=20=D0=BE?= =?UTF-8?q?=20=D1=81=D1=82=D1=80=D0=BE=D0=B9=D0=BA=D0=B5=20=D0=BD=D0=B5=20?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D1=80=D1=88=D0=B5=2010=20=D0=BC=D0=B8=D0=BD?= =?UTF-8?q?=D1=83=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/profile.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/functions/profile.py b/core/functions/profile.py index e1e41a4..190d276 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -136,7 +136,7 @@ def parse_repair_reports(report, user_id, date, session): @user_allowed(False) def build_report_received(bot: Bot, update: Update, session): - if datetime.now() - update.message.forward_date > timedelta(minutes=5): + if datetime.now() - update.message.forward_date > timedelta(minutes=10): send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_TOO_OLD) return report = re.search(BUILD_REPORT, update.message.text) @@ -156,7 +156,7 @@ def build_report_received(bot: Bot, update: Update, session): @user_allowed(False) def repair_report_received(bot: Bot, update: Update, session): - if datetime.now() - update.message.forward_date > timedelta(minutes=5): + if datetime.now() - update.message.forward_date > timedelta(minutes=10): send_async(bot, chat_id=update.message.from_user.id, text=MSG_BUILD_REPORT_TOO_OLD) return report = re.search(REPAIR_REPORT, update.message.text) From 5789dbc623f8aa630d2ef430134dc6036d980a2b Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Mon, 11 Dec 2017 00:58:40 +0300 Subject: [PATCH 210/284] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B4=D0=B5?= =?UTF-8?q?=D0=BB=D1=8B=D0=B2=D0=B0=D0=B5=D0=BC=20=D0=BF=D0=BE=D0=B4=20eu?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/enums.py | 28 ++++++++++++++-------------- core/functions/inline_markup.py | 13 +++++++------ core/regexp.py | 33 +++++++++++++++++---------------- 3 files changed, 38 insertions(+), 36 deletions(-) diff --git a/core/enums.py b/core/enums.py index 634313f..4e3480d 100644 --- a/core/enums.py +++ b/core/enums.py @@ -4,26 +4,26 @@ class Castle(Enum): UNDEFINED = 0 - BLACK = '\U0001f1ec\U0001f1f5' - RED = '\U0001f1ee\U0001f1f2' - BLUE = '\U0001f1ea\U0001f1fa' - YELLOW = '\U0001f1fb\U0001f1e6' - WHITE = '\U0001f1e8\U0001f1fe' - MINT = '\U0001F1F2\U0001F1F4' - DUSK = '\U0001F1F0\U0001F1EE' + BLACK = '🌑' + RED = '🐺' + BLUE = '🥔' + YELLOW = '🦅' + WHITE = '🦌' + MINT = '🐉' + DUSK = '🦈' LES = '\U0001f332Лесной форт' GORY = '\u26f0Горный форт' SEA = '\u2693\uFE0FМорской форт' class Icons(Enum): - BLACK = '\U0001f1ec\U0001f1f5' - RED = '\U0001f1ee\U0001f1f2' - BLUE = '\U0001f1ea\U0001f1fa' - YELLOW = '\U0001f1fb\U0001f1e6' - WHITE = '\U0001f1e8\U0001f1fe' - MINT = '\U0001F1F2\U0001F1F4' - DUSK = '\U0001F1F0\U0001F1EE' + BLACK = '🌑' + RED = '🐺' + BLUE = '🥔' + YELLOW = '🦅' + WHITE = '🦌' + MINT = '🐉' + DUSK = '🦈' LES = '\U0001f332' GORY = '\u26f0' SEA = '\u2693\uFE0F' diff --git a/core/functions/inline_markup.py b/core/functions/inline_markup.py index f8326fc..b5c07dd 100644 --- a/core/functions/inline_markup.py +++ b/core/functions/inline_markup.py @@ -92,12 +92,13 @@ def generate_flag_orders(): {'t': QueryType.OrderGroup.value, 'txt': Castle.DUSK.value})), InlineKeyboardButton(Castle.MINT.value, callback_data=json.dumps( {'t': QueryType.OrderGroup.value, 'txt': Castle.MINT.value})), - InlineKeyboardButton(Castle.GORY.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Icons.GORY.value})), - InlineKeyboardButton(Castle.LES.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Icons.LES.value})), - InlineKeyboardButton(Castle.SEA.value, callback_data=json.dumps( - {'t': QueryType.OrderGroup.value, 'txt': Icons.SEA.value}))] + # InlineKeyboardButton(Castle.GORY.value, callback_data=json.dumps( + # {'t': QueryType.OrderGroup.value, 'txt': Icons.GORY.value})), + # InlineKeyboardButton(Castle.LES.value, callback_data=json.dumps( + # {'t': QueryType.OrderGroup.value, 'txt': Icons.LES.value})), + # InlineKeyboardButton(Castle.SEA.value, callback_data=json.dumps( + # {'t': QueryType.OrderGroup.value, 'txt': Icons.SEA.value})) + ] btns = [] i = 0 for btn in flag_btns: diff --git a/core/regexp.py b/core/regexp.py index 19e60ec..321ef7f 100644 --- a/core/regexp.py +++ b/core/regexp.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # FIX: переделать строки в """ -PROFILE = '(🇬🇵|🇮🇲|🇨🇾|🇻🇦|🇪🇺|🇲🇴|🇰🇮)(.+), (.+) .+ замка\n' \ +PROFILE = '(🌑|🐺|🥔|🦅|🦌|🐉|🦈)(.+), (.+) .+ замка\n' \ '🏅Уровень: ([0-9]+)\n' \ '(?:.*)Атака: ([0-9]+) 🛡Защита: ([0-9]+)\n' \ '🔥Опыт: ([0-9]+)/([0-9]+)\n' \ @@ -11,25 +11,26 @@ '🎒Рюкзак: ([0-9]+)/([0-9]+) /inv' \ '(?:\n\nПомощник:\n(.+?) (?:.+?) (.+)? \(([0-9]+) ур\.\) (.+) /pet)?' -HERO = '(🇬🇵|🇮🇲|🇨🇾|🇻🇦|🇪🇺|🇲🇴|🇰🇮)(.+), (.+) .+ замка\n' \ - '🏅Уровень: ([0-9]+)\n' \ - '(?:.*)Атака: ([0-9]+) 🛡Защита: ([0-9]+)\n' \ - '🔥Опыт: ([0-9]+)/([0-9]+)\n' \ - '🔋Выносливость: ([0-9]+)/([0-9]+)\n' \ +HERO = '(🌑|🐺|🥔|🦅|🦌|🐉|🦈)(.+) of (.+) .+\n' \ + '🏅Level: ([0-9]+)\n' \ + '⚔Atk: ([0-9]+) 🛡Def: ([0-9]+)\n' \ + '🔥Exp: ([0-9]+)/([0-9]+)\n' \ + '🔋Stamina: ([0-9]+)/([0-9]+)\n' \ '(?:💧Мана: [0-9]+/[0-9]+\n)?' \ - '💰(-?[0-9]+) 💠([0-9]+)\n' \ - '🤺Побед: ([0-9]+)\n\n' \ - '🎽Экипировка(?:(.+)(?:\n)?((?:.|\n)+)?)\n\n' \ - '🎒Рюкзак: ([0-9]+)/([0-9]+) /inv\n' \ - '📦Склад: (?:[0-9]+) /stock(?:\n\n' \ + '💰Gold: (-?[0-9]+) 💠([0-9]+)\n' \ + '🤺PVP: ([0-9]+)\n' \ + '.+\n\n' \ + '🎽Equipment(?:(.+)(?:\n)?((?:.|\n)+)?)\n\n' \ + '🎒Bag: ([0-9]+)/([0-9]+) /inv\n' \ + '📦Warehouse: (?:[0-9]+) /stock(?:\n\n' \ 'Помощник:\n' \ '(.+?) (?:.+?) (.+)? \(([0-9]+) ур\.\) (.+) /pet)?' -REPORT = '(🇬🇵|🇮🇲|🇨🇾|🇻🇦|🇪🇺|🇲🇴|🇰🇮)(.+) ⚔️:([0-9]+) 🛡:([0-9]+) \(([0-9]+) ур.\)\n' \ - 'Твои результаты в бою:(?:\n' \ - '🔥Опыт: ([0-9]+) ед)?(?:\n' \ - '💰Золото: (-?[0-9]+))?(?:\n' \ - '📦Склад: (-?[0-9]+))?' +REPORT = '(🌑|🐺|🥔|🦅|🦌|🐉|🦈)(.+) ⚔️:([0-9]+) 🛡:([0-9]+) \(Lvl: ([0-9]+)\)\n' \ + 'Your result on the battlefield:(?:\n' \ + '🔥Exp: ([0-9]+) ед)?(?:\n' \ + '💰Gold: (-?[0-9]+))?(?:\n' \ + '📦Stock: (-?[0-9]+))?' BUILD_REPORT = 'Ты вернулся со стройки: (.+), прогресс работ: ([0-9]+)%' From 969affd94e5e456f79d835eb39f88938f2706978 Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Mon, 11 Dec 2017 01:27:27 +0300 Subject: [PATCH 211/284] =?UTF-8?q?=D0=9F=D0=B0=D1=80=D0=B0=20=D1=84=D0=B8?= =?UTF-8?q?=D0=BA=D1=81=D0=BE=D0=B2=20=D1=81=20=D0=BF=D1=80=D0=BE=D1=84?= =?UTF-8?q?=D0=B8=D0=BB=D0=B5=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/profile.py | 2 +- core/regexp.py | 2 +- main.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/functions/profile.py b/core/functions/profile.py index 190d276..4a2ab7e 100644 --- a/core/functions/profile.py +++ b/core/functions/profile.py @@ -61,7 +61,7 @@ def parse_hero(profile, user_id, date, session): char.needExp = int(parsed_data.group(8)) char.maxStamina = int(parsed_data.group(10)) char.gold = int(parsed_data.group(11)) - char.donateGold = int(parsed_data.group(12)) + char.donateGold = 0 # int(parsed_data.group(12)) if parsed_data.group(18): char.pet = str(parsed_data.group(18)) char.petLevel = int(parsed_data.group(20)) diff --git a/core/regexp.py b/core/regexp.py index 321ef7f..bbc0e6a 100644 --- a/core/regexp.py +++ b/core/regexp.py @@ -17,7 +17,7 @@ '🔥Exp: ([0-9]+)/([0-9]+)\n' \ '🔋Stamina: ([0-9]+)/([0-9]+)\n' \ '(?:💧Мана: [0-9]+/[0-9]+\n)?' \ - '💰Gold: (-?[0-9]+) 💠([0-9]+)\n' \ + '💰Gold: (-?[0-9]+)()\n' \ '🤺PVP: ([0-9]+)\n' \ '.+\n\n' \ '🎽Equipment(?:(.+)(?:\n)?((?:.|\n)+)?)\n\n' \ diff --git a/main.py b/main.py index f4d943c..6219d21 100644 --- a/main.py +++ b/main.py @@ -76,7 +76,7 @@ from sqlalchemy.exc import SQLAlchemyError # -----constants---- -CWBOT_ID = 265204902 +CWBOT_ID = 408101137 TRADEBOT_ID = 278525885 # ------------------- From ada7acfcfe96fdf2e271ab9bb90da869d9db1ee2 Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Mon, 11 Dec 2017 01:42:19 +0300 Subject: [PATCH 212/284] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=B2=D0=BA=D0=B0=20?= =?UTF-8?q?=D0=BD=D0=B5=D0=B4=D0=B5=D0=BB=D1=8C=D0=BD=D1=8B=D1=85=20=D1=82?= =?UTF-8?q?=D0=BE=D0=BF=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/top.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/functions/top.py b/core/functions/top.py index d52691d..e193fec 100644 --- a/core/functions/top.py +++ b/core/functions/top.py @@ -153,7 +153,7 @@ def week_build_top(bot: Bot, update: Update, session): actual_profiles = session.query(Character.user_id, func.max(Character.date)). \ group_by(Character.user_id) actual_profiles = actual_profiles.all() - today = datetime.today() + today = datetime.today().date() builds = session.query(Character, func.count(BuildReport.user_id))\ .filter(tuple_(Character.user_id, Character.date) .in_([(a[0], a[1]) for a in actual_profiles]), @@ -185,7 +185,7 @@ def week_squad_build_top(bot: Bot, update: Update, session): actual_profiles = session.query(Character.user_id, func.max(Character.date)). \ group_by(Character.user_id) actual_profiles = actual_profiles.all() - today = datetime.today() + today = datetime.today().date() builds = session.query(Squad, func.count(BuildReport.user_id))\ .join(SquadMember).join(Character, SquadMember.user_id == Character.user_id)\ .filter(tuple_(Character.user_id, Character.date) @@ -242,7 +242,7 @@ def week_battle_top(bot: Bot, update: Update, session): actual_profiles = session.query(Character.user_id, func.max(Character.date)). \ group_by(Character.user_id) actual_profiles = actual_profiles.all() - today = datetime.today() + today = datetime.today().date() battles = session.query(Character, func.count(Report.user_id))\ .filter(tuple_(Character.user_id, Character.date) .in_([(a[0], a[1]) for a in actual_profiles]), From b4d8b0dae205e5b198bcdaf0971020c0822d42ea Mon Sep 17 00:00:00 2001 From: "Ruckus.DJ" Date: Mon, 11 Dec 2017 01:51:10 +0300 Subject: [PATCH 213/284] =?UTF-8?q?=D0=A4=D0=B8=D0=BA=D1=81=20=D1=82=D0=BE?= =?UTF-8?q?=D0=BF=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/top.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/core/functions/top.py b/core/functions/top.py index e193fec..d2569ae 100644 --- a/core/functions/top.py +++ b/core/functions/top.py @@ -136,7 +136,7 @@ def global_build_top(bot: Bot, update: Update, session): if update.message: user_id = update.message.from_user.id elif update.callback_query: - user_id = update.callback_query.message.from_user.id + user_id = update.callback_query.from_user.id text = gen_top_msg(builds, user_id, MSG_TOP_GLOBAL_BUILDERS, '⚒') markup = generate_build_top() if update.message: @@ -168,7 +168,7 @@ def week_build_top(bot: Bot, update: Update, session): if update.message: user_id = update.message.from_user.id elif update.callback_query: - user_id = update.callback_query.message.from_user.id + user_id = update.callback_query.from_user.id text = gen_top_msg(builds, user_id, MSG_TOP_WEEK_BUILDERS, '⚒') markup = generate_build_top() if update.message: @@ -258,7 +258,7 @@ def week_battle_top(bot: Bot, update: Update, session): if update.message: user_id = update.message.from_user.id elif update.callback_query: - user_id = update.callback_query.message.from_user.id + user_id = update.callback_query.from_user.id text = gen_top_msg(battles, user_id, MSG_TOP_WEEK_WARRIORS, '⚔🛡') markup = generate_battle_top() if update.message: @@ -290,7 +290,7 @@ def global_battle_top(bot: Bot, update: Update, session): if update.message: user_id = update.message.from_user.id elif update.callback_query: - user_id = update.callback_query.message.from_user.id + user_id = update.callback_query.from_user.id text = gen_top_msg(battles, user_id, MSG_TOP_WEEK_WARRIORS, '⚔🛡') markup = generate_battle_top() if update.message: From 86cfb89290c362c20670557ecc307efda10a0436 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Mon, 11 Dec 2017 15:00:57 +0300 Subject: [PATCH 214/284] PY-2017.3 + + + + \ No newline at end of file diff --git a/codestyles/Default.xml b/codestyles/Default.xml new file mode 100644 index 0000000..e94f32a --- /dev/null +++ b/codestyles/Default.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/colors.scheme.xml b/colors.scheme.xml new file mode 100644 index 0000000..39308cd --- /dev/null +++ b/colors.scheme.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/debugger.xml b/debugger.xml new file mode 100644 index 0000000..544ab15 --- /dev/null +++ b/debugger.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/editor.codeinsight.xml b/editor.codeinsight.xml new file mode 100644 index 0000000..b43f2d4 --- /dev/null +++ b/editor.codeinsight.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/editor.xml b/editor.xml new file mode 100644 index 0000000..19bd26a --- /dev/null +++ b/editor.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/filetypes.xml b/filetypes.xml new file mode 100644 index 0000000..324c956 --- /dev/null +++ b/filetypes.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/github_settings.xml b/github_settings.xml new file mode 100644 index 0000000..0e4cecb --- /dev/null +++ b/github_settings.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/ignore.xml b/ignore.xml new file mode 100644 index 0000000..64ae0d4 --- /dev/null +++ b/ignore.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From a6b053e38720c3a1f0bd8954e4414e09d1b9355b Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Mon, 11 Dec 2017 17:01:21 +0300 Subject: [PATCH 215/284] PY-2017.3 + + + \ No newline at end of file From c80ee2f9f912c807bc7338afede366eafd1feae9 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Mon, 11 Dec 2017 17:18:48 +0300 Subject: [PATCH 216/284] PY-2017.3 + + + \ No newline at end of file diff --git a/vcs.xml b/vcs.xml new file mode 100644 index 0000000..7ce08f8 --- /dev/null +++ b/vcs.xml @@ -0,0 +1,13 @@ + + + + + \ No newline at end of file From 8201bafea6f07928a8985f13dbff51634d3814d9 Mon Sep 17 00:00:00 2001 From: toxydose Date: Mon, 11 Dec 2017 17:19:22 +0200 Subject: [PATCH 217/284] =?UTF-8?q?=D0=BF=D0=BE=D0=BC=D0=B5=D0=BD=D1=8F?= =?UTF-8?q?=D0=BB=20=D1=8D=D0=BC=D0=BE=D0=B4=D0=B7=D0=B8=20=D0=BD=D0=B0=20?= =?UTF-8?q?=D0=BA=D0=BD=D0=BE=D0=BF=D0=BA=D0=B0=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/commands.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/commands.py b/core/commands.py index 3400358..c0740de 100644 --- a/core/commands.py +++ b/core/commands.py @@ -21,8 +21,8 @@ TOP_COMMAND_ATTACK = '⚔' TOP_COMMAND_DEFENCE = '🛡' TOP_COMMAND_EXP = '🔥' -TOP_COMMAND_BUILD = '⚒' +TOP_COMMAND_BUILD = '👷🏻' -TOP_COMMAND_BATTLES = '⚔🛡' +TOP_COMMAND_BATTLES = '⛳️' STATISTICS_COMMAND_EXP = '🔥Опыт' From 0a53cdef039f9d9f208c135ccb8f4306ee2f0e48 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Mon, 11 Dec 2017 19:23:13 +0300 Subject: [PATCH 218/284] =?UTF-8?q?=D0=A7=D1=82=D0=BE-=D1=82=D0=BE=20?= =?UTF-8?q?=D1=82=D0=B0=D0=BC=20=D1=81=20=D1=8E=D0=B7=D0=B5=D1=80=D0=BD?= =?UTF-8?q?=D1=8D=D0=B9=D0=BC=D0=B0=D0=BC=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/functions/squad.py | 4 +++- core/texts.py | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/core/functions/squad.py b/core/functions/squad.py index 5b44ac4..ff58d76 100644 --- a/core/functions/squad.py +++ b/core/functions/squad.py @@ -125,7 +125,9 @@ def squad_list(bot: Bot, update: Update, session): def squad_request(bot: Bot, update: Update, session): user = session.query(User).filter_by(id=update.message.from_user.id).first() if user is not None: - if user.character: + if user.username is None: + send_async(bot, chat_id=update.message.chat.id, text=MSG_NO_USERNAME) + elif user.character: if user.member: markup = generate_leave_squad(user.id) send_async(bot, chat_id=update.message.chat.id, text=MSG_SQUAD_REQUEST_EXISTS, reply_markup=markup) diff --git a/core/texts.py b/core/texts.py index acb2a39..34df6e7 100644 --- a/core/texts.py +++ b/core/texts.py @@ -211,6 +211,8 @@ MSG_CLEARED = 'Выполнено' +MSG_NO_USERNAME = 'Нам с тобой будет сложно общаться, пока ты не сделаешь себе юзернэйм. ' \ + 'Его можно задать в настройках телеграма. А пока часть функций тебе недоступна.' MSG_SQUAD_LIST = 'Список ваших отрядов:' MSG_SQUAD_REQUEST_EXISTS = 'Вы уже состоите в отряде или подали запрос. \ Выйдите из текущего отряда или отмените запрос, чтобы создать новый.' From 8cf035b77c324cb07bd92310fc0784eead8ed2b1 Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Mon, 11 Dec 2017 19:25:00 +0300 Subject: [PATCH 219/284] =?UTF-8?q?=D0=A7=D1=82=D0=BE,=20=D0=B05=3F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- _windows/git.xml | 5 ----- _windows/laf.xml | 5 ----- codestyles/Default.xml | 1 - colors.scheme.xml | 5 ----- debugger.xml | 13 ------------- editor.codeinsight.xml | 6 ------ editor.xml | 6 ------ filetypes.xml | 9 --------- github_settings.xml | 5 ----- ignore.xml | 32 -------------------------------- usageView.xml | 8 -------- 11 files changed, 95 deletions(-) delete mode 100644 _windows/git.xml delete mode 100644 _windows/laf.xml delete mode 100644 codestyles/Default.xml delete mode 100644 colors.scheme.xml delete mode 100644 debugger.xml delete mode 100644 editor.codeinsight.xml delete mode 100644 editor.xml delete mode 100644 filetypes.xml delete mode 100644 github_settings.xml delete mode 100644 ignore.xml delete mode 100644 usageView.xml diff --git a/_windows/git.xml b/_windows/git.xml deleted file mode 100644 index a8092bd..0000000 --- a/_windows/git.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - \ No newline at end of file diff --git a/_windows/laf.xml b/_windows/laf.xml deleted file mode 100644 index c1f98d9..0000000 --- a/_windows/laf.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/codestyles/Default.xml b/codestyles/Default.xml deleted file mode 100644 index e94f32a..0000000 --- a/codestyles/Default.xml +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/colors.scheme.xml b/colors.scheme.xml deleted file mode 100644 index 39308cd..0000000 --- a/colors.scheme.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/debugger.xml b/debugger.xml deleted file mode 100644 index 544ab15..0000000 --- a/debugger.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/editor.codeinsight.xml b/editor.codeinsight.xml deleted file mode 100644 index b43f2d4..0000000 --- a/editor.codeinsight.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - \ No newline at end of file diff --git a/editor.xml b/editor.xml deleted file mode 100644 index 19bd26a..0000000 --- a/editor.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - \ No newline at end of file diff --git a/filetypes.xml b/filetypes.xml deleted file mode 100644 index 324c956..0000000 --- a/filetypes.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/github_settings.xml b/github_settings.xml deleted file mode 100644 index 0e4cecb..0000000 --- a/github_settings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - \ No newline at end of file diff --git a/ignore.xml b/ignore.xml deleted file mode 100644 index 64ae0d4..0000000 --- a/ignore.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/usageView.xml b/usageView.xml deleted file mode 100644 index 1e05532..0000000 --- a/usageView.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - \ No newline at end of file From 16fafa6fdec0c50eef57738330f6ac7a3c7fff9f Mon Sep 17 00:00:00 2001 From: Alexey Pankratov Date: Mon, 11 Dec 2017 19:36:40 +0300 Subject: [PATCH 220/284] PY-2017.3