Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@leandrotoledo
Last active February 2, 2024 00:08
Show Gist options
  • Star 57 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save leandrotoledo/4e9362acdc5db33ae16c to your computer and use it in GitHub Desktop.
Save leandrotoledo/4e9362acdc5db33ae16c to your computer and use it in GitHub Desktop.
Webhook using self-signed certificate and Flask (with python-telegram-bot library)
#!/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)
@dcsan
Copy link

dcsan commented Sep 9, 2015

thanks for sharing this!

@splendido
Copy link

thanks!

@mengyyy
Copy link

mengyyy commented Mar 13, 2017

update = telegram.update.Update.de_json(request.get_json(force=True))
will rise TypeError: de_json() takes exactly 2 arguments (1 given)
i think should be
update = telegram.update.Update.de_json(request.get_json(force=True), bot)

between
setWebhook() and app.run(...)
should have delay like time.sleep(5)
like this issue
python-telegram-bot/python-telegram-bot#526

@hyperdesignir
Copy link

what is the 'path/to/ssl/server.crt' ? please help me.
i write this string and i get erroe

@nikitahartanovich
Copy link

it's path to certificate, look for another path, it seems that you have another one

@vonthecreator
Copy link

Been looking everywhere! You're a life saver

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment