Skip to main content
 首页 » 编程设计

python之如何使用 Nginx 反向代理部署 Telegram Bot

2024年12月31日15lonelyxmas

我使用 python-telegram-bot 库开发了一个 Telegram 机器人,现在我想将它部署到我的服务器中,所以我设置了一个 webhook(在 Official Wiki 之后)但是当我尝试与我的机器人沟通我没有得到任何回复。

这是机器人的来源:

def main(): 
   PRIVTOKEN = "1134xxxx" 
   updater = Updater(PRIVTOKEN) 
 
   dp = updater.dispatcher 
 
   dp.add_handler(CommandHandler("start", start)) 
   # ... 
 
   updater.start_webhook(listen='127.0.0.1', 
                         port=8843, 
                         url_path=PRIVTOKEN) 
   updater.bot.set_webhook(webhook_url='https://example.com/' + PRIVTOKEN, 
                           certificate=open("cert.pem", "rb")) 
   print("bot started") 
   updater.idle() 

nginx 配置文件:

server { 
  listen 443 ssl; 
  server_name example.com; 
 
 
  location /1134xxxx { 
     proxy_pass http://127.0.0.1:8443; 
  } 
} 

网络统计状态:

sudo netstat -an | grep 8843 
tcp        0      127.0.0.1:8843            0.0.0.0:*               LISTEN  

机器人(我已启用错误日志)或 nginx(访问/错误日志)没有记录其他错误

我还在防火墙中为 8843 端口添加了自定义规则。

请您参考如下方法:

Telegram 仅支持 https 请求。注意这一点。

我的 nginx 配置:

server { 
        listen 80; 
        listen 443 ssl; 
        server_name example.com www.example.com; 
        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; 
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; 
        if ($scheme = http) { 
            return 301 https://$server_name$request_uri; 
        } 
    location / { 
            proxy_set_header Host $http_host; 
            proxy_redirect off; 
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
            proxy_set_header X-Real-IP $remote_addr; 
            proxy_set_header X-Scheme $scheme; 
            proxy_pass http://localhost:5005/; 
    } 
}