本文使用 Flask
框架和 pyTelegramBotAPI
开发,前提是你有一台能访问国际互联网,并使用 NGINX
部署了 HTTPS
网站的服务器。
安装依赖
首先安装 Python3
。
- # Debain 9+ / Ubuntu 18+
- apt install -y python3
-
- # CentOS 7+
- yum install -y epel-release
- yum install -y python3
随后 创建项目目录
,创建 virtualenv
。
- PROJECT_PATH=/usr/local/etc/tgbot
- mkdir -p $PROJECT_PATH
- cd $PROJECT_PATH
- pip3 install virtualenv
- virtualenv --python python3 --no-site-packages env
最后安装核心依赖 flask
、pyTelegramBotAPI
,以及 python 与 nginx 间的高性能网关 uwsgi
。
- source env/bin/activate
- pip3 install uwsgi
- pip3 install flask
- pip3 install pyTelegramBotAPI
- deactivate
编写测试代码
首先编写核心逻辑文件 tgbot.py
,只需要修改 API_TOKEN
和 WEBHOOK_HOST
,端口不修改,后文采用 nginx 反代
。
- #!/usr/bin/python3
- # -*- coding: utf-8 -*-
-
- import time
- import telebot
- from flask import Flask, request, abort
-
- # Bot Token
- API_TOKEN = '123456789:BAF9kk9nneRpG5ktIeeT-YiOIz81GRBHDUk'
- # 域名
- WEBHOOK_HOST = 'logi.im'
- # 端口
- WEBHOOK_PORT = 443
-
- WEBHOOK_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, WEBHOOK_PORT)
- WEBHOOK_URL_PATH = "/%s/" % (API_TOKEN)
-
- app = Flask(__name__)
- bot = telebot.TeleBot(API_TOKEN, threaded=False)
-
-
- # Flask Webhook 入口
- @app.route(WEBHOOK_URL_PATH, methods=['POST'])
- def webhook():
- if request.headers.get('content-type') == 'application/json':
- json_string = request.get_data().decode('utf-8')
- update = telebot.types.Update.de_json(json_string)
- bot.process_new_updates([update])
- return 'got it.'
- else:
- abort(403)
-
-
- # 响应 start 命令
- @bot.message_handler(commands=['start'])
- def send_welcome(message):
- bot.send_message(message.chat.id, 'welcome!')
-
-
- bot.remove_webhook()
- time.sleep(3)
- bot.set_webhook(url=WEBHOOK_URL_BASE + WEBHOOK_URL_PATH)
编写生产环境配置
首先编写 uwsgi
网关配置 tgbot.ini
。
- [uwsgi]
- project = tgbot
- base = /usr/local/etc
- chdir = %(base)/%(project)
- wsgi-file = %(chdir)/tgbot.py
- callable = app
-
- socket = %(chdir)/%(project).sock
- chmod-socket = 666
-
- vacuum = true
- processes = 4
- threads = 2
接着编写启动脚本 tgbot.sh
。
- #!/usr/bin/env bash
- cd /usr/local/etc/tgbot
- source env/bin/activate
- uwsgi tgbot.ini
随后编写开机自启服务 tgbot.service
。
- [Unit]
- Description=Tgbot Service
- After=network.target
- Wants=network.target
-
- [Service]
- Type=simple
- PIDFile=/run/tgbot.pid
- WorkingDirectory=/usr/local/etc/tgbot
- ExecStart=/usr/local/etc/tgbot/tgbot.sh
- Restart=on-failure
-
- [Install]
- WantedBy=multi-user.target
接下来 启动服务
并将其 加入开机自启
。
- cp tgbot.service /etc/systemd/system/
- systemctl daemon-reload
- systemctl start tgbot
- systemctl enable tgbot
最后配置 nginx 反代
。
- # 在已部署的 HTTPS 网站配置中添加 location 块,路径为 Bot Token
- location /123456789:BAF9kk9nneRpG5ktIeeT-YiOIz81GRBHDUk {
- include uwsgi_params;
- uwsgi_pass unix:/usr/local/etc/tgbot/tgbot.sock;
- }
重启 nginx。
- nginx -s reload
测试 Bot
私聊机器人,发送 /start
观察其是否响应 welcome!
。
后续开发
接下来,只需在 tgbot.py
中编写更多处理函数,即可丰富该 BOT 功能。每次修改代码后使用以下命令重启。
- systemctl restart tgbot
如有问题请在下方留言,文章转载请注明出处,详细交流请加下方群组!请大佬不要屏蔽文中广告,因为它将帮我分担服务器开支,如果能帮忙点击我将万分感谢。
强调几点:(该留言由系统自动生成!)
1. 请不要刷广告,本站没有流量!
2. 我不回复虚假邮箱,因为回复了你也看不到!
3. 存在必须回复的隐藏内容时,可以直接使用表情框里的阿鲁表情!