Answer the question
In order to leave comments, you need to log in
How to implement multi-threading in Telegram bot (Aiogram)?
How to fix it: When many people send a command to the bot to get the number of players online, does the last person receive a response for a long time?
from aiogram import Bot, Dispatcher, executor, types
from mcstatus import MinecraftServer
import logging
bot = Bot(token="token")
dp = Dispatcher(bot)
server = MinecraftServer.lookup('localhost')
logging.basicConfig(level=logging.INFO)
@dp.message_handler(commands=["players"])
async def cmd_test1(message: types.Message):
status = server.status()
await message.reply('Онлайн сервера: ' + str(status.players.online))
if __name__ == "__main__":
executor.start_polling(dp, skip_updates=True)
Answer the question
In order to leave comments, you need to log in
Mixing multithreading with asynchrony is a bad idea.
In general, it depends on the implementation of server.status (). If it makes a synchronous network request, then of course the bot will stand up for the duration of its execution.
If there is no asynchronous implementation, I would launch a new task, which polls the server every minute or two in a cycle and remembers the current one online. And on command, I would give only the last memorized value.
In principle, one can use loop.run_in_executor() to execute a thread as an asynchronous task. It's more or less safe.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question