如何使用python-telegram-bot获取Telegram消息发送者用户名并在回复中带出
解决方案
你不需要将update参数传入main函数,消息触发的回调函数handle_message本身就会自动接收update和context两个参数,直接在这个回调里提取用户信息,再传递给responses模块的函数即可,修改步骤如下:
第一步:修改main.py
补全缺失的依赖导入和回调函数定义:
from telegram import * from telegram.ext import * from dotenv import load_dotenv import os import responses as R load_dotenv() # 新增消息处理回调 def handle_message(update, context): # 提取用户信息 chat = update.effective_chat # 兼容未设置用户名的情况,优先用用户名,没有就用用户昵称 username = chat.username if chat.username else chat.first_name # 提取用户发送的消息内容 text = update.effective_message.text # 调用responses模块的函数,同时传入消息和用户名 response = R.sample_responses(text, username) # 发送回复 update.message.reply_text(response) # 新增错误处理回调 def error(update, context): print(f"Update {update} caused error {context.error}") def main(): updater=Updater(os.getenv("BOT_TOKEN"), use_context=True) dp=updater.dispatcher dp.add_handler(MessageHandler(Filters.text,handle_message)) dp.add_error_handler(error) updater.start_polling() updater.idle() main()
第二步:修改responses.py
给响应函数增加用户名参数,调整返回内容的拼接逻辑:
def sample_responses(message, username): message = message.lower() if message in ("hello", "hi"): return f"Hey! @{username} How's it going?" elif message in ("who are you", "who are you?"): return "Hi! I am Buddy Bot. Developed by Soham." # 可自行补充其他响应逻辑 return "Sorry, I don't understand what you said."
内容的提问来源于stack exchange,提问作者Soham Program learner
相关产品推荐
相关产品推荐

