MENU

10 分钟编写一个 Telegram Bot

2019 年 11 月 21 日 • 阅读: 11710 • 后端

本文使用 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

最后安装核心依赖 flaskpyTelegramBotAPI,以及 python 与 nginx 间的高性能网关 uwsgi

  • source env/bin/activate
  • pip3 install uwsgi
  • pip3 install flask
  • pip3 install pyTelegramBotAPI
  • deactivate

编写测试代码

首先编写核心逻辑文件 tgbot.py,只需要修改 API_TOKENWEBHOOK_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
TG 大佬群 QQ 大佬群

最后编辑于: 2019 年 12 月 08 日
返回文章列表 文章二维码
本页链接的二维码
打赏二维码
添加新评论

Loading captcha...

已有 9 条评论
  1. 强调几点:(该留言由系统自动生成!)
    1. 请不要刷广告,本站没有流量!
    2. 我不回复虚假邮箱,因为回复了你也看不到!
    3. 存在必须回复的隐藏内容时,可以直接使用表情框里的阿鲁表情!

  1. Escher Escher   Windows 10 x64 Edition  Google Chrome 78.0.3904.108

    哎哟,不错哟

  2. 你好 你好   Windows 10 x64 Edition  Google Chrome 78.0.3904.70

    12

  3. 嘿嘿嘿 嘿嘿嘿   Windows 10 x64 Edition  Google Chrome 78.0.3904.97

    我来试试

  4. 嘿嘿嘿 嘿嘿嘿   Windows 10 x64 Edition  Google Chrome 78.0.3904.97

    woc 你怎么获取的我的头像 通过邮箱嘛

  5. 嘿嘿嘿 嘿嘿嘿   Windows 10 x64 Edition  Google Chrome 78.0.3904.97

    发现新大陆

    1. LOGI LOGI   Windows 10 x64 Edition  Google Chrome 78.0.3904.108

      @嘿嘿嘿欢迎帮找 bug

  6. repostone repostone   Windows 8.1 x64 Edition  Google Chrome 78.0.3904.87

    非技术的路过。

    1. LOGI LOGI   Windows 10 x64 Edition  Google Chrome 78.0.3904.108

      @repostone 您怕不是个机器人 @(哈哈)