Telegram bot stuck on 'Getting updates...' and won't launch game

I’ve been facing a problem with my Telegram bot. It works well for sending messages and responding to commands, but when I try to launch the game, it gets stuck on ‘Getting updates…’ and doesn’t move on to process new messages or callbacks.

Here’s a new version of my Python code:

import requests
import time
import json

BOT_TOKEN = 'MY_SECRET_TOKEN'
GAME_LINK = 'https://example.com/game'

API_BASE = f'https://api.telegram.org/bot{BOT_TOKEN}'
last_update = None

def message_user(user_id, content, buttons=None):
    endpoint = f'{API_BASE}/sendMessage'
    data = {'chat_id': user_id, 'text': content}
    if buttons:
        data['reply_markup'] = json.dumps(buttons)
    requests.post(endpoint, json=data)

def handle_callback(callback_id, link):
    full_link = f'{link}?game_link={GAME_LINK}'
    response = requests.get(f'{API_BASE}/answerCallbackQuery', params={'callback_query_id': callback_id, 'url': full_link})
    print(f'Callback response: {response.text}')

def launch_game(user_id):
    message_user(user_id, 'Launching game, please wait...')

while True:
    try:
        print('Fetching updates...')
        response = requests.get(f'{API_BASE}/getUpdates', params={'offset': last_update}).json()
        if response['ok']:
            updates = response['result']
            for update in updates:
                if 'message' in update:
                    user_id = update['message']['chat']['id']
                    text = update['message'].get('text', '')
                    game_button = {'inline_keyboard': [[{'text': 'Play Now', 'callback_data': 'start_game'}]]}
                    if text.startswith('/'):
                        message_user(user_id, 'Hi there! Ready to play?', game_button)
                    else:
                        message_user(user_id, 'Not sure what you mean. Want to play?', game_button)
                elif 'callback_query' in update:
                    callback_id = update['callback_query']['id']
                    if update['callback_query']['data'] == 'start_game':
                        launch_game(update['callback_query']['message']['chat']['id'])
                        handle_callback(callback_id, GAME_LINK)
                last_update = update['update_id'] + 1
        else:
            print(f'Update fetch failed: {response}')
    except Exception as e:
        print(f'Error occurred: {e}')
    time.sleep(1)

I suspect that the issue is with the updating of the last_update variable. It might not be getting updated properly after each batch of updates, causing the bot to repeatedly fetch the same updates. Any suggestions on how to resolve this issue so that the bot processes new messages and initiates the game when the button is pressed?

I’ve encountered a similar issue with Telegram bots getting stuck on ‘Getting updates…’ before. In my experience, the problem often lies in how the updates are processed and the offset is managed.

Looking at your code, I notice you’re updating ‘last_update’ inside the loop that processes each update. This could potentially cause issues if there are multiple updates in a single response.

Try moving the ‘last_update’ assignment outside the update processing loop, like this:

if response['ok'] and updates:
    for update in updates:
        # Your existing update processing code here
    last_update = updates[-1]['update_id'] + 1

This ensures you’re always using the ID of the last update in the batch, regardless of how many updates were received.

Also, consider adding some debug logging to track the values of ‘last_update’ and the number of updates received in each iteration. This can help pinpoint where the issue occurs.

If the problem persists, you might want to look into using a library like python-telegram-bot, which handles a lot of these low-level details for you and can make bot development much smoother.

hey mate, i think ur problem might be with how ur handling the updates. try adding a timeout to ur getUpdates call like this:

response = requests.get(f’{API_BASE}/getUpdates’, params={‘offset’: last_update, ‘timeout’: 30}).json()

this’ll make ur bot wait for new updates instead of constantly polling. could help with the stuck issue. good luck!

I’ve dealt with this ‘Getting updates…’ issue before, and it can be quite frustrating. One thing I noticed in your code is that you’re not handling the case where no updates are received. This could potentially cause your bot to get stuck in a loop.

Try adding a check for empty updates like this:

if response[‘ok’]:
updates = response[‘result’]
if not updates:
time.sleep(5) # Wait a bit longer if no updates
continue

# Process updates here

This way, if there are no new updates, your bot will wait a bit longer before checking again, which can help reduce unnecessary API calls and potential rate limiting.

Also, consider implementing a long polling mechanism using the ‘timeout’ parameter in your getUpdates call. This can make your bot more efficient and responsive to new messages.