Бот для капчи в чатах
Roman Sergienko
8 hours ago c80fb18220a339f2b1a218fd1b5886e0a41725f6
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
from aiogram import F, types
from aiogram.filters import Command, CommandObject
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo
 
import db
import cfg
import perms as pm
from cfg import VERSION, bot, dp
from perms import P_CFG, P_PERMS, PERM_LABELS, check_perm, member_status
from util import mention, msg_target, now_ts, resolve_usr
 
HELP_TEXT = (
    "Команды бота:\n"
    "/help - этот список\n"
    "/version - версия бота\n"
    "/stats - статистика чата\n"
    "/areport <текст> - жалоба администрации (можно ответом на сообщение)\n"
    "\n"
    "Для администраторов:\n"
    "/panel - открыть панель управления этим чатом (Mini App)\n"
    "/config - настройки капчи\n"
    "/config <кнопки> <секунды> <попытки> - изменить капчу\n"
    "/warncfg <лимит> <mute|ban> <время> - настроить систему варнов\n"
    "/floodcfg - настройки антифлуда и фильтра ссылок\n"
    "/aperm - права администраторов\n"
    "/aperm @user <право> on|off - изменить право\n"
    "/alarm (/achtung, /uwaga) - включить режим тревоги\n"
    "/unalarm (/unachtung, /unuwaga) - выключить режим тревоги\n"
    "\n"
    "Модерация (ответом на сообщение или @username/ID):\n"
    "/aban [время] [причина] - бан\n"
    "/amute [время] [причина] - мут\n"
    "/awarn [причина] - предупреждение\n"
    "/aunban [причина] - снять бан\n"
    "/aunmute [причина] - снять мут\n"
    "/aunwarn - снять одно предупреждение\n"
    "/awarns - список предупреждений\n"
    "\n"
    "Время: 30s, 10m, 2h, 7d, без времени или '-' - бессрочно."
)
 
 
async def _is_staff(chat_id: int, user_id: int) -> bool:
    # Владелец бота имеет доступ везде, независимо от статуса в чате.
    if user_id == cfg.OWNER_ID:
        return True
    st = await member_status(chat_id, user_id)
    return st in ("administrator", "creator")
 
 
def _cfg_text(cfg: dict) -> str:
    action = "бан" if cfg["warn_action"] == "ban" else "мут"
    return (
        "Текущие настройки:\n"
        f"Кнопок капчи: {cfg['btn_count']}\n"
        f"Таймаут капчи: {cfg['timeout']} сек.\n"
        f"Попыток до наказания: {cfg['max_attempts']}\n"
        f"Лимит варнов: {cfg['warn_limit']}\n"
        f"Действие при лимите: {action}\n"
        f"Длительность наказания: {cfg['warn_duration']} сек.\n"
        f"Антифлуд: {'вкл' if cfg['flood_enabled'] else 'выкл'} "
        f"({cfg['flood_count']} сообщ. / {cfg['flood_window']} сек, мут {cfg['flood_mute']} сек)\n"
        f"Фильтр ссылок: {'вкл' if cfg['no_links'] else 'выкл'}"
    )
 
 
FLOOD_KEYS = {
    "count": "flood_count",
    "window": "flood_window",
    "mute": "flood_mute",
    "alarmmute": "flood_alarm_mute",
    "newdays": "new_member_days",
    "slow": "slow_mode",
}
 
 
@dp.message(Command("start"))
async def cmd_start(message: types.Message, command: CommandObject) -> None:
    if message.chat.type == "private" and message.from_user is not None:
        # Запоминаем, что боту можно писать в ЛС (для уведомлений тревоги).
        await db.add_dm(message.from_user.id, now_ts())
 
        # Обработка параметра start для panel_{chat_id}
        args = (command.args or "").strip()
        if args and args.startswith("panel_"):
            if not cfg.WEB_BASE_URL:
                await message.answer("Панель недоступна.")
                return
            try:
                chat_id = int(args[6:])
                # Проверяем права на этот чат
                if not await check_perm(chat_id, message.from_user.id, P_CFG):
                    await message.answer("У вас нет доступа к панели этого чата.")
                    return
                keyboard = InlineKeyboardMarkup(inline_keyboard=[[
                    InlineKeyboardButton(
                        text="Открыть панель",
                        web_app=WebAppInfo(url=f"{cfg.WEB_BASE_URL}/miniapp?chat_id={chat_id}"),
                    )
                ]])
                await message.answer("Панель управления чатом:", reply_markup=keyboard)
                return
            except ValueError:
                pass
 
        # Стандартный старт
        keyboard = None
        if cfg.WEB_BASE_URL:
            keyboard = InlineKeyboardMarkup(inline_keyboard=[[
                InlineKeyboardButton(
                    text="Открыть панель",
                    web_app=WebAppInfo(url=f"{cfg.WEB_BASE_URL}/miniapp"),
                )
            ]])
        await message.answer(
            "Привет! Я Amadeus. Теперь сюда будут приходить уведомления о тревоге. "
            "Добавь меня в чат и выдай права администратора.",
            reply_markup=keyboard,
        )
    else:
        await message.answer("Привет! Список команд: /help")
 
 
@dp.message(Command("panel"))
async def cmd_panel(message: types.Message) -> None:
    if message.from_user is None or message.chat.type == "private":
        return
    if not cfg.WEB_BASE_URL:
        await message.answer("Панель недоступна.")
        return
    if not await check_perm(message.chat.id, message.from_user.id, P_CFG):
        await message.answer("У вас нет доступа к панели.")
        return
    # Формируем ссылку на открытие бота с параметром panel_{chat_id}
    bot_username = (await bot.get_me()).username
    panel_link = f"https://t.me/{bot_username}?start=panel_{message.chat.id}"
    keyboard = InlineKeyboardMarkup(inline_keyboard=[[
        InlineKeyboardButton(
            text="Открыть панель",
            url=panel_link,
        )
    ]])
    await message.answer("Панель управления чатом:", reply_markup=keyboard)
 
 
@dp.message(Command("floodcfg"))
async def cmd_floodcfg(message: types.Message, command: CommandObject) -> None:
    if message.from_user is None:
        return
    chat_id = message.chat.id
    if not await check_perm(chat_id, message.from_user.id, P_CFG):
        return
    cfg = await db.get_chat_cfg(chat_id)
    args = (command.args or "").split()
 
    if not args:
        await message.answer(
            f"Антифлуд: {'вкл' if cfg['flood_enabled'] else 'выкл'}\n"
            f"Порог: {cfg['flood_count']} за {cfg['flood_window']} сек\n"
            f"Мут за флуд: {cfg['flood_mute']} сек\n"
            f"Мут в тревоге (новым): {cfg['flood_alarm_mute']} сек\n"
            f"Новый участник до: {cfg['new_member_days']} дн.\n"
            f"Фильтр ссылок: {'вкл' if cfg['no_links'] else 'выкл'}\n"
            f"Медленный режим в тревоге: {cfg['slow_mode']} сек\n\n"
            "Изменение: /floodcfg on|off | links on|off | count|window|mute|alarmmute|newdays|slow <n>"
        )
        return
 
    cmd = args[0].lower()
    if cmd in ("on", "off"):
        await db.save_chat_cfg(chat_id, flood_enabled=1 if cmd == "on" else 0)
        await message.answer("Антифлуд включён." if cmd == "on" else "Антифлуд выключен.")
        return
    if cmd == "links" and len(args) == 2:
        val = 1 if args[1].lower() in ("on", "1", "вкл") else 0
        await db.save_chat_cfg(chat_id, no_links=val)
        await message.answer("Фильтр ссылок включён." if val else "Фильтр ссылок выключен.")
        return
    if cmd in FLOOD_KEYS and len(args) == 2:
        try:
            val = int(args[1])
            if val < 0:
                raise ValueError
        except ValueError:
            await message.answer("Нужно целое неотрицательное число.")
            return
        await db.save_chat_cfg(chat_id, **{FLOOD_KEYS[cmd]: val})
        await message.answer("Значение обновлено.")
        return
    await message.answer("Неизвестный параметр. Смотрите /floodcfg без аргументов.")
 
 
@dp.message(Command("help"))
async def cmd_help(message: types.Message) -> None:
    if message.from_user is None:
        return
    text = HELP_TEXT
    # Текущие настройки чата показываем только администраторам и владельцу.
    if await _is_staff(message.chat.id, message.from_user.id):
        cfg = await db.get_chat_cfg(message.chat.id)
        text += "\n\n" + _cfg_text(cfg)
    await message.answer(text)
 
 
@dp.message(Command("version"))
async def cmd_version(message: types.Message) -> None:
    if message.from_user is None:
        return
    if not await _is_staff(message.chat.id, message.from_user.id):
        return
    username = f"@{cfg.BOT_USERNAME}" if cfg.BOT_USERNAME else "неизвестен"
    await message.answer(
        f"Amadeus\nВерсия: {VERSION}\nБот: {username}\nID: {cfg.BOT_ID}"
    )
 
 
@dp.message(Command("config"))
async def cmd_cfg(message: types.Message, command: CommandObject) -> None:
    if message.from_user is None:
        return
    if not await check_perm(message.chat.id, message.from_user.id, P_CFG):
        return
 
    if not command.args:
        cfg = await db.get_chat_cfg(message.chat.id)
        await message.answer(_cfg_text(cfg) + "\n\nИзменение: /config <кнопки> <секунды> <попытки>")
        return
 
    try:
        args = command.args.split()
        if len(args) != 3:
            raise ValueError
        btn_count, timeout, max_attempts = (int(x) for x in args)
    except ValueError:
        await message.answer("Ошибка формата. Использование: /config 4 60 3")
        return
 
    if not (1 <= btn_count <= 9) or not (5 <= timeout <= 300) or not (1 <= max_attempts <= 10):
        await message.answer("Ошибка диапазона: кнопки 1-9, таймаут 5-300, попытки 1-10")
        return
 
    await db.save_chat_cfg(
        message.chat.id, btn_count=btn_count, timeout=timeout, max_attempts=max_attempts
    )
    await message.answer("Настройки капчи обновлены.")
 
 
@dp.message(Command("warncfg"))
async def cmd_warncfg(message: types.Message, command: CommandObject) -> None:
    if message.from_user is None:
        return
    if not await check_perm(message.chat.id, message.from_user.id, P_CFG):
        return
    if not command.args:
        cfg = await db.get_chat_cfg(message.chat.id)
        await message.answer("Использование: /warncfg <лимит> <mute|ban> <секунды>\n\n" + _cfg_text(cfg))
        return
    try:
        args = command.args.split()
        if len(args) != 3:
            raise ValueError
        limit = int(args[0])
        action = args[1].lower()
        duration = int(args[2])
    except ValueError:
        await message.answer("Ошибка формата. Использование: /warncfg 3 mute 3600")
        return
    if action not in ("mute", "ban"):
        await message.answer("Действие должно быть mute или ban.")
        return
    if not (1 <= limit <= 10) or not (0 <= duration <= 2592000):
        await message.answer("Ошибка диапазона: лимит 1-10, длительность 0-2592000 сек.")
        return
    await db.save_chat_cfg(
        message.chat.id, warn_limit=limit, warn_action=action, warn_duration=duration
    )
    await message.answer("Настройки варнов обновлены.")
 
 
@dp.message(Command("aperm"))
async def cmd_aperm(message: types.Message, command: CommandObject) -> None:
    if message.from_user is None:
        return
    chat_id = message.chat.id
    if not await check_perm(chat_id, message.from_user.id, P_PERMS):
        return
 
    args = (command.args or "").split()
    if not args or args[0].lower() in ("list", "ls"):
        rows = await db.list_perm_rows(chat_id)
        if not rows:
            await message.answer(
                "Переопределений прав нет. Админам доступна модерация по умолчанию.\n"
                "Изменение: /aperm @user <право> on|off\n"
                "Права: " + ", ".join(PERM_LABELS)
            )
            return
        lines = ["Переопределения прав:"]
        for r in rows:
            state = "on" if r["allow"] else "off"
            lines.append(f"- {r['user_id']}: {PERM_LABELS.get(r['perm'], r['perm'])} = {state}")
        await message.answer("\n".join(lines))
        return
 
    if len(args) != 3:
        await message.answer("Использование: /aperm @user <право> on|off")
        return
    target = await resolve_usr(bot, args[0])
    if not target:
        await message.answer("Не удалось определить пользователя.")
        return
    perm = args[1].lower()
    if perm not in PERM_LABELS:
        await message.answer("Неизвестное право. Доступно: " + ", ".join(PERM_LABELS))
        return
    state = args[2].lower()
    if state not in ("on", "off", "1", "0", "вкл", "выкл"):
        await message.answer("Состояние должно быть on или off.")
        return
    allow = state in ("on", "1", "вкл")
    ok, text = await pm.set_perm(chat_id, message.from_user.id, target[0], perm, allow)
    await message.answer(text)
 
 
@dp.message(F.text)
async def chk_nullpo(message: types.Message) -> None:
    # Реакция на упоминания Nullpo в любом регистре.
    if not message.text:
        return
    text_lower = message.text.lower()
    variants = ("nullpo", "нулпо", "нуллпо", "nulpo")
    if any(variant in text_lower for variant in variants):
        try:
            await message.reply("Gah!")
        except Exception:
            pass