Skip to content

Commit

Permalink
rewrite shitty code
Browse files Browse the repository at this point in the history
  • Loading branch information
pomid0rko0 committed Jun 8, 2021
1 parent 7107c24 commit aa7842b
Show file tree
Hide file tree
Showing 2 changed files with 134 additions and 91 deletions.
110 changes: 86 additions & 24 deletions 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)
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"]
115 changes: 48 additions & 67 deletions tgbot_v2/bot.py
Expand Up @@ -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')

Expand All @@ -40,82 +41,64 @@ 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))
bot.copy_message(user_id, from_chat_id=message.chat.id, message_id=message.id)

@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<len(btntxt):
genmessage +=str(i+1) + '. *'+ btntxt[i] + '*\n'
i+=1
btnclbc, btntxt = unzip_id_value(database.topic_get_subotpics(topic_id))
genmessage = f"Выберите тему, которая вас интересует:\n{make_text_list(btntxt)}\n"
bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=genmessage,
reply_markup=m.create_markup(btntxt, btnclbc, len(btntxt), 2, -1), parse_mode= 'Markdown')

if call.data[0] == 's':
subtopic_id = re.sub('\D', '', call.data)
url = f'{DB_API}/Subtopics/get/' + subtopic_id + '/questions'
btntxt, btnclbc = DB.gethandler(url, temptoken)
url2 = f'{DB_API}/Subtopics/get/' + subtopic_id + '/topic'
headers = {'Accept': 'text/plain', 'Authorization': 'Bearer ' + temptoken}
request = json.loads((r.get(url2, headers = headers)).text)
previousID = request["id"]
genmessage = 'Выберите тему, которая вас интересует:\n'
i = 0
while i < len(btntxt):
genmessage += str(i + 1) + '. *' + btntxt[i] + '*\n'
i += 1
btnclbc, btntxt = unzip_id_value(database.subtopic_get_questions(subtopic_id))
topic = database.subtopic_get_topic(subtopic_id)
previousID = topic["id"]
genmessage = f"Выберите тему, которая вас интересует:\n{make_text_list(btntxt)}\n"
bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=genmessage,
reply_markup=m.create_markup(btntxt, btnclbc, len(btntxt), 3, previousID), parse_mode= 'Markdown')


if call.data[0] == 'q':
question_id = re.sub('\D', '', call.data)
url = f'{DB_API}/Questions/get/' + question_id + '/answer'
headers = {'Accept': 'text/plain', 'Authorization': 'Bearer ' + temptoken}
requestvalue = json.loads((r.get(url, headers=headers)).text)["value"]
print(requestvalue)
url2 = f'{DB_API}/Questions/get/' + question_id + '/subtopic'
previousID = json.loads((r.get(url2, headers=headers)).text)["id"]
url3 = f'{DB_API}/Questions/get/' + question_id
questiontext = json.loads((r.get(url3, headers=headers)).text)["value"]
genmessage = 'Ваш вопрос:\n*' + questiontext + '*\nВаш ответ:\n*' + requestvalue + '*'
answer = database.question_get_answer(question_id)
answervalue = answer["value"]
subtopic = database.question_get_subtopic(question_id)
previousID = subtopic["id"]
question = database.question_get_question(question_id)
questiontext = question["value"]
genmessage = f"Ваш вопрос:\n*{questiontext}*\nВаш ответ:\n*{answervalue}*"
bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=genmessage,
reply_markup=m.create_additional_markup(3, -1), parse_mode= 'Markdown')

if call.data[0] == 'a':
url = f'{DB_API}/Topics/get/all?offset=0&size=1000'
btntxt, btnclbc = DB.gethandler(url, temptoken)
genmessage = 'Выберите тему, которая вас интересует:\n'
i = 0
while i < len(btntxt):
genmessage += str(i + 1) + '. *' + btntxt[i] + '*\n'
i += 1
btnclbc, btntxt = unzip_id_value(database.get_topics())
genmessage = f"Выберите тему, которая вас интересует:\n{make_text_list(btntxt)}\n"
bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=genmessage,
reply_markup=m.create_markup(btntxt, btnclbc, len(btntxt), 1, -1), parse_mode= 'Markdown')

if call.data[0] == 'b':
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 < len(btntxt):
genmessage += str(i + 1) + '. *' + btntxt[i] + '*\n'
i += 1
btnclbc, btntxt = unzip_id_value(database.topic_get_subotpics(topic_id))
genmessage = f"Выберите тему, которая вас интересует:\n{make_text_list(btntxt)}\n"
bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=genmessage,
reply_markup=m.create_markup(btntxt, btnclbc, len(btntxt), 2, -1, -1), parse_mode= 'Markdown')

Expand All @@ -130,13 +113,11 @@ def allcallbacks_handler(call):
if call.data == '/start':
bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=call.message.text, parse_mode ='Markdown')
DB.users.update({call.message.chat.id: 0})
url = f'{DB_API}/Topics/get/all?offset=0&size=1000'
btntxt, btnclbc = DB.gethandler(url, temptoken)
genmessage = 'Выберите тему, которая вас интересует:\n'
i = 0
while i < len(btntxt):
genmessage += str(i + 1) + '. *' + btntxt[i] + '*\n'
i += 1
btnclbc, btntxt = unzip_id_value(database.get_topics())
genmessage = f"Выберите тему, которая вас интересует:\n{make_text_list(btntxt)}\n"
print()
print(genmessage)
print()
bot.send_message(call.message.chat.id, genmessage,
reply_markup=m.create_markup(btntxt, btnclbc, len(btntxt), 1, -1), parse_mode='Markdown')
if call.data[0] == 'c':
Expand All @@ -150,7 +131,7 @@ def allcallbacks_handler(call):
'Спасибо, что воспользовались нашим ботом, если у вас ещё есть вопросы - начните заново*',
reply_markup = m.create_additional_markup(3, -1), parse_mode= 'Markdown')
nick = bot.get_chat_member(userID, userID).user.username
bot.send_message(CHATID, 'Тикет: ' + userID + ' / @' + nick + ' закрыт')
bot.send_message(CHATID, f"Тикет: {userID} / @{nick} закрыт")


bot.polling()
Expand Down

0 comments on commit aa7842b

Please sign in to comment.