diff --git a/tgbot_v2/DB.py b/tgbot_v2/DB.py index 15585a6..8559f9d 100644 --- a/tgbot_v2/DB.py +++ b/tgbot_v2/DB.py @@ -1,28 +1,90 @@ -import json -import requests as r +import requests +from requests.auth import AuthBase import os +from datetime import datetime, timedelta users = {} -DB_API = os.environ["DB_API_HOST"] - -def gethandler(url, temptoken): - headers = {'Accept': 'text/plain', 'Authorization': 'Bearer ' + temptoken} - request = json.loads((r.get(url, headers=headers)).text) - print('-----REQUEST COMPLETED-----') - i = 0 - DB = [] - DB2 = [] - while i != len(request): - DB.append(request[i]["value"]) - DB2.append(request[i]["id"]) - i += 1 - - return DB, DB2 - -def gentempkey(): - url = f'{DB_API}/AuthManagement/Login' - data = {'email': 'legalov.2017@stud.nstu.ru', 'password': '~biSXA7SSU]pwI0x&1f'} - headers = {'Content-type': 'application/json', 'Accept': '*/*'} - temptoken = json.loads(r.post(url, data=json.dumps(data), headers=headers).text)["token"] - return(temptoken) \ No newline at end of file +class TokenAuth(AuthBase): + """Implements a custom authentication scheme.""" + + def __init__(self, auth_url, email, password): + self.auth_url = auth_url + self.auth_data = { "email": email, "password": password } + self.auth_token = { "token": "", "expire_date": datetime.utcnow() } + + def __call__(self, r): + """Attach an API token to a custom auth header.""" + expire_date = self.auth_token["expire_date"] + if expire_date <= datetime.utcnow(): + response = requests.post(self.auth_url, json=self.auth_data).json() + token = response["token"] + expires = response["expires"] + expire_date = datetime.utcnow() + timedelta(seconds=expires - 30) + self.auth_token = { "token": token, "expire_date": expire_date } + r.headers["Authorization"] = f"Bearer {self.auth_token['token']}" + return r + + + + +class Database: + + def __init__(self): + self.db_host = os.environ["DB_API_HOST"] + auth_url = self.db_host + "/AuthManagement/Login" + email = os.environ["DB_API_USER"] + password = os.environ["DB_API_PASSWORD"] + self.auth = TokenAuth(auth_url, email, password) + + def request(self, method, endpoint, *args, **kwargs): + print("=========================") + print(method) + print(endpoint) + print(args) + print(kwargs) + print("=========================") + response = requests.request( + method=method, + url=self.db_host + endpoint, + auth=self.auth, + *args, + **kwargs, + ) + print(response.url) + print(response.status_code) + print(response.text) + print(response.headers) + print(response.content) + print("=========================") + return response.json() + + def get(self, endpoint, *args, **kwargs): + return self.request(method="GET", endpoint=endpoint, *args, **kwargs) + + def post(self, endpoint, *args, **kwargs): + return self.request(method="POST", endpoint=endpoint, *args, **kwargs) + + def get_topics(self, offset=0, size=100): + return self.get(endpoint="/Topics/get/all", params={ "offset": offset, "size": size }) + + def topic_get_subotpics(self, topic_id): + return self.get(f"/Topics/get/{topic_id}/subtopics") + + def subtopic_get_topic(self, subtopic_id): + return self.get(f"/Subtopics/get/{subtopic_id}/topic") + + def subtopic_get_questions(self, subtopic_id): + return self.get(f"/Subtopics/get/{subtopic_id}/ui_questions") + + def question_get_question(self, question_id): + return self.get(f"/Questions/get/{question_id}") + + def question_get_answer(self, question_id): + return self.get(f"/Questions/get/{question_id}/answer") + + def question_get_subtopic(self, question_id): + return self.get(f"/Questions/get/{question_id}/subtopic") + + def parse(self, msg): + return self.post(endpoint=f"/Nlu/parse", json=msg)["response_selector"]["default"]["responses"][0]["text"] diff --git a/tgbot_v2/bot.py b/tgbot_v2/bot.py index c92fa6e..5a342f1 100644 --- a/tgbot_v2/bot.py +++ b/tgbot_v2/bot.py @@ -3,35 +3,36 @@ import markups as m import DB import re -import requests as r -import json import os TOKEN = os.environ["TG_TOKEN"] CHATID = os.environ["TG_CHAT_ID"] -DB_API = DB.DB_API + +database = DB.Database() switch = 0 bot = telebot.TeleBot(TOKEN) print('-----BOT STARTED-----') -temptoken = DB.gentempkey() -print('-----AUTH DONE-----') +def unzip_id_value(arr): + ids = [] + values = [] + for obj in arr: + ids.append(obj["id"]) + values.append(obj["value"]) + return ids, values + +def make_text_list(arr): + return "\n".join(f"{i + 1}. *{text}*" for i, text in enumerate(arr)) @bot.message_handler(commands=['start', 'go']) def start_handler(message): user_info = message.from_user.to_dict() DB.users.update({message.chat.id:0}) - bot.send_message(CHATID, text = f"""*Connected new user*\n {user_info}.""", parse_mode= 'Markdown') - url = f'{DB_API}/Topics/get/all?offset=0&size=1000' - btntxt, btnclbc = DB.gethandler(url, temptoken) - bot.send_message(message.chat.id, 'Вас приветствует бот-помощник НГТУ!') - genmessage = 'Выберите тему, которая вас интересует:\n' - i = 0 - while i < len(btntxt): - genmessage += str(i + 1) + '. *' + btntxt[i] + '*\n' - i += 1 + bot.send_message(CHATID, text = f"Connected new user:\n*{message.from_user}*", parse_mode= 'Markdown') + btnclbc, btntxt = unzip_id_value(database.get_topics()) + genmessage = f"Выберите тему, которая вас интересует:\n{make_text_list(btntxt)}\n" bot.send_message(message.chat.id, genmessage, reply_markup=m.create_markup(btntxt, btnclbc, len(btntxt), 1, -1), parse_mode= 'Markdown') @@ -40,11 +41,18 @@ def start_handler(message): def forward(message): if message.chat.type == 'private': if DB.users.get(message.chat.id) == 1: - bot.send_message(CHATID, 'new message from: *@' + str(message.chat.username) + '* userID: *' + str( - message.chat.id) + '*', parse_mode= 'Markdown', reply_markup=m.create_additional_markup(1, message.chat.id)) + bot.send_message(CHATID, f"new message from: *@{message.chat.username}* userID: *{message.chat.id}*", + parse_mode= 'Markdown', reply_markup=m.create_additional_markup(1, message.chat.id)) bot.forward_message(CHATID, message.chat.id, message.id) else: - bot.send_message(message.chat.id, 'я не понимаю, что ты от меня хочешь!') + print() + print(message) + print() + print() + print(message.text) + print() + bot.send_message(database.parse(message.text)) + # bot.send_message(message.chat.id, 'я не понимаю, что ты от меня хочешь!') if message.chat.type == 'group': user_id = message.reply_to_message.forward_from.id bot.send_message(user_id, 'new answer from: *SUPPORT*', parse_mode='Markdown', reply_markup=m.create_additional_markup(2, user_id)) @@ -52,70 +60,45 @@ def forward(message): @bot.callback_query_handler(func=lambda call: True) def allcallbacks_handler(call): - print(call.data) if call.data[0] == 't': topic_id = re.sub('\D', '', call.data) - url = f'{DB_API}/Topics/get/' + topic_id + '/subtopics' - btntxt, btnclbc = DB.gethandler(url, temptoken) - genmessage = 'Выберите тему, которая вас интересует:\n' - i = 0 - while i