| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036 |
- from __future__ import annotations
- from datetime import UTC, datetime, timedelta
- from html import escape
- from secrets import token_urlsafe
- from typing import Any
- from pyrogram import StopPropagation, filters
- from pyrogram.enums import ChatMemberStatus, ParseMode
- from pyrogram.types import (
- CallbackQuery,
- ChatMemberUpdated,
- InlineKeyboardButton,
- InlineKeyboardMarkup,
- KeyboardButton,
- Message,
- ReplyKeyboardMarkup,
- )
- from wbb import BOT_USERNAME, app, log
- from wbb.services.directory import (
- DirectoryServiceError,
- admin_change_teacher_state,
- admin_decide_teacher,
- apply_as_teacher,
- change_own_teacher_state,
- clear_user_location,
- directory_for_user,
- format_distance,
- observe_directory_user,
- observe_group_member,
- profile_summary,
- public_teacher,
- require_platform_membership,
- start_presence_sweeper,
- status_value,
- update_user_geocode_consent,
- update_user_location,
- verify_platform_membership,
- )
- from wbb.services.directory_geocoding import (
- NOMINATIM_ATTRIBUTION,
- NOMINATIM_ATTRIBUTION_URL,
- )
- from wbb.utils.dbdirectory import (
- APPLICATION_APPROVED,
- APPLICATION_PENDING,
- APPLICATION_REJECTED,
- APPLICATION_REVOKED,
- get_directory_location,
- get_directory_profile,
- list_directory_profiles,
- list_teacher_applications,
- )
- __MODULE__ = "师生与附近"
- __HELP__ = """/directory - 打开师生服务菜单或在群内验证成员身份。
- /nearby - 选择范围并查找附近老师。
- /teacher_rank - 按距离查看全部上榜老师。
- /teacher_apply - 申请成为老师。
- /teacher_online - 老师上线。
- /teacher_offline - 老师下线。
- /teacher_list - 老师上榜。
- /teacher_unlist - 老师下榜。"""
- APPLICATION_LABELS = {
- "none": "学生",
- APPLICATION_PENDING: "老师申请待审批",
- APPLICATION_APPROVED: "老师",
- APPLICATION_REJECTED: "老师申请已拒绝",
- APPLICATION_REVOKED: "老师资格已撤销",
- }
- TEACHER_ACTION_LABELS = {
- "list": "上榜",
- "unlist": "下榜",
- "online": "上线",
- "offline": "下线",
- }
- BUTTON_NEARBY = "附近老师"
- BUTTON_RANK = "老师榜单"
- BUTTON_APPLY = "申请成为老师"
- BUTTON_APPROVAL = "老师审批"
- BUTTON_STATUS = "我的状态"
- BUTTON_LIST = "上榜"
- BUTTON_UNLIST = "下榜"
- BUTTON_ONLINE = "上线"
- BUTTON_OFFLINE = "下线"
- BUTTON_PRIVACY = "位置隐私"
- BUTTON_CLEAR_LOCATION = "清除位置"
- _admin_flows: dict[int, dict[str, Any]] = {}
- _admin_confirmations: dict[str, dict[str, Any]] = {}
- def _display_name(profile: dict[str, Any]) -> str:
- return str(profile.get("display_name") or f"用户 {profile['user_id']}")
- def _directory_keyboard(
- profile: dict[str, Any] | None,
- *,
- is_admin: bool,
- ) -> ReplyKeyboardMarkup:
- status = str((profile or {}).get("application_status") or "none")
- rows: list[list[KeyboardButton]] = [
- [KeyboardButton("更新位置", request_location=True)],
- [KeyboardButton(BUTTON_NEARBY), KeyboardButton(BUTTON_RANK)],
- ]
- if status == APPLICATION_APPROVED:
- rows.extend(
- [
- [
- KeyboardButton(
- BUTTON_UNLIST if profile and profile.get("listed") else BUTTON_LIST
- ),
- KeyboardButton(
- BUTTON_OFFLINE
- if profile and profile.get("online")
- else BUTTON_ONLINE
- ),
- ],
- [KeyboardButton(BUTTON_STATUS)],
- ]
- )
- else:
- rows.append([KeyboardButton(BUTTON_APPLY), KeyboardButton(BUTTON_STATUS)])
- rows.append([KeyboardButton(BUTTON_PRIVACY), KeyboardButton(BUTTON_CLEAR_LOCATION)])
- if is_admin:
- rows.append([KeyboardButton(BUTTON_APPROVAL)])
- return ReplyKeyboardMarkup(
- rows,
- resize_keyboard=True,
- is_persistent=True,
- selective=True,
- placeholder="选择师生服务或输入消息",
- )
- async def send_directory_menu(message: Message) -> None:
- if not message.from_user:
- return
- try:
- await require_platform_membership(int(message.from_user.id))
- except DirectoryServiceError as exc:
- await message.reply_text(str(exc))
- return
- profile = await observe_directory_user(message.from_user)
- location = await get_directory_location(int(message.from_user.id))
- admin_result = await verify_platform_membership(
- user_id=int(message.from_user.id),
- require_admin=True,
- )
- summary = profile_summary(profile, location)
- status_label = APPLICATION_LABELS.get(summary["application_status"], "学生")
- lines = [
- "<b>师生与附近</b>",
- f"身份:{escape(status_label)}",
- f"位置:{escape(summary['region'] or '尚未更新')}",
- ]
- if summary["application_status"] == APPLICATION_APPROVED:
- lines.extend(
- [
- f"榜单:{'已上榜' if summary['listed'] else '未上榜'}",
- f"状态:{'在线' if summary['online'] else '离线'}",
- ]
- )
- await message.reply_text(
- "\n".join(lines),
- parse_mode=ParseMode.HTML,
- reply_markup=_directory_keyboard(
- {**profile, "online": summary["online"]},
- is_admin=bool(admin_result.get("allowed")),
- ),
- )
- async def _verify_group_member(message: Message) -> bool:
- if not message.from_user:
- return False
- try:
- member = await app.get_chat_member(message.chat.id, message.from_user.id)
- except Exception:
- await message.reply_text("暂时无法验证你的群成员身份,请稍后重试。")
- return False
- active = member.status in {
- ChatMemberStatus.OWNER,
- ChatMemberStatus.ADMINISTRATOR,
- ChatMemberStatus.MEMBER,
- ChatMemberStatus.RESTRICTED,
- }
- await observe_group_member(
- chat_id=message.chat.id,
- chat_title=message.chat.title or "",
- user=message.from_user,
- status=status_value(member.status),
- active=active,
- verified=True,
- )
- if not active:
- await message.reply_text("该功能仅对当前群成员开放。")
- return active
- @app.on_message(filters.command("directory"))
- async def directory_command(_, message: Message):
- if message.chat.type.value == "private":
- return await send_directory_menu(message)
- if not await _verify_group_member(message):
- return
- url = f"https://t.me/{BOT_USERNAME}?start=directory"
- await message.reply_text(
- "身份验证成功。请点击下方按钮在私聊中使用师生与附近功能。",
- reply_markup=InlineKeyboardMarkup(
- [[InlineKeyboardButton("打开师生服务", url=url)]]
- ),
- )
- @app.on_message(filters.command("nearby") & filters.private)
- async def nearby_command(_, message: Message):
- await _show_radius_picker(message)
- @app.on_message(filters.command("teacher_rank") & filters.private)
- async def teacher_rank_command(_, message: Message):
- await _show_teacher_results(message, radius_km=None, page=1)
- @app.on_message(filters.command("teacher_apply") & filters.private)
- async def teacher_apply_command(_, message: Message):
- await _apply_teacher(message)
- async def _self_state_command(message: Message, action: str) -> None:
- if not message.from_user:
- return
- try:
- profile, _ = await change_own_teacher_state(
- user=message.from_user,
- action=action,
- )
- await message.reply_text(
- f"已{TEACHER_ACTION_LABELS[action]}。"
- + (
- "本次上线状态将在 24 小时后自动失效。"
- if action == "online"
- else ""
- )
- )
- await _refresh_keyboard(message, profile)
- except DirectoryServiceError as exc:
- await message.reply_text(str(exc))
- @app.on_message(filters.command("teacher_online") & filters.private)
- async def teacher_online_command(_, message: Message):
- await _self_state_command(message, "online")
- @app.on_message(filters.command("teacher_offline") & filters.private)
- async def teacher_offline_command(_, message: Message):
- await _self_state_command(message, "offline")
- @app.on_message(filters.command("teacher_list") & filters.private)
- async def teacher_list_command(_, message: Message):
- await _self_state_command(message, "list")
- @app.on_message(filters.command("teacher_unlist") & filters.private)
- async def teacher_unlist_command(_, message: Message):
- await _self_state_command(message, "unlist")
- @app.on_message(filters.private & filters.location, group=12)
- async def directory_location_message(_, message: Message):
- if not message.from_user or not message.location:
- return
- try:
- location, previous_consent = await update_user_location(
- user=message.from_user,
- longitude=message.location.longitude,
- latitude=message.location.latitude,
- )
- except DirectoryServiceError as exc:
- return await message.reply_text(str(exc))
- await message.reply_text("位置已更新,可立即使用附近老师和老师榜单。")
- if previous_consent is None:
- await message.reply_text(
- "是否同意将本次及以后更新的精确坐标发送给 "
- "OpenStreetMap Nominatim,仅用于解析省、市、区县?\n\n"
- "不会发送 Telegram 用户信息;选择“仅计算距离”后,附近功能仍可正常使用。",
- reply_markup=InlineKeyboardMarkup(
- [
- [
- InlineKeyboardButton(
- "同意解析区域",
- callback_data="dir:consent:yes",
- ),
- InlineKeyboardButton(
- "仅计算距离",
- callback_data="dir:consent:no",
- ),
- ]
- ]
- ),
- )
- elif previous_consent is True:
- await message.reply_text("区域解析已进入队列,完成前会显示“区域暂不可用”。")
- await _refresh_keyboard(message, await get_directory_profile(message.from_user.id))
- async def _refresh_keyboard(
- message: Message,
- profile: dict[str, Any] | None,
- ) -> None:
- if not message.from_user:
- return
- admin_result = await verify_platform_membership(
- user_id=int(message.from_user.id),
- require_admin=True,
- )
- summary = profile_summary(
- profile or {"user_id": message.from_user.id},
- await get_directory_location(message.from_user.id),
- )
- await message.reply_text(
- "菜单已更新。",
- reply_markup=_directory_keyboard(
- {**(profile or {}), "online": summary["online"]},
- is_admin=bool(admin_result.get("allowed")),
- ),
- )
- async def _apply_teacher(message: Message) -> None:
- if not message.from_user:
- return
- try:
- profile = await apply_as_teacher(user=message.from_user)
- except DirectoryServiceError as exc:
- return await message.reply_text(str(exc))
- await message.reply_text(
- "老师申请已提交,管理员审批后会通过申请来源机器人通知你。"
- if profile.get("application_status") == APPLICATION_PENDING
- else "当前申请状态未发生变化。"
- )
- await _refresh_keyboard(message, profile)
- async def _show_status(message: Message) -> None:
- if not message.from_user:
- return
- profile = await observe_directory_user(message.from_user)
- summary = profile_summary(profile, await get_directory_location(message.from_user.id))
- lines = [
- "<b>我的师生状态</b>",
- f"身份:{escape(APPLICATION_LABELS.get(summary['application_status'], '学生'))}",
- f"位置:{escape(summary['region'] or '尚未更新')}",
- ]
- if summary["application_status"] == APPLICATION_APPROVED:
- lines.extend(
- [
- f"榜单:{'已上榜' if summary['listed'] else '未上榜'}",
- f"上下线:{'在线' if summary['online'] else '离线'}",
- (
- "自动下线:"
- + escape(
- summary["online_until"].astimezone(UTC).strftime(
- "%Y-%m-%d %H:%M UTC"
- )
- )
- if summary["online"] and summary["online_until"]
- else ""
- ),
- ]
- )
- await message.reply_text(
- "\n".join(line for line in lines if line),
- parse_mode=ParseMode.HTML,
- )
- async def _show_privacy(message: Message) -> None:
- if not message.from_user:
- return
- location = await get_directory_location(message.from_user.id)
- if not location:
- return await message.reply_text("尚未保存位置。")
- consent = location.get("geocode_consent")
- text = {
- True: "当前已同意将精确坐标发送给 Nominatim 解析行政区域。",
- False: "当前只在本系统保存位置并计算距离,不向地图服务发送坐标。",
- None: "尚未选择是否使用 Nominatim 解析行政区域。",
- }[consent]
- await message.reply_text(
- text
- + "\n关闭授权只影响后续请求;第三方已接收的历史请求无法撤回。",
- reply_markup=InlineKeyboardMarkup(
- [
- [
- InlineKeyboardButton("同意区域解析", callback_data="dir:consent:yes"),
- InlineKeyboardButton("关闭区域解析", callback_data="dir:consent:no"),
- ]
- ]
- ),
- )
- async def _show_radius_picker(target: Message | CallbackQuery) -> None:
- markup = InlineKeyboardMarkup(
- [
- [
- InlineKeyboardButton(
- f"{radius} 公里",
- callback_data=f"dir:list:{radius}:1",
- )
- for radius in (5, 10)
- ],
- [
- InlineKeyboardButton(
- f"{radius} 公里",
- callback_data=f"dir:list:{radius}:1",
- )
- for radius in (20, 50)
- ],
- ]
- )
- if isinstance(target, CallbackQuery):
- await target.message.edit_text("请选择附近老师的搜索范围:", reply_markup=markup)
- else:
- await target.reply_text("请选择附近老师的搜索范围:", reply_markup=markup)
- def _teacher_result_markup(
- teachers: list[dict[str, Any]],
- *,
- radius_key: str,
- page: int,
- total: int,
- ) -> InlineKeyboardMarkup:
- rows: list[list[InlineKeyboardButton]] = []
- for item in teachers:
- username = str(item.get("username") or "")
- label = f"{item['display_name']} (@{username})"
- rows.append(
- [
- InlineKeyboardButton(
- label[:48],
- url=f"https://t.me/{username}",
- )
- ]
- )
- navigation: list[InlineKeyboardButton] = []
- if page > 1:
- navigation.append(
- InlineKeyboardButton(
- "上一页",
- callback_data=f"dir:list:{radius_key}:{page - 1}",
- )
- )
- if page * 10 < total:
- navigation.append(
- InlineKeyboardButton(
- "下一页",
- callback_data=f"dir:list:{radius_key}:{page + 1}",
- )
- )
- if navigation:
- rows.append(navigation)
- rows.append([InlineKeyboardButton("切换附近范围", callback_data="dir:radius")])
- return InlineKeyboardMarkup(rows)
- async def _show_teacher_results(
- target: Message | CallbackQuery,
- *,
- radius_km: int | None,
- page: int,
- ) -> None:
- user = target.from_user
- try:
- raw_items, total = await directory_for_user(
- user=user,
- radius_km=radius_km,
- page=page,
- page_size=10,
- )
- except DirectoryServiceError as exc:
- if isinstance(target, CallbackQuery):
- return await target.answer(str(exc), show_alert=True)
- return await target.reply_text(str(exc))
- teachers = [public_teacher(item) for item in raw_items]
- title = (
- f"<b>{radius_km} 公里内的老师</b>"
- if radius_km is not None
- else "<b>老师榜单</b>"
- )
- lines = [title, f"共 {total} 位已上榜老师,按距离排序。"]
- for index, item in enumerate(teachers, start=(page - 1) * 10 + 1):
- lines.append(
- f"\n{index}. <b>{escape(item['display_name'])}</b> "
- f"(@{escape(item['username'])})\n"
- f"状态:{'在线' if item['online'] else '离线'} | "
- f"距离:{format_distance(item['distance_meters'])} | "
- f"区域:{escape(item['region'])}"
- )
- if not teachers:
- lines.append("\n当前范围内没有已上榜老师。")
- lines.append(
- f'\n<a href="{NOMINATIM_ATTRIBUTION_URL}">{NOMINATIM_ATTRIBUTION}</a>'
- )
- markup = _teacher_result_markup(
- teachers,
- radius_key=str(radius_km) if radius_km is not None else "all",
- page=page,
- total=total,
- )
- if isinstance(target, CallbackQuery):
- await target.message.edit_text(
- "\n".join(lines),
- parse_mode=ParseMode.HTML,
- disable_web_page_preview=True,
- reply_markup=markup,
- )
- await target.answer()
- else:
- await target.reply_text(
- "\n".join(lines),
- parse_mode=ParseMode.HTML,
- disable_web_page_preview=True,
- reply_markup=markup,
- )
- async def _show_admin_applications(
- target: Message | CallbackQuery,
- *,
- page: int = 1,
- ) -> None:
- try:
- await require_platform_membership(int(target.from_user.id), require_admin=True)
- except DirectoryServiceError as exc:
- if isinstance(target, CallbackQuery):
- return await target.answer(str(exc), show_alert=True)
- return await target.reply_text(str(exc))
- items, total = await list_teacher_applications(
- status=APPLICATION_PENDING,
- page=page,
- page_size=5,
- )
- lines = ["<b>老师申请审批</b>", f"待审批:{total}"]
- rows: list[list[InlineKeyboardButton]] = []
- for item in items:
- lines.append(
- f"\n{escape(_display_name(item))} (@{escape(item.get('username') or '')})"
- f"\n用户 ID:<code>{item['user_id']}</code>"
- )
- rows.append(
- [
- InlineKeyboardButton(
- f"查看 {_display_name(item)[:18]}",
- callback_data=f"dir:admin:detail:{item['user_id']}",
- )
- ]
- )
- if page > 1:
- rows.append(
- [
- InlineKeyboardButton(
- "上一页",
- callback_data=f"dir:admin:pending:{page - 1}",
- )
- ]
- )
- if page * 5 < total:
- rows.append(
- [
- InlineKeyboardButton(
- "下一页",
- callback_data=f"dir:admin:pending:{page + 1}",
- )
- ]
- )
- rows.append(
- [InlineKeyboardButton("已批准老师", callback_data="dir:admin:teachers:1")]
- )
- markup = InlineKeyboardMarkup(rows)
- if isinstance(target, CallbackQuery):
- await target.message.edit_text(
- "\n".join(lines),
- parse_mode=ParseMode.HTML,
- reply_markup=markup,
- )
- await target.answer()
- else:
- await target.reply_text(
- "\n".join(lines),
- parse_mode=ParseMode.HTML,
- reply_markup=markup,
- )
- async def _show_admin_teachers(target: CallbackQuery, page: int) -> None:
- try:
- await require_platform_membership(
- int(target.from_user.id),
- require_admin=True,
- )
- except DirectoryServiceError as exc:
- return await target.answer(str(exc), show_alert=True)
- items, total = await list_directory_profiles(
- application_status=APPLICATION_APPROVED,
- page=page,
- page_size=8,
- )
- rows = [
- [
- InlineKeyboardButton(
- _display_name(item)[:28],
- callback_data=f"dir:admin:detail:{item['user_id']}",
- )
- ]
- for item in items
- ]
- navigation: list[InlineKeyboardButton] = []
- if page > 1:
- navigation.append(
- InlineKeyboardButton(
- "上一页",
- callback_data=f"dir:admin:teachers:{page - 1}",
- )
- )
- if page * 8 < total:
- navigation.append(
- InlineKeyboardButton(
- "下一页",
- callback_data=f"dir:admin:teachers:{page + 1}",
- )
- )
- if navigation:
- rows.append(navigation)
- rows.append([InlineKeyboardButton("待审批", callback_data="dir:admin:pending:1")])
- await target.message.edit_text(
- f"<b>已批准老师</b>\n共 {total} 人",
- parse_mode=ParseMode.HTML,
- reply_markup=InlineKeyboardMarkup(rows),
- )
- await target.answer()
- async def _show_admin_teacher_detail(target: CallbackQuery, user_id: int) -> None:
- try:
- await require_platform_membership(
- int(target.from_user.id),
- require_admin=True,
- )
- except DirectoryServiceError as exc:
- return await target.answer(str(exc), show_alert=True)
- profile = await get_directory_profile(user_id)
- if not profile:
- return await target.answer("未找到该成员资料。", show_alert=True)
- summary = profile_summary(profile, await get_directory_location(user_id))
- lines = [
- f"<b>{escape(summary['display_name'])}</b>",
- f"用户名:@{escape(summary.get('username') or '未设置')}",
- f"用户 ID:<code>{user_id}</code>",
- f"申请:{escape(APPLICATION_LABELS.get(summary['application_status'], '学生'))}",
- f"位置:{escape(summary['region'] or '尚未更新')}",
- f"榜单:{'已上榜' if summary['listed'] else '未上榜'}",
- f"状态:{'在线' if summary['online'] else '离线'}",
- ]
- rows: list[list[InlineKeyboardButton]] = []
- if summary["application_status"] == APPLICATION_PENDING:
- rows.append(
- [
- InlineKeyboardButton(
- "批准",
- callback_data=f"dir:admin:approveask:{user_id}",
- ),
- InlineKeyboardButton(
- "拒绝",
- callback_data=f"dir:admin:flow:reject:{user_id}",
- ),
- ]
- )
- if summary["application_status"] == APPLICATION_APPROVED:
- rows.extend(
- [
- [
- InlineKeyboardButton(
- "强制下榜" if summary["listed"] else "强制上榜",
- callback_data=(
- f"dir:admin:flow:"
- f"{'unlist' if summary['listed'] else 'list'}:{user_id}"
- ),
- ),
- InlineKeyboardButton(
- "强制下线" if summary["online"] else "强制上线",
- callback_data=(
- f"dir:admin:flow:"
- f"{'offline' if summary['online'] else 'online'}:{user_id}"
- ),
- ),
- ],
- [
- InlineKeyboardButton(
- "撤销老师资格",
- callback_data=f"dir:admin:flow:revoke:{user_id}",
- )
- ],
- ]
- )
- rows.append([InlineKeyboardButton("返回审批", callback_data="dir:admin:pending:1")])
- await target.message.edit_text(
- "\n".join(lines),
- parse_mode=ParseMode.HTML,
- reply_markup=InlineKeyboardMarkup(rows),
- )
- try:
- await target.answer()
- except Exception:
- pass
- async def _start_admin_reason_flow(
- target: CallbackQuery,
- *,
- action: str,
- user_id: int,
- ) -> None:
- try:
- await require_platform_membership(
- int(target.from_user.id),
- require_admin=True,
- )
- except DirectoryServiceError as exc:
- return await target.answer(str(exc), show_alert=True)
- _admin_flows[int(target.from_user.id)] = {
- "action": action,
- "user_id": int(user_id),
- "expires_at": datetime.now(UTC) + timedelta(minutes=10),
- }
- await target.message.reply_text(
- f"请输入“{TEACHER_ACTION_LABELS.get(action, action)}”的原因,"
- "发送 /cancel 可取消。"
- )
- await target.answer()
- async def _confirm_admin_action(target: CallbackQuery, token: str) -> None:
- confirmation = _admin_confirmations.get(token)
- if not confirmation or confirmation["actor_id"] != target.from_user.id:
- return await target.answer("确认已失效,请重新操作。", show_alert=True)
- if confirmation["expires_at"] < datetime.now(UTC):
- _admin_confirmations.pop(token, None)
- return await target.answer("确认已超时,请重新操作。", show_alert=True)
- action = confirmation["action"]
- user_id = int(confirmation["user_id"])
- reason = str(confirmation.get("reason") or "")
- try:
- if action in {"reject", "revoke"}:
- profile = await admin_decide_teacher(
- actor=target.from_user,
- user_id=user_id,
- action=action,
- reason=reason,
- )
- else:
- profile = await admin_change_teacher_state(
- actor=target.from_user,
- user_id=user_id,
- action=action,
- reason=reason,
- )
- with_reason = f"\n原因:{reason}" if reason else ""
- with_suppressed_notification = (
- "老师申请已被拒绝" if action == "reject" else
- "老师资格已被撤销" if action == "revoke" else
- f"老师状态已被管理员修改为“{TEACHER_ACTION_LABELS[action]}”"
- )
- try:
- await app.send_message(
- user_id,
- f"{with_suppressed_notification}。{with_reason}",
- )
- except Exception:
- pass
- _admin_confirmations.pop(token, None)
- await target.answer("操作成功。")
- await _show_admin_teacher_detail(target, int(profile["user_id"]))
- except DirectoryServiceError as exc:
- await target.answer(str(exc), show_alert=True)
- @app.on_callback_query(filters.regex(r"^dir:"))
- async def directory_callback(_, query: CallbackQuery):
- parts = str(query.data).split(":")
- try:
- if parts[1] == "consent":
- consent = parts[2] == "yes"
- await update_user_geocode_consent(
- user=query.from_user,
- consent=consent,
- )
- await query.message.edit_text(
- "已同意区域解析,当前位置已进入解析队列。"
- if consent
- else "已关闭区域解析,位置只用于本地距离计算。"
- )
- return await query.answer("设置已保存。")
- if parts[1] == "radius":
- return await _show_radius_picker(query)
- if parts[1] == "list":
- radius = None if parts[2] == "all" else int(parts[2])
- return await _show_teacher_results(
- query,
- radius_km=radius,
- page=int(parts[3]),
- )
- if parts[1] == "clearask":
- return await query.message.edit_text(
- "清除位置后会自动下榜并下线,确认继续吗?",
- reply_markup=InlineKeyboardMarkup(
- [
- [
- InlineKeyboardButton(
- "确认清除",
- callback_data="dir:clear",
- ),
- InlineKeyboardButton("取消", callback_data="dir:cancel"),
- ]
- ]
- ),
- )
- if parts[1] == "clear":
- await clear_user_location(user=query.from_user)
- await query.message.edit_text("位置已清除,老师状态已同步下线并下榜。")
- return await query.answer("已清除。")
- if parts[1] == "cancel":
- await query.message.edit_text("已取消。")
- return await query.answer()
- if parts[1] == "admin":
- if parts[2] == "pending":
- return await _show_admin_applications(query, page=int(parts[3]))
- if parts[2] == "teachers":
- return await _show_admin_teachers(query, int(parts[3]))
- if parts[2] == "detail":
- return await _show_admin_teacher_detail(query, int(parts[3]))
- if parts[2] == "approveask":
- user_id = int(parts[3])
- return await query.message.edit_text(
- "批准后老师身份将在全部群和 Bot 中生效,确认继续吗?",
- reply_markup=InlineKeyboardMarkup(
- [
- [
- InlineKeyboardButton(
- "确认批准",
- callback_data=f"dir:admin:approve:{user_id}",
- ),
- InlineKeyboardButton(
- "取消",
- callback_data=f"dir:admin:detail:{user_id}",
- ),
- ]
- ]
- ),
- )
- if parts[2] == "approve":
- profile = await admin_decide_teacher(
- actor=query.from_user,
- user_id=int(parts[3]),
- action="approve",
- )
- try:
- await app.send_message(
- int(profile["user_id"]),
- "你的老师申请已通过,可以在菜单中自助上榜。",
- )
- except Exception:
- pass
- await query.answer("已批准。")
- return await _show_admin_teacher_detail(
- query,
- int(profile["user_id"]),
- )
- if parts[2] == "flow":
- return await _start_admin_reason_flow(
- query,
- action=parts[3],
- user_id=int(parts[4]),
- )
- if parts[2] == "confirm":
- return await _confirm_admin_action(query, parts[3])
- except (DirectoryServiceError, ValueError) as exc:
- return await query.answer(str(exc), show_alert=True)
- except Exception as exc:
- log.error(f"师生目录回调失败:{exc}")
- return await query.answer("操作失败,请稍后重试。", show_alert=True)
- @app.on_message(filters.command("cancel") & filters.private, group=-20)
- async def cancel_directory_flow(_, message: Message):
- flow = _admin_flows.pop(message.from_user.id, None) if message.from_user else None
- if not flow:
- return
- await message.reply_text("已取消当前老师管理操作。")
- raise StopPropagation
- @app.on_message(filters.private & filters.text, group=13)
- async def directory_private_text(_, message: Message):
- if not message.from_user:
- return
- flow = _admin_flows.get(message.from_user.id)
- if flow:
- if flow["expires_at"] < datetime.now(UTC):
- _admin_flows.pop(message.from_user.id, None)
- return await message.reply_text("操作已超时,请重新打开老师审批。")
- reason = str(message.text or "").strip()
- if not reason:
- return await message.reply_text("原因不能为空,请重新输入。")
- token = token_urlsafe(8)
- _admin_confirmations[token] = {
- **flow,
- "actor_id": message.from_user.id,
- "reason": reason,
- "expires_at": datetime.now(UTC) + timedelta(minutes=10),
- }
- _admin_flows.pop(message.from_user.id, None)
- return await message.reply_text(
- f"确认执行“{TEACHER_ACTION_LABELS.get(flow['action'], flow['action'])}”吗?"
- f"\n用户 ID:{flow['user_id']}\n原因:{escape(reason)}",
- reply_markup=InlineKeyboardMarkup(
- [
- [
- InlineKeyboardButton(
- "确认执行",
- callback_data=f"dir:admin:confirm:{token}",
- ),
- InlineKeyboardButton("取消", callback_data="dir:cancel"),
- ]
- ]
- ),
- )
- text = str(message.text or "").strip()
- if text == BUTTON_NEARBY:
- return await _show_radius_picker(message)
- if text == BUTTON_RANK:
- return await _show_teacher_results(message, radius_km=None, page=1)
- if text == BUTTON_APPLY:
- return await _apply_teacher(message)
- if text == BUTTON_STATUS:
- return await _show_status(message)
- if text == BUTTON_PRIVACY:
- return await _show_privacy(message)
- if text == BUTTON_CLEAR_LOCATION:
- return await message.reply_text(
- "清除位置后会自动下榜并下线,确认继续吗?",
- reply_markup=InlineKeyboardMarkup(
- [
- [
- InlineKeyboardButton("确认清除", callback_data="dir:clear"),
- InlineKeyboardButton("取消", callback_data="dir:cancel"),
- ]
- ]
- ),
- )
- if text == BUTTON_APPROVAL:
- return await _show_admin_applications(message)
- action = {
- BUTTON_LIST: "list",
- BUTTON_UNLIST: "unlist",
- BUTTON_ONLINE: "online",
- BUTTON_OFFLINE: "offline",
- }.get(text)
- if action:
- return await _self_state_command(message, action)
- @app.on_message(filters.group & filters.text, group=13)
- async def teacher_presence_group_text(_, message: Message):
- if not message.from_user:
- return
- text = str(message.text or "").strip()
- action = {"上线": "online", "下线": "offline"}.get(text)
- if not action:
- return
- profile = await get_directory_profile(message.from_user.id)
- if not profile or profile.get("application_status") != APPLICATION_APPROVED:
- return
- if not await _verify_group_member(message):
- return
- try:
- _, applied = await change_own_teacher_state(
- user=message.from_user,
- action=action,
- source="telegram_group",
- idempotency_key=(
- f"teacher-presence:{message.chat.id}:{message.id}:"
- f"{message.from_user.id}"
- ),
- chat_id=message.chat.id,
- )
- if applied:
- await message.reply_text(
- f"全平台状态已切换为{'在线' if action == 'online' else '离线'}。"
- + ("24 小时后将自动下线。" if action == "online" else "")
- )
- except DirectoryServiceError as exc:
- await message.reply_text(str(exc))
- @app.on_chat_member_updated(group=13)
- async def directory_chat_member_updated(_, update: ChatMemberUpdated):
- member = update.new_chat_member or update.old_chat_member
- if not member or not member.user or member.user.is_bot:
- return
- status = update.new_chat_member.status if update.new_chat_member else ChatMemberStatus.LEFT
- active = status in {
- ChatMemberStatus.OWNER,
- ChatMemberStatus.ADMINISTRATOR,
- ChatMemberStatus.MEMBER,
- ChatMemberStatus.RESTRICTED,
- }
- await observe_group_member(
- chat_id=update.chat.id,
- chat_title=update.chat.title or "",
- user=member.user,
- status=status_value(status),
- active=active,
- verified=True,
- )
- start_presence_sweeper()
|