My apologies. This is the first bit of code I've written. Spent all day trying to find a way to sort it and this is my last resort. When someone forwards a message with a username I've defined - the bot sends a message back saying it's a real user. When someone forwards a message with no username, the bot sends a message back saying it's probably a scammer... but when someone forwards a message from someone with no username and who's disallowed message forwarding in their Telegram settings, I get an undefined attribute error.
AttributeError: 'NoneType' object has no attribute 'username'
here is my code
`
#!/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()
`
From the telegram docs, forward_from
is optional, so it could be None
. You should verify that update.effective_message.forward_from is not None
before accessing effective_message.forward_from.username
.
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