I’m trying to make a code that will include both a conversation with a bot and a command that will cause the bot to send an image but I always get the same error
These are parts of the code.
import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger()
from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove)
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters,
ConversationHandler)
from telegram.ext import Updater
updater = Updater(token='Token', use_context=True)
dispatcher = updater.dispatcher
from telegram.ext import CommandHandler
import telegram
bot = telegram.Bot('Token')
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
def sic(update, context):
chat_id=update.effective_chat.id
file = r"C:UsersYoavDesktopsicily_botuser_photo.jpg"
bot.send_photo(chat_id, photo=open(file, 'rb'))
bot.send_photo(chat_id, 'https://bitcoin.org/img/icons/opengraph.png')
def main():
updater = Updater("Token", use_context=True)
dp = updater.dispatcher
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
LOOKS: [MessageHandler(Filters.regex('^(Mehh|Okay.|Great|Amazing)$'), looks)],
PHOTO: [MessageHandler(Filters.photo, photo),
CommandHandler('skip', skip_photo)],
EDUCATION: [MessageHandler(Filters.text & ~Filters.command, education),
CommandHandler('skip', skip_education)],
BIO: [MessageHandler(Filters.text & ~Filters.command, bio)]
},
fallbacks=[CommandHandler('cancel', cancel)],
)
dp.add_handler(conv_handler)
dispatcher.add_handler(sic)
sic = CommandHandler('sic', sic)
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
I always get this error:
Traceback (most recent call last):
File "C:UsersYoavDesktopsicily_botbot_comb.py", line 161, in <module>
main()
File "C:UsersYoavDesktopsicily_botbot_comb.py", line 151, in main
dispatcher.add_handler(sic)
UnboundLocalError: local variable 'sic' referenced before assignment
how can i fix this?
thanks in advance
2
Answers
Well, why don’t you swap the line with dispatcher.add_handler and the one with sic = CommandHandler?
Is your intention with this line to override the
sic
function?If you want to override the function, you should mark
sic
as a global variable:[option 1]
if that’s not your intention, don’t assign to
sic
. I don’t know the telegram library, but my guess is thatCommandHandler
objects are supposed to be passed todispatcher.add_handler
. That means you should change your code to:[option 2]