Не могу понять в чем ошибка? Python

В чем ошибка кода? При нажатии на кнопку Мой баланс работает как надо, а когда нажимаешь VK, то выдаёт кучу ошибок.

import telebot
from telebot import types

bot = telebot.TeleBot("<TOKEN>")


@bot.message_handler(commands=['start'])
def send_welcome(message):
    bot.send_message(
        message.chat.id,
        '''
        Магазин услуг прямиком из net! 
        \nЗдесь ты можешь заказать страницы!
        ''',
        reply_markup=keyboard())


@bot.message_handler(commands=['help'])
def send_help(message):
    bot.reply_to(message, "Если что-то пошло не так, то просто перезапусти бота!")


@bot.message_handler(content_types=["text"])
def send_balance(message):
    chat_id = message.chat.id
    if message.text == 'Мой баланс':
        text = 'Ваш баланс - 0 рублей. \nПополните баланс для продолжения'
    bot.send_message(chat_id, text, reply_markup=keyboard())


@bot.message_handler(content_types=["text1"])
def vkcrack(message):
    chat_id = message.chat.id
    if message.text == 'VK':
        text1 = 'Ваш баланс - 0 рублей. \nПополните баланс для продолжения'
    bot.send_message(chat_id, text1, reply_markup=keyboard())


def keyboard():
    markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
    btn0 = types.KeyboardButton('Мой баланс')
    btn1 = types.KeyboardButton('Пополнить баланс')
    btn2 = types.KeyboardButton('VK')
    btn3 = types.KeyboardButton('Instagram')
    btn4 = types.KeyboardButton('Одноклассники')
    btn5 = types.KeyboardButton('Youtube')
    btn6 = types.KeyboardButton('TikTok')
    btn7 = types.KeyboardButton('Telegram')
    btn8 = types.KeyboardButton('WhatsApp')
    markup.add(btn0, btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8)
    return markup


bot.polling()

Ошибка

2020-09-18 22:14:53,657 (util.py:75 WorkerThread1) ERROR - TeleBot: "UnboundLocalError occurred, args=("local variable 'text' referenced before assignment",)
Traceback (most recent call last):
  File "C:\Users\Александр.DESKTOP-UICV52D\PycharmProjects\pythonProject\venv\lib\site-packages\telebot\util.py", line 69, in run
    task(*args, **kwargs)
  File "C:/Users/Александр.DESKTOP-UICV52D/PycharmProjects/pythonProject/main.py", line 28, in send_balance
    bot.send_message(chat_id, text, reply_markup=keyboard())
UnboundLocalError: local variable 'text' referenced before assignment
"
Traceback (most recent call last):
  File "C:/Users/Александр.DESKTOP-UICV52D/PycharmProjects/pythonProject/main.py", line 54, in <module>
    bot.polling()
  File "C:\Users\Александр.DESKTOP-UICV52D\PycharmProjects\pythonProject\venv\lib\site-packages\telebot\__init__.py", line 427, in polling
    self.__threaded_polling(none_stop, interval, timeout)
  File "C:\Users\Александр.DESKTOP-UICV52D\PycharmProjects\pythonProject\venv\lib\site-packages\telebot\__init__.py", line 451, in __threaded_polling
    self.worker_pool.raise_exceptions()
  File "C:\Users\Александр.DESKTOP-UICV52D\PycharmProjects\pythonProject\venv\lib\site-packages\telebot\util.py", line 118, in raise_exceptions
    six.reraise(self.exc_info[0], self.exc_info[1], self.exc_info[2])
  File "C:\Users\Александр.DESKTOP-UICV52D\PycharmProjects\pythonProject\venv\lib\site-packages\six.py", line 703, in reraise
    raise value
  File "C:\Users\Александр.DESKTOP-UICV52D\PycharmProjects\pythonProject\venv\lib\site-packages\telebot\util.py", line 69, in run
    task(*args, **kwargs)
  File "C:/Users/Александр.DESKTOP-UICV52D/PycharmProjects/pythonProject/main.py", line 28, in send_balance
    bot.send_message(chat_id, text, reply_markup=keyboard())
UnboundLocalError: local variable 'text' referenced before assignment

Ответы (1 шт):

Автор решения: gil9red

У вас переменная text создается только внутри условия, поэтому если код в условие не попадет, то она не будет создана, что приведет к ошибке.

Нужно или только в if выполнять bot.send_message, чтобы быть уверенным, что text существует, либо заранее создавать эту переменную (т.е. до условия), либо в else.

Вариант с else, думаю, самый оптимальный:

@bot.message_handler(content_types=["text"])
def send_balance(message):
    chat_id = message.chat.id
    if message.text == 'Мой баланс':
        text = 'Ваш баланс - 0 рублей. \nПополните баланс для продолжения'
    else:
        text = f'Неизвестная команда {message.text!r}'
    bot.send_message(chat_id, text, reply_markup=keyboard())
→ Ссылка