我试图将 django 设置为电报机器人的 webhooks。 我使用以下命令创建了一个 ssl 证书:
openssl genrsa -out webhook_pkey.pem 2048
openssl req -new -x509 -days 3650 -key webhook_pkey.pem -out webhook_cert.pem
# In Common Name i type a server IP address
设置在端口 800 上运行 gunicorn,将 nginx 中的 proxy_pass 设置为 localhost:800。网站工作正常,我可以在浏览器上打开它并查看我的主页。 Gunicorn 以该命令开始:
gunicorn wsgi -b 127.0.0.1:800
# wsgi is django generated wsgi.py file
我的 nginx.conf 文件:
upstream django {
server 127.0.0.1:800;
}
server {
listen 80;
listen 443 ssl;
server_name 111.111.111.111 # these ip addres of my server
ssl_certificate /path/to/webhook.cert;
ssl_certificate_key /path/to/webhook.pkey;
charset utf-8;
client_max_body_size 10M;
location /media {
alias /path/to/media;
}
location /static {
alias /path/to/static;
}
location / {
proxy_pass http://127.0.0.1:800;
proxy_set_header Host $server_name;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Protocol $scheme;
}
}
我使用的是 pyTelegramBotApi。
from telebot import TeleBot
bot = TeleBot(token)
cert = open('webhook.cert', 'r')
bot.remove_webhook()
bot.set_webhook("https://111.111.111.111:80/user_bots/, certificate=cert)
# I'm trying a differents ports
cert.close()
user_bots - 它是在 django 中查看的一些路径,其中记录了一些来自请求的数据 在我运行这段代码后,我在 nginx access.log 中看到了这个:
149.154.167.200 - - [26/Oct/2017:15:36:13 +0000] "\x16\x03\x01\x00\xC3\x01\x00\x00\xBF\x03\x03\x19\xB3\x937v\x14\xF0\xDCj\xC1\x93\xB2?\xF9tOK\x10\x9FA\x87|\xA9!\x81e\xCFC\xDD\x92\x94\x97\x00\x008\xC0,\xC00\x00\x9F\xCC\xA9\xCC\xA8\xCC\xAA\xC0+\xC0/\x00\x9E\xC0$\xC0(\x00k\xC0#\xC0'\x00g\xC0" 400 182 "-" "-"
# And then many some logs, it stopped after i run bot.remove_webhook()
Google 说 ssl 证书有误。
django urls.py
urlpatterns += url(r'user_bots/(?P<token>[0-9]+:\w*)/.*$', views.bot_test, name="bot_test")
bot_test View :
def bot_test(request, token):
logging.info(f"Request from bot with token {token}")
return HttpResponse("OK")
我需要在我的 Django 应用程序中选择机器人需要通过它的标记引用的内容。
我被困住了 :( 我整天都在努力解决这个问题,也许有人可以帮助我?
请您参考如下方法:
解决方案很简单:) 替换
cert = open(PATH_TO_CERT, 'r')
bot.set_webhook(url=f'https://111.111.111.111:80/user_bots/{token}/',
certificate=cert)
到
bot.set_webhook(url=f'https://111.111.111.111:443/user_bots/{token}/',
certificate=open(PATH_TO_CERT, 'r')
一切正常!
