Бот для капчи в чатах
Roman Sergienko
2026-10-10 cf4285e1e0ac8e76dc02729e64beb7cb28511fa1
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
import asyncio
import re
from typing import Optional, Tuple
 
from aiogram import types
from aiogram.filters import Command, CommandObject
 
import db
from cfg import OWNER_ID, FULL_PERMS, NO_PERMS, DEF_WARN_EXPIRE, bot, dp, logger
from perms import P_BAN, P_MUTE, P_UNBAN, P_UNMUTE, P_UNWARN, P_WARN, check_perm, member_status
from util import fmt_dur, mention, msg_target, now_ts, parse_dur, refuse_phrase, resolve_usr
 
# Шаблон токена длительности: 10m, 2h, 7d, '-' (бессрочно).
DUR_RE = re.compile(r"^(\d+[smhdwSMHDW]?|-|forever|perm|permanent)$", re.IGNORECASE)
 
NOT_ENOUGH = "Недостаточно прав."
OWNER_BLOCK = "Владельца бота наказать нельзя."
 
 
# --- Ядро действий ---
 
async def apply_mute(chat_id: int, user_id: int, name: str, until: Optional[int], admin_id: int, reason: str) -> bool:
    ts = now_ts()
    try:
        await bot.restrict_chat_member(chat_id, user_id, permissions=NO_PERMS, until_date=until)
    except Exception as e:
        logger.error("mute failed chat=%s user=%s: %s", chat_id, user_id, e)
        return False
    await db.add_punish(chat_id, user_id, "mute", admin_id, reason, ts, until)
    await db.add_log(chat_id, admin_id, user_id, "mute", reason, ts)
    await _notice(chat_id, f"Пользователь {mention(user_id, name)} замучен на {fmt_dur(until)}. Причина: {reason or '-'}")
    return True
 
 
async def apply_ban(chat_id: int, user_id: int, name: str, until: Optional[int], admin_id: int, reason: str) -> bool:
    ts = now_ts()
    try:
        await bot.ban_chat_member(chat_id, user_id)
    except Exception as e:
        logger.error("ban failed chat=%s user=%s: %s", chat_id, user_id, e)
        return False
    await db.add_punish(chat_id, user_id, "ban", admin_id, reason, ts, until)
    await db.add_log(chat_id, admin_id, user_id, "ban", reason, ts)
    await _notice(chat_id, f"Пользователь {mention(user_id, name)} забанен на {fmt_dur(until)}. Причина: {reason or '-'}")
    return True
 
 
async def apply_unmute(chat_id: int, user_id: int, name: str, admin_id: int, reason: str) -> bool:
    ts = now_ts()
    try:
        await bot.restrict_chat_member(chat_id, user_id, permissions=FULL_PERMS)
    except Exception as e:
        logger.error("unmute failed chat=%s user=%s: %s", chat_id, user_id, e)
        return False
    await db.end_punish(chat_id, user_id, "mute")
    await db.add_log(chat_id, admin_id, user_id, "unmute", reason, ts)
    await _notice(chat_id, f"С пользователя {mention(user_id, name)} снят мут.")
    return True
 
 
async def apply_unban(chat_id: int, user_id: int, name: str, admin_id: int, reason: str) -> bool:
    ts = now_ts()
    try:
        await bot.unban_chat_member(chat_id, user_id, only_if_banned=True)
    except Exception as e:
        logger.error("unban failed chat=%s user=%s: %s", chat_id, user_id, e)
        return False
    await db.end_punish(chat_id, user_id, "ban")
    await db.add_log(chat_id, admin_id, user_id, "unban", reason, ts)
    await _notice(chat_id, f"Пользователь {mention(user_id, name)} разбанен.")
    return True
 
 
async def apply_warn(chat_id: int, user_id: int, name: str, admin_id: int, reason: str) -> Tuple[int, int, bool]:
    # Возвращает (текущее число варнов, лимит, сработало ли наказание).
    ts = now_ts()
    cfg = await db.get_chat_cfg(chat_id)
    await db.add_warn(chat_id, user_id, admin_id, reason, ts, DEF_WARN_EXPIRE)
    count = await db.cnt_warns(chat_id, user_id, ts)
    await db.add_log(chat_id, admin_id, user_id, "warn", reason, ts)
 
    if count >= cfg["warn_limit"]:
        # Достигнут лимит: применяем настроенное наказание и обнуляем варны.
        dur = cfg["warn_duration"] or None
        if cfg["warn_action"] == "ban":
            await apply_ban(chat_id, user_id, name, dur, admin_id, f"Лимит варнов ({count})")
        else:
            await apply_mute(chat_id, user_id, name, dur, admin_id, f"Лимит варнов ({count})")
        await db.clr_warns(chat_id, user_id)
        return count, cfg["warn_limit"], True
 
    await _notice(chat_id, f"{mention(user_id, name)} получил предупреждение ({count}/{cfg['warn_limit']}). Причина: {reason or '-'}")
    return count, cfg["warn_limit"], False
 
 
async def apply_unwarn(chat_id: int, user_id: int, name: str, admin_id: int) -> bool:
    ok = await db.del_last_warn(chat_id, user_id)
    ts = now_ts()
    await db.add_log(chat_id, admin_id, user_id, "unwarn", "", ts)
    if ok:
        await _notice(chat_id, f"С {mention(user_id, name)} снято одно предупреждение.")
    return ok
 
 
async def _notice(chat_id: int, text: str) -> None:
    try:
        await bot.send_message(chat_id, text, parse_mode="HTML")
    except Exception as e:
        logger.warning("notice failed chat=%s: %s", chat_id, e)
 
 
# --- Разбор аргументов ---
 
async def _target(message: types.Message, command: CommandObject):
    # Возвращает (user_id, name, rest_args) либо (None, text_ошибки, None).
    args = list((command.args or "").split())
    rep = msg_target(message)
    if rep:
        return rep[0], rep[1], args
    if not args:
        return None, "Укажите цель: ответом на сообщение или @username/ID.", None
    res = await resolve_usr(bot, args[0])
    if not res:
        return None, "Не удалось определить пользователя.", None
    return res[0], res[1], args[1:]
 
 
def _dur_reason(rest, default: Optional[int] = None) -> Tuple[Optional[int], str]:
    if rest and DUR_RE.match(rest[0]):
        try:
            dur = parse_dur(rest[0])
        except ValueError:
            dur = default
        return dur, " ".join(rest[1:])
    return default, " ".join(rest)
 
 
async def _guard(message: types.Message, perm: str, target_id: int) -> bool:
    if message.from_user is None:
        return False
    chat_id = message.chat.id
    actor = message.from_user.id
    if target_id == OWNER_ID:
        await message.reply(f"{OWNER_BLOCK} {refuse_phrase()}")
        return False
    if target_id == actor:
        await message.reply("Нельзя применить это к себе.")
        return False
    if await member_status(chat_id, target_id) == "creator":
        await message.reply("Создателя чата трогать нельзя.")
        return False
    if not await check_perm(chat_id, actor, perm):
        await message.reply(NOT_ENOUGH)
        return False
    return True
 
 
async def _delete_cmd(message: types.Message) -> None:
    try:
        await message.delete()
    except Exception:
        pass
 
 
# --- Команды ---
 
@dp.message(Command("aban"))
async def cmd_aban(message: types.Message, command: CommandObject) -> None:
    target_id, name, rest = await _target(message, command)
    if target_id is None:
        await message.reply(name)
        return
    if not await _guard(message, P_BAN, target_id):
        return
    dur, reason = _dur_reason(rest)
    ok = await apply_ban(message.chat.id, target_id, name, dur, message.from_user.id, reason)
    if not ok:
        await message.reply("Не удалось забанить (проверьте права бота).")
 
 
@dp.message(Command("amute"))
async def cmd_amute(message: types.Message, command: CommandObject) -> None:
    target_id, name, rest = await _target(message, command)
    if target_id is None:
        await message.reply(name)
        return
    if not await _guard(message, P_MUTE, target_id):
        return
    dur, reason = _dur_reason(rest)
    ok = await apply_mute(message.chat.id, target_id, name, dur, message.from_user.id, reason)
    if not ok:
        await message.reply("Не удалось замутить (проверьте права бота).")
 
 
@dp.message(Command("awarn"))
async def cmd_awarn(message: types.Message, command: CommandObject) -> None:
    target_id, name, rest = await _target(message, command)
    if target_id is None:
        await message.reply(name)
        return
    if not await _guard(message, P_WARN, target_id):
        return
    reason = " ".join(rest)
    await apply_warn(message.chat.id, target_id, name, message.from_user.id, reason)
 
 
@dp.message(Command("aunban"))
async def cmd_aunban(message: types.Message, command: CommandObject) -> None:
    target_id, name, rest = await _target(message, command)
    if target_id is None:
        await message.reply(name)
        return
    if not await check_perm(message.chat.id, message.from_user.id, P_UNBAN):
        await message.reply(NOT_ENOUGH)
        return
    if not await apply_unban(message.chat.id, target_id, name, message.from_user.id, " ".join(rest)):
        await message.reply("Не удалось разбанить.")
 
 
@dp.message(Command("aunmute"))
async def cmd_aunmute(message: types.Message, command: CommandObject) -> None:
    target_id, name, rest = await _target(message, command)
    if target_id is None:
        await message.reply(name)
        return
    if not await check_perm(message.chat.id, message.from_user.id, P_UNMUTE):
        await message.reply(NOT_ENOUGH)
        return
    if not await apply_unmute(message.chat.id, target_id, name, message.from_user.id, " ".join(rest)):
        await message.reply("Не удалось снять мут.")
 
 
@dp.message(Command("aunwarn"))
async def cmd_aunwarn(message: types.Message, command: CommandObject) -> None:
    target_id, name, rest = await _target(message, command)
    if target_id is None:
        await message.reply(name)
        return
    if not await check_perm(message.chat.id, message.from_user.id, P_UNWARN):
        await message.reply(NOT_ENOUGH)
        return
    await apply_unwarn(message.chat.id, target_id, name, message.from_user.id)
 
 
@dp.message(Command("awarns"))
async def cmd_awarns(message: types.Message, command: CommandObject) -> None:
    target_id, name, rest = await _target(message, command)
    if target_id is None:
        await message.reply(name)
        return
    rows = await db.list_warns(message.chat.id, target_id)
    ts = now_ts()
    active = [w for w in rows if not w["expires_at"] or w["expires_at"] > ts]
    if not active:
        await message.reply(f"У {mention(target_id, name)} нет активных предупреждений.", parse_mode="HTML")
        return
    lines = [f"Предупреждения {mention(target_id, name)}: {len(active)}"]
    for w in active:
        lines.append(f"- {w['reason'] or 'без причины'}")
    await message.reply("\n".join(lines), parse_mode="HTML")
 
 
# --- Фоновые задачи: уборка варнов и автоснятие временных наказаний ---
 
async def _bg_tick() -> None:
    ts = now_ts()
    await db.exp_warns(ts)
    for row in await db.due_unbans(ts):
        chat_id = row["chat_id"]
        user_id = row["user_id"]
        try:
            if row["kind"] == "ban":
                await bot.unban_chat_member(chat_id, user_id, only_if_banned=True)
            else:
                await bot.restrict_chat_member(chat_id, user_id, permissions=FULL_PERMS)
        except Exception as e:
            logger.warning("auto-release %s chat=%s user=%s: %s", row["kind"], chat_id, user_id, e)
        await db.end_punish(chat_id, user_id, row["kind"])
        await db.add_log(chat_id, 0, user_id, "auto-" + row["kind"], "истёк срок", ts)
 
 
async def bg_loop() -> None:
    while True:
        try:
            await _bg_tick()
        except Exception as e:
            logger.error("bg_loop: %s", e)
        await asyncio.sleep(60)
 
 
def start_bg() -> asyncio.Task:
    return asyncio.create_task(bg_loop())