Python开发Telegram Bot:实现App启动时发送欢迎消息求助
Telegram Bot启动时发送欢迎消息的实现方法
核心问题是启动时Bot未完成初始化,或缺少目标用户的ID记录,以下是具体实现步骤:
1. 先记录交互过的用户ID
你需要先把所有和Bot聊过的用户ID存起来,比如用文本文件或数据库,示例用文本文件:
from telegram import Update from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes # 保存用户ID到文件,避免重复存储 def save_user_id(user_id): with open('user_ids.txt', 'a+') as f: f.seek(0) existing_ids = [int(line.strip()) for line in f if line.strip().isdigit()] if user_id not in existing_ids: f.write(f"{user_id}\n") # 处理/start命令,同时保存用户ID async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): user_id = update.effective_user.id save_user_id(user_id) await context.bot.send_message(chat_id=user_id, text="欢迎使用本Bot!")
2. 启动时批量发送欢迎消息
在Bot初始化完成后,读取存储的用户ID,逐个发送消息,以下两种方式可选:
方式一:启动前异步发送
import asyncio async def send_welcome_on_startup(application): # 读取已存储的用户ID try: with open('user_ids.txt', 'r') as f: user_ids = [int(line.strip()) for line in f if line.strip().isdigit()] # 逐个发送消息,加短延迟避免触发频率限制 for user_id in user_ids: try: await application.bot.send_message(chat_id=user_id, text="Bot已重启上线,欢迎回来!") await asyncio.sleep(0.5) except Exception as e: print(f"发送给用户{user_id}失败: {e}") except FileNotFoundError: print("暂无用户记录") if __name__ == '__main__': application = ApplicationBuilder().token("YOUR_BOT_TOKEN").build() start_handler = CommandHandler('start', start) application.add_handler(start_handler) # 先执行启动欢迎消息 asyncio.run(send_welcome_on_startup(application)) # 启动Bot application.run_polling()
方式二:用post_init回调(python-telegram-bot v20+)
如果使用v20及以上版本,用初始化回调更优雅:
async def post_init(application: Application): await send_welcome_on_startup(application) if __name__ == '__main__': application = ApplicationBuilder().token("YOUR_BOT_TOKEN").post_init(post_init).build() start_handler = CommandHandler('start', start) application.add_handler(start_handler) application.run_polling()
注意事项
- 替换
YOUR_BOT_TOKEN为你实际的Bot令牌 - 发送消息时加短延迟,避免触发Telegram的频率限制
- 捕获发送异常,防止用户拉黑Bot导致程序崩溃
- 生产环境建议用SQLite/MySQL等数据库替代文本文件存储用户ID
内容的提问来源于stack exchange,提问作者user183312
相关产品推荐
相关产品推荐

