Download app.py from kikl/kookbot: direct link, hf CLI and curl.
- Browser
- Download file 34 kB
-
https://huggingface.co/spaces/kikl/kookbot/resolve/main/app.py
- Command line
-
hf download hf://spaces/kikl/kookbot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/kikl/kookbot/resolve/main/app.py
34 kB
| import asyncio | |
| import json | |
| import math | |
| import os | |
| import re | |
| import signal | |
| import time | |
| import logging | |
| import aiohttp | |
| from aiohttp import web | |
| from khl import Bot, Message, Event, EventTypes, MessageTypes, api | |
| from khl.card import CardMessage | |
| from core.config import (BOT_TOKEN, CMD_COOLDOWN, USER_PAGE_SIZE, logger, | |
| SELF_PING_URL, SELF_PING_INTERVAL) | |
| from core.database import db | |
| from services import finance, checkin | |
| from utils import card_builder as cb | |
| from utils import permission, timeutil | |
| from utils.money import parse_amount, fmt, MAX_AMOUNT_CENTS | |
| from utils.rate_limiter import rate_limiter | |
| from utils.card_builder import BTN_CHECKIN, BTN_CHECKOUT | |
| from utils import khl_patch | |
| # 必须在 bot.start() 之前打——khl.py 的 websocket 接收循环遇到异常会静默死掉, | |
| # 打完补丁才会退避重试,且连接生命周期会记进日志。 | |
| khl_patch.apply() | |
| bot = Bot(token=BOT_TOKEN) | |
| _start_time = time.monotonic() | |
| # 健康检查用的标记:KOOK 的 HTTP API 是否还能调通 | |
| _api_ok = True | |
| _api_checked_at = 0.0 | |
| # ============================================================ | |
| # 工具 | |
| # ============================================================ | |
| def _display_name(user) -> str: | |
| for attr in ("nickname", "username"): | |
| value = getattr(user, attr, None) | |
| if value: | |
| return str(value) | |
| return str(getattr(user, "id", "")) | |
| async def reply_card(msg: Message, card): | |
| """发卡片。引用发送失败时自动降级为普通消息。 | |
| KOOK 会以 40000「引用不存在或者你没有权限操作」拒绝带引用的发送。 | |
| 这时必须退化成不引用再发一次 —— 记账/打卡**已经生效了**,用户收不到 | |
| 结果就可能重发命令,那才是真正的麻烦(账已动、人不知)。 | |
| """ | |
| cm = CardMessage(card) | |
| try: | |
| await msg.reply(cm) | |
| except Exception as e: | |
| logger.warning("[Reply] 引用发送失败(%s),改为不引用重发", e) | |
| try: | |
| await msg.reply(cm, use_quote=False) | |
| except Exception as e2: | |
| logger.error("[Reply] 不引用重发也失败: %s", e2) | |
| async def touch(msg: Message): | |
| """记录/更新发言者,这样后续按昵称查找时能找到他。""" | |
| try: | |
| await finance.register(str(msg.author.id), _display_name(msg.author)) | |
| except Exception as e: | |
| logger.warning("[Touch] 注册用户失败: %s", e) | |
| async def gate(msg: Message) -> bool: | |
| """每个命令的第一道关:检查使用资格 + 登记用户。 | |
| 客户要求「只有在本服务器有身份牌的人可以用,其他都不可以」。 | |
| 未配置 MEMBER_ROLE_IDS 时不限制(见 permission.is_member)。 | |
| 不通过时回复提示并返回 False,调用方直接 return。 | |
| """ | |
| if not permission.is_member(msg.author): | |
| logger.info("[Gate] 拒绝无身份牌的用户 %s(%s)", | |
| _display_name(msg.author), msg.author.id) | |
| await reply_card(msg, cb.build_error( | |
| "❌ 你没有使用权限\n" | |
| "需要在本服务器拥有指定身份组才能使用这个机器人。" | |
| )) | |
| return False | |
| await touch(msg) | |
| return True | |
| def throttled(msg: Message, key: str) -> bool: | |
| limited, remaining = rate_limiter.check_limit(str(msg.author.id), key, CMD_COOLDOWN) | |
| if limited: | |
| logger.info("[RateLimit] %s 触发限流 %s", msg.author.id, key) | |
| return limited | |
| async def search_members(guild_id: str, keyword: str): | |
| """在服务器成员里搜昵称/用户名,返回 [{'id','name','username'}, ...]。 | |
| KOOK 的 search 是**子串匹配**(在用户名或昵称里找),所以打不全也能搜到 | |
| —— 「轰」能搜出「轰仔210」。khl.py 没封装这个接口,直接走底层请求。 | |
| 这是「不用对方先发一次 /查询」的关键:成员列表里有所有服务器成员, | |
| 不限于用过机器人的。 | |
| """ | |
| try: | |
| data = await bot.client.gate.request( | |
| "GET", "guild/user-list", | |
| params={"guild_id": guild_id, "search": keyword, "page_size": 20}, | |
| ) | |
| except Exception as e: | |
| logger.warning("[Resolve] 搜服务器成员失败: %r", e) | |
| return [] | |
| items = (data or {}).get("items") or [] | |
| out = [] | |
| for u in items: | |
| uid = str(u.get("id") or "") | |
| if not uid: | |
| continue | |
| out.append({ | |
| "id": uid, | |
| "name": u.get("nickname") or u.get("username") or uid, | |
| "username": u.get("username") or "", | |
| }) | |
| return out | |
| async def resolve_target(msg: Message, token: str, create_if_missing: bool = False): | |
| """把命令参数解析成用户,返回 (user_id, name, 候选列表)。 | |
| 顺序: | |
| 1. 本地缓存(快,覆盖用过机器人的人) | |
| 2. KOOK 服务器成员搜索(覆盖没用过机器人的人) | |
| 3. create_if_missing 时,仍然找不到就**当场按名字建档** | |
| 第 3 步是客户明确要求的:`/汽修+ 轰轰 1000000` 要能直接用,不要先绑定、 | |
| 不要任何前置步骤。服务器人数固定,打错字建出垃圾账户的风险可接受 —— | |
| 代价是**不区分"打错字"和"新名字"**,两者都会建号。 | |
| 命中唯一结果就顺手写进缓存,下次第一层就能查到。 | |
| 失败时返回 (None, None, 候选列表);候选为空即彻底找不到。 | |
| """ | |
| uid, name = await finance.resolve_user(token) | |
| if uid: | |
| return uid, name, [] | |
| candidates = [] | |
| guild_id = (getattr(msg, "extra", None) or {}).get("guild_id") | |
| if guild_id: | |
| members = await search_members(guild_id, token) | |
| # 先看有没有精确匹配的(昵称或用户名完全一致,忽略大小写) | |
| low = token.strip().lower() | |
| exact = [m for m in members | |
| if m["name"].lower() == low or m["username"].lower() == low] | |
| if len(exact) == 1: | |
| m = exact[0] | |
| await finance.register(m["id"], m["name"]) # 写进缓存 | |
| return m["id"], m["name"], [] | |
| if len(members) == 1: | |
| m = members[0] | |
| await finance.register(m["id"], m["name"]) | |
| return m["id"], m["name"], [] | |
| if len(members) > 1: | |
| # 多个模糊结果 → 交给调用方列出来让用户挑 | |
| return None, None, [m["name"] for m in members[:8]] | |
| if create_if_missing: | |
| # 用名字本身当 _id。真实 KOOK 用户 id 全是数字,不会撞。 | |
| await finance.register(token, token) | |
| logger.info("[Resolve] 未见过的名字,按名字建档: %s", token) | |
| return token, token, [] | |
| return None, None, candidates | |
| def not_found_msg(token: str, candidates: list) -> str: | |
| """查不到用户时的提示。有候选就列出来,别让用户卡在死胡同里。""" | |
| if candidates: | |
| picks = "、".join(f"`{c}`" for c in candidates) | |
| return f"❌ 「{token}」匹配到多个人,请写完整昵称:\n{picks}" | |
| return (f"❌ 找不到用户「{token}」\n" | |
| "请确认写法与对方在服务器里的昵称一致") | |
| def parse_int_arg(args, default: int, maximum: int) -> int: | |
| """从命令参数里取一个正整数,非法或超范围就夹到 [1, maximum]。 | |
| /打卡记录 用天数上限 90,/用户列表 用页码上限(总页数)。 | |
| """ | |
| if args and str(args[0]).isdigit(): | |
| return max(1, min(maximum, int(args[0]))) | |
| return default | |
| # ============================================================ | |
| # 记账命令 | |
| # ============================================================ | |
| async def _do_adjust(msg: Message, args, shop: str, is_add: bool, usage: str, | |
| require_admin: bool = True): | |
| """记账的统一入口。 | |
| require_admin=False 用于 /汽修± —— 客户要求店铺命令放开给所有人, | |
| 只有 /充值 限管理员。 | |
| """ | |
| if require_admin and not permission.is_admin(msg.author): | |
| if not permission.admin_configured(): | |
| return await reply_card(msg, cb.build_error( | |
| "❌ 尚未配置管理员白名单,写操作已全部禁用。\n" | |
| "请在 Space 的 Secrets 里设置 `ADMIN_ROLE_IDS` 或 `ADMIN_USER_IDS` 后重启。" | |
| )) | |
| return await reply_card(msg, cb.build_error("❌ 你没有权限执行该操作")) | |
| if len(args) < 2: | |
| return await reply_card(msg, cb.build_error(f"用法:`{usage}`")) | |
| target_token, amount_raw = args[0], args[1] | |
| # 不支持 @ 提及(客户反馈 @ 不好用)。先查本地缓存,再搜服务器成员, | |
| # 都找不到就按名字当场建档 —— 客户要求写操作零摩擦,不要前置绑定。 | |
| uid, name, candidates = await resolve_target(msg, target_token, | |
| create_if_missing=True) | |
| if not uid: | |
| return await reply_card(msg, cb.build_error( | |
| not_found_msg(target_token, candidates))) | |
| cents = parse_amount(amount_raw) | |
| if cents is None: | |
| limit = fmt(MAX_AMOUNT_CENTS).lstrip("¥") | |
| return await reply_card(msg, cb.build_error( | |
| f"❌ 金额不合法:需为正数,最多两位小数(上限 {limit})" | |
| )) | |
| delta = cents if is_add else -cents | |
| shop_label = {"admin": "管理员", "points": "积分", | |
| "tattoo": "纹身店", "repair": "汽修店"}.get(shop, shop) | |
| # 记下这次处理的入口和消息 id —— 万一又出重复,日志里能直接看出 | |
| # _do_adjust 被调了几次、msg_id 是否相同 | |
| logger.info("[Adjust] 处理 msg_id=%s shop=%s uid=%s delta=%s", | |
| msg.id, shop, uid, delta) | |
| try: | |
| balance = await finance.adjust(uid, name, delta, shop, | |
| str(msg.author.id), idem_key=msg.id) | |
| except finance.InsufficientBalance as e: | |
| return await reply_card(msg, cb.build_error( | |
| f"❌ 余额不足\n{name} 当前余额 {fmt(e.args[0])},本次需扣 {fmt(cents)}" | |
| )) | |
| except Exception as e: | |
| logger.error("[Adjust] 异常: %s", e, exc_info=True) | |
| return await reply_card(msg, cb.build_error("❌ 记账失败,请稍后重试")) | |
| # 积分命令说「增加/扣除」,充值命令说「充值/扣款」—— 用词跟命令名对齐 | |
| verb = ("充值" if is_add else "扣款") if shop == "admin" \ | |
| else ("增加" if is_add else "扣除") | |
| await reply_card(msg, cb.build_adjust_card(shop_label, name, cents, | |
| balance, is_add, verb)) | |
| async def cmd_recharge(msg: Message, *args): | |
| if not await gate(msg): | |
| return | |
| await _do_adjust(msg, args, "admin", True, "/充值 用户名 金额") | |
| # 加/扣积分对所有人开放(参照客户给的那个机器人:加积分、扣积分都没标管理员)。 | |
| # 只有 /充值 仍限管理员 —— 客户明确要求保留这个受控入口。 | |
| async def cmd_add_points(msg: Message, *args): | |
| if not await gate(msg): | |
| return | |
| await _do_adjust(msg, args, "points", True, "/加积分 用户名 数量", | |
| require_admin=False) | |
| async def cmd_sub_points(msg: Message, *args): | |
| if not await gate(msg): | |
| return | |
| await _do_adjust(msg, args, "points", False, "/扣积分 用户名 数量", | |
| require_admin=False) | |
| # 快捷写法:/用户名+金额、/用户名-金额。整条消息一个 token(无空格), | |
| # 所以必须用正则匹配 —— khl.py 的默认分词器只会把它当成一个不认识的名字。 | |
| _QUICK_RE = re.compile(r"^/(?P<name>.+?)(?P<op>[+\-])(?P<amount>\d+(?:\.\d+)?)$") | |
| # 长得像日期/路径的一律不当用户名,避免 /2026-09-21 这种被误判 | |
| _NOT_A_NAME_RE = re.compile(r"^[\d\-./:*_\s]+$") | |
| async def cmd_quick_adjust(msg: Message): | |
| """`/轰轰+500000` 这种连写形式。 | |
| 正则只用来判断「这条消息像不像快捷加减」,真正的取值在函数体里自己做, | |
| 这样不依赖 khl 把正则分组映射到处理函数参数的规则。 | |
| """ | |
| m = _QUICK_RE.match((msg.content or "").strip()) | |
| if not m: | |
| return | |
| name = m.group("name").strip() | |
| if not name or _NOT_A_NAME_RE.match(name): | |
| return # 不是名字,是日期之类的东西,交给别的命令/忽略 | |
| if not await gate(msg): | |
| return | |
| is_add = m.group("op") == "+" | |
| await _do_adjust(msg, [name, m.group("amount")], "points", is_add, | |
| f"/{name}{m.group('op')}数量", require_admin=False) | |
| async def cmd_query(msg: Message, *args): | |
| if not await gate(msg): | |
| return | |
| if not args: | |
| balance = await finance.get_balance(str(msg.author.id)) | |
| return await reply_card(msg, cb.build_balance_card( | |
| _display_name(msg.author), balance, is_self=True)) | |
| # 查别人暂不设权限 —— 需求原文里 /查询 没标「需要管理员权限」, | |
| # 而 /充值、/所有打卡记录 都明确标了,客户应有此区分。若后续确认要收回, | |
| # 在这里加回 permission.can_view_all() 校验即可。 | |
| uid, name, candidates = await resolve_target(msg, args[0]) | |
| if not uid: | |
| return await reply_card(msg, cb.build_error( | |
| not_found_msg(args[0], candidates))) | |
| balance = await finance.get_balance(uid) | |
| await reply_card(msg, cb.build_balance_card(name, balance, is_self=False)) | |
| async def cmd_user_list(msg: Message, *args): | |
| if not await gate(msg): | |
| return | |
| # 同 /查询:需求原文未标注管理员权限,暂对所有人开放。 | |
| total = await finance.count_users() | |
| pages = max(1, math.ceil(total / USER_PAGE_SIZE)) if total else 1 | |
| page = parse_int_arg(args, default=1, maximum=pages) | |
| users = await finance.list_users(skip=(page - 1) * USER_PAGE_SIZE, | |
| limit=USER_PAGE_SIZE) | |
| await reply_card(msg, cb.build_user_list_card(users, total, page, USER_PAGE_SIZE)) | |
| # ============================================================ | |
| # 打卡命令 | |
| # ============================================================ | |
| async def cmd_checkin_card(msg: Message): | |
| await touch(msg) | |
| if throttled(msg, "checkin_card"): | |
| return | |
| state = await _current_state(str(msg.author.id), _display_name(msg.author)) | |
| await reply_card(msg, cb.build_checkin_card(state)) | |
| async def cmd_worktime(msg: Message, *args): | |
| """自己的工时,或(管理员)查别人的。 | |
| 参数是纯数字就当作天数,否则当作用户名 —— `/工时 7` 是查自己近 7 天, | |
| `/工时 张三` 是查张三。 | |
| """ | |
| await touch(msg) | |
| if args and not str(args[0]).isdigit(): | |
| if not permission.can_view_all(msg.author): | |
| return await reply_card(msg, cb.build_error("❌ 查看他人工时需要管理员权限")) | |
| uid, name, candidates = await resolve_target(msg, args[0]) | |
| if not uid: | |
| return await reply_card(msg, cb.build_error( | |
| not_found_msg(args[0], candidates))) | |
| days = parse_int_arg(args[1:], default=7, maximum=90) | |
| records = await checkin.get_records(uid, days) | |
| return await reply_card(msg, cb.build_records_card(name, days, records)) | |
| days = parse_int_arg(args, default=7, maximum=90) | |
| records = await checkin.get_records(str(msg.author.id), days) | |
| await reply_card(msg, cb.build_records_card( | |
| _display_name(msg.author), days, records)) | |
| async def cmd_all_records(msg: Message, *args): | |
| if not await gate(msg): | |
| return | |
| if not permission.can_view_all(msg.author): | |
| return await reply_card(msg, cb.build_error("❌ 你没有权限执行该操作")) | |
| days = parse_int_arg(args, default=7, maximum=90) | |
| records = await checkin.get_all_records(days) | |
| await reply_card(msg, cb.build_all_records_card(days, records)) | |
| # ============================================================ | |
| # 打卡按钮回调 | |
| # ============================================================ | |
| async def send_dm_to(user_id: str, card) -> bool: | |
| """给用户发私信。 | |
| 打卡结果走私信 —— 客户明确要求(参照的那个机器人就是发到私信里)。 | |
| 发到频道等于把所有人的打卡时间广播出去,既刷屏又没隐私。 | |
| """ | |
| content = json.dumps(CardMessage(card)) | |
| try: | |
| await bot.client.gate.exec_req(api.DirectMessage.create( | |
| type=MessageTypes.CARD, target_id=user_id, content=content)) | |
| return True | |
| except Exception as e: | |
| logger.warning("[DM] 给 %s 发私信失败: %r", user_id, e) | |
| return False | |
| async def send_card_to(target_id: str, card) -> bool: | |
| """往频道里发一条卡片消息。 | |
| 按钮回调里没有 Message 对象可 reply —— 事件只给 target_id(频道), | |
| 所以直接调 message/create。 | |
| """ | |
| content = json.dumps(CardMessage(card)) | |
| try: | |
| await bot.client.gate.exec_req(api.Message.create( | |
| type=MessageTypes.CARD, target_id=target_id, content=content)) | |
| return True | |
| except Exception as e: | |
| logger.error("[Send] 往频道 %s 发消息失败: %r", target_id, e) | |
| return False | |
| async def update_card_for_user(msg_id: str, user_id: str, card): | |
| """只对点击者更新卡片。其他人看到的仍是最初那张 —— 这是打卡卡片能 | |
| 群发一张给大家点的关键,而且临时消息不计入每日配额。""" | |
| content = json.dumps(CardMessage(card)) | |
| await bot.client.gate.exec_req( | |
| api.Message.update(msg_id=msg_id, content=content, temp_target_id=user_id) | |
| ) | |
| async def on_btn_click(_bot: Bot, ev: Event): | |
| # khl.py 的事件处理器签名是 (Bot, Event),两个参数缺一不可 —— | |
| # 它内部是 await event_handler(self, event) 这样调的。 | |
| # 第一个参数不用(下面统一走模块级的 bot),命名为 _bot 以免遮蔽全局。 | |
| body = ev.body or {} | |
| value = body.get("value") | |
| user_id = str(body.get("user_id") or "") | |
| msg_id = body.get("msg_id") | |
| user_info = body.get("user_info") or {} | |
| if value not in (BTN_CHECKIN, BTN_CHECKOUT) or not user_id or not msg_id: | |
| return | |
| # 防连点。单日多班次之后,checkins 不再有「一天一条」的天然幂等 —— | |
| # 连点两次上班会在两次 open_record() 之间产生竞态,开出两条记录。 | |
| # clock_in 内部的 open_record 检查能挡住「先后到达」的重复, | |
| # 这个冷却挡的是「几乎同时到达」的。 | |
| if rate_limiter.check_limit(user_id, "checkin_btn", 2.0)[0]: | |
| logger.info("[BtnClick] %s 连点被拦下", user_id) | |
| return | |
| name = permission.user_name(user_info) or user_id | |
| # 打卡不设门槛 —— 客户原话「打卡无所谓,都可以用」,所以按钮回调也放行 | |
| try: | |
| await finance.register(user_id, name) | |
| if value == BTN_CHECKIN: | |
| res = await checkin.clock_in(user_id, name) | |
| if res["ok"]: | |
| note = f"✅ **{name}** 已记录上班时间" | |
| if res.get("closed_date"): | |
| note += (f"\n🔸 顺手补上了 `{res['closed_date']}` 那天的下班卡" | |
| "(客户规则:漏卡以下一次打卡记)") | |
| else: | |
| note = f"ℹ️ 今天已经打过上班卡了" | |
| else: | |
| res = await checkin.clock_out(user_id, name) | |
| if res["ok"]: | |
| if res.get("abnormal"): | |
| note = "⚠️ 检测到异常工时,本次按 **0** 记录,请联系管理员核对" | |
| else: | |
| note = (f"✅ **{name}** 已记录下班时间\n" | |
| f"今日工时 **{timeutil.fmt_minutes(res['worked_min'])}**") | |
| elif res["code"] == "no_checkin": | |
| note = "❌ 还没有今天的上班记录,请先点「上班打卡」" | |
| elif res["code"] == "already_out": | |
| note = "ℹ️ 今天已经打过下班卡了" | |
| else: | |
| note = "❌ 操作失败,请稍后重试" | |
| # 结果发**私信**(客户要求)。只发成功的情况 —— 客户明确说不要 | |
| # 「打卡提示」那类通知(「已经打过卡了」刷屏)。 | |
| # 没成功时点击者仍能在卡片上看到说明(卡片是临时消息,只有他能看到)。 | |
| if res.get("ok"): | |
| if value == BTN_CHECKIN: | |
| result = cb.build_checkin_result_card( | |
| "上班", res.get("in_ts") or timeutil.now(), | |
| note=(f"🔸 顺手补上了 `{res['closed_date']}` 那天的下班卡" | |
| if res.get("closed_date") else None)) | |
| else: | |
| result = cb.build_checkin_result_card( | |
| "下班", res.get("out_ts") or timeutil.now(), | |
| # 今日工时取今天所有班次的合计(单日可多班次) | |
| res.get("today_min"), res.get("week_min"), | |
| note=("⚠️ 检测到异常工时,本次按 **0** 记录,请联系管理员核对" | |
| if res.get("abnormal") else None)) | |
| if not await send_dm_to(user_id, result): | |
| target_id = str(body.get("target_id") or "") | |
| if target_id: | |
| logger.info("[DM] 退回频道 %s 发送打卡结果", target_id) | |
| await send_card_to(target_id, result) | |
| # 卡片也同步刷新(对点击者可见),两边都有最稳妥 | |
| state = await _current_state(user_id, name) | |
| state["note"] = note | |
| if res["ok"] and value == BTN_CHECKOUT: | |
| state["abnormal"] = res.get("abnormal") | |
| await update_card_for_user(msg_id, user_id, cb.build_checkin_card(state)) | |
| except Exception as e: | |
| logger.error("[BtnClick] 处理失败 value=%s user=%s: %s", | |
| value, user_id, e, exc_info=True) | |
| async def _current_state(user_id: str, name: str) -> dict: | |
| """卡片状态:当前这一班的上下班时间 + 今日合计 + 本周累计。 | |
| 单日可多班次之后,一天可能有好几条记录 —— 所以「当前这一班」优先取 | |
| 未闭合的那条,没有就取今天最后一条。 | |
| """ | |
| rec = await checkin.open_record(user_id) | |
| if rec is None: | |
| rec = await db.checkins.find_one( | |
| {"user_id": user_id, "date": timeutil.today_str()}, | |
| sort=[("in_ts", -1)]) | |
| rec = rec or {} | |
| return { | |
| "name": name, | |
| "in_ts": rec.get("in_ts"), | |
| "out_ts": rec.get("out_ts"), | |
| "worked_min": rec.get("worked_min"), | |
| "today_min": await checkin.day_total_minutes(user_id), | |
| "week_min": await checkin.week_total_minutes(user_id), | |
| } | |
| async def cmd_help(msg: Message): | |
| await reply_card(msg, cb.build_help_card(await build_status())) | |
| async def cmd_roles(msg: Message): | |
| """列出本服务器所有角色及其 ID。 | |
| 配置 MEMBER_ROLE_IDS / ADMIN_ROLE_IDS 时要填的是角色 ID —— 而 KOOK | |
| 客户端里复制角色 ID 的入口不好找,所以让机器人直接打出来。 | |
| """ | |
| if not await gate(msg): | |
| return | |
| if not permission.is_admin(msg.author): | |
| return await reply_card(msg, cb.build_error("❌ 你没有权限执行该操作")) | |
| guild_id = (getattr(msg, "extra", None) or {}).get("guild_id") | |
| if not guild_id: | |
| return await reply_card(msg, cb.build_error("❌ 只在服务器频道里可用")) | |
| try: | |
| # exec_paged_req 自动翻页并直接返回 items 列表 | |
| items = await bot.client.gate.exec_paged_req(api.GuildRole.list(guild_id)) | |
| except Exception as e: | |
| logger.error("[Roles] 拉取角色列表失败: %r", e) | |
| return await reply_card(msg, cb.build_error("❌ 拉取角色列表失败,稍后再试")) | |
| if not items: | |
| return await reply_card(msg, cb.build_error("❌ 没拿到角色数据")) | |
| lines = [] | |
| for r in items: | |
| rid = r.get("role_id") | |
| name = r.get("name") or "(无名)" | |
| lines.append(f"`{rid}` — {name}") | |
| lines.append("") | |
| lines.append("把要授权的角色 ID 填进 Space 的 `MEMBER_ROLE_IDS`(逗号分隔)") | |
| await reply_card(msg, cb.build_simple_card( | |
| f"🎭 角色列表({len(items)} 个)", "\n".join(lines))) | |
| async def cmd_clear_worktime(msg: Message): | |
| """清空所有打卡记录。管理员命令,参考图里有这一条。""" | |
| if not await gate(msg): | |
| return | |
| if not permission.can_view_all(msg.author): | |
| return await reply_card(msg, cb.build_error("❌ 你没有权限执行该操作")) | |
| deleted = await checkin.clear_all() | |
| logger.warning("[Checkin] %s 清除了全部打卡记录(%d 条)", | |
| msg.author.id, deleted) | |
| await reply_card(msg, cb.build_simple_card( | |
| "✅ 已清除", | |
| f"共删除 **{deleted}** 条打卡记录。\n此操作不可恢复。")) | |
| # ============================================================ | |
| # 健康检查 / 启动 | |
| # ============================================================ | |
| def _fmt_uptime() -> str: | |
| seconds = int(time.monotonic() - _start_time) | |
| h, m = seconds // 3600, (seconds % 3600) // 60 | |
| return f"{h}小时{m}分" if h else f"{m}分" | |
| async def check_kook_api() -> bool: | |
| """真的去调一次 KOOK 的 HTTP API,而不是只看进程还活着 —— | |
| 否则 WS 掉线、token 失效时接口照样返回 ok,保活监控和 /help 的状态都成了摆设。 | |
| 结果缓存 30 秒:UptimeRobot 每次打 /health、用户每次发 /help 都实时调一次 | |
| 没必要,也容易把 KOOK 的速率限制吃满。 | |
| """ | |
| global _api_ok, _api_checked_at | |
| now = time.monotonic() | |
| if now - _api_checked_at <= 30: | |
| return _api_ok | |
| try: | |
| await asyncio.wait_for(bot.client.gate.exec_req(api.User.me()), timeout=8) | |
| _api_ok = True | |
| except Exception as e: | |
| logger.warning("[Health] KOOK API 不可达: %s", e) | |
| _api_ok = False | |
| _api_checked_at = now | |
| return _api_ok | |
| async def build_status() -> dict: | |
| """/help 里展示的机器状态。""" | |
| api_ok = await check_kook_api() | |
| try: | |
| users = await finance.count_users() | |
| except Exception as e: | |
| logger.warning("[Status] 统计用户数失败: %s", e) | |
| users = "?" | |
| return { | |
| "uptime": _fmt_uptime(), | |
| "database": "✅ 在线" if db.connected else "❌ 异常", | |
| "kook_api": "✅ 正常" if api_ok else "❌ 不可达", | |
| "users": users, | |
| } | |
| # /health 的访问记录。Space 会睡,说明保活没打进来 —— 但到底是 | |
| # 「没人打」还是「打了不算活动」,从外面看不出来。记下每次请求的 | |
| # User-Agent 和间隔,读取时返回**上一次**(不是本次)的情况。 | |
| _health_hits = 0 | |
| _last_health_ua = "" | |
| _last_health_method = "" | |
| _last_health_at = 0.0 | |
| async def health_check(request): | |
| """给 UptimeRobot 打。""" | |
| global _health_hits, _last_health_ua, _last_health_method, _last_health_at | |
| prev_hits, prev_ua = _health_hits, _last_health_ua | |
| prev_method = _last_health_method | |
| prev_gap = round(time.time() - _last_health_at, 1) if _last_health_at else None | |
| _health_hits += 1 | |
| _last_health_ua = (request.headers.get("User-Agent") or "")[:90] | |
| _last_health_method = request.method | |
| _last_health_at = time.time() | |
| api_ok = await check_kook_api() | |
| # 状态码刻意避开 503。 | |
| # 503 是 HF 代理在「容器没就绪」(启动中/正在唤醒)时返回的 —— 我们这边 | |
| # 也回 503 的话,监控历史里两者混在一起,根本分不清是平台的锅还是我们的锅。 | |
| # 现在:503 一律是平台,500 才是「我们活着但连不上 KOOK」。 | |
| status_code = 200 if api_ok else 500 | |
| payload = { | |
| "status": "ok" if api_ok else "degraded", | |
| "database": "connected" if db.connected else "disconnected", | |
| "kook_api": "ok" if api_ok else "unreachable", | |
| "uptime_sec": int(time.monotonic() - _start_time), | |
| # 冷启动自愈的诊断信息:heals > 0 表示这次启动撞上了僵尸会话 | |
| **khl_patch.diagnostics(), | |
| # 权限门槛是否已配置 —— 用来远程确认 secret 生效了, | |
| # 而不是靠猜(secret 的值读不回来) | |
| "member_gate": "on" if permission.member_gate_configured() else "off", | |
| "admin_gate": "on" if permission.admin_configured() else "off", | |
| # 上一次访问 /health 的情况 —— 用来判断保活到底有没有打进来 | |
| "prev_health_hits": prev_hits, | |
| "prev_health_ua": prev_ua, | |
| "prev_health_method": prev_method, | |
| "prev_health_gap_sec": prev_gap, | |
| } | |
| return web.json_response(payload, status=status_code) | |
| async def log_lifecycle(event: str, detail: str = ""): | |
| """把进程启停写进数据库,用来排查休眠和重启。 | |
| 为什么需要:HF 的 sleep 会把容器整个换掉,理论上也可疑地存在"最长开机 | |
| 时间"之类的定期重启(官方文档没写)。光看单次 `/health` 的 uptime_sec | |
| 分不清「一直没重启」和「刚重启过」。 | |
| 记下来之后就能看出两种模式: | |
| - stop 之后跟着 start → 正常重启(收到了 SIGTERM) | |
| - start 前面没有 stop → **被硬杀或睡死**,这才是要警惕的 | |
| """ | |
| try: | |
| await db.lifecycle.insert_one({ | |
| "event": event, | |
| "detail": detail, | |
| "at": timeutil.now(), | |
| "uptime_sec": int(time.monotonic() - _start_time), | |
| }) | |
| logger.info("[Lifecycle] 记录 %s (%s)", event, detail or "-") | |
| except Exception as e: | |
| logger.warning("[Lifecycle] 记录失败: %r", e) | |
| async def _graceful_exit(reason: str): | |
| """容器被换掉时先把 WebSocket 关干净,再退出。 | |
| 不这么做的话 TCP 会被硬断,KOOK 不知道我们已经死了、会话会挂到超时, | |
| 期间事件全被推到这条死连接上 —— 下一个容器连得上、握手也成功, | |
| 但永远收不到消息,也就是「重建后必然失联」那个 bug。 | |
| """ | |
| logger.info("[System] 收到 %s,正在优雅关闭...", reason) | |
| await log_lifecycle("stop", reason) | |
| await khl_patch.graceful_close(bot) | |
| try: | |
| await asyncio.wait_for(bot.client.offline(), timeout=5) | |
| logger.info("[System] 已通知 KOOK 机器人离线") | |
| except Exception as e: | |
| logger.warning("[System] 通知离线失败: %r", e) | |
| logger.info("[System] 退出") | |
| os._exit(0) | |
| async def self_ping_loop(): | |
| """定时用 GET 打自己的公网 /health,防止 HF 把免费 Space 判为闲置。 | |
| 为什么不用 UptimeRobot:免费版只能用 HEAD 请求,而实测 HEAD 打不进去 | |
| —— Space 照样休眠(/health 记录了每次访问的方法和 UA,证据确凿)。 | |
| 这里从容器内部发 GET,走的是同一套代理,算真实访问。 | |
| 容器睡死之后自己醒不过来(进程冻结了),所以这只能「防睡」不能「唤醒」。 | |
| """ | |
| if not SELF_PING_URL: | |
| logger.info("[KeepAlive] 未配置 SELF_PING_URL,跳过自保活") | |
| return | |
| logger.info("[KeepAlive] 已启动,每 %s 秒 GET 一次 %s", | |
| SELF_PING_INTERVAL, SELF_PING_URL) | |
| while True: | |
| await asyncio.sleep(SELF_PING_INTERVAL) | |
| try: | |
| async with aiohttp.ClientSession() as s: | |
| async with s.get(SELF_PING_URL, timeout=20) as r: | |
| await r.read() | |
| logger.info("[KeepAlive] 自检 %s -> HTTP %s", SELF_PING_URL, r.status) | |
| except Exception as e: | |
| logger.warning("[KeepAlive] 自检失败: %r", e) | |
| def _install_signal_handlers(): | |
| loop = asyncio.get_running_loop() | |
| for sig, name in ((signal.SIGTERM, "SIGTERM"), (signal.SIGINT, "SIGINT")): | |
| try: | |
| loop.add_signal_handler( | |
| sig, lambda n=name: asyncio.ensure_future(_graceful_exit(n))) | |
| except (NotImplementedError, RuntimeError) as e: | |
| # Windows 的事件循环不支持,本地调试时会走到这里;容器里是 Linux,没问题 | |
| logger.warning("[System] 无法注册 %s 处理器: %s", name, e) | |
| async def main(): | |
| if not await db.connect(): | |
| logger.error("[System] MongoDB 连接失败,请检查 MONGO_URI") | |
| return | |
| app = web.Application() | |
| app.router.add_get("/health", health_check) | |
| app.router.add_get("/", health_check) | |
| runner = web.AppRunner(app) | |
| await runner.setup() | |
| await web.TCPSite(runner, "0.0.0.0", 7860).start() | |
| await log_lifecycle("start", "container") | |
| logger.info("[init] HTTP 服务已启动 :7860,正在连接 KOOK...") | |
| _install_signal_handlers() | |
| asyncio.ensure_future(self_ping_loop()) | |
| await bot.start() | |
| if __name__ == "__main__": | |
| asyncio.run(main()) | |