Below is my function for making an http request using aiohttp and 2nd is handler function for a callback query in python-telegram-bot Although the function to make http call is async but it still blocks the event loop of whole bot Async does not appear to be working quite as intended.
For one user it works as expected, but while waiting for the API call to return for the VM option, the bot is unresponsive to any other user.
The flow is: User 1 makes call to API (this takes 70 seconds). User 2 tries to use the bot while user 1 is waiting. The bot is unresponsive for user 2 until the result from User 1's API call is complete. The bot still seems to be processing requests in the order they come in instead of being parallel even though I'm using aync client for making requests.
async def async_post(url, json_data):
async with aiohttp.ClientSession() as session:
async with session.post(url, json=json_data) as response:
return {
'status': response.status, # Get the status code
'json': await response.json() # Assuming the response is JSON
}
async def VM(update: Update, context: CallbackContext) -> None:
query = update.callback_query
await query.answer()
# Notify user that the process has started
text = '''please wait about 70 seconds'''
await query.edit_message_text(text=text)
logger.info(f"User {update.effective_user.username} ({update.effective_user.id}) at (add in the time) in the chat {update.effective_chat.id} initiated VM request.")
# Make the API call to the Lambda function
start_ec2_url = 'https://myaws ur/'
data = {
'username': update.effective_user.username,
'user_id': update.effective_user.id,
'chat_id': update.effective_chat.id
}
logger.info('about to make call to api')
response = await async_post(start_ec2_url, data)
logger.info('made call to api successfully')
if response["status"] == 200:
response_data = response["json"]
environment_url = response_data.get('environment_url', 'No URL found in the response.')
text = f'''Please access your VM by using this link:\n<a href="environment_url}">Click here to access your VM</a>'''
submenu_keyboard = [
[InlineKeyboardButton("Back to Main Menu", callback_data='back')]
]
submenu_markup = InlineKeyboardMarkup(submenu_keyboard)
await query.edit_message_text(text=text, reply_markup=submenu_markup, parse_mode='HTML')
else:
# Handle any bad responses or errors
submenu_keyboard = [
[InlineKeyboardButton("Back to Main Menu", callback_data='back')]
]
submenu_markup = InlineKeyboardMarkup(submenu_keyboard)
await query.edit_message_text(text=f"AnzenVM failed with status code: {response['status']}. Please seek assistance", reply_markup=submenu_markup)
app = ApplicationBuilder().token(bot_token).build()
app.add_handler(CallbackQueryHandler('call_back_button_press',VM))
app.run_polling()