aboutsummaryrefslogtreecommitdiff
path: root/commands.py
blob: 71570c88c332fdcd846c4a3bf00f84157571d220 (plain)
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
from io import BytesIO
from typing import Optional, Union

from aiogram import Bot, Dispatcher, F, Router
from aiogram.methods import SendRichMessage
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ChatAction, ChatType
from aiogram.exceptions import TelegramForbiddenError
from aiogram.filters import Command, CommandStart, CommandObject
from aiogram.types import (
    BufferedInputFile,
    CallbackQuery,
    ChosenInlineResult,
    InlineKeyboardButton,
    InlineKeyboardMarkup,
    InlineQuery,
    InlineQueryResultArticle,
    InputRichMessage,
    InputTextMessageContent,
    Message,
    User,
)
from aiogram.utils.deep_linking import create_start_link

from collections import Counter

from colors import *
from config import *
from statistics import *
from vars import *
from helpers import *
from supergenerator import *


router = Router()

commands = [
    "/stats", 
    "/broadcast", 
    "/ben", 
    "/reporn", 
    "/start", 
    "/prompt",
    "/config",
    "/settings",
    "/clear",
    "/stop",
    "/markpidor",
    "/aben",
    "/button",
    "/clean",
    "/reset",
    "/tben",
]

@router.message(Command("stats"))
async def stats_handler(message: Message):
    users = get_all_users()

    total_users = len(users)

    models = Counter()
    streams = Counter()
    calls = Counter()
    prompts = Counter()

    for data in users.values():
        if isinstance(data, dict):
            models[data.get("model")] += 1
            streams[data.get("stream")] += 1
            calls[data.get("call")] += 1
            prompts[data.get("prompt")] += 1

    top_models = models.most_common(5)
    top_streams = streams.most_common(2)
    top_prompts = prompts.most_common(10)

    text = [
        "✅ *общая статистика*",
        f"☝️пользователей: {total_users}",
        f"📞всего генераций: {get_stats('stats/gens')}",
        f"👻ген в гостевом: {get_stats('stats/guest')}",
        f"🙏ген в инлайне: {get_stats('stats/inline')}",
        f"🤝ben: {get_stats('stats/ben')}",
        f"🤝reporn: {get_stats('stats/reporn')}",
        "🥺топ 5 моделей:",
        *(f"- `{m}`: {c}" for m, c in top_models),
        "✍️топ режимов стрима:",
        *(f"- `{s}`: {c}" for s, c in top_streams),
        "👀топ режимов вызова:",
        *(f"- `{c}`: {n}" for c, n in calls.most_common()),
        "📝топ 10 промптов:",
        *(f"- `{c}`: {n}" for c, n in top_prompts),
    ]

    await message.reply("\n".join(text))


@router.message(Command("button"))
async def button_handler(message: Message):
    if message.from_user.id != ADMIN_ID:
        return await message.reply("🚫 pashol naxxuy.")

    text = message.text.removeprefix("/button").strip()
    if not text:
        return await message.reply(
            "крч это типо генератор инлайн кнопки да только для тестов пж использовать\n"
            "🚫 напиши callback после команды ало."
        )

    keyboard = InlineKeyboardMarkup(
        inline_keyboard=[
            [InlineKeyboardButton(text=text, callback_data=text)],
        ]
    )

    await message.reply(
        "✅ кнопка крутая ниже"
        " кнопка крутая ниже"
        " кнопка крутая ниже"
        " кнопка крутая ниже"
        " кнопка крутая ниже",
        reply_markup=keyboard
    )


@router.message(Command("reset"))
async def reset_handler(message: Message, command: CommandObject):
    if message.from_user.id != ADMIN_ID: 
        return
    args = command.args
    if not args or len(args.split()) < 2: 
        return await message.answer("dayn eblan suka")
    users = get_all_user_ids()
    key, val = args.split()[0], args.split()[1]
    for user_id in users:
        reset_user_setting(user_id, key, val)
    await message.answer(f"✅ сбросил всем {key} на {val}")


@router.message(Command("tben"))
async def tben_handler(message: Message, command: CommandObject):
    if message.from_user.id != ADMIN_ID: 
        return
    args = command.args
    if not args or " " not in args:
        return await message.answer("dayn eblan suka")
    key, val = args.split(" ", 1)
    temp_benned[str(key)] = val
    await message.answer(f"✅ хамха забенен")
    

@router.message(Command("clean"))
async def clean_db_handler(message: Message):
    if message.from_user.id != ADMIN_ID: 
        return
    users = get_all_user_ids()
    success, deleted = 0, 0
    for user_id in users:
        try:
            await message.bot.send_chat_action(user_id, "typing")
            success += 1
        except:
            delete_user_from_db(user_id)
            deleted += 1
    await message.answer(f"✅ *готово врат.*\n- сохранено {success}\n- удалено {deleted}")


@router.message(Command("broadcast"))
async def broadcast_handler(message: Message):
    if message.from_user.id != ADMIN_ID:
        return await message.reply("🚫 pashol naxxuy.")

    text = message.text.removeprefix("/broadcast").strip()
    if not text:
        return await message.reply("🚫 напиши текст после команды ало.")

    users = get_all_user_ids(only_notify=True)

    success = 0
    failed = 0

    for user_id in users:
        try:
            if user_id > 0:
                await message.bot.send_message(user_id, text)
                success += 1
        except TelegramForbiddenError:
            failed += 1
        except Exception as e:
            print(f"{RED} -- broadcast err - {e}{RESET}")
            failed += 1

    await message.reply(
        f"✅ *готово врат.*\n- успешно: {success}\n- не удалось: {failed}"
    )


@router.message(Command("stop"))
async def stop_handler(message: Message):
    if message.sender_chat:
        user_id = message.sender_chat.id
    else:
        user_id = message.from_user.id
        
    config = get_user_config(user_id)
    set_user_config(
        user_id, 
        config.get("model"), 
        config.get("stream"), 
        config.get("call"), 
        config.get("prompt"), 
        "net", 
        config.get("markdown")
    )
    await message.reply("✅ *рассылка успешно отключена!* чтобы включить её обратно:\n/settings --> рассылка")

@router.message(Command("ben"))
async def ben_handler(message: Message):
    if message.chat.type in [ChatType.GROUP, ChatType.SUPERGROUP]:
        if message.chat.id in BEN_IDS:
            replied = message.reply_to_message or None
            if replied:
                name = replied.from_user.first_name
                ben_id = replied.from_user.id
            else:
                name = message.from_user.first_name
                ben_id = message.from_user.id
                
            await message.reply(
                f"{name} ({ben_id}) заbenен за Botting, spamming, and coordinated inauthentic behavior.😡✅\n"
                f"админ: Ben (958011829)✅"
            )
            add_one_to("stats/ben")
    return


@router.message(Command("aben"))
async def ben_handler(message: Message):
    if message.chat.type in [ChatType.GROUP, ChatType.SUPERGROUP]:
        if message.chat.id in ABEN_IDS:
            replied = message.reply_to_message or None
            if replied:
                name = replied.from_user.first_name
                ben_id = replied.from_user.id
            else:
                name = message.from_user.first_name
                ben_id = message.from_user.id
                
            await message.reply(f"""✅ *Benned*

• 👤 *User:* {name} ({ben_id})

👮 *Admin:* a (@U837373) (8539910994)
💬 *Reason:* a completely dishonest person: he lies, and even admits it himself. He has no shame in lying. He is fake and hypocritical. He says one thing to your face and another behind your back. And, if he gets the chance, he'll stab you in the back.""")
    return


@router.message(Command("reporn"))
async def reporn_handler(message: Message):
    user_name = message.from_user.first_name or message.sender_chat.title or "вы"
    if message.chat.type in [ChatType.GROUP, ChatType.SUPERGROUP]:
        if message.chat.id in REPORN_IDS:
            replied = message.reply_to_message or None
            if replied:
                name = replied.from_user.first_name
                ben_id = replied.from_user.id
            else:
                name = message.from_user.first_name
                ben_id = message.from_user.id
            
            await message.reply(
                f"отправлен репорт на {name} ({ben_id})!📞"
            )
            add_one_to("stats/reporn")
    return
        

@router.message(CommandStart())
async def start_handler(message: Message, command: CommandObject):
    if message.chat.type in [ChatType.GROUP, ChatType.SUPERGROUP]:
        await message.reply(
            "привет, запусти эту команду в ЛиС (личные сообщения) бота✅"
        )
        return
        
    if message.sender_chat:
        user_id = message.sender_chat.id
    else:
        user_id = message.from_user.id
    
    config = get_user_config(user_id)

    payload = command.args
    if payload == "new_md":
        set_user_config(
            user_id, 
            config.get("model"), 
            config.get("stream"), 
            config.get("call"), 
            config.get("prompt"), 
            config.get("notify"), 
            "new"
        )
        return await message.answer("✅ установлен *новый* стиль выделения сообщений!")
    elif payload == "old_md":
        set_user_config(
            user_id, 
            config.get("model"), 
            config.get("stream"), 
            config.get("call"), 
            config.get("prompt"), 
            config.get("notify"), 
            "old"
        )
        return await message.answer("✅ установлен *старый* стиль выделения сообщений!")
    elif payload and payload.startswith("prompt-"):
        prompt_spl = payload.split("-", 2)
        if len(prompt_spl) != 3:
            return await message.answer("❌ говно твой payload ты читар уйди")
        prompt_user_id = int(prompt_spl[1])
        prompt_id = prompt_spl[2]
        try:
            if prompt_user_id == 0:
                prompt = SYSTEM_PROMPTS.get(prompt_id, {})
                if not prompt:
                    return await message.reply("❌ промпт kal suka либо приватный либо удалён либо его никогда не было")
                prompt_pub = True
            else:
                prompt = get_user_config(prompt_user_id)["prompts"].get(
                    prompt_id, {}
                )
                if not prompt:
                    return await message.reply("❌ промпт говно suka либо приватный либо удалён либо его никогда не было")
                prompt_pub = prompt.get("public", False)
            if len(config["prompts"]) >= MAX_PROMPTS and prompt_pub:
                keyboard = InlineKeyboardMarkup(
                    inline_keyboard=[
                        [InlineKeyboardButton(text="достигнут лимит промптов", callback_data=f"hamza")],
                    ]
                )
            elif prompt_pub and prompt_user_id != 0:
                keyboard = InlineKeyboardMarkup(
                    inline_keyboard=[
                        [InlineKeyboardButton(text="✅ добавить", callback_data=f"ap%{user_id}%{prompt_user_id}%{prompt_id}")],
                        [InlineKeyboardButton(text="✅🔗 доб. + установить", callback_data=f"sp%{user_id}%{prompt_user_id}%{prompt_id}%2")],
                    ]
                )
            else:
                keyboard = InlineKeyboardMarkup(
                    inline_keyboard=[
                        [InlineKeyboardButton(text="✅установить", callback_data=f"sp%{user_id}%{prompt_user_id}%{prompt_id}%2")],
                    ]
                )
            
            
            if prompt_user_id == user_id:
                return await message.reply(
                    f"✅ это твой промпт `{prompt.get('name', 'говно')}`:"
                    f"```\n{prompt.get('text')}\n```",
                    reply_markup=InlineKeyboardMarkup(
                        inline_keyboard=[
                            [
                                InlineKeyboardButton(text="✅ установить", callback_data=f"sp%{user_id}%0%{prompt_id}%2"),
                                InlineKeyboardButton(text="⚙️ настроить", callback_data=f"vp%{user_id}%{prompt_id}"),
                            ],
                        ]
                    )
                )
            elif prompt_pub:
                return await message.reply(
                    f"✅ вот `{prompt.get('name', 'говно')}` промпт крутой da:"
                    f"```\n{prompt.get('text')}\n```",
                    reply_markup=keyboard
                )
        except Exception as e: 
            print(f"{YELLOW} -- prompt - {e}{RESET}")
        return await message.reply("❌ промпт говно suka либо приватный либо удалён либо его никогда не было")

    invite_url = f"https://t.me/{BOT_USERNAME}?startgroup=start"

    keyboard = InlineKeyboardMarkup(
        inline_keyboard=[
            [InlineKeyboardButton(text="команды", callback_data="start")],
            [InlineKeyboardButton(text="настройки", callback_data=f"settings%{user_id}")],
            [InlineKeyboardButton(text="добавить в группу", url=invite_url)]
        ]
    )

    try:
        await message.reply(
            "Привет, я УзбекГПТ✅ национальный бот Узбикестан и я готов не помочь. Напиши любае сообщение или отправь файл чтоб я быстра ответил!1!1 Или нажми кнопку ниже чтоба посмотрет мои команды..",
            reply_markup=keyboard,
        )
    except Exception as e:
        print(f"{RED} -- {e}{RESET}")


@router.message(Command("prompt"))
async def prompt_handler(message: Message):
    if message.sender_chat:
        user_id = message.sender_chat.id
    else:
        user_id = message.from_user.id
    config = get_user_config(user_id)
    system_prompt_name = config["prompt"]
    if system_prompt_name in SYSTEM_PROMPTS:
        system_prompt = SYSTEM_PROMPTS[system_prompt_name]["text"]
    else:
        await message.reply(
            f"🤝 произошла ошибка при отображении промпта `{system_prompt_name}`\n*для фото*: ```prompt\n{IMAGE_PROMPT}```изменить системный промпт узбекгпт пока что нельзя."
        )
        return
    
    if PROMPT_COMMAND:
        await message.reply(
            f"🤝 *ваш выбранный промпт* `{system_prompt_name}`: ```prompt\n{system_prompt}```\n*для фото*: ```prompt\n{IMAGE_PROMPT}```\nизменить системный промпт узбекгпт пока что нельзя."
        )
    else:
        if SHOW_ACC_MSG:
            await message.reply(
                "🚫 *данный команда отключен в этом боте.* попросите владельца включить🤝"
            )
    return


@router.message(Command("config"))
async def config_handler(message: Message):
    if CONFIG_COMMAND:
        await message.reply(
            f"🤝 *конфиг узбекгпт*:\n`MAX_CONTEXT` = `{MAX_CONTEXT}`\n`MAX_PROMPT` = `{MAX_PROMPT}`\n"
            f"`DEFAULT_MODEL` = `{DEFAULT_MODEL}`\n`IMAGE_MODEL` = `{IMAGE_MODEL}`\n"
            f"`DEFAULT_STREAM` = `{DEFAULT_STREAM}`\n"
            "/settings для изменения настроек!"
        )
    else:
        if SHOW_ACC_MSG:
            await message.reply(
                "🚫 *данный команда отключен в этом боте.* попросите владельца включить🤝"
            )


async def settings_handler(event: Union[Message, CallbackQuery]):
    user_id = (
        event.sender_chat.id
        if isinstance(event, Message) and event.sender_chat
        else event.from_user.id
    )

    config = get_user_config(user_id)
    models_count = sum(len(models) for models in MODELS.values())
    prompts = SYSTEM_PROMPTS | config["prompts"]
    prompts_count = len(prompts)

    if config["stream"] == "native":
        stream_status = "натив"
        stream_cb = "edit"
    elif config["stream"] == "edit":
        stream_status = "редакт"
        stream_cb = "none"
    else:
        stream_status = "net"
        stream_cb = "native"

    if config["call"] == "da":
        call_status = "da"
        call_cb = "net"
    else:
        call_status = "net"
        call_cb = "da"

    if config["notify"] == "da":
        notify_status = "da"
        notify_cb = "net"
    else:
        notify_status = "net"
        notify_cb = "da"

    if config["markdown"] == "new":
        markdown_status = "новый"
        markdown_cb = "old"
    else:
        markdown_status = "старый"
        markdown_cb = "new"

    keyboard = InlineKeyboardMarkup(
        inline_keyboard=[
            [
                InlineKeyboardButton(
                    text=f"модели ({models_count})", callback_data=f"models%{user_id}"
                ),
                InlineKeyboardButton(
                    text=f"промпты ({prompts_count})", callback_data=f"prompts%{user_id}"
                )
            ],
            [
                InlineKeyboardButton(
                    text=f"стрим: {stream_status}",
                    callback_data=f"set%stream%{user_id}%{stream_cb}",
                ),
                InlineKeyboardButton(
                    text=f"отклик: {call_status}",
                    callback_data=f"set%call%{user_id}%{call_cb}",
                )
            ],
            [
                InlineKeyboardButton(
                    text=f"рассылка: {notify_status}",
                    callback_data=f"set%notify%{user_id}%{notify_cb}",
                ),
                InlineKeyboardButton(
                    text=f"маркдаун: {markdown_status}",
                    callback_data=f"set%markdown%{user_id}%{markdown_cb}",
                ),
                                
            ],
            [InlineKeyboardButton(text="💸 донат", callback_data=f"donate%{user_id}")],
            [InlineKeyboardButton(text="🤖 о боте", callback_data=f"about%{user_id}")],
        ]
    )

    text = f"⚡ *алло узбекгпт настройки*\nтекущая модель: `{config.get('model')}`\n" \
        f"текущий промпт: `{prompts[config.get('prompt')]['name']} ({config.get('prompt')[:4]})`"

    if isinstance(event, Message):
        await event.reply(text, reply_markup=keyboard)
    else:
        await event.message.edit_text(text, reply_markup=keyboard)
        await event.answer()


@router.message(Command("settings"))
async def settings_command(message: Message):
    if not SETTINGS_COMMAND:
        if SHOW_ACC_MSG:
            await message.reply(
                "🚫 *данный команда отключен в этом боте.* попросите владельца включить🤝"
            )
        return
    await settings_handler(message)


@router.message(Command("clear"))
async def clear_handler(message: Message):
    if not CLEAR_COMMAND:
        if SHOW_ACC_MSG:
            await message.reply(
                "🚫 *данный команда отключен в этом боте.* попросите владельца включить🤝"
            )
        return
    user_id = message.sender_chat.id if message.sender_chat else message.from_user.id

    user_contexts[user_id] = []
    try:
        await message.reply("контекст очищен. ✅")
    except TelegramForbiddenError as e:
        user_contexts[user_id] = []
    except Exception as e:
        print(f"{RED} -- {e}{RESET}")

        
@router.message(Command("markpidor"))
async def alo(message: Message):
    await message.reply_rich(InputRichMessage(markdown="# ало"))
    return