Skip to content

Commit f4b5bcf

Browse files
committed
28janOK
1 parent 2051371 commit f4b5bcf

File tree

3,370 files changed

+8318
-293132
lines changed

Some content is hidden

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

3,370 files changed

+8318
-293132
lines changed

README.md

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,14 @@
33

44
ChatGPT + Telegram bot. В интернете таких много, мой возможно не лучше. Сделал потому что понадобился мне. К сожалению в РФ использовать стандартные методы - это искусство запуска VPN. Потому было решено быстренько сделать телеграм бот с ChatGPT. Который позволит в простейшем формате и быстро получить ответ.
55

6+
Коротко:
7+
8+
9+
10+
Подробненько:
11+
12+
13+
614
Особенности:
715
1. Логирование на logging,
816
2. Бот на библиотеке telebot,
@@ -28,4 +36,5 @@ Features:
2836
1. Logging on logging,
2937
2. Bot on the telebot library,
3038
3. If the waiting is exceeded, it is automatically re-logged,
31-
4. ..
39+
4. ..
40+

app/open_ai.py

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5,43 +5,41 @@
55
from worker_db import add_session_data, read_data_ans_ques
66
import datetime
77

8-
# Получаем текущую дату и время
9-
current_datetime = datetime.datetime.now()
10-
# Преобразуем дату и время в строку
11-
formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
12-
# Выводим результат
13-
print("Текущая дата и время:", formatted_datetime)
14-
158

169
client = AsyncOpenAI(api_key=api_key)
1710

18-
async def main(question: str, id): # -> Union[str, None]:
11+
the_gap = 0.10 # Часы.минуты время использования истории общения
12+
models_chat = "gpt-3.5-turbo" #"gpt-4", "text-davinci-002", "text-curie-003", or "gpt-3.5-turbo"
13+
14+
async def main(question: str, id: int): # -> Union[str, None]:
1915
session_data = [] # Clear переменную ОЗУ каждый раз на всякий случай
2016
# Условие вычитывания истории вопросов-ответа, наверно проверяется время обновления времени последней записи, если больше часа, то или очищает, то ли другую ячейку..
2117
read_data = read_data_ans_ques(id)
2218
if read_data:
23-
session_data.append(read_data[0])
24-
session_date = read_data[1]
25-
time_time = session_date.strftime('%Y-%m-%d') # ('%Y-%m-%d %H:%M')
26-
time_date = session_date.strftime('%H.%M')
27-
# print(session_data)
28-
print(f"{time_time}\n{time_date}")
19+
session_date = read_data[1] # Дата и время переписки из DB
20+
time_data = session_date.strftime("%Y-%m-%d"), session_date.strftime("%H.%M") # Вывод в кортеже
21+
date_time = datetime.datetime.utcnow() # Получаем текущую дату и время
22+
formatted_datetime = date_time.strftime("%Y-%m-%d"), date_time.strftime("%H.%M")
23+
difference = float(formatted_datetime[1]) - float(time_data[1])
24+
if time_data[0] == formatted_datetime[0] and difference < the_gap and read_data[0] is not None: # Условие использование данных из базы
25+
session_data.append(read_data[0]) # Добавляем к переменной историю из DB
26+
2927
#raise
3028

3129

3230

3331
session_data.append(f"{question}\n") # Добавляю новый вопрос в переменную ОЗУ
3432
format_session_data = ' '.join(session_data) # Пробелы между словами и убираю запятую
3533

36-
raise
34+
#raise
3735
chat_completion = await client.chat.completions.create(
3836
messages=[
3937
{
4038
"role": "user",
4139
"content": format_session_data,
4240
}
4341
],
44-
model="gpt-3.5-turbo", #"gpt-4", "text-davinci-002", "text-curie-003", or "gpt-3.5-turbo"
42+
model=models_chat,
4543
)
4644

4745
answer = chat_completion.choices[0].message.content # Ответ
@@ -53,7 +51,7 @@ async def main(question: str, id): # -> Union[str, None]:
5351
session_data.append(f"{answer}\n") # Добавляю ответ
5452
clear_data = ' '.join(session_data) # Пробелы между словами и убираю запятую
5553
# Передаю переменую ОЗУ в DB переписывая ячейку по id
56-
54+
#raise
5755
add_session_data(id, clear_data) # Вношу данные из переменной в DB, дата меняется автоматом
5856
session_data = [] # Чистим переменную
5957
return total_answer or None # Возвращаю ответ

app/tele_bot.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def handle_message(message):
5555
async def run_main():
5656
bot.send_chat_action(message.chat.id, 'typing') # Typing bot
5757
result = await main(message.text, id)
58-
send = f"{result[0]}\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nВерсия модели: {result[1]}\nЗавершенные токены: {result[2]}\nПодсказки токены: {result[3]}\nВсего токенов: {result[4]}"
58+
send = f"{result[0]}\n- - - - - - - - - - - - - - - - - - - - - - - - - -\nВерсия модели: {result[1]}\nЗавершенные токены: {result[2]}\nПодсказки токены: {result[3]}\nВсего токенов: {result[4]}"
5959
# send = f"{переменная}\n<b>Жирным - b</b> <i>Курсив - i</i> <code>Код - code</code> <pre>Отдельный блок для копирования - pre</pre>"
6060
bot.reply_to(message, send) # bot.reply_to(message, send, parse_mode='HTML')
6161
loop = asyncio.new_event_loop()

db/sqlite3.db

0 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)