@uyrsr

При попытке проверки переменной выдаёт ошибку, что делать?

При попытке проверки переменной выдаёт вот такую ошибку:
5edb9b7798b41653857134.jpeg
Код:
import telebot
from telebot import types
import random
import config
import time

bot = telebot.TeleBot(config.TOKEN)


@bot.message_handler(commands=['start'])
def welcome(message):
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    item1 = types.KeyboardButton("случайная картинка")
    item2 = types.KeyboardButton("теги")
    markup.add(item1, item2)
    bot.send_message(message.chat.id, "добро пожаловать!\nя - бот лошара".format(message.from_user, bot.get_me()), reply_markup=markup,
    parse_mode='html')
@bot.message_handler(content_types=['text'])
def gu(message):
    if message.chat.type == 'private':
        if message.text == 'случайная картинка':
            number = str(random.randint(1, 5))
            if number == '1':
                photo = open('C:\матвей\c.jpg', 'rb')
                bot.send_photo(message.chat.id, photo)
                bot.send_message(message.chat.id, 'Лукака')
            elif number == '2':
                photo2 = open('C:\матвей\wow.jpg', 'rb')
                bot.send_photo(message.chat.id, photo2)
                bot.send_message(message.chat.id, 'уха')
            elif number == '3':
                photo3 = open('C:\матвей\gori.jpg', 'rb')
                bot.send_photo(message.chat.id, photo3)
                bot.send_message(message.chat.id, 'gorrilaz')
            elif number == '4':
                photo4 = open('C:\матвей\phototest.jpg', 'rb')
                bot.send_photo(message.chat.id, photo4)
                bot.send_message(message.chat.id, 'Мой рисунок')
            elif number == '5':
                photo5 = open('C:\матвей\onime.png', 'rb')
                bot.send_photo(message.chat.id, photo5)
                bot.send_message(message.chat.id, 'Аниме женщина')
        elif message.text == 'теги':
            markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
            item1 = types.KeyboardButton("европа")
            item2 = types.KeyboardButton("азия")
            item3 = types.KeyboardButton("америка")
            item4 = types.KeyboardButton("росcия")
            item5 = types.KeyboardButton("япония")
            item6 = types.KeyboardButton("беларусь")
            item7 = types.KeyboardButton("сша")
            item8 = types.KeyboardButton("франция")
            item9 = types.KeyboardButton("великобритания")
            markup.add(item1, item2, item3, item4, item5, item6, item7, item8, item9)
            bot.send_message(message.chat.id, 'теги', reply_markup=markup)
        elif message.text == 'европа':
            number = str(random.randint(1, 4))
            markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
            item1 = types.KeyboardButton("случайная картинка")
            item2 = types.KeyboardButton("теги")
            item3 = types.KeyboardButton('подробности')
            markup.add(item1, item2, item3)
            if number == '1':
                country = '1'
                photo1 = open('C:\матвей\moscow.jpg', 'rb')
                bot.send_photo(message.chat.id, photo1, reply_markup=markup)
            elif number == '2':
                country = '7'
                photo2 = open('C:\матвей\paris.jpg', 'rb')
                bot.send_photo(message.chat.id, photo2, reply_markup=markup)
            elif number == '3':
                country = '8'
                photo3 = open('C:\матвей\london.jpg', 'rb')
                bot.send_photo(message.chat.id, photo3, reply_markup=markup)
            elif number == '4':
                country = '4'
                photo4 = open('C:\матвей\minsk.jpg', 'rb')
                bot.send_photo(message.chat.id, photo4, reply_markup=markup, dog='4')
        elif message.text == 'россия':
             country = '1'
             markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
             item1 = types.KeyboardButton("случайная картинка")
             item2 = types.KeyboardButton("теги")
             item3 = types.KeyboardButton('подробности')
             markup.add(item1, item2, item3)
             photo = open('C:\матвей\moscow.jpg', 'rb')
             bot.send_photo(message.chat.id, photo, reply_markup=markup)
        elif message.text == 'азия':
             country = '2'
             markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
             item1 = types.KeyboardButton("случайная картинка")
             item2 = types.KeyboardButton("теги")
             item3 = types.KeyboardButton('подробности')
             markup.add(item1, item2, item3)
             photo = open('C:\матвей\pokyo.jpg', 'rb')
             bot.send_photo(message.chat.id, photo, reply_markup=markup)
        elif message.text == 'япония':
             country = '3'
             markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
             item1 = types.KeyboardButton("случайная картинка")
             item2 = types.KeyboardButton("теги")
             item3 = types.KeyboardButton('подробности')
             markup.add(item1, item2, item3)
             photo = open('C:\матвей\pokyo.jpg', 'rb')
             bot.send_photo(message.chat.id, photo, reply_markup=markup)
        elif message.text == 'беларусь':
             country = '4'
             markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
             item1 = types.KeyboardButton("случайная картинка")
             item2 = types.KeyboardButton("теги")
             item3 = types.KeyboardButton('подробности')
             markup.add(item1, item2, item3)
             photo = open('C:\матвей\minsk.jpg', 'rb')
             bot.send_photo(message.chat.id, photo, reply_markup=markup)
        elif message.text == 'америка':
             country = '5'
             markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
             item1 = types.KeyboardButton("случайная картинка")
             item2 = types.KeyboardButton("теги")
             item3 = types.KeyboardButton('подробности')
             markup.add(item1, item2, item3)
             photo = open('C:\матвей\pew_york.jpg', 'rb')
             bot.send_photo(message.chat.id, photo, reply_markup=markup)
        elif message.text == 'сша':
             country = '6'
             markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
             item1 = types.KeyboardButton("случайная картинка")
             item2 = types.KeyboardButton("теги")
             item3 = types.KeyboardButton('подробности')
             markup.add(item1, item2, item3)
             photo = open('C:\матвей\pew_york.jpg', 'rb')
             bot.send_photo(message.chat.id, photo, reply_markup=markup)
        elif message.text == 'франция':
             country = '7'
             markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
             item1 = types.KeyboardButton("случайная картинка")
             item2 = types.KeyboardButton("теги")
             item3 = types.KeyboardButton('подробности')
             markup.add(item1, item2, item3)
             photo = open('C:\матвей\paris.jpg', 'rb')
             bot.send_photo(message.chat.id, photo, reply_markup=markup)
        elif message.text == 'великобритания ':
             country = '8'
             markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
             item1 = types.KeyboardButton("случайная картинка")
             item2 = types.KeyboardButton("теги")
             item3 = types.KeyboardButton('подробности')
             markup.add(item1, item2, item3)
             photo = open('C:\матвей\london.jpg', 'rb')
             bot.send_photo(message.chat.id, photo, reply_markup=markup)
        if message.text == 'подробности':
            if country == '1':
                bot.send_message(message.chat.id, 'Москва')
            elif country == '2':
                bot.send_message(message.chat.id, 'Токио')
            elif country == '3':
                bot.send_message(message.chat.id, 'Токио')
            elif country == '4':
                bot.send_message(message.chat.id, 'Минск')
            elif country == '5':
                bot.send_message(message.chat.id, 'Нью-Уорк')
            elif country == '6':
                bot.send_message(message.chat.id, 'Нью-Уорк')
            elif country == '7':
                bot.send_message(message.chat.id, 'Париж')
            elif country == '8':
                bot.send_message(message.chat.id, 'Лондон')

if __name__ == '__main__':
    while True:
        try:
            bot.polling(none_stop=True)
        except Exception as e:
            time.sleep(3)
            print(e)
  • Вопрос задан
  • 71 просмотр
Решения вопроса 1
NeiroNx
@NeiroNx
Программист
не видел нигде что переменная country глобальная. Значение сразу теряется после завершения функции.
Во вторых глобальная переменная может нести значение только для последнего пользователя.

Поэтому переменную надо привязать к пользователю.
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
trapwalker
@trapwalker Куратор тега Python
Программист, энтузиаст
Вам же белым по черному в тексте ошибки написано, что переменная country используется до объявления. То есть в программе вы еще ни разу в нее ничего не присвоили, а уже пытаетесь проверять ее значение. КОнечно тут ошибка.
Там даже показано в какой именно строке. Что делать? Исправлять.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы