point_settings.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. from __future__ import annotations
  2. from typing import Any
  3. from pyrogram.types import KeyboardButton, ReplyKeyboardMarkup, ReplyKeyboardRemove
  4. from wbb import app
  5. from wbb.utils.dbpoints import (
  6. PointsError,
  7. get_point_rules,
  8. normalize_point_rules,
  9. set_point_rules,
  10. )
  11. CHECKIN_BUTTON_TEXT = "签到"
  12. def checkin_button_active(rules: dict[str, Any]) -> bool:
  13. return bool(
  14. rules.get("enabled")
  15. and rules.get("checkin_enabled")
  16. and rules.get("checkin_button_enabled")
  17. )
  18. def checkin_keyboard() -> ReplyKeyboardMarkup:
  19. return ReplyKeyboardMarkup(
  20. [[KeyboardButton(CHECKIN_BUTTON_TEXT)]],
  21. is_persistent=True,
  22. resize_keyboard=True,
  23. selective=False,
  24. placeholder="输入消息",
  25. )
  26. async def _sync_checkin_keyboard(chat_id: int, enabled: bool) -> None:
  27. if enabled:
  28. text = "签到快捷按钮已开启。点击下方“签到”即可领取每日积分。"
  29. reply_markup = checkin_keyboard()
  30. else:
  31. text = "签到快捷按钮已关闭。"
  32. reply_markup = ReplyKeyboardRemove(selective=False)
  33. try:
  34. await app.send_message(chat_id, text, reply_markup=reply_markup)
  35. except Exception as exc:
  36. raise PointsError(
  37. "无法更新群底部签到按钮,请确认机器人可以在群内发言。"
  38. ) from exc
  39. async def apply_point_rules(chat_id: int, values: dict[str, Any]) -> dict[str, Any]:
  40. current = await get_point_rules(chat_id)
  41. target = normalize_point_rules({**current, **values})
  42. current_active = checkin_button_active(current)
  43. target_active = checkin_button_active(target)
  44. saved = await set_point_rules(chat_id, target)
  45. if current_active == target_active:
  46. return saved
  47. try:
  48. await _sync_checkin_keyboard(chat_id, target_active)
  49. except Exception:
  50. await set_point_rules(chat_id, current)
  51. raise
  52. return saved