Hands-On Guide: Building a Telegram Bot Command Listener in Python
While receiving automated alerts on Telegram is great, being able to send commands *back* to your mobile scripts takes your automation to the next level. Imagine checking your account balance or stopping a running market scanner simply by typing a quick command inside your Telegram chat.
In this hands-on tutorial, we will build a lightweight Python command listener using long-polling to control background scripts remotely.
---------------------------------------------------
1. How Telegram Long-Polling Works
Instead of requiring a complex webhook server with a public IP address (which can be difficult to set up on a mobile device), our script uses a simple polling loop. It repeatedly asks Telegram’s servers if any new messages have arrived, parses the text command, and executes matching actions.
---------------------------------------------------
2. Complete Python Telegram Command Listener Script
Open Termux or your preferred environment, create a new file named bot_listener.py, and paste the following code:
import time
import requests
import logging
# Configuration (Replace with your actual Bot Token)
TOKEN = "YOUR_TELEGRAM_BOT_TOKEN"
BASE_URL = f"https://api.telegram.org/bot{TOKEN}"
logging.basicConfig(
filename='bot_listener.log',
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
def get_updates(offset=None):
"""Fetches incoming messages from Telegram using long polling."""
url = f"{BASE_URL}/getUpdates?timeout=30"
if offset:
url += f"&offset={offset}"
try:
response = requests.get(url, timeout=35)
if response.status_code == 200:
return response.json().get("result", [])
except Exception as e:
logging.error(f"Polling error: {e}")
return []
def send_message(chat_id, text):
"""Sends a response message back to the Telegram chat."""
url = f"{BASE_URL}/sendMessage"
payload = {"chat_id": chat_id, "text": text}
try:
requests.post(url, json=payload, timeout=10)
except Exception as e:
logging.error(f"Error sending message: {e}")
def main():
print("--- Telegram Command Listener Active ---")
logging.info("Starting Telegram listener bot...")
last_update_id = None
while True:
updates = get_updates(last_update_id)
for update in updates:
last_update_id = update["update_id"] + 1
if "message" in update and "text" in update["message"]:
chat_id = update["message"]["chat"]["id"]
command = update["message"]["text"].strip().lower()
print(f"Received command: {command} from chat ID: {chat_id}")
# Command Routing Logic
if command == "/status":
send_message(chat_id, "System Status: ONLINE. All scripts running smoothly.")
elif command == "/balance":
send_message(chat_id, "Account Balance: Simulated Equity $10,450.00")
elif command == "/help":
send_message(chat_id, "Available commands:\n/status - Check system health\n/balance - View simulated equity")
else:
send_message(chat_id, "Unknown command. Type /help for available options.")
time.sleep(1)
if __name__ == "__main__":
main()
---------------------------------------------------
3. Running and Testing on Mobile (Termux)
1. Save your file in nano (Ctrl + O, Enter, Ctrl + X).
2. Run your listener script:
python bot_listener.py
3. Open your Telegram bot in your mobile app, send `/status` or `/help`, and watch your script respond in real time!
---------------------------------------------------
Final Thoughts
Adding interactive command listening transforms your Python scripts from passive notification tools into fully controllable remote background utilities.
Stay tuned as we roll right into **Post #18** on our march to 20 posts!
Comments
Post a Comment