I’m working on a Telegram bot that is supposed to respond to user commands and start a game upon pressing a button. However, my bot’s main loop seems stuck at “Getting updates…” and doesn’t proceed to handle incoming messages or callbacks. Here’s a simplified version of my Python code:
import requests
import time
import json
TOKEN = 'TOKEN'
GAME_URL = 'https://www.yyyyyyy.info/index.html'
URL = f"https://api.telegram.org/bot{TOKEN}"
offset = None # Initialized offset
def send_message(chat_id, text, keyboard=None):
url = f"{URL}/sendMessage"
if keyboard:
payload = {'chat_id': chat_id, 'text': text, 'reply_markup': json.dumps(keyboard)}
else:
payload = {'chat_id': chat_id, 'text': text}
requests.post(url, json=payload)
def answer_callback_query(callback_query_id, url):
answer_url = f"{url}?game_url={GAME_URL}"
requests.get(f"{URL}/answerCallbackQuery", params={'callback_query_id': callback_query_id, 'url': answer_url})
while True:
try:
print("Getting updates...")
response = requests.get(f"{URL}/getUpdates", params={'offset': offset}).json()
if response.get('ok'):
updates = response['result']
for update in updates:
print(f"Update: {update}")
if 'message' in update:
chat_id = update['message']['chat']['id']
text = update['message'].get('text', '')
keyboard = {
'inline_keyboard': [[{'text': 'Start game', 'callback_data': 'start_game'}]]
}
if text == '/start' or text.startswith('/'):
print(f"Sending welcome message to chat {chat_id}")
send_message(chat_id, 'Welcome! Press the button to start the game.', keyboard)
else:
print(f"Sending unknown command message to chat {chat_id}")
send_message(chat_id, 'Unknown command. Press the button to start the game.', keyboard)
elif 'callback_query' in update:
callback_query_id = update['callback_query']['id']
if update['callback_query']['data'] == 'start_game':
print(f"Responding to callback query {callback_query_id} to start the game")
answer_callback_query(callback_query_id, GAME_URL)
# Update offset after processing updates
if updates:
offset = updates[-1]['update_id'] + 1
except Exception as e:
print(f"Error: {e}")
time.sleep(1) # Wait before next request
The offset variable doesn’t seem to update correctly after handling updates, causing the bot to repeatedly fetch the same updates. How can I modify my code to ensure the bot correctly handles incoming messages and starts the game upon pressing the “Start game” button?
Feel free to adjust the details further if needed, and good luck with your bot development!
Daniella Dimitrievna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.