python Webhook使用自签名证书和Flask(使用python-telegram-bot库)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Webhook使用自签名证书和Flask(使用python-telegram-bot库)相关的知识,希望对你有一定的参考价值。

#!/usr/bin/env python

'''Using Webhook and self-signed certificate'''

# This file is an annotated example of a webhook based bot for
# telegram. It does not do anything useful, other than provide a quick
# template for whipping up a testbot. Basically, fill in the CONFIG
# section and run it.
# Dependencies (use pip to install them):
# - python-telegram-bot: https://github.com/leandrotoledo/python-telegram-bot
# - Flask              : http://flask.pocoo.org/
# Self-signed SSL certificate (make sure 'Common Name' matches your FQDN):
# $ openssl req -new -x509 -nodes -newkey rsa:1024 -keyout server.key -out server.crt -days 3650
# You can test SSL handshake running this script and trying to connect using wget:
# $ wget -O /dev/null https://$HOST:$PORT/

from flask import Flask, request

import telegram

# CONFIG
TOKEN    = ''
HOST     = '' # Same FQDN used when generating SSL Cert
PORT     = 8443
CERT     = 'path/to/ssl/server.crt'
CERT_KEY = 'path/to/ssl/server.key'

bot = telegram.Bot(TOKEN)
app = Flask(__name__)
context = (CERT, CERT_KEY)

@app.route('/')
def hello():
    return 'Hello World!'

@app.route('/' + TOKEN, methods=['POST'])
def webhook():
    update = telegram.update.Update.de_json(request.get_json(force=True))
    bot.sendMessage(chat_id=update.message.chat_id, text='Hello, there')

    return 'OK'


def setWebhook():
    bot.setWebhook(webhook_url='https://%s:%s/%s' % (HOST, PORT, TOKEN),
                   certificate=open(CERT, 'rb'))

if __name__ == '__main__':
    setWebhook()

    app.run(host='0.0.0.0',
            port=PORT,
            ssl_context=context,
            debug=True)

以上是关于python Webhook使用自签名证书和Flask(使用python-telegram-bot库)的主要内容,如果未能解决你的问题,请参考以下文章

带有自签名证书的 Telegram bot webhook 不起作用

PayPal + RESTful API + WebHooks + 自签名证书

如何使用Python和Flask创建自签名证书

确定 SSL 证书是不是使用 Python 自签名

Python 发送带自签名证书的 https 请求

Python 3.6 SSL - 使用TLSv1.0而不是TLSv1.2密码 - (2路身份验证和自签名证书)