python-3.x 电报API的属性未定义

093gszye  于 2022-12-05  发布在  Python
关注(0)|答案(1)|浏览(171)

抱歉,这是我写的第一段代码。我花了一整天的时间试图找到一种排序的方法,这是我最后的手段。当有人用我定义的用户名转发邮件时,机器人会发回一条消息说这是一个真实的用户。当有人转发没有用户名的邮件时,机器人发回一条消息,说它可能是一个骗子...但是当有人转发来自没有用户名的人的消息时,我会收到一个未定义的属性错误。
属性错误:'NoneType'对象没有'username'属性
这是我代码
`

#!/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 update.effective_message.forward_from.username == "admin1":
        update.effective_message.reply_text("✅This message was sent from the real admin1, an authorised reseller from this group")
     elif update.effective_message.forward_from.username == "dev1":
          update.effective_message.reply_text("✅This message was sent from the real dev1, an authorised developer of group")
     elif update.effective_message.forward_from.username == None:
          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. 🚨🚨🚨🚨🚨") #works but only if the user has no privacy settings
     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. 🚨🚨🚨🚨🚨") #would have thought it works if the user hides their privacy settings but it doesn't 

updater.dispatcher.add_handler(CommandHandler("start", start))
updater.dispatcher.add_handler(MessageHandler(Filters.forwarded, usercheck))
updater.start_polling()
updater.idle()

`

x4shl7ld

x4shl7ld1#

根据电报文档,forward_from是可选的,因此它可能是None。您应该在访问effective_message.forward_from.username之前验证update.effective_message.forward_from is not None

def usercheck(update: Update, context: CallbackContext):
    if update.effective_message.forward_from is not None:
        if update.effective_message.forward_from.username == "admin1":
        # ...
    else:
        # do something else

相关问题