Skip to content
This repository was archived by the owner on Oct 23, 2023. It is now read-only.

Commit b52c876

Browse files
committedAug 26, 2023
feat: refactor code for flake8
1 parent 4b2e85c commit b52c876

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

46 files changed

+2048
-1268
lines changed
 

‎clients/GPTGenerate.py

+25-31
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
"""GPT generate clients."""
12
import time
23
from threading import Thread
34

@@ -8,65 +9,63 @@
89
from logger import logger
910
from models.configs import GlobalConfigs
1011

11-
12-
STOP_TYPING = False
12+
stop_typing = False
1313
cfg = GlobalConfigs()
1414
bot = telebot.TeleBot(cfg.telegram_token_bot.get_secret_value())
1515

16-
IGNORE_ERRORS = [
16+
IGNORE_ERRORS = [ # Hardcode, need refactor
1717
"A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: message is not modified: specified new message content and reply markup are exactly the same as a current content and reply markup of the message" # noqa E501
1818
]
1919

2020

2121
def set_is_typing(chat_id):
22+
"""Set bot status typing."""
2223
while True:
23-
if STOP_TYPING:
24+
if stop_typing:
2425
return
25-
logger.debug(f"STOP_TYPING is False. Seting status typing. Chat id: {chat_id}")
26+
logger.debug(f"stop_typing is False. Seting status typing. Chat id: {chat_id}")
2627
bot.send_chat_action(chat_id, action="typing")
2728
time.sleep(4)
2829

2930

3031
def get_full_len_list(my_list: list):
32+
"""Get full len list."""
3133
cnt = 0
3234
for i in my_list:
3335
cnt += len(i)
3436
return cnt
3537

3638

3739
def get_str_from_list(my_list: list):
38-
return ''.join(str(x) for x in my_list)
40+
"""Get string from list."""
41+
return "".join(str(x) for x in my_list)
3942

4043

4144
class GPT4TextGenerate(BaseSettings):
45+
"""GPT4TextGenerate class."""
4246

4347
def message_responser(self, prompt, chat_id, msg_id):
48+
"""Set typing bot status and generate text."""
4449
if chat_id != 0:
4550
Thread(target=set_is_typing, args=(chat_id,)).start()
46-
# try:
4751
result_generate = self.gpt4_generate(
48-
prompt=prompt,
49-
chat_id=chat_id,
50-
msg_id=msg_id
52+
prompt=prompt, chat_id=chat_id, msg_id=msg_id
5153
)
5254
if result_generate:
53-
STOP_TYPING = True
55+
stop_typing = True
5456
logger.debug(f"Result sent successful for chat id: {chat_id}")
5557
return True
56-
# except Exception as e:
57-
# logger.error(f"Fatal error: {e}")
58-
STOP_TYPING = True # noqa F841
58+
stop_typing = True # noqa F841
5959
self.send_message("Smth error", chat_id)
6060
raise RuntimeError
6161

62-
def gpt4_generate(self, chat_id, prompt, msg_id):
62+
def gpt4_generate(self, chat_id, prompt, msg_id): # noqa: CFQ004,CFQ001
63+
"""Generate text with prompt and send."""
6364
prompt = cfg.pre_prompt + prompt
6465
response = g4f.ChatCompletion.create(
65-
# model='gpt-3.5-turbo',
66-
model='gpt-4',
66+
model="gpt-4",
6767
messages=[{"role": "user", "content": prompt}],
68-
# stream=True,
69-
provider=g4f.Provider.ChatgptAi
68+
provider=g4f.Provider.ChatgptAi,
7069
)
7170
full_text = []
7271
max_length = 150
@@ -84,7 +83,7 @@ def gpt4_generate(self, chat_id, prompt, msg_id):
8483
return True
8584
msg_id = self.send_message(
8685
text=get_str_from_list(full_text[last_len_list:]),
87-
chat_id=chat_id
86+
chat_id=chat_id,
8887
)
8988
len_list = len(full_text)
9089
cnt_divisions += 1
@@ -94,13 +93,13 @@ def gpt4_generate(self, chat_id, prompt, msg_id):
9493
bot.edit_message_text(
9594
chat_id=chat_id,
9695
text=get_str_from_list(full_text[len_list:]),
97-
message_id=msg_id
96+
message_id=msg_id,
9897
)
9998
last_len_list = len(full_text)
10099
if chat_id == 0:
101100
bot.edit_message_text(
102101
inline_message_id=msg_id,
103-
text=get_str_from_list(full_text[len_list:])
102+
text=get_str_from_list(full_text[len_list:]),
104103
)
105104
except telebot.apihelper.ApiTelegramException as e:
106105
if str(e) in IGNORE_ERRORS:
@@ -113,27 +112,23 @@ def gpt4_generate(self, chat_id, prompt, msg_id):
113112
bot.edit_message_text(
114113
inline_message_id=msg_id,
115114
text=get_str_from_list(full_text[len_list:]),
116-
# parse_mode='Markdown'
117-
# Added markdown validator
118115
)
119116
return True
120117
bot.edit_message_text(
121118
chat_id=chat_id,
122119
text=get_str_from_list(full_text[len_list:]),
123120
message_id=msg_id,
124-
# parse_mode='Markdown'
125-
# Added markdown validator
126121
)
127122
except telebot.apihelper.ApiTelegramException as e:
128123
if str(e) in IGNORE_ERRORS:
129124
return True
130-
else:
131-
raise RuntimeError(e)
125+
raise RuntimeError(e)
132126
return True
133127

134128
def send_message(self, text, chat_id):
129+
"""Send message with chunk per 4096 sumbol."""
135130
max_length = 4096
136-
chunks = [text[i:i+max_length] for i in range(0, len(text), max_length)]
131+
chunks = [text[i: i + max_length] for i in range(0, len(text), max_length)]
137132
msg_id = 0
138133
try:
139134
for chunk in chunks:
@@ -144,5 +139,4 @@ def send_message(self, text, chat_id):
144139
except telebot.apihelper.ApiTelegramException as e:
145140
if str(e) in IGNORE_ERRORS:
146141
return msg_id
147-
else:
148-
raise RuntimeError(e)
142+
raise RuntimeError(e)

‎clients/middleware.py

+9-10
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
1-
import json
1+
# Need refactor.
22
import asyncio
3+
import json
34

4-
from sqlalchemy import select
55
from pydantic import BaseSettings
6+
from sqlalchemy import select
67

7-
from models.history import MessageHistory, CallbackQueryHistory, Chats
88
from db.base import get_session
99
from logger import logger
10+
from models.history import CallbackQueryHistory, Chats, MessageHistory
1011

1112

1213
class UpdateLastTimeMessage(BaseSettings):
@@ -24,11 +25,7 @@ async def update_time(self, time, chat_id: int):
2425
chat.message_last_time = time
2526
chat.message_count += 1
2627
else:
27-
chat = Chats(
28-
chat_id=chat_id,
29-
message_last_time=time,
30-
message_count=1
31-
)
28+
chat = Chats(chat_id=chat_id, message_last_time=time, message_count=1)
3229
session.add(chat)
3330
try:
3431
await session.commit()
@@ -71,12 +68,14 @@ def save_qc(self, callback_query):
7168
async def save_cq(self, callback_query):
7269
session = [session_q async for session_q in get_session()][0]
7370
logger.debug(callback_query)
74-
callback_query_h = CallbackQueryHistory(callback_query=json.loads(str(callback_query)))
71+
callback_query_h = CallbackQueryHistory(
72+
callback_query=json.loads(str(callback_query))
73+
)
7574
session.add(callback_query_h)
7675
try:
7776
await session.commit()
7877
return True
7978
except Exception as ex:
8079
await session.rollback()
81-
logger.error(ex)
80+
logger.error(f"Error in func CallbackQuerySaver: {ex}")
8281
return False

0 commit comments

Comments
 (0)
This repository has been archived.