Telegram机器人遇AttributeError:NoneType对象无username属性求助
问题解决:AttributeError处理与Telegram隐私转发消息适配
问题原因
当用户开启消息转发隐私设置时,Telegram不会向机器人暴露转发来源用户的forward_from对象,此时update.effective_message.forward_from为None。你的代码直接访问forward_from.username,必然触发AttributeError: 'NoneType' object has no attribute 'username'。
修复方案
先判断forward_from是否存在,再处理后续逻辑;同时调整判断顺序,优先处理异常场景:
#!/usr/bin/python3 from telegram.ext.updater import Updater from telegram.update import Update from telegram.ext.callbackcontext import CallbackContext from telegram.ext.commandhandler import CommandHandler from telegram.ext.messagehandler import MessageHandler from telegram.ext.filters import Filters updater = Updater("My Token", use_context=True) def start(update: Update, context: CallbackContext): update.message.reply_text( "Hi. I'm a bot that sniffs out this softwares scammers so you don't get exploited. Simply forward a message from the scammer to me " "and I'll tell you if it's the real support or not.") def usercheck(update: Update, context: CallbackContext): # 优先处理隐私用户(无转发来源信息) if not update.effective_message.forward_from: update.effective_message.reply_text("🚨🚨🚨🚨🚨 If this user says they're from My softwares support - they are trying to scam you. " "Please report them and stop talking to them immediately. 🚨🚨🚨🚨🚨") return # 提取转发用户的用户名,减少重复访问 forward_username = update.effective_message.forward_from.username if forward_username == "admin1": update.effective_message.reply_text("✅This message was sent from the real admin1, an authorised reseller from this group") elif forward_username == "dev1": update.effective_message.reply_text("✅This message was sent from the real dev1, an authorised developer of group") elif not forward_username: # 用户本身无用户名 update.effective_message.reply_text("🚨🚨🚨🚨🚨 If this user says they're from Gunbot support - they are trying to scam you. " "Please report them and stop talking to them immediately. 🚨🚨🚨🚨🚨") else: # 其他有用户名的非授权用户 update.effective_message.reply_text("🚨🚨🚨🚨🚨 If this user says they're from My softwares support - they are trying to scam you. " "Please report them and stop talking to them immediately. 🚨🚨🚨🚨🚨") updater.dispatcher.add_handler(CommandHandler("start", start)) updater.dispatcher.add_handler(MessageHandler(Filters.forwarded, usercheck)) updater.start_polling() updater.idle()
关键修改说明
- 新增
if not update.effective_message.forward_from:判断,直接拦截隐私用户的转发请求,避免空指针错误 - 将
forward_from.username提取为变量,简化代码逻辑 - 调整判断顺序:先处理无来源的异常情况,再依次匹配授权用户、无用户名用户、其他用户
内容的提问来源于stack exchange,提问作者Doomian
相关产品推荐
相关产品推荐

