I’m using the python-telegram-bot library with asynchronous functions, but I’m facing a challenge. My bot is able to work with a single group, but when I try to run it in two different groups at the same time, it handles the requests one after the other instead of processing them concurrently. It finishes the operation in the first group before it starts responding to commands in the second group.
Here is a snippet of my code:
async def start_blackjack(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
if not await check_player(update, context):
return
chat_id = update.message.chat_id
game = await sync_to_async(lambda: Game.objects.filter(chat_id=chat_id).order_by('-id').first())()
if not game or game.ended:
game, created = await sync_to_async(Game.objects.get_or_create)(chat_id=chat_id, ended=False)
game.betting = True
game.started = False
await sync_to_async(game.save)()
await asyncio.sleep(2) # Non-blocking sleep
await context.bot.send_message(chat_id=chat_id, text="🃏 Set the bet amount for the blackjack game to start.")
await create_poll(update, context) # Assume this is an async function
await asyncio.sleep(2) # Non-blocking sleep
await context.bot.send_message(chat_id=chat_id, text="🃏 Betting process has started!")
return
if game.betting:
await update.message.reply_text("A Blackjack game is in betting progress. Wait for the betting process to end and use /join to join the game.")
elif game.started:
await update.message.reply_text("A game has already started. Use the /next command to be prompted when the next game starts.")
elif game.join_time:
await update.message.reply_text("A game is in join time. Use the /join command to join the game.")
else:
await update.message.reply_text("An error occurred, please try again.")
Initially, I wrote the code without async functions. I thought that converting everything to async would solve the problem, but it hasn’t.
This is my Django model for the game:
class Game(models.Model):
chat_id = models.CharField(max_length=100)
betting = models.BooleanField(default=False)
started = models.BooleanField(default=False)
join_time = models.BooleanField(default=False)
ended = models.BooleanField(default=False)
hands_reset = models.BooleanField(default=False)
bet_amount = models.IntegerField(default=5)
dealer_hand = models.JSONField(default=list)
turn_order = models.JSONField(default=list)
current_round = models.IntegerField(default=1)
total_rounds = models.IntegerField(default=5)
pot = models.IntegerField(default=0)
join_start_time = models.DateTimeField(null=True, blank=True)
Why is the bot not processing multiple groups simultaneously even with async functions?