我已按照this教程使用nginx设置python脚本。一切似乎都很好,只是我无法使电报机器人正常工作。
bot.set_webhook返回“确定”,但服务器未从电报服务器接收到任何更新(消息)。
这是我说完教程之后所做的:
cd /etc/ssl/
sudo openssl genrsa -des3 -passout pass:x -out server.pass.key 2048
sudo openssl rsa -passin pass:x -in server.pass.key -out server.key
rm server.pass.key
sudo openssl req -new -key server.key -out server.csr
sudo openssl x509 -req -sha256 -days 365 -in server.csr -signkey server.key -out server.crt
以下是配置文件:
etc/nginx/sites-available/bot
server {
listen 80;
server_name librarybot.marqueewinq.life;
location / {
include uwsgi_params;
uwsgi_pass unix:/home/sally/bot/bot.sock;
}
}
server {
listen 443 default ssl;
server_name librarybot.marqueewinq.life;
keepalive_timeout 60;
ssl_certificate /etc/ssl/server.crt;
ssl_certificate_key /etc/ssl/server.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers "HIGH:!RC4:!aNULL:!MD5:!kEDH";
add_header Strict-Transport-Security 'max-age=604800';
access_log /var/log/nginx_access.log;
error_log /var/log/ngingx_error.log;
location / {
include uwsgi_params;
uwsgi_pass unix:/home/sally/bot/bot.sock;
}
}
/home/sally/bot/bot.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from flask import Flask, request
import telegram
app = Flask(__name__)
app.debug = True
TOKEN = ...
global bot
bot = telegram.Bot(token=TOKEN)
URL = "librarybot.marqueewinq.life"
#WebHook
@app.route('/HOOK', methods=['POST', 'GET'])
def webhook_handler():
if request.method == "POST":
update = telegram.Update.de_json(request.get_json(force=True), bot)
try:
chat_id = update.message.chat.id
text = update.message.text
userid = update.message.from_user.id
username = update.message.from_user.username
bot.send_message(chat_id=chat_id, text="hello")
except Exception, e:
print e
return 'ok'
#Set_webhook
@app.route('/set_webhook', methods=['GET', 'POST'])
def set_webhook():
s = bot.setWebhook('https://%s:443/HOOK' % URL, certificate=open('/etc/ssl/server.crt', 'rb'))
if s:
print(s)
return "webhook setup ok"
else:
return "webhook setup failed"
@app.route('/')
def index():
return '<h1>Hello</h1>'
bot/uwsgi.ini
[uwsgi]
module = wsgi:app
master = true
processes = 5
socket = bot.sock
chmod-socket = 660
vacuum = true
die-on-term = true
bot/wsgi.py
from bot import app
if __name__ == "__main__":
app.run()