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?