teacher_directory.py 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  1. from __future__ import annotations
  2. from datetime import UTC, datetime, timedelta
  3. from html import escape
  4. from secrets import token_urlsafe
  5. from typing import Any
  6. from pyrogram import StopPropagation, filters
  7. from pyrogram.enums import ChatMemberStatus, ParseMode
  8. from pyrogram.types import (
  9. CallbackQuery,
  10. ChatMemberUpdated,
  11. InlineKeyboardButton,
  12. InlineKeyboardMarkup,
  13. KeyboardButton,
  14. Message,
  15. ReplyKeyboardMarkup,
  16. )
  17. from wbb import BOT_USERNAME, app, log
  18. from wbb.services.directory import (
  19. DirectoryServiceError,
  20. admin_change_teacher_state,
  21. admin_decide_teacher,
  22. apply_as_teacher,
  23. change_own_teacher_state,
  24. clear_user_location,
  25. directory_for_user,
  26. format_distance,
  27. observe_directory_user,
  28. observe_group_member,
  29. profile_summary,
  30. public_teacher,
  31. require_platform_membership,
  32. start_presence_sweeper,
  33. status_value,
  34. update_user_geocode_consent,
  35. update_user_location,
  36. verify_platform_membership,
  37. )
  38. from wbb.services.directory_geocoding import (
  39. NOMINATIM_ATTRIBUTION,
  40. NOMINATIM_ATTRIBUTION_URL,
  41. )
  42. from wbb.utils.dbdirectory import (
  43. APPLICATION_APPROVED,
  44. APPLICATION_PENDING,
  45. APPLICATION_REJECTED,
  46. APPLICATION_REVOKED,
  47. get_directory_location,
  48. get_directory_profile,
  49. list_directory_profiles,
  50. list_teacher_applications,
  51. )
  52. __MODULE__ = "师生与附近"
  53. __HELP__ = """/directory - 打开师生服务菜单或在群内验证成员身份。
  54. /nearby - 选择范围并查找附近老师。
  55. /teacher_rank - 按距离查看全部上榜老师。
  56. /teacher_apply - 申请成为老师。
  57. /teacher_online - 老师上线。
  58. /teacher_offline - 老师下线。
  59. /teacher_list - 老师上榜。
  60. /teacher_unlist - 老师下榜。"""
  61. APPLICATION_LABELS = {
  62. "none": "学生",
  63. APPLICATION_PENDING: "老师申请待审批",
  64. APPLICATION_APPROVED: "老师",
  65. APPLICATION_REJECTED: "老师申请已拒绝",
  66. APPLICATION_REVOKED: "老师资格已撤销",
  67. }
  68. TEACHER_ACTION_LABELS = {
  69. "list": "上榜",
  70. "unlist": "下榜",
  71. "online": "上线",
  72. "offline": "下线",
  73. }
  74. BUTTON_NEARBY = "附近老师"
  75. BUTTON_RANK = "老师榜单"
  76. BUTTON_APPLY = "申请成为老师"
  77. BUTTON_APPROVAL = "老师审批"
  78. BUTTON_STATUS = "我的状态"
  79. BUTTON_LIST = "上榜"
  80. BUTTON_UNLIST = "下榜"
  81. BUTTON_ONLINE = "上线"
  82. BUTTON_OFFLINE = "下线"
  83. BUTTON_PRIVACY = "位置隐私"
  84. BUTTON_CLEAR_LOCATION = "清除位置"
  85. _admin_flows: dict[int, dict[str, Any]] = {}
  86. _admin_confirmations: dict[str, dict[str, Any]] = {}
  87. def _display_name(profile: dict[str, Any]) -> str:
  88. return str(profile.get("display_name") or f"用户 {profile['user_id']}")
  89. def _directory_keyboard(
  90. profile: dict[str, Any] | None,
  91. *,
  92. is_admin: bool,
  93. ) -> ReplyKeyboardMarkup:
  94. status = str((profile or {}).get("application_status") or "none")
  95. rows: list[list[KeyboardButton]] = [
  96. [KeyboardButton("更新位置", request_location=True)],
  97. [KeyboardButton(BUTTON_NEARBY), KeyboardButton(BUTTON_RANK)],
  98. ]
  99. if status == APPLICATION_APPROVED:
  100. rows.extend(
  101. [
  102. [
  103. KeyboardButton(
  104. BUTTON_UNLIST if profile and profile.get("listed") else BUTTON_LIST
  105. ),
  106. KeyboardButton(
  107. BUTTON_OFFLINE
  108. if profile and profile.get("online")
  109. else BUTTON_ONLINE
  110. ),
  111. ],
  112. [KeyboardButton(BUTTON_STATUS)],
  113. ]
  114. )
  115. else:
  116. rows.append([KeyboardButton(BUTTON_APPLY), KeyboardButton(BUTTON_STATUS)])
  117. rows.append([KeyboardButton(BUTTON_PRIVACY), KeyboardButton(BUTTON_CLEAR_LOCATION)])
  118. if is_admin:
  119. rows.append([KeyboardButton(BUTTON_APPROVAL)])
  120. return ReplyKeyboardMarkup(
  121. rows,
  122. resize_keyboard=True,
  123. is_persistent=True,
  124. selective=True,
  125. placeholder="选择师生服务或输入消息",
  126. )
  127. async def send_directory_menu(message: Message) -> None:
  128. if not message.from_user:
  129. return
  130. try:
  131. await require_platform_membership(int(message.from_user.id))
  132. except DirectoryServiceError as exc:
  133. await message.reply_text(str(exc))
  134. return
  135. profile = await observe_directory_user(message.from_user)
  136. location = await get_directory_location(int(message.from_user.id))
  137. admin_result = await verify_platform_membership(
  138. user_id=int(message.from_user.id),
  139. require_admin=True,
  140. )
  141. summary = profile_summary(profile, location)
  142. status_label = APPLICATION_LABELS.get(summary["application_status"], "学生")
  143. lines = [
  144. "<b>师生与附近</b>",
  145. f"身份:{escape(status_label)}",
  146. f"位置:{escape(summary['region'] or '尚未更新')}",
  147. ]
  148. if summary["application_status"] == APPLICATION_APPROVED:
  149. lines.extend(
  150. [
  151. f"榜单:{'已上榜' if summary['listed'] else '未上榜'}",
  152. f"状态:{'在线' if summary['online'] else '离线'}",
  153. ]
  154. )
  155. await message.reply_text(
  156. "\n".join(lines),
  157. parse_mode=ParseMode.HTML,
  158. reply_markup=_directory_keyboard(
  159. {**profile, "online": summary["online"]},
  160. is_admin=bool(admin_result.get("allowed")),
  161. ),
  162. )
  163. async def _verify_group_member(message: Message) -> bool:
  164. if not message.from_user:
  165. return False
  166. try:
  167. member = await app.get_chat_member(message.chat.id, message.from_user.id)
  168. except Exception:
  169. await message.reply_text("暂时无法验证你的群成员身份,请稍后重试。")
  170. return False
  171. active = member.status in {
  172. ChatMemberStatus.OWNER,
  173. ChatMemberStatus.ADMINISTRATOR,
  174. ChatMemberStatus.MEMBER,
  175. ChatMemberStatus.RESTRICTED,
  176. }
  177. await observe_group_member(
  178. chat_id=message.chat.id,
  179. chat_title=message.chat.title or "",
  180. user=message.from_user,
  181. status=status_value(member.status),
  182. active=active,
  183. verified=True,
  184. )
  185. if not active:
  186. await message.reply_text("该功能仅对当前群成员开放。")
  187. return active
  188. @app.on_message(filters.command("directory"))
  189. async def directory_command(_, message: Message):
  190. if message.chat.type.value == "private":
  191. return await send_directory_menu(message)
  192. if not await _verify_group_member(message):
  193. return
  194. url = f"https://t.me/{BOT_USERNAME}?start=directory"
  195. await message.reply_text(
  196. "身份验证成功。请点击下方按钮在私聊中使用师生与附近功能。",
  197. reply_markup=InlineKeyboardMarkup(
  198. [[InlineKeyboardButton("打开师生服务", url=url)]]
  199. ),
  200. )
  201. @app.on_message(filters.command("nearby") & filters.private)
  202. async def nearby_command(_, message: Message):
  203. await _show_radius_picker(message)
  204. @app.on_message(filters.command("teacher_rank") & filters.private)
  205. async def teacher_rank_command(_, message: Message):
  206. await _show_teacher_results(message, radius_km=None, page=1)
  207. @app.on_message(filters.command("teacher_apply") & filters.private)
  208. async def teacher_apply_command(_, message: Message):
  209. await _apply_teacher(message)
  210. async def _self_state_command(message: Message, action: str) -> None:
  211. if not message.from_user:
  212. return
  213. try:
  214. profile, _ = await change_own_teacher_state(
  215. user=message.from_user,
  216. action=action,
  217. )
  218. await message.reply_text(
  219. f"已{TEACHER_ACTION_LABELS[action]}。"
  220. + (
  221. "本次上线状态将在 24 小时后自动失效。"
  222. if action == "online"
  223. else ""
  224. )
  225. )
  226. await _refresh_keyboard(message, profile)
  227. except DirectoryServiceError as exc:
  228. await message.reply_text(str(exc))
  229. @app.on_message(filters.command("teacher_online") & filters.private)
  230. async def teacher_online_command(_, message: Message):
  231. await _self_state_command(message, "online")
  232. @app.on_message(filters.command("teacher_offline") & filters.private)
  233. async def teacher_offline_command(_, message: Message):
  234. await _self_state_command(message, "offline")
  235. @app.on_message(filters.command("teacher_list") & filters.private)
  236. async def teacher_list_command(_, message: Message):
  237. await _self_state_command(message, "list")
  238. @app.on_message(filters.command("teacher_unlist") & filters.private)
  239. async def teacher_unlist_command(_, message: Message):
  240. await _self_state_command(message, "unlist")
  241. @app.on_message(filters.private & filters.location, group=12)
  242. async def directory_location_message(_, message: Message):
  243. if not message.from_user or not message.location:
  244. return
  245. try:
  246. location, previous_consent = await update_user_location(
  247. user=message.from_user,
  248. longitude=message.location.longitude,
  249. latitude=message.location.latitude,
  250. )
  251. except DirectoryServiceError as exc:
  252. return await message.reply_text(str(exc))
  253. await message.reply_text("位置已更新,可立即使用附近老师和老师榜单。")
  254. if previous_consent is None:
  255. await message.reply_text(
  256. "是否同意将本次及以后更新的精确坐标发送给 "
  257. "OpenStreetMap Nominatim,仅用于解析省、市、区县?\n\n"
  258. "不会发送 Telegram 用户信息;选择“仅计算距离”后,附近功能仍可正常使用。",
  259. reply_markup=InlineKeyboardMarkup(
  260. [
  261. [
  262. InlineKeyboardButton(
  263. "同意解析区域",
  264. callback_data="dir:consent:yes",
  265. ),
  266. InlineKeyboardButton(
  267. "仅计算距离",
  268. callback_data="dir:consent:no",
  269. ),
  270. ]
  271. ]
  272. ),
  273. )
  274. elif previous_consent is True:
  275. await message.reply_text("区域解析已进入队列,完成前会显示“区域暂不可用”。")
  276. await _refresh_keyboard(message, await get_directory_profile(message.from_user.id))
  277. async def _refresh_keyboard(
  278. message: Message,
  279. profile: dict[str, Any] | None,
  280. ) -> None:
  281. if not message.from_user:
  282. return
  283. admin_result = await verify_platform_membership(
  284. user_id=int(message.from_user.id),
  285. require_admin=True,
  286. )
  287. summary = profile_summary(
  288. profile or {"user_id": message.from_user.id},
  289. await get_directory_location(message.from_user.id),
  290. )
  291. await message.reply_text(
  292. "菜单已更新。",
  293. reply_markup=_directory_keyboard(
  294. {**(profile or {}), "online": summary["online"]},
  295. is_admin=bool(admin_result.get("allowed")),
  296. ),
  297. )
  298. async def _apply_teacher(message: Message) -> None:
  299. if not message.from_user:
  300. return
  301. try:
  302. profile = await apply_as_teacher(user=message.from_user)
  303. except DirectoryServiceError as exc:
  304. return await message.reply_text(str(exc))
  305. await message.reply_text(
  306. "老师申请已提交,管理员审批后会通过申请来源机器人通知你。"
  307. if profile.get("application_status") == APPLICATION_PENDING
  308. else "当前申请状态未发生变化。"
  309. )
  310. await _refresh_keyboard(message, profile)
  311. async def _show_status(message: Message) -> None:
  312. if not message.from_user:
  313. return
  314. profile = await observe_directory_user(message.from_user)
  315. summary = profile_summary(profile, await get_directory_location(message.from_user.id))
  316. lines = [
  317. "<b>我的师生状态</b>",
  318. f"身份:{escape(APPLICATION_LABELS.get(summary['application_status'], '学生'))}",
  319. f"位置:{escape(summary['region'] or '尚未更新')}",
  320. ]
  321. if summary["application_status"] == APPLICATION_APPROVED:
  322. lines.extend(
  323. [
  324. f"榜单:{'已上榜' if summary['listed'] else '未上榜'}",
  325. f"上下线:{'在线' if summary['online'] else '离线'}",
  326. (
  327. "自动下线:"
  328. + escape(
  329. summary["online_until"].astimezone(UTC).strftime(
  330. "%Y-%m-%d %H:%M UTC"
  331. )
  332. )
  333. if summary["online"] and summary["online_until"]
  334. else ""
  335. ),
  336. ]
  337. )
  338. await message.reply_text(
  339. "\n".join(line for line in lines if line),
  340. parse_mode=ParseMode.HTML,
  341. )
  342. async def _show_privacy(message: Message) -> None:
  343. if not message.from_user:
  344. return
  345. location = await get_directory_location(message.from_user.id)
  346. if not location:
  347. return await message.reply_text("尚未保存位置。")
  348. consent = location.get("geocode_consent")
  349. text = {
  350. True: "当前已同意将精确坐标发送给 Nominatim 解析行政区域。",
  351. False: "当前只在本系统保存位置并计算距离,不向地图服务发送坐标。",
  352. None: "尚未选择是否使用 Nominatim 解析行政区域。",
  353. }[consent]
  354. await message.reply_text(
  355. text
  356. + "\n关闭授权只影响后续请求;第三方已接收的历史请求无法撤回。",
  357. reply_markup=InlineKeyboardMarkup(
  358. [
  359. [
  360. InlineKeyboardButton("同意区域解析", callback_data="dir:consent:yes"),
  361. InlineKeyboardButton("关闭区域解析", callback_data="dir:consent:no"),
  362. ]
  363. ]
  364. ),
  365. )
  366. async def _show_radius_picker(target: Message | CallbackQuery) -> None:
  367. markup = InlineKeyboardMarkup(
  368. [
  369. [
  370. InlineKeyboardButton(
  371. f"{radius} 公里",
  372. callback_data=f"dir:list:{radius}:1",
  373. )
  374. for radius in (5, 10)
  375. ],
  376. [
  377. InlineKeyboardButton(
  378. f"{radius} 公里",
  379. callback_data=f"dir:list:{radius}:1",
  380. )
  381. for radius in (20, 50)
  382. ],
  383. ]
  384. )
  385. if isinstance(target, CallbackQuery):
  386. await target.message.edit_text("请选择附近老师的搜索范围:", reply_markup=markup)
  387. else:
  388. await target.reply_text("请选择附近老师的搜索范围:", reply_markup=markup)
  389. def _teacher_result_markup(
  390. teachers: list[dict[str, Any]],
  391. *,
  392. radius_key: str,
  393. page: int,
  394. total: int,
  395. ) -> InlineKeyboardMarkup:
  396. rows: list[list[InlineKeyboardButton]] = []
  397. for item in teachers:
  398. username = str(item.get("username") or "")
  399. label = f"{item['display_name']} (@{username})"
  400. rows.append(
  401. [
  402. InlineKeyboardButton(
  403. label[:48],
  404. url=f"https://t.me/{username}",
  405. )
  406. ]
  407. )
  408. navigation: list[InlineKeyboardButton] = []
  409. if page > 1:
  410. navigation.append(
  411. InlineKeyboardButton(
  412. "上一页",
  413. callback_data=f"dir:list:{radius_key}:{page - 1}",
  414. )
  415. )
  416. if page * 10 < total:
  417. navigation.append(
  418. InlineKeyboardButton(
  419. "下一页",
  420. callback_data=f"dir:list:{radius_key}:{page + 1}",
  421. )
  422. )
  423. if navigation:
  424. rows.append(navigation)
  425. rows.append([InlineKeyboardButton("切换附近范围", callback_data="dir:radius")])
  426. return InlineKeyboardMarkup(rows)
  427. async def _show_teacher_results(
  428. target: Message | CallbackQuery,
  429. *,
  430. radius_km: int | None,
  431. page: int,
  432. ) -> None:
  433. user = target.from_user
  434. try:
  435. raw_items, total = await directory_for_user(
  436. user=user,
  437. radius_km=radius_km,
  438. page=page,
  439. page_size=10,
  440. )
  441. except DirectoryServiceError as exc:
  442. if isinstance(target, CallbackQuery):
  443. return await target.answer(str(exc), show_alert=True)
  444. return await target.reply_text(str(exc))
  445. teachers = [public_teacher(item) for item in raw_items]
  446. title = (
  447. f"<b>{radius_km} 公里内的老师</b>"
  448. if radius_km is not None
  449. else "<b>老师榜单</b>"
  450. )
  451. lines = [title, f"共 {total} 位已上榜老师,按距离排序。"]
  452. for index, item in enumerate(teachers, start=(page - 1) * 10 + 1):
  453. lines.append(
  454. f"\n{index}. <b>{escape(item['display_name'])}</b> "
  455. f"(@{escape(item['username'])})\n"
  456. f"状态:{'在线' if item['online'] else '离线'} | "
  457. f"距离:{format_distance(item['distance_meters'])} | "
  458. f"区域:{escape(item['region'])}"
  459. )
  460. if not teachers:
  461. lines.append("\n当前范围内没有已上榜老师。")
  462. lines.append(
  463. f'\n<a href="{NOMINATIM_ATTRIBUTION_URL}">{NOMINATIM_ATTRIBUTION}</a>'
  464. )
  465. markup = _teacher_result_markup(
  466. teachers,
  467. radius_key=str(radius_km) if radius_km is not None else "all",
  468. page=page,
  469. total=total,
  470. )
  471. if isinstance(target, CallbackQuery):
  472. await target.message.edit_text(
  473. "\n".join(lines),
  474. parse_mode=ParseMode.HTML,
  475. disable_web_page_preview=True,
  476. reply_markup=markup,
  477. )
  478. await target.answer()
  479. else:
  480. await target.reply_text(
  481. "\n".join(lines),
  482. parse_mode=ParseMode.HTML,
  483. disable_web_page_preview=True,
  484. reply_markup=markup,
  485. )
  486. async def _show_admin_applications(
  487. target: Message | CallbackQuery,
  488. *,
  489. page: int = 1,
  490. ) -> None:
  491. try:
  492. await require_platform_membership(int(target.from_user.id), require_admin=True)
  493. except DirectoryServiceError as exc:
  494. if isinstance(target, CallbackQuery):
  495. return await target.answer(str(exc), show_alert=True)
  496. return await target.reply_text(str(exc))
  497. items, total = await list_teacher_applications(
  498. status=APPLICATION_PENDING,
  499. page=page,
  500. page_size=5,
  501. )
  502. lines = ["<b>老师申请审批</b>", f"待审批:{total}"]
  503. rows: list[list[InlineKeyboardButton]] = []
  504. for item in items:
  505. lines.append(
  506. f"\n{escape(_display_name(item))} (@{escape(item.get('username') or '')})"
  507. f"\n用户 ID:<code>{item['user_id']}</code>"
  508. )
  509. rows.append(
  510. [
  511. InlineKeyboardButton(
  512. f"查看 {_display_name(item)[:18]}",
  513. callback_data=f"dir:admin:detail:{item['user_id']}",
  514. )
  515. ]
  516. )
  517. if page > 1:
  518. rows.append(
  519. [
  520. InlineKeyboardButton(
  521. "上一页",
  522. callback_data=f"dir:admin:pending:{page - 1}",
  523. )
  524. ]
  525. )
  526. if page * 5 < total:
  527. rows.append(
  528. [
  529. InlineKeyboardButton(
  530. "下一页",
  531. callback_data=f"dir:admin:pending:{page + 1}",
  532. )
  533. ]
  534. )
  535. rows.append(
  536. [InlineKeyboardButton("已批准老师", callback_data="dir:admin:teachers:1")]
  537. )
  538. markup = InlineKeyboardMarkup(rows)
  539. if isinstance(target, CallbackQuery):
  540. await target.message.edit_text(
  541. "\n".join(lines),
  542. parse_mode=ParseMode.HTML,
  543. reply_markup=markup,
  544. )
  545. await target.answer()
  546. else:
  547. await target.reply_text(
  548. "\n".join(lines),
  549. parse_mode=ParseMode.HTML,
  550. reply_markup=markup,
  551. )
  552. async def _show_admin_teachers(target: CallbackQuery, page: int) -> None:
  553. try:
  554. await require_platform_membership(
  555. int(target.from_user.id),
  556. require_admin=True,
  557. )
  558. except DirectoryServiceError as exc:
  559. return await target.answer(str(exc), show_alert=True)
  560. items, total = await list_directory_profiles(
  561. application_status=APPLICATION_APPROVED,
  562. page=page,
  563. page_size=8,
  564. )
  565. rows = [
  566. [
  567. InlineKeyboardButton(
  568. _display_name(item)[:28],
  569. callback_data=f"dir:admin:detail:{item['user_id']}",
  570. )
  571. ]
  572. for item in items
  573. ]
  574. navigation: list[InlineKeyboardButton] = []
  575. if page > 1:
  576. navigation.append(
  577. InlineKeyboardButton(
  578. "上一页",
  579. callback_data=f"dir:admin:teachers:{page - 1}",
  580. )
  581. )
  582. if page * 8 < total:
  583. navigation.append(
  584. InlineKeyboardButton(
  585. "下一页",
  586. callback_data=f"dir:admin:teachers:{page + 1}",
  587. )
  588. )
  589. if navigation:
  590. rows.append(navigation)
  591. rows.append([InlineKeyboardButton("待审批", callback_data="dir:admin:pending:1")])
  592. await target.message.edit_text(
  593. f"<b>已批准老师</b>\n共 {total} 人",
  594. parse_mode=ParseMode.HTML,
  595. reply_markup=InlineKeyboardMarkup(rows),
  596. )
  597. await target.answer()
  598. async def _show_admin_teacher_detail(target: CallbackQuery, user_id: int) -> None:
  599. try:
  600. await require_platform_membership(
  601. int(target.from_user.id),
  602. require_admin=True,
  603. )
  604. except DirectoryServiceError as exc:
  605. return await target.answer(str(exc), show_alert=True)
  606. profile = await get_directory_profile(user_id)
  607. if not profile:
  608. return await target.answer("未找到该成员资料。", show_alert=True)
  609. summary = profile_summary(profile, await get_directory_location(user_id))
  610. lines = [
  611. f"<b>{escape(summary['display_name'])}</b>",
  612. f"用户名:@{escape(summary.get('username') or '未设置')}",
  613. f"用户 ID:<code>{user_id}</code>",
  614. f"申请:{escape(APPLICATION_LABELS.get(summary['application_status'], '学生'))}",
  615. f"位置:{escape(summary['region'] or '尚未更新')}",
  616. f"榜单:{'已上榜' if summary['listed'] else '未上榜'}",
  617. f"状态:{'在线' if summary['online'] else '离线'}",
  618. ]
  619. rows: list[list[InlineKeyboardButton]] = []
  620. if summary["application_status"] == APPLICATION_PENDING:
  621. rows.append(
  622. [
  623. InlineKeyboardButton(
  624. "批准",
  625. callback_data=f"dir:admin:approveask:{user_id}",
  626. ),
  627. InlineKeyboardButton(
  628. "拒绝",
  629. callback_data=f"dir:admin:flow:reject:{user_id}",
  630. ),
  631. ]
  632. )
  633. if summary["application_status"] == APPLICATION_APPROVED:
  634. rows.extend(
  635. [
  636. [
  637. InlineKeyboardButton(
  638. "强制下榜" if summary["listed"] else "强制上榜",
  639. callback_data=(
  640. f"dir:admin:flow:"
  641. f"{'unlist' if summary['listed'] else 'list'}:{user_id}"
  642. ),
  643. ),
  644. InlineKeyboardButton(
  645. "强制下线" if summary["online"] else "强制上线",
  646. callback_data=(
  647. f"dir:admin:flow:"
  648. f"{'offline' if summary['online'] else 'online'}:{user_id}"
  649. ),
  650. ),
  651. ],
  652. [
  653. InlineKeyboardButton(
  654. "撤销老师资格",
  655. callback_data=f"dir:admin:flow:revoke:{user_id}",
  656. )
  657. ],
  658. ]
  659. )
  660. rows.append([InlineKeyboardButton("返回审批", callback_data="dir:admin:pending:1")])
  661. await target.message.edit_text(
  662. "\n".join(lines),
  663. parse_mode=ParseMode.HTML,
  664. reply_markup=InlineKeyboardMarkup(rows),
  665. )
  666. try:
  667. await target.answer()
  668. except Exception:
  669. pass
  670. async def _start_admin_reason_flow(
  671. target: CallbackQuery,
  672. *,
  673. action: str,
  674. user_id: int,
  675. ) -> None:
  676. try:
  677. await require_platform_membership(
  678. int(target.from_user.id),
  679. require_admin=True,
  680. )
  681. except DirectoryServiceError as exc:
  682. return await target.answer(str(exc), show_alert=True)
  683. _admin_flows[int(target.from_user.id)] = {
  684. "action": action,
  685. "user_id": int(user_id),
  686. "expires_at": datetime.now(UTC) + timedelta(minutes=10),
  687. }
  688. await target.message.reply_text(
  689. f"请输入“{TEACHER_ACTION_LABELS.get(action, action)}”的原因,"
  690. "发送 /cancel 可取消。"
  691. )
  692. await target.answer()
  693. async def _confirm_admin_action(target: CallbackQuery, token: str) -> None:
  694. confirmation = _admin_confirmations.get(token)
  695. if not confirmation or confirmation["actor_id"] != target.from_user.id:
  696. return await target.answer("确认已失效,请重新操作。", show_alert=True)
  697. if confirmation["expires_at"] < datetime.now(UTC):
  698. _admin_confirmations.pop(token, None)
  699. return await target.answer("确认已超时,请重新操作。", show_alert=True)
  700. action = confirmation["action"]
  701. user_id = int(confirmation["user_id"])
  702. reason = str(confirmation.get("reason") or "")
  703. try:
  704. if action in {"reject", "revoke"}:
  705. profile = await admin_decide_teacher(
  706. actor=target.from_user,
  707. user_id=user_id,
  708. action=action,
  709. reason=reason,
  710. )
  711. else:
  712. profile = await admin_change_teacher_state(
  713. actor=target.from_user,
  714. user_id=user_id,
  715. action=action,
  716. reason=reason,
  717. )
  718. with_reason = f"\n原因:{reason}" if reason else ""
  719. with_suppressed_notification = (
  720. "老师申请已被拒绝" if action == "reject" else
  721. "老师资格已被撤销" if action == "revoke" else
  722. f"老师状态已被管理员修改为“{TEACHER_ACTION_LABELS[action]}”"
  723. )
  724. try:
  725. await app.send_message(
  726. user_id,
  727. f"{with_suppressed_notification}。{with_reason}",
  728. )
  729. except Exception:
  730. pass
  731. _admin_confirmations.pop(token, None)
  732. await target.answer("操作成功。")
  733. await _show_admin_teacher_detail(target, int(profile["user_id"]))
  734. except DirectoryServiceError as exc:
  735. await target.answer(str(exc), show_alert=True)
  736. @app.on_callback_query(filters.regex(r"^dir:"))
  737. async def directory_callback(_, query: CallbackQuery):
  738. parts = str(query.data).split(":")
  739. try:
  740. if parts[1] == "consent":
  741. consent = parts[2] == "yes"
  742. await update_user_geocode_consent(
  743. user=query.from_user,
  744. consent=consent,
  745. )
  746. await query.message.edit_text(
  747. "已同意区域解析,当前位置已进入解析队列。"
  748. if consent
  749. else "已关闭区域解析,位置只用于本地距离计算。"
  750. )
  751. return await query.answer("设置已保存。")
  752. if parts[1] == "radius":
  753. return await _show_radius_picker(query)
  754. if parts[1] == "list":
  755. radius = None if parts[2] == "all" else int(parts[2])
  756. return await _show_teacher_results(
  757. query,
  758. radius_km=radius,
  759. page=int(parts[3]),
  760. )
  761. if parts[1] == "clearask":
  762. return await query.message.edit_text(
  763. "清除位置后会自动下榜并下线,确认继续吗?",
  764. reply_markup=InlineKeyboardMarkup(
  765. [
  766. [
  767. InlineKeyboardButton(
  768. "确认清除",
  769. callback_data="dir:clear",
  770. ),
  771. InlineKeyboardButton("取消", callback_data="dir:cancel"),
  772. ]
  773. ]
  774. ),
  775. )
  776. if parts[1] == "clear":
  777. await clear_user_location(user=query.from_user)
  778. await query.message.edit_text("位置已清除,老师状态已同步下线并下榜。")
  779. return await query.answer("已清除。")
  780. if parts[1] == "cancel":
  781. await query.message.edit_text("已取消。")
  782. return await query.answer()
  783. if parts[1] == "admin":
  784. if parts[2] == "pending":
  785. return await _show_admin_applications(query, page=int(parts[3]))
  786. if parts[2] == "teachers":
  787. return await _show_admin_teachers(query, int(parts[3]))
  788. if parts[2] == "detail":
  789. return await _show_admin_teacher_detail(query, int(parts[3]))
  790. if parts[2] == "approveask":
  791. user_id = int(parts[3])
  792. return await query.message.edit_text(
  793. "批准后老师身份将在全部群和 Bot 中生效,确认继续吗?",
  794. reply_markup=InlineKeyboardMarkup(
  795. [
  796. [
  797. InlineKeyboardButton(
  798. "确认批准",
  799. callback_data=f"dir:admin:approve:{user_id}",
  800. ),
  801. InlineKeyboardButton(
  802. "取消",
  803. callback_data=f"dir:admin:detail:{user_id}",
  804. ),
  805. ]
  806. ]
  807. ),
  808. )
  809. if parts[2] == "approve":
  810. profile = await admin_decide_teacher(
  811. actor=query.from_user,
  812. user_id=int(parts[3]),
  813. action="approve",
  814. )
  815. try:
  816. await app.send_message(
  817. int(profile["user_id"]),
  818. "你的老师申请已通过,可以在菜单中自助上榜。",
  819. )
  820. except Exception:
  821. pass
  822. await query.answer("已批准。")
  823. return await _show_admin_teacher_detail(
  824. query,
  825. int(profile["user_id"]),
  826. )
  827. if parts[2] == "flow":
  828. return await _start_admin_reason_flow(
  829. query,
  830. action=parts[3],
  831. user_id=int(parts[4]),
  832. )
  833. if parts[2] == "confirm":
  834. return await _confirm_admin_action(query, parts[3])
  835. except (DirectoryServiceError, ValueError) as exc:
  836. return await query.answer(str(exc), show_alert=True)
  837. except Exception as exc:
  838. log.error(f"师生目录回调失败:{exc}")
  839. return await query.answer("操作失败,请稍后重试。", show_alert=True)
  840. @app.on_message(filters.command("cancel") & filters.private, group=-20)
  841. async def cancel_directory_flow(_, message: Message):
  842. flow = _admin_flows.pop(message.from_user.id, None) if message.from_user else None
  843. if not flow:
  844. return
  845. await message.reply_text("已取消当前老师管理操作。")
  846. raise StopPropagation
  847. @app.on_message(filters.private & filters.text, group=13)
  848. async def directory_private_text(_, message: Message):
  849. if not message.from_user:
  850. return
  851. flow = _admin_flows.get(message.from_user.id)
  852. if flow:
  853. if flow["expires_at"] < datetime.now(UTC):
  854. _admin_flows.pop(message.from_user.id, None)
  855. return await message.reply_text("操作已超时,请重新打开老师审批。")
  856. reason = str(message.text or "").strip()
  857. if not reason:
  858. return await message.reply_text("原因不能为空,请重新输入。")
  859. token = token_urlsafe(8)
  860. _admin_confirmations[token] = {
  861. **flow,
  862. "actor_id": message.from_user.id,
  863. "reason": reason,
  864. "expires_at": datetime.now(UTC) + timedelta(minutes=10),
  865. }
  866. _admin_flows.pop(message.from_user.id, None)
  867. return await message.reply_text(
  868. f"确认执行“{TEACHER_ACTION_LABELS.get(flow['action'], flow['action'])}”吗?"
  869. f"\n用户 ID:{flow['user_id']}\n原因:{escape(reason)}",
  870. reply_markup=InlineKeyboardMarkup(
  871. [
  872. [
  873. InlineKeyboardButton(
  874. "确认执行",
  875. callback_data=f"dir:admin:confirm:{token}",
  876. ),
  877. InlineKeyboardButton("取消", callback_data="dir:cancel"),
  878. ]
  879. ]
  880. ),
  881. )
  882. text = str(message.text or "").strip()
  883. if text == BUTTON_NEARBY:
  884. return await _show_radius_picker(message)
  885. if text == BUTTON_RANK:
  886. return await _show_teacher_results(message, radius_km=None, page=1)
  887. if text == BUTTON_APPLY:
  888. return await _apply_teacher(message)
  889. if text == BUTTON_STATUS:
  890. return await _show_status(message)
  891. if text == BUTTON_PRIVACY:
  892. return await _show_privacy(message)
  893. if text == BUTTON_CLEAR_LOCATION:
  894. return await message.reply_text(
  895. "清除位置后会自动下榜并下线,确认继续吗?",
  896. reply_markup=InlineKeyboardMarkup(
  897. [
  898. [
  899. InlineKeyboardButton("确认清除", callback_data="dir:clear"),
  900. InlineKeyboardButton("取消", callback_data="dir:cancel"),
  901. ]
  902. ]
  903. ),
  904. )
  905. if text == BUTTON_APPROVAL:
  906. return await _show_admin_applications(message)
  907. action = {
  908. BUTTON_LIST: "list",
  909. BUTTON_UNLIST: "unlist",
  910. BUTTON_ONLINE: "online",
  911. BUTTON_OFFLINE: "offline",
  912. }.get(text)
  913. if action:
  914. return await _self_state_command(message, action)
  915. @app.on_message(filters.group & filters.text, group=13)
  916. async def teacher_presence_group_text(_, message: Message):
  917. if not message.from_user:
  918. return
  919. text = str(message.text or "").strip()
  920. action = {"上线": "online", "下线": "offline"}.get(text)
  921. if not action:
  922. return
  923. profile = await get_directory_profile(message.from_user.id)
  924. if not profile or profile.get("application_status") != APPLICATION_APPROVED:
  925. return
  926. if not await _verify_group_member(message):
  927. return
  928. try:
  929. _, applied = await change_own_teacher_state(
  930. user=message.from_user,
  931. action=action,
  932. source="telegram_group",
  933. idempotency_key=(
  934. f"teacher-presence:{message.chat.id}:{message.id}:"
  935. f"{message.from_user.id}"
  936. ),
  937. chat_id=message.chat.id,
  938. )
  939. if applied:
  940. await message.reply_text(
  941. f"全平台状态已切换为{'在线' if action == 'online' else '离线'}。"
  942. + ("24 小时后将自动下线。" if action == "online" else "")
  943. )
  944. except DirectoryServiceError as exc:
  945. await message.reply_text(str(exc))
  946. @app.on_chat_member_updated(group=13)
  947. async def directory_chat_member_updated(_, update: ChatMemberUpdated):
  948. member = update.new_chat_member or update.old_chat_member
  949. if not member or not member.user or member.user.is_bot:
  950. return
  951. status = update.new_chat_member.status if update.new_chat_member else ChatMemberStatus.LEFT
  952. active = status in {
  953. ChatMemberStatus.OWNER,
  954. ChatMemberStatus.ADMINISTRATOR,
  955. ChatMemberStatus.MEMBER,
  956. ChatMemberStatus.RESTRICTED,
  957. }
  958. await observe_group_member(
  959. chat_id=update.chat.id,
  960. chat_title=update.chat.title or "",
  961. user=member.user,
  962. status=status_value(status),
  963. active=active,
  964. verified=True,
  965. )
  966. start_presence_sweeper()