Hola a todos, en este artículo les diré cómo hacer el bot de telegramas más simple en Python para enviar el clima actual en Moscú.
El artículo está dirigido a principiantes en Python que deseen obtener más información sobre cómo interactuar con servicios externos a través de API.
Tecnologías y API:
- Python es un lenguaje de programación
- Frasco: un marco para crear aplicaciones web,
- Telegram Bot API,
- API de Weatherstack
- Ngrok es un servicio para crear un túnel a localhost.
¿Cómo funcionará todo?
- El usuario escribe un mensaje de telegrama al bot.
- Telegram reenvía el mensaje de usuario al servidor.
- El servidor solicita información meteorológica de Weatherstack.
- El servidor envía información meteorológica a Telegram.
- El usuario recibe información meteorológica.
Telegram registro bot
En esta etapa, necesitamos crear un bot y obtener acceso a él. Para hacer esto, inicie el bot @botfather en Telegram con el comando a continuación.
/start
Creamos un nuevo bot de acuerdo con las instrucciones del mensaje del bot.
!
Se crea el bot, pero si le escribe algún mensaje, no reaccionará de ninguna manera. Arreglalo.
Ayuda de matraces
Flask es un marco para crear aplicaciones web en el lenguaje de programación Python, utilizando el kit de herramientas Werkzeug, así como el motor de plantillas Jinja2. Pertenece a la categoría de los llamados microframes, marcos minimalistas de aplicaciones web que proporcionan deliberadamente solo las características más básicas.
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 — , .
- ngrok.
- .
- 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. , .
!
, . "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)
El código de toda la aplicación Flask consta de 3 funciones: recibir mensajes de Telegram, enviar mensajes a Telegram y recibir información meteorológica de 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}
¡Eso es todo! De esta manera simple, enseñamos a nuestro bot a informarnos sobre el clima en Moscú.