Files
tg-spam-guard/services/message_utils.py
T

40 lines
1.4 KiB
Python

"""消息工具函数"""
from __future__ import annotations
import asyncio
import logging
import config
logger = logging.getLogger("spam_guard")
async def auto_delete(message, seconds: int | None = None) -> None:
"""延迟删除消息。删除失败不影响主流程。"""
if not message:
return
try:
await asyncio.sleep(seconds or config.AUTO_DELETE_SECONDS)
await message.delete()
except Exception as e:
logger.debug(f"自动删除消息失败: {e}")
def schedule_delete(message, seconds: int | None = None) -> None:
"""创建自动删除任务。"""
asyncio.create_task(auto_delete(message, seconds=seconds))
async def safe_reply(update, context, text: str, **kwargs):
"""优先回复原消息;原消息已被删除/不可回复时,降级为普通群消息。"""
try:
if update and update.message:
return await update.message.reply_text(text, **kwargs)
except Exception as e:
if "Message to be replied not found" not in str(e):
logger.warning(f"回复消息失败,降级普通发送: {type(e).__name__}: {e}")
chat_id = update.effective_chat.id if update and update.effective_chat else None
if not chat_id:
raise RuntimeError("missing chat_id for safe_reply")
return await context.bot.send_message(chat_id=chat_id, text=text, **kwargs)