points.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. from __future__ import annotations
  2. import asyncio
  3. import re
  4. from html import escape
  5. from pyrogram import filters
  6. from pyrogram.enums import ParseMode
  7. from pyrogram.types import Message, User
  8. from wbb import app, log
  9. from wbb.core.decorators.permissions import adminsOnly
  10. from wbb.services.point_settings import (
  11. CHECKIN_BUTTON_TEXT,
  12. apply_point_rules,
  13. checkin_button_active,
  14. )
  15. from wbb.utils.dbpoints import (
  16. SOURCE_ADMIN,
  17. InsufficientPoints,
  18. PointsError,
  19. adjust_points,
  20. award_activity,
  21. award_checkin,
  22. get_point_account,
  23. get_point_rules,
  24. list_point_accounts,
  25. list_point_transactions,
  26. reconcile_all_accounts,
  27. set_points,
  28. )
  29. from wbb.utils.i18n import point_source_label
  30. __MODULE__ = "积分管理"
  31. __HELP__ = """/points - 查看自己或被回复成员的积分余额。
  32. /checkin - 领取每日签到积分。
  33. /points_rank - 查看本群积分排行榜。
  34. /points_history - 查看自己或被回复成员的最近积分流水。
  35. /points_add <成员> <数值> <原因> - 增加积分。
  36. /points_deduct <成员> <数值> <原因> - 扣减积分。
  37. /points_set <成员> <余额> <原因> - 通过新流水设置余额。
  38. /points_toggle <开启|关闭> - 开关本群积分系统。
  39. /checkin_button <开启|关闭> - 开关输入框底部的签到按钮。"""
  40. _VOTE_RE = re.compile(
  41. r"^(\++|\+1|thx|tnx|tq|ty|thankyou|thank you|thanx|thanks|pro|cool|good|agree|👍|-+|-1|not cool|disagree|worst|bad|👎)$",
  42. re.IGNORECASE,
  43. )
  44. _reconciler_started = False
  45. RECONCILE_INTERVAL_SECONDS = 3600
  46. _TOGGLE_CHOICES = {
  47. "enable": True,
  48. "enabled": True,
  49. "on": True,
  50. "开启": True,
  51. "打开": True,
  52. "disable": False,
  53. "disabled": False,
  54. "off": False,
  55. "关闭": False,
  56. }
  57. def _mention(user_id: int, label: str | None) -> str:
  58. return f'<a href="tg://user?id={user_id}">{escape(label or str(user_id))}</a>'
  59. def _user_display_name(user: User) -> str:
  60. return " ".join(
  61. value for value in (user.first_name, user.last_name) if value
  62. ) or (f"@{user.username}" if user.username else str(user.id))
  63. def _message_content(message: Message) -> str:
  64. text = (message.text or message.caption or "").strip()
  65. if text:
  66. return text
  67. media = (
  68. message.photo
  69. or message.animation
  70. or message.video
  71. or message.document
  72. or message.audio
  73. or message.voice
  74. or message.sticker
  75. )
  76. unique_id = getattr(media, "file_unique_id", None)
  77. return f"media:{unique_id}" if unique_id else ""
  78. async def _resolve_target(message: Message, raw: str | None = None) -> User | None:
  79. if message.reply_to_message and message.reply_to_message.from_user:
  80. return message.reply_to_message.from_user
  81. if not raw:
  82. return message.from_user
  83. try:
  84. return await app.get_users(int(raw) if raw.lstrip("-").isdigit() else raw)
  85. except Exception:
  86. return None
  87. def _adjustment_parts(message: Message) -> tuple[str | None, str | None, str]:
  88. parts = message.text.split() if message.text else []
  89. if message.reply_to_message:
  90. amount = parts[1] if len(parts) > 1 else None
  91. reason = " ".join(parts[2:]).strip()
  92. return None, amount, reason
  93. target = parts[1] if len(parts) > 1 else None
  94. amount = parts[2] if len(parts) > 2 else None
  95. reason = " ".join(parts[3:]).strip()
  96. return target, amount, reason
  97. @app.on_message(filters.command("points") & filters.group)
  98. async def points_balance_command(_, message: Message):
  99. target = await _resolve_target(message)
  100. if not target:
  101. return await message.reply_text("未找到该成员。")
  102. account = await get_point_account(message.chat.id, target.id)
  103. return await message.reply_text(
  104. f"{_mention(target.id, target.first_name)} 当前有 "
  105. f"<b>{int(account['balance'])}</b> 积分。",
  106. parse_mode=ParseMode.HTML,
  107. )
  108. @app.on_message(
  109. filters.group
  110. & (filters.command("checkin") | filters.regex(r"^签到$"))
  111. )
  112. async def points_checkin_command(_, message: Message):
  113. if not message.from_user:
  114. return await message.reply_text("匿名管理员无法签到。")
  115. try:
  116. account, created = await award_checkin(
  117. chat_id=message.chat.id,
  118. user_id=message.from_user.id,
  119. username=message.from_user.username,
  120. first_name=message.from_user.first_name,
  121. display_name=_user_display_name(message.from_user),
  122. )
  123. except PointsError as exc:
  124. return await message.reply_text(str(exc))
  125. if not created:
  126. return await message.reply_text(
  127. f"你今天已经签到过了,当前余额:{int(account['balance'])}。"
  128. )
  129. rules = await get_point_rules(message.chat.id)
  130. return await message.reply_text(
  131. f"签到成功:+{rules['checkin_points']} 积分,"
  132. f"当前余额:{int(account['balance'])}。"
  133. )
  134. @app.on_message(filters.command("points_rank") & filters.group)
  135. async def points_rank_command(_, message: Message):
  136. accounts, _ = await list_point_accounts(
  137. chat_id=message.chat.id, page=1, page_size=10
  138. )
  139. if not accounts:
  140. return await message.reply_text("本群尚无积分记录。")
  141. lines = ["<b>本群积分排行榜</b>"]
  142. for index, account in enumerate(accounts, 1):
  143. label = (
  144. account.get("display_name")
  145. or account.get("first_name")
  146. or (f"@{account['username']}" if account.get("username") else None)
  147. or str(account["user_id"])
  148. )
  149. lines.append(
  150. f"{index}. {_mention(int(account['user_id']), str(label))} - "
  151. f"<b>{int(account['balance'])}</b> 积分"
  152. )
  153. return await message.reply_text(
  154. "\n".join(lines), parse_mode=ParseMode.HTML, disable_web_page_preview=True
  155. )
  156. @app.on_message(filters.command("points_history") & filters.group)
  157. async def points_history_command(_, message: Message):
  158. target = await _resolve_target(message)
  159. if not target:
  160. return await message.reply_text("未找到该成员。")
  161. items, _ = await list_point_transactions(
  162. chat_id=message.chat.id, user_id=target.id, page=1, page_size=10
  163. )
  164. if not items:
  165. return await message.reply_text("未找到积分流水。")
  166. lines = [f"<b>{escape(target.first_name)} 的最近积分流水</b>"]
  167. for item in items:
  168. sign = "+" if int(item["delta"]) > 0 else ""
  169. created_at = item["created_at"].strftime("%Y-%m-%d %H:%M UTC")
  170. lines.append(
  171. f"{sign}{int(item['delta'])} · "
  172. f"{escape(point_source_label(item['source']))} · "
  173. f"余额 {int(item['balance_after'])} · {created_at}"
  174. )
  175. return await message.reply_text("\n".join(lines), parse_mode=ParseMode.HTML)
  176. async def _adjust_points_command(message: Message, operation: str):
  177. target_raw, amount_raw, reason = _adjustment_parts(message)
  178. if not amount_raw or not amount_raw.isdigit() or not reason:
  179. operation_labels = {
  180. "add": "add",
  181. "deduct": "deduct",
  182. "set": "set",
  183. }
  184. return await message.reply_text(
  185. f"用法:/points_{operation_labels[operation]} "
  186. "<成员> <积分数值> <原因>(也可以回复成员消息后使用)"
  187. )
  188. target = await _resolve_target(message, target_raw)
  189. if not target:
  190. return await message.reply_text("未找到该成员。")
  191. value = int(amount_raw)
  192. if operation == "deduct":
  193. value = -value
  194. actor_id = message.from_user.id if message.from_user else message.chat.id
  195. key = f"admin-points:{message.chat.id}:{message.id}:{operation}:{target.id}"
  196. try:
  197. if operation == "set":
  198. account, created = await set_points(
  199. chat_id=message.chat.id,
  200. user_id=target.id,
  201. balance=value,
  202. actor_id=actor_id,
  203. reason=reason,
  204. idempotency_key=key,
  205. username=target.username,
  206. first_name=target.first_name,
  207. display_name=_user_display_name(target),
  208. )
  209. else:
  210. account, created = await adjust_points(
  211. chat_id=message.chat.id,
  212. user_id=target.id,
  213. delta=value,
  214. source=SOURCE_ADMIN,
  215. idempotency_key=key,
  216. actor_id=actor_id,
  217. reason=reason,
  218. username=target.username,
  219. first_name=target.first_name,
  220. display_name=_user_display_name(target),
  221. )
  222. except (PointsError, InsufficientPoints) as exc:
  223. return await message.reply_text(str(exc))
  224. state = "已更新" if created else "此前已处理"
  225. return await message.reply_text(
  226. f"积分{state}。{target.first_name} 的当前余额:"
  227. f"{int(account['balance'])}。"
  228. )
  229. @app.on_message(filters.command("points_add") & ~filters.private)
  230. @adminsOnly("can_change_info")
  231. async def points_add_command(_, message: Message):
  232. return await _adjust_points_command(message, "add")
  233. @app.on_message(filters.command("points_deduct") & ~filters.private)
  234. @adminsOnly("can_change_info")
  235. async def points_deduct_command(_, message: Message):
  236. return await _adjust_points_command(message, "deduct")
  237. @app.on_message(filters.command("points_set") & ~filters.private)
  238. @adminsOnly("can_change_info")
  239. async def points_set_command(_, message: Message):
  240. return await _adjust_points_command(message, "set")
  241. @app.on_message(filters.command("points_toggle") & ~filters.private)
  242. @adminsOnly("can_change_info")
  243. async def points_toggle_command(_, message: Message):
  244. choice = message.command[1].lower() if len(message.command) == 2 else ""
  245. if choice not in _TOGGLE_CHOICES:
  246. return await message.reply_text("用法:/points_toggle <开启|关闭>")
  247. enabled = _TOGGLE_CHOICES[choice]
  248. try:
  249. await apply_point_rules(message.chat.id, {"enabled": enabled})
  250. except PointsError as exc:
  251. return await message.reply_text(str(exc))
  252. return await message.reply_text(
  253. f"本群积分系统已{'开启' if enabled else '关闭'}。"
  254. )
  255. @app.on_message(filters.command("checkin_button") & ~filters.private)
  256. @adminsOnly("can_change_info")
  257. async def checkin_button_command(_, message: Message):
  258. choice = message.command[1].lower() if len(message.command) == 2 else ""
  259. if choice not in _TOGGLE_CHOICES:
  260. return await message.reply_text("用法:/checkin_button <开启|关闭>")
  261. enabled = _TOGGLE_CHOICES[choice]
  262. try:
  263. rules = await apply_point_rules(
  264. message.chat.id, {"checkin_button_enabled": enabled}
  265. )
  266. except PointsError as exc:
  267. return await message.reply_text(str(exc))
  268. if enabled and not checkin_button_active(rules):
  269. return await message.reply_text(
  270. "底部签到按钮设置已开启;启用积分系统和签到规则后会自动显示。"
  271. )
  272. return await message.reply_text(
  273. f"群底部签到按钮已{'开启' if enabled else '关闭'}。"
  274. )
  275. @app.on_message(filters.group & filters.incoming, group=13)
  276. async def points_activity_listener(_, message: Message):
  277. if not message.from_user or message.from_user.is_bot:
  278. return
  279. if getattr(message, "service", None):
  280. return
  281. content = _message_content(message)
  282. if not content or content.startswith("/"):
  283. return
  284. if content == CHECKIN_BUTTON_TEXT:
  285. return
  286. if message.reply_to_message and _VOTE_RE.fullmatch(content.strip()):
  287. return
  288. await award_activity(
  289. chat_id=message.chat.id,
  290. user_id=message.from_user.id,
  291. message_id=message.id,
  292. content=content,
  293. username=message.from_user.username,
  294. first_name=message.from_user.first_name,
  295. display_name=_user_display_name(message.from_user),
  296. )
  297. async def _reconcile_points_loop() -> None:
  298. await asyncio.sleep(60)
  299. while True:
  300. try:
  301. await reconcile_all_accounts(limit=10000)
  302. except Exception as exc:
  303. log.error(f"Points reconciliation failed: {exc}")
  304. await asyncio.sleep(RECONCILE_INTERVAL_SECONDS)
  305. def _start_reconciler() -> None:
  306. global _reconciler_started
  307. if _reconciler_started:
  308. return
  309. try:
  310. loop = asyncio.get_running_loop()
  311. except RuntimeError:
  312. return
  313. _reconciler_started = True
  314. loop.create_task(_reconcile_points_loop(), name="points-reconciler")
  315. _start_reconciler()