Files
tg-spam-guard/handlers/bind.py
T
2026-07-06 19:26:00 +08:00

66 lines
2.2 KiB
Python

"""账号绑定 handler"""
import asyncio
import logging
from telegram import Update
from telegram.ext import ContextTypes, CommandHandler, filters
from db.models import Action
from services.bind_service import generate_bind_token, unbind, get_binding
logger = logging.getLogger("spam_guard")
async def cmd_bind(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""绑定 harvest 账号"""
user = update.effective_user
# 检查是否已绑定
existing = await get_binding(user.id)
if existing:
reply = await update.message.reply_text(
f"🔗 你已绑定 harvest 账号\n"
f"📦 UID: {existing['harvest_uid']}\n"
f"📅 绑定时间: {existing['bound_at']}\n\n"
f"如需重新绑定,先 /unbind"
)
asyncio.create_task(auto_delete(update.message))
asyncio.create_task(auto_delete(reply))
return
token, url = generate_bind_token(user.id, user.username or user.first_name)
reply = await update.message.reply_text(
"🔗 账号绑定\n"
"━━━━━━━━━━━━━━━━━━━━\n\n"
f"请点击以下链接完成绑定:\n{url}\n\n"
"⏳ 链接 5 分钟内有效"
)
asyncio.create_task(auto_delete(update.message))
asyncio.create_task(auto_delete(reply, seconds=120))
async def cmd_unbind(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""解绑 harvest 账号"""
user = update.effective_user
deleted = await unbind(user.id)
if deleted:
reply = await update.message.reply_text("🔓 已解除账号绑定")
await Action.create(action="UNBIND", user_id=user.id, username=user.username)
else:
reply = await update.message.reply_text("❌ 你没有绑定的账号")
asyncio.create_task(auto_delete(update.message))
asyncio.create_task(auto_delete(reply))
async def auto_delete(message, seconds=60):
try:
await asyncio.sleep(seconds)
await message.delete()
except Exception:
pass
def register_bind(app):
app.add_handler(CommandHandler("bind", cmd_bind, filters.ChatType.GROUPS))
app.add_handler(CommandHandler("unbind", cmd_unbind, filters.ChatType.GROUPS))