diff options
| author | Andrew <saintruler@gmail.com> | 2020-02-11 14:17:19 +0400 |
|---|---|---|
| committer | Andrew <saintruler@gmail.com> | 2020-02-11 14:17:19 +0400 |
| commit | 1ca68c0b1af0f7fb5812c831d61cd85d282f08e1 (patch) | |
| tree | e2d5be0c35718f27955c705252d09cdf938a3370 | |
Basic functionality
| -rw-r--r-- | .gitignore | 3 | ||||
| -rw-r--r-- | backend_api.py | 28 | ||||
| -rw-r--r-- | bot.py | 154 | ||||
| -rw-r--r-- | requirements.txt | 13 |
4 files changed, 198 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2999ba7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.idea +config.py +venv
\ No newline at end of file diff --git a/backend_api.py b/backend_api.py new file mode 100644 index 0000000..2c8f268 --- /dev/null +++ b/backend_api.py @@ -0,0 +1,28 @@ +import requests +from config import BACKEND_URL +import logging + + +logger = logging.getLogger(__name__) +logger.setLevel(logging.DEBUG) + + +def register_user(tg_id, username, fullname) -> bool: + logger.debug(f"Registering user with id={tg_id}; username={username}") + response = requests.post(f"{BACKEND_URL}/profiles/", data={ + "tg_id": tg_id, + "username": username, + "fullname": fullname + }) + logger.debug( + f"Got response from backend: " + f"Status={response.status_code}; " + f"Text={response.text}" + ) + + return response.status_code == 201 + + +def get_tasks(): + response = requests.get(f"{BACKEND_URL}/tasks/") + return response.json() @@ -0,0 +1,154 @@ +from telegram.ext import Updater, CommandHandler, ConversationHandler, MessageHandler, Filters, CallbackQueryHandler +from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, InlineKeyboardMarkup, InlineKeyboardButton + +# Typing +from telegram import Update, User, Bot + +import logging +from os import environ +from config import TG_TOKEN, REQUEST_KWARGS + +import backend_api + +logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.DEBUG) + + +def start(bot: Bot, update: Update, user_data): + update.message.reply_text( + "Привет! Ты вошел в телеграм-квиз с мемами про наш любимый КНиИТ.", + reply_markup=ReplyKeyboardRemove() + ) + + user: User = update.message.from_user + if user.username is None: + update.message.reply_text( + "По правилам квиза ты не можешь участвовать, если у тебя не указано " + "имя пользователя, поэтому укажи его и возвращайся как только это сделаешь!", + reply_markup=ReplyKeyboardMarkup([['Я указал имя пользователя']]) + ) + return USERNAME_CHECK + + else: + logger.debug(backend_api.register_user(user.id, user.username, user.full_name)) + update.message.reply_text("Ты успешно зарегистрирован в системе!") + + update.message.reply_text("Твой счет: 0") + update.message.reply_text( + "Выбери следующее действие...", + reply_markup=ReplyKeyboardMarkup([ + ["Сдать задачу"], + ["Топ-10", "Правила"] + ]) + ) + + return MAIN_MENU + + +def username_check(bot: Bot, update: Update, user_data): + user: User = update.message.from_user + if user.username is None: + update.message.reply_text( + "Ты все еще не указал имя пользователя!", + reply_markup=ReplyKeyboardMarkup([['Я указал имя пользователя']]) + ) + return USERNAME_CHECK + + else: + logger.debug(backend_api.register_user(user.id, user.username, user.full_name)) + update.message.reply_text("Ты успешно зарегистрирован в системе!") + + update.message.reply_text("Твой счет: 0") + update.message.reply_text( + "Выбери следующее действие...", + reply_markup=ReplyKeyboardMarkup([ + ["Сдать задачу"], + ["Топ-10", "Правила"] + ]) + ) + + return MAIN_MENU + + +def main_menu(bot, update, user_data): + text = update.message.text + + if text == "Сдать задачу": + update.message.reply_text("А пока что нельзя!!") + return MAIN_MENU + + elif text == "Топ-10": + update.message.reply_text("Топ-1:\n1.Андрей Гущин") + return MAIN_MENU + + elif text == "Правила": + update.message.reply_text("Какие-то правила!!!!") + return MAIN_MENU + + return MAIN_MENU + + +def rules(bot: Bot, update: Update, user_data): + update.message.reply_text("Какие-то правила!!!!") + return MAIN_MENU + + +def top_10(bot: Bot, update: Update, user_data): + update.message.reply_text("Топ-1:\n1.Андрей Гущин") + return MAIN_MENU + + +def task_choose(bot: Bot, update: Update, user_data): + update.message.reply_text("А пока что нельзя!!") + return MAIN_MENU + + +def stop(bot, update): + update.message.reply_text('Пока!', reply_markup=ReplyKeyboardRemove()) + update.message.reply_text('Для того, чтобы начать работу с ботом заново напишите /start') + return ConversationHandler.END + + +def error(bot, update, error): + logger.warning('Update "%s" caused error "%s"', update, error) + + +def main(): + updater = Updater(TG_TOKEN, request_kwargs=REQUEST_KWARGS) + + dp = updater.dispatcher + dp.add_error_handler(error) + dp.add_handler(conversation_handler) + + updater.start_polling() + updater.idle() + + +( + USERNAME_CHECK, USERNAME_HOLD, + MAIN_MENU, TOP_10, RULES, + TASK_CHOOSE, CANCEL_CHOOSE, + TASK_SHOW, CANCEL_SHOW, + ENTER_ANSWER, CANCEL_ANSWER, + *_ +) = range(100) + +conversation_handler = ConversationHandler( + entry_points=[ + CommandHandler('start', start, pass_user_data=True) + ], + + states={ + USERNAME_CHECK: [MessageHandler(Filters.text, username_check, pass_user_data=True)], + MAIN_MENU: [MessageHandler(Filters.text, main_menu, pass_user_data=True)], + RULES: [MessageHandler(Filters.text, rules, pass_user_data=True)], + TOP_10: [MessageHandler(Filters.text, top_10, pass_user_data=True)], + TASK_CHOOSE: [MessageHandler(Filters.text, task_choose, pass_user_data=True)], + }, + + fallbacks=[CommandHandler('stop', stop)] +) + +if __name__ == '__main__': + main() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..4ca965a --- /dev/null +++ b/requirements.txt @@ -0,0 +1,13 @@ +certifi==2019.11.28 +cffi==1.13.2 +chardet==3.0.4 +cryptography==2.8 +future==0.18.2 +idna==2.8 +pycparser==2.19 +PySocks==1.7.1 +python-telegram-bot==12.3.0 +requests==2.22.0 +six==1.14.0 +tornado==6.0.3 +urllib3==1.25.8 |