Write a simple Telegram bot in Python Flask
Private research annotation
Sign in to add a private research label or note.
- User
Write a simple Telegram bot in Python Flask
- Assistant
Sign in to add a private research label or note.
Write a simple Telegram bot in Python Flask
Sure! Let's create a simple Telegram bot using Python and Flask. This bot will echo back any message you send to it.
pip install flask).pip install requests)./start to see all available commands./newbot to create a new bot.Create a new Python file, e.g., app.py, and add the following code:
from flask import Flask, request
import requests
app = Flask(__name__)
# Replace 'YOUR_TELEGRAM_BOT_TOKEN' with your bot's token
BOT_TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN'
# URL to send messages via Telegram API
TELEGRAM_API_URL = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
@app.route('/', methods=['POST'])
def webhook():
# Get the JSON data from Telegram
data = request.get_json()
# Check if the message contains text
if 'message' in data and 'text' in data['message']:
chat_id = data['message']['chat']['id']
message_text = data['message']['text']
# Prepare a response by echoing the received message
response_text = f"You said: {message_text}"
# Send the response back to the user
payload = {
'chat_id': chat_id,
'text': response_text
}
requests.post(TELEGRAM_API_URL, data=payload)
return 'ok', 200
if __name__ == '__main__':
app.run(port=5000)
Explanation:
flask for the web framework and requests to send HTTP requests./ that listens for POST requests (this will be our webhook endpoint).chat_id and message_text.In the code above, replace 'YOUR_TELEGRAM_BOT_TOKEN' with the token you received from BotFather:
BOT_TOKEN = '123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZ'
If you're running the app locally, you need to expose your local server to the internet using a tool like ngrok.
Download and install ngrok from ngrok.com.
Run your Flask app:
python app.py
Start ngrok to tunnel HTTP traffic to your local port 5000:
ngrok http 5000
Copy the HTTPS URL provided by ngrok. It will look something like https://abcd1234.ngrok.io.
If you have access to a server or cloud service (like Heroku, AWS, etc.), deploy your Flask app there and obtain the public URL.
Now that your app is running and accessible, you need to tell Telegram where to send updates for your bot.
Make a GET request to the following URL (replace {BOT_TOKEN} and {YOUR_WEBHOOK_URL} accordingly):
https://api.telegram.org/bot{BOT_TOKEN}/setWebhook?url={YOUR_WEBHOOK_URL}
Example using curl:
curl -F "url=https://abcd1234.ngrok.io/" https://api.telegram.org/bot123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZ/setWebhook
Note: Ensure that your webhook URL starts with https as Telegram requires a valid SSL certificate.
Go back to Telegram and find your bot (search for its username). Send a message to your bot, and it should reply with "You said: <your message>".
Here's the complete app.py code for reference:
from flask import Flask, request
import requests
app = Flask(__name__)
# Replace this with your actual bot token
BOT_TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN'
# URL for Telegram API calls
TELEGRAM_API_URL = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
@app.route('/', methods=['POST'])
def webhook():
data = request.get_json()
# Debugging: print incoming data
# print(data)
if 'message' in data and 'text' in data['message']:
chat_id = data['message']['chat']['id']
message_text = data['message']['text']
response_text = f"You said: {message_text}"
payload = {
'chat_id': chat_id,
'text': response_text
}
# Send the message back via Telegram
requests.post(TELEGRAM_API_URL, data=payload)
return 'ok', 200
if __name__ == '__main__':
app.run(port=5000)
You've now created a simple Telegram bot using Python Flask that echoes back any message you send to it. From here, you can expand its functionality based on your needs.
If you have any questions or need further assistance, feel free to ask!
Not yet included in a published release.