A simple Telegram bot on Flask with weather reporting

Hello everyone, in this article I will tell you how to make the simplest telegram bot in Python to send the current weather in Moscow.


The article is intended for beginners in Python who would like to learn more about how to interact with external services via API.


Technologies and APIs:


  • Python is a programming language
  • Flask - a framework for creating web applications,
  • Telegram Bot API,
  • Weatherstack API
  • Ngrok is a service for creating a tunnel to localhost.

How will everything work?


  1. The user writes a telegram message to the bot.
  2. Telegram forwards the user message to the server.
  3. The server requests weather information from Weatherstack.
  4. The server sends weather information to Telegram.
  5. The user receives weather information.

Telegram registration bot


At this stage, we need to create a bot and get access to it. To do this, launch the @botfather bot in Telegram with the command below.


/start

We create a new bot according to the instructions from the message from the bot.


Telegram registration bot!


The bot is created, but if you write some message to it, it will not react to it in any way. Fix it.


Flask Help


Flask is a framework for creating web applications in the Python programming language, using the Werkzeug toolkit, as well as the Jinja2 template engine. It belongs to the category of so-called microframes - minimalistic frameworks of web applications that deliberately provide only the most basic features.


PyPI, 1.0 Python 2.7, Python 3.3 .


.


Flask


Python . . .


$ mkdir weather_bot
$ cd weather_bot
$ python3 -m venv venv

Flask.


(venv)$ pip install Flask

Installation.


Flask


weather_bot app.py .


from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

.


(venv)$ export FLASK_APP=app.py
(venv)$ flask run
 * Running on http://127.0.0.1:5000/

http://127.0.0.1:5000/ , "Hello, World!".
Quickstart.


localhost ngrok


Ngrok โ€” , .


  1. ngrok.
  2. .
  3. HTTP 5000 .

$ ./ngrok http 5000


, Telegram , . , Telegram. POST setWebhook. .


$ curl --location --request POST 'https://api.telegram.org/bot{token}/setWebhook' \
--header 'Content-Type: application/json' \
--data-raw '{
    "url": "{url}"
}'

{token} โ€” 840446984:AAFuVTW-FYP5tJVu8mqhc9y4E0j1fr2lCD0, BotFather,
{url} โ€” https://32515a83.ngrok.io, ngrok. . https, Telegram url.


cURL wiki.


"ok": true, .


{
    "ok": true,
    "result": true,
    "description": "Webhook was set"
}

, . app.py .


from flask import Flask, request

app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def receive_update():
    if request.method == "POST":
        print(request.json)
    return {"ok": True}

Flask. Ctrl+C .


(venv)$ flask run

. Telegram. , .


Message in the console!



, . "pong" .


API Telegram sendMessage. .


requests, , . .


(venv)$ pip install requests

requests from flask import Flask, request app.py.


import requests

id . Telegram-.


chat_id = request.json["message"]["chat"]["id"]

, id .


def send_message(chat_id, text):
    method = "sendMessage"
    token = "840446984:AAFuVTW-FYP5tJVu8mqhc9y4E0j1fr2lCD0"
    url = f"https://api.telegram.org/bot{token}/{method}"
    data = {"chat_id": chat_id, "text": text}
    requests.post(url, data=data)

requests .


send_message() receive_update().


send_message(chat_id, "pong")

app.py


from flask import Flask, request
import requests

app = Flask(__name__)

def send_message(chat_id, text):
    method = "sendMessage"
    token = "840446984:AAFuVTW-FYP5tJVu8mqhc9y4E0j1fr2lCD0"
    url = f"https://api.telegram.org/bot{token}/{method}"
    data = {"chat_id": chat_id, "text": text}
    requests.post(url, data=data)

@app.route("/", methods=["GET", "POST"])
def receive_update():
    if request.method == "POST":
        print(request.json)
        chat_id = request.json["message"]["chat"]["id"]
        send_message(chat_id, "pong")
    return {"ok": True}


current Weatherstack API .
2 Query Params: access_key โ€” 86a3fe972756lk34a6a042bll348b1e3, , query โ€” , , โ€” Moscow.


.


app = Flask(__name__).


def get_weather():
    params = {"access_key": "86a3fe972756lk34a6a042bll348b1e3", "query": "Moscow"}
    api_result = requests.get('http://api.weatherstack.com/current', params)
    api_response = api_result.json()
    return f"   {api_response['current']['temperature']} "

receive_update() "pong" .


weather = get_weather()
send_message(chat_id, weather)

The code of the entire Flask application consists of 3 functions: receiving messages from Telegram, sending messages to Telegram and receiving weather information from Weatherstack.


from flask import Flask, request
import requests

app = Flask(__name__)

def get_weather():
    params = {"access_key": "86a3fe972756lk34a6a042bll348b1e3", "query": "Moscow"}
    api_result = requests.get('http://api.weatherstack.com/current', params)
    api_response = api_result.json()
    return f"   {api_response['current']['temperature']} "

def send_message(chat_id, text):
    method = "sendMessage"
    token = "840446984:AAFuVTW-FYP5tJVu8mqhc9y4E0j1fr2lCD0"
    url = f"https://api.telegram.org/bot{token}/{method}"
    data = {"chat_id": chat_id, "text": text}
    requests.post(url, data=data)

@app.route("/", methods=["GET", "POST"])
def receive_update():
    if request.method == "POST":
        print(request.json)
        chat_id = request.json["message"]["chat"]["id"]
        weather = get_weather()
        send_message(chat_id, weather)
    return {"ok": True}

That's all! In this simple way, we taught our bot to inform us about the weather in Moscow.


All Articles