Flask上的一个简单Telegram机器人,提供天气报告

大家好,在本文中,我将告诉您如何使用Python创建最简单的电报机器人来发送莫斯科的当前天气。


本文面向Python初学者,他们想了解更多有关如何通过API与外部服务进行交互的信息。


技术和API:


  • Python是一种编程语言
  • Flask-用于创建Web应用程序的框架,
  • 电报Bot API,
  • Weatherstack API
  • Ngrok是用于创建到本地主机的隧道的服务。

一切将如何运作?


  1. 用户将电报消息写入机器人。
  2. 电报将用户消息转发到服务器。
  3. 服务器从Weatherstack请求天气信息。
  4. 服务器将天气信息发送给Telegram。
  5. 用户接收天气信息。

电报注册机器人


在此阶段,我们需要创建一个机器人并对其进行访问。为此,请使用以下命令在Telegram中启动@botfather机器人。


/start

我们根据机器人发出的消息中的说明创建一个新的机器人。


电报注册机器人


该漫游器已创建,但是如果您向其中写入一些消息,它将不会对其产生任何反应。修理它。


烧瓶帮助


Flask是使用Werkzeug工具包以及Jinja2模板引擎以Python编程语言创建Web应用程序的框架。它属于所谓的微框架(microframe)类别-网络应用程序的简约框架,仅故意提供最基本的功能。


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. , .


控制台中的消息!



, . "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)

整个Flask应用程序的代码包含3个功能:从Telegram接收消息,向Telegram发送消息以及从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}

就这样!通过这种简单的方式,我们教会了我们的漫游器将莫斯科的天气情况告知我们。


All Articles