1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
|
import asyncio
import base64
import io
import sys
import gconfig
# from aiogram.methods import SendMessageDraft
from datetime import datetime
from aiogram import Bot, Dispatcher, F
from aiogram.client.default import DefaultBotProperties
from aiogram.types import Update
from aiogram.methods import AnswerGuestQuery
from aiogram.types import InlineQueryResultArticle, InputTextMessageContent
from aiogram import BaseMiddleware
from aiogram.enums import ChatType
from aiogram.exceptions import TelegramForbiddenError
from aiogram.types import (
ChosenInlineResult,
InlineKeyboardButton,
InlineKeyboardMarkup,
InlineQuery,
InlineQueryResultArticle,
InputTextMessageContent,
Message,
)
from callbacks import *
from colors import *
from commands import *
from dotenv import load_dotenv
try:
from config import *
except:
gconfig.copy_config()
finally:
from config import *
from supergenerator import *
load_dotenv()
print(f"{BOLD}{GREEN} -- uzbekgpt - привет как дела. {RESET}")
if not API_TOKEN:
print(f"{RED}{BOLD} !! suka API_TOKEN поставь в .env либо pashol naxxuy {RESET}")
sys.exit(1)
try:
bot = Bot(token=API_TOKEN, default=DefaultBotProperties(parse_mode="Markdown"))
dp = Dispatcher()
dp.include_router(router)
except Exception as e:
print(f"{RED}{BOLD} !! вирус у вас тут ошибка: {e}{RESET}")
sys.exit(1)
def parse_tools(text):
...
return text
def is_blocked(user_id):
current_time = time.time()
if user_id:
if user_id in last_command_time:
time_diff = current_time - last_command_time[user_id]
if time_diff < 3:
alo = "🚫 *файл не вошёл.* хватит так быстро слать свои сообщения.\n" \
f"подожди {round(3 - time_diff, 3)} секунд, брат😡😡"
return alo, True
return "", False
def is_replied_bot(message, is_channel, user_text, config=None):
if message.chat.type in [ChatType.GROUP, ChatType.SUPERGROUP, ChatType.CHANNEL]:
if not is_channel:
is_reply_to_bot = (
message.reply_to_message
and message.reply_to_message.from_user
and message.reply_to_message.from_user.is_bot
and message.reply_to_message.from_user.username == BOT_USERNAME
)
if config:
if config.get("call") == "da":
mentions_bot = any(
user_text.lower().startswith(call.lower()) for call in BOT_CALLS
)
else:
mentions_bot = False
else:
mentions_bot = any(
user_text.lower().startswith(call.lower()) for call in BOT_CALLS
)
if not (is_reply_to_bot or mentions_bot):
return False
return True
@dp.update.outer_middleware()
async def guest_middleware(handler, event, data):
# print("e: ", event)
if event.guest_message:
message = event.guest_message
user_id = message.sender_chat.id if message.sender_chat else message.from_user.id
current_time = time.time()
if user_id:
text, blocked = is_blocked(user_id)
if blocked:
await data["bot"](
AnswerGuestQuery(
guest_query_id=message.guest_query_id,
result=InlineQueryResultArticle(
id="1",
title="err",
input_message_content=InputTextMessageContent(
message_text=text
),
),
)
)
return
last_command_time[user_id] = current_time
user_text = message.text or message.caption or ""
replied = message.reply_to_message or None
if replied:
replied_text = message.reply_to_message.text or message.reply_to_message.caption or None
else:
replied_text = None
prompt = ""
if replied and replied.photo and IMAGE_MODEL != "":
try:
photo = replied.photo[-1]
file_bytes = await bot.download(photo)
image_bytes = file_bytes.read()
b64_image = base64.b64encode(image_bytes).decode("utf-8")
image_text = await image2text(image=b64_image)
except Exception as e:
image_text = "произошла ошибка при анализе фото"
print(f"{RED} -- photo - {e}{RESET}")
prompt = f"{prompt}<фото в ответе>{image_text}</фото в ответе>\n"
if message.photo and IMAGE_MODEL != "":
try:
photo = message.photo[-1]
file_bytes = await bot.download(photo)
image_bytes = file_bytes.read()
b64_image = base64.b64encode(image_bytes).decode("utf-8")
image_text = await image2text(image=b64_image)
except Exception as e:
image_text = "произошла ошибка при анализе фото"
print(f"{RED} -- photo - {e}{RESET}")
prompt = f"{prompt}<фото>{image_text}</фото>\n"
prompt = f"{prompt}\n{user_text}"
if replied_text:
prompt = f"<ответ на>{replied_text}</ответ> {prompt}"
prompt = prompt[:MAX_PROMPT]
result = await generate(
bot=bot,
prompt=prompt,
chat_id=None,
user_id=user_id,
message_id=None,
)
try:
await data["bot"](
AnswerGuestQuery(
guest_query_id=message.guest_query_id,
result=InlineQueryResultArticle(
id="1",
title="ok",
input_message_content=InputTextMessageContent(
message_text=result
),
),
)
)
except Exception as e:
try:
await data["bot"](
AnswerGuestQuery(
guest_query_id=message.guest_query_id,
result=InlineQueryResultArticle(
id="1",
title="ok",
input_message_content=InputTextMessageContent(
message_text=result,
parse_mode="None"
),
),
)
)
except Exception as e:
print(f"{RED} -- send guest - {e}{RESET}")
else:
print(f"{YELLOW} -- markdown - {e}{RESET}")
return
return await handler(event, data)
@router.message(F.content_type.in_({"text", "photo", "document"}))
async def text_handler(message: Message):
chat_type = message.sender_chat.type if message.sender_chat else ""
user_id = message.sender_chat.id if message.sender_chat else message.from_user.id
is_channel = (
ChatType.CHANNEL == chat_type
and message.from_user
and message.from_user.id == 777000
)
user_text = message.text or message.caption or ""
msg = None
config = get_user_config(user_id)
stream = config.get("stream")
current_time = time.time()
if not is_replied_bot(message, is_channel, user_text, config):
return
if user_id:
text, blocked = is_blocked(user_id)
if blocked:
error_message = await message.reply(text)
await asyncio.sleep(7)
try:
await error_message.delete()
except Exception as e:
print(f"{YELLOW} -- del err - {e}{RESET}")
return
last_command_time[user_id] = current_time
replied = message.reply_to_message
prompt = ""
try:
await bot.send_chat_action(chat_id=message.chat.id, action="typing")
except TelegramForbiddenError:
return
if message.document:
if message.document.file_size > 4096:
await message.reply("слишком много данных не хочу отвечать☝️☝️")
return
file_bytes = io.BytesIO()
try:
await bot.download(message.document, destination=file_bytes)
file_bytes.seek(0)
file_content = file_bytes.read().decode("utf-8", errors="ignore")
file_bytes.close()
prompt = f"<файл>{file_content}</файл>"
except UnicodeDecodeError:
await message.reply("файл не вошёл брат❌❌")
return
except Exception:
await message.reply("файл не вошёл ало❌")
return
if replied and replied.document:
if replied.document.file_size > 4096:
await message.reply("файл не вошёл слишком много весит❌😡")
return
file_bytes = io.BytesIO()
try:
await bot.download(replied.document, destination=file_bytes)
file_bytes.seek(0)
file_content = file_bytes.read().decode("utf-8", errors="ignore")
prompt = f"<файл>{file_content}</файл>{user_text}"
except UnicodeDecodeError:
await message.reply("файл не вошёл❌")
return
except Exception as e:
print(f"{RED} -- {e}{RESET}")
return
elif replied and replied.photo and IMAGE_MODEL != "":
try:
msg = await message.reply("👀")
except Exception:
return
try:
photo = replied.photo[-1]
file_bytes = await bot.download(photo)
image_bytes = file_bytes.read()
b64_image = base64.b64encode(image_bytes).decode("utf-8")
image_text = await image2text(image=b64_image)
except Exception as e:
image_text = "произошла ошибка при анализе фото"
print(f"{RED} -- photo - {e}{RESET}")
if replied.caption:
prompt = f"<ответ на фото>{image_text}</ответ на фото>\n<подпись в ответе>{replied.caption}</подпись в ответе>\n"
else:
prompt = f"<ответ на фото>{image_text}</ответ на фото>\n<подпись в ответе>{replied.caption}\n"
await msg.edit_text("💬")
elif replied and replied.text:
replied_text = message.reply_to_message.text
prompt = f"<ответил на сообщение> {replied_text} </ответил на сообщение>\n"
if message.photo and IMAGE_MODEL != "":
try:
msg = await message.reply("👀")
except Exception:
return
try:
photo = message.photo[-1]
file_bytes = await bot.download(photo)
image_bytes = file_bytes.read()
b64_image = base64.b64encode(image_bytes).decode("utf-8")
image_text = await image2text(image=b64_image)
except Exception as e:
image_text = "произошла ошибка при анализе фото"
print(f"{RED} -- photo - {e}{RESET}")
prompt = f"<фото>{image_text}</фото>\n"
await msg.edit_text("💬")
prompt = f"{prompt}\n{user_text}"
prompt = prompt[:MAX_PROMPT]
try:
await bot.send_chat_action(chat_id=message.chat.id, action="typing")
except TelegramForbiddenError:
return
if stream == "edit":
if not msg:
try:
msg = await message.reply("💬")
except Exception:
return
message_id = msg.message_id
else:
message_id = None
if is_channel:
result = await generate(
bot=bot,
prompt=prompt,
chat_id=message.chat.id,
user_id=None,
message_id=message_id,
)
else:
result = await generate(
bot=bot,
prompt=prompt,
chat_id=message.chat.id,
user_id=user_id,
message_id=message_id,
)
result = parse_tools(result)
try:
if result:
if msg:
if stream == "native":
await msg.delete()
await message.reply(result)
else:
await msg.edit_text(result)
else:
await message.reply(result)
except Exception as e:
try:
if msg:
if stream == "native":
await msg.delete()
await message.reply(result, parse_mode="None")
else:
await msg.edit_text(result, parse_mode="None")
else:
await message.reply(result, parse_mode="None")
except Exception as e:
print(f"{RED} -- {e}{RESET}")
return
print(f"{YELLOW} -- {e}{RESET}")
@router.inline_query()
async def inline_handler(inline_query: InlineQuery):
user_id = inline_query.from_user.id
button = InlineKeyboardButton(text="ало жди 📞", callback_data="pasholnaxxuy")
if inline_query.query == "clear":
result = [
InlineQueryResultArticle(
id="1",
title="очистить контекст",
description="нажми сюда чтоб узбэкгпт прочистил свои мозги✅",
input_message_content=InputTextMessageContent(
message_text="я промыл себе мозги и контекст очищен✅"
),
)
]
else:
result = [
InlineQueryResultArticle(
id="1",
title="генерация думат",
description=f'думать "{inline_query.query}" ',
input_message_content=InputTextMessageContent(
message_text="я думаю врат... как дела✅"
),
reply_markup=InlineKeyboardMarkup(inline_keyboard=[[button]]),
)
]
await inline_query.answer(results=result, cache_time=0)
@router.chosen_inline_result()
async def chosen_inline_result_handler(chosen_result: ChosenInlineResult):
inline_message_id = chosen_result.inline_message_id
user_id = chosen_result.from_user.id
if chosen_result.query == "clear":
user_contexts[user_id] = []
else:
current_time = time.time()
alo, blocked = is_blocked(user_id)
if alo and blocked:
await bot.edit_message_text(
text=alo,
inline_message_id=inline_message_id
)
return
last_command_time[user_id] = current_time
if inline_message_id:
try:
result = await generate(
prompt=chosen_result.query[:MAX_PROMPT],
user_id=chosen_result.from_user.id,
)
except Exception as e:
error = parse_response(str(e))
await bot.edit_message_text(
text=error["message"],
inline_message_id=inline_message_id,
)
print(f"{RED} -- {error['type']} -- {error['message']}")
return
if result:
if result.startswith("<!block>") or result.endswith("<!block>"):
result = result.replace("<!block>", "")
last_block_time[user_id] = current_time
try:
await bot.edit_message_text(
text=result, inline_message_id=inline_message_id
)
except Exception as e:
print(f"{RED} -- {e}{RESET}")
if "MESSAGE_TOO_LONG" not in str(e):
await bot.edit_message_text(
text=result,
inline_message_id=inline_message_id,
parse_mode="None",
)
else:
await bot.edit_message_text(
text=result[:800],
inline_message_id=inline_message_id,
parse_mode="None",
)
async def main():
await bot.delete_webhook(drop_pending_updates=True)
await dp.start_polling(
bot,
allowed_updates = [
"message",
"callback_query",
"guest_message",
"inline_query",
"chosen_inline_result"
],
)
if __name__ == "__main__":
asyncio.run(main())
|