简体   繁体   中英

Why my telegram bot (aiogram) doesn't work right?

the bot offers to guess a number from 0 to 10. But for the correct answer, it answers "False"

I guess the problem is using asynchronous functions, but I'm not good at them

from aiogram import Bot, Dispatcher, executor, types
import random

bot = Bot(token=BOT_TOKEN)
dp = Dispatcher(bot)

# number to guess
NUMBER = 0


# comes up with a number
def setRand():
    NUMBER = random.randrange(10)
    print(NUMBER)


# handler for /start
@dp.message_handler(commands=['start'])
async def start(msg: types.Message):
    setRand()
    await msg.answer("Try to guess the number from 0 to 10")


# handler for getting answer
@dp.message_handler()
async def getNumber(msg: types.Message):
    if msg.text == str(NUMBER):
        await msg.answer('True!')
    else:
        await msg.answer('False :с')
        await msg.answer('But I came up with new number!')

        setRand()


executor.start_polling(dp)```

Use global for global variables!

def setRand():
    global NUMBER
    NUMBER = random.randrange(10)
    print(NUMBER)```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM