Ошибка в коде телеграмм бота

Рейтинг: 0Ответов: 1Опубликовано: 30.04.2023

Я пишу тг-бота на python с использованием aiogram.

При написании логики для очков здоровья я наткнулся на ошибку:

UnboundLocalError: cannot access local variable 'health' where it is not associated with a value

Вот полный код:

from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor

TOKEN = ''

bot = Bot(token=TOKEN)
dp = Dispatcher(bot)
health = int(100)
coins = 0
commands = ['hit']

@dp.message_handler(commands=['start'])
async def type_start_bot(message: types.Message):
await message.reply('выбирай что будем делать?')
@dp.message_handler(commands=['hit'])
async def type_hit_bot(message:types.Message):
    await message.reply('бот избил вас так как он сильней')
    if commands == ['hit']: 
        health -= 50 <--- ОШИБКА ТУТ
        async def type_health_bot(message:types.Message):
        await message.reply(health)
@dp.message_handler(commands=['mybio'])
async def type_bio_bot(message: types.Message):
    await message.reply(health)

if __name__ == '__main__':
    executor.start_polling(dp)

Подскажите пожалуйста, что нужно сделать для устранения ошибки?

Заранее спасибо!

Ответы

▲ 0

В начале функции type_hit_bot пропиши global health. Должно помочь.