Skip to content

Commit d6552eb

Browse files
committed
Add webhook examples
1 parent 117c5a1 commit d6552eb

4 files changed

Lines changed: 304 additions & 0 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Webhook examples using pyTelegramBotAPI
2+
3+
There are 3 examples in this directory using different libraries:
4+
5+
* **Python (CPython):** *webhook_cpython_echo_bot.py*
6+
* **Pros:**
7+
* Official python libraries, it works out of the box (doesn't require to
8+
install anything).
9+
* Works with Python 2 and Python 3 (need to be converted with 2to3).
10+
* **Cons:**
11+
* Ugly code.
12+
* Many things to handle yourself, this can lead to errors.
13+
* Not powerful, do the trick but the performance is low.
14+
15+
* **CherryPy (3.8.0):** *webhook_cherrypy_echo_bot.py*
16+
* **Pros:**
17+
* It's a web application framework, cleaner code, uses objects for defining
18+
the web application.
19+
* Very good performance.
20+
* The project seems to be active, latest version is recent.
21+
* Works with Python 2 and Python 3.
22+
* **Cons:**
23+
* Some things are not very intuitive, reading the doc is a must.
24+
25+
* **Flask (0.10.1):** *webhook_flask_echo_bot.py*
26+
* **Pros:**
27+
* It's a web application framework, cleaner code, uses decorator which can
28+
be nice.
29+
* Good performance.
30+
* It's intuitive if you know how web application works.
31+
* **Cons:**
32+
* The project seems not to be very active, latest version dates 2013.
33+
* They don't recommend to use it with Python 3, but may work.
34+
* May be a oversized for just handling webhook petitions.
35+
36+
*Latest update of this document: 2015-10-06*
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
# This is a simple echo bot using decorators and webhook with CherryPy
5+
# It echoes any incoming text messages and does not use the polling method.
6+
7+
import cherrypy
8+
import telebot
9+
import logging
10+
11+
12+
API_TOKEN = '<api_token>'
13+
14+
WEBHOOK_HOST = '<ip/host where the bot is running>'
15+
WEBHOOK_PORT = 8443 # 443, 80, 88 or 8443 (port need to be 'open')
16+
WEBHOOK_LISTEN = '0.0.0.0' # In some VPS you may need to put here the IP addr
17+
18+
WEBHOOK_SSL_CERT = './webhook_cert.pem' # Path to the ssl certificate
19+
WEBHOOK_SSL_PRIV = './webhook_pkey.pem' # Path to the ssl private key
20+
21+
# Quick'n'dirty SSL certificate generation:
22+
#
23+
# openssl genrsa -out webhook_pkey.pem 2048
24+
# openssl req -new -x509 -days 3650 -key webhook_pkey.pem -out webhook_cert.pem
25+
#
26+
# When asked for "Common Name (e.g. server FQDN or YOUR name)" you should reply
27+
# with the same value in you put in WEBHOOK_HOST
28+
29+
WEBHOOK_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, WEBHOOK_PORT)
30+
WEBHOOK_URL_PATH = "/%s/" % (API_TOKEN)
31+
32+
33+
logger = telebot.logger
34+
telebot.logger.setLevel(logging.INFO)
35+
36+
bot = telebot.TeleBot(API_TOKEN)
37+
38+
39+
# WebhookServer, process webhook calls
40+
class WebhookServer(object):
41+
@cherrypy.expose
42+
def index(self):
43+
if 'content-length' in cherrypy.request.headers and \
44+
'content-type' in cherrypy.request.headers and \
45+
cherrypy.request.headers['content-type'] == 'application/json':
46+
length = int(cherrypy.request.headers['content-length'])
47+
json_string = cherrypy.request.body.read(length)
48+
update = telebot.types.Update.de_json(json_string)
49+
bot.process_new_messages([update.message])
50+
return ''
51+
else:
52+
raise cherrypy.HTTPError(403)
53+
54+
55+
# Handle '/start' and '/help'
56+
@bot.message_handler(commands=['help', 'start'])
57+
def send_welcome(message):
58+
bot.reply_to(message,
59+
("Hi there, I am EchoBot.\n"
60+
"I am here to echo your kind words back to you."))
61+
62+
63+
# Handle all other messages
64+
@bot.message_handler(func=lambda message: True, content_types=['text'])
65+
def echo_message(message):
66+
bot.reply_to(message, message.text)
67+
68+
69+
# Remove webhook, it fails sometimes the set if there is a previous webhook
70+
bot.remove_webhook()
71+
72+
# Set webhook
73+
bot.set_webhook(url=WEBHOOK_URL_BASE+WEBHOOK_URL_PATH,
74+
certificate=open(WEBHOOK_SSL_CERT, 'r'))
75+
76+
# Start cherrypy server
77+
cherrypy.config.update({
78+
'server.socket_host': WEBHOOK_LISTEN,
79+
'server.socket_port': WEBHOOK_PORT,
80+
'server.ssl_module': 'builtin',
81+
'server.ssl_certificate': WEBHOOK_SSL_CERT,
82+
'server.ssl_private_key': WEBHOOK_SSL_PRIV
83+
})
84+
85+
cherrypy.quickstart(WebhookServer(), WEBHOOK_URL_PATH, {'/': {}})
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
# This is a simple echo bot using decorators and webhook with BaseHTTPServer
5+
# It echoes any incoming text messages and does not use the polling method.
6+
7+
import BaseHTTPServer
8+
import ssl
9+
import telebot
10+
import logging
11+
12+
13+
API_TOKEN = '<api_token>'
14+
15+
WEBHOOK_HOST = '<ip/host where the bot is running>'
16+
WEBHOOK_PORT = 8443 # 443, 80, 88 or 8443 (port need to be 'open')
17+
WEBHOOK_LISTEN = '0.0.0.0' # In some VPS you may need to put here the IP addr
18+
19+
WEBHOOK_SSL_CERT = './webhook_cert.pem' # Path to the ssl certificate
20+
WEBHOOK_SSL_PRIV = './webhook_pkey.pem' # Path to the ssl private key
21+
22+
# Quick'n'dirty SSL certificate generation:
23+
#
24+
# openssl genrsa -out webhook_pkey.pem 2048
25+
# openssl req -new -x509 -days 3650 -key webhook_pkey.pem -out webhook_cert.pem
26+
#
27+
# When asked for "Common Name (e.g. server FQDN or YOUR name)" you should reply
28+
# with the same value in you put in WEBHOOK_HOST
29+
30+
WEBHOOK_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, WEBHOOK_PORT)
31+
WEBHOOK_URL_PATH = "/%s/" % (API_TOKEN)
32+
33+
34+
logger = telebot.logger
35+
telebot.logger.setLevel(logging.INFO)
36+
37+
bot = telebot.TeleBot(API_TOKEN)
38+
39+
40+
# WebhookHandler, process webhook calls
41+
class WebhookHandler(BaseHTTPServer.BaseHTTPRequestHandler):
42+
server_version = "WebhookHandler/1.0"
43+
44+
def do_HEAD(self):
45+
self.send_response(200)
46+
self.end_headers()
47+
48+
def do_GET(self):
49+
self.send_response(200)
50+
self.end_headers()
51+
52+
def do_POST(self):
53+
if self.path == WEBHOOK_URL_PATH and \
54+
'content-type' in self.headers and \
55+
'content-length' in self.headers and \
56+
self.headers['content-type'] == 'application/json':
57+
json_string = self.rfile.read(int(self.headers['content-length']))
58+
59+
self.send_response(200)
60+
self.end_headers()
61+
62+
update = telebot.types.Update.de_json(json_string)
63+
bot.process_new_messages([update.message])
64+
else:
65+
self.send_error(403)
66+
self.end_headers()
67+
68+
69+
# Handle '/start' and '/help'
70+
@bot.message_handler(commands=['help', 'start'])
71+
def send_welcome(message):
72+
bot.reply_to(message,
73+
("Hi there, I am EchoBot.\n"
74+
"I am here to echo your kind words back to you."))
75+
76+
77+
# Handle all other messages
78+
@bot.message_handler(func=lambda message: True, content_types=['text'])
79+
def echo_message(message):
80+
bot.reply_to(message, message.text)
81+
82+
83+
# Remove webhook, it fails sometimes the set if there is a previous webhook
84+
bot.remove_webhook()
85+
86+
# Set webhook
87+
bot.set_webhook(url=WEBHOOK_URL_BASE+WEBHOOK_URL_PATH,
88+
certificate=open(WEBHOOK_SSL_CERT, 'r'))
89+
90+
# Start server
91+
httpd = BaseHTTPServer.HTTPServer((WEBHOOK_LISTEN, WEBHOOK_PORT),
92+
WebhookHandler)
93+
94+
httpd.socket = ssl.wrap_socket(httpd.socket,
95+
certfile=WEBHOOK_SSL_CERT,
96+
keyfile=WEBHOOK_SSL_PRIV,
97+
server_side=True)
98+
99+
httpd.serve_forever()
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
# This is a simple echo bot using decorators and webhook with flask
5+
# It echoes any incoming text messages and does not use the polling method.
6+
7+
import flask
8+
import telebot
9+
import logging
10+
11+
12+
API_TOKEN = '<api_token>'
13+
14+
WEBHOOK_HOST = '<ip/host where the bot is running>'
15+
WEBHOOK_PORT = 8443 # 443, 80, 88 or 8443 (port need to be 'open')
16+
WEBHOOK_LISTEN = '0.0.0.0' # In some VPS you may need to put here the IP addr
17+
18+
WEBHOOK_SSL_CERT = './webhook_cert.pem' # Path to the ssl certificate
19+
WEBHOOK_SSL_PRIV = './webhook_pkey.pem' # Path to the ssl private key
20+
21+
# Quick'n'dirty SSL certificate generation:
22+
#
23+
# openssl genrsa -out webhook_pkey.pem 2048
24+
# openssl req -new -x509 -days 3650 -key webhook_pkey.pem -out webhook_cert.pem
25+
#
26+
# When asked for "Common Name (e.g. server FQDN or YOUR name)" you should reply
27+
# with the same value in you put in WEBHOOK_HOST
28+
29+
WEBHOOK_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, WEBHOOK_PORT)
30+
WEBHOOK_URL_PATH = "/%s/" % (API_TOKEN)
31+
32+
33+
logger = telebot.logger
34+
telebot.logger.setLevel(logging.INFO)
35+
36+
bot = telebot.TeleBot(API_TOKEN)
37+
38+
app = flask.Flask(__name__)
39+
40+
41+
# Empty webserver index, return nothing, just http 200
42+
@app.route('/', methods=['GET', 'HEAD'])
43+
def index():
44+
return ''
45+
46+
47+
# Process webhook calls
48+
@app.route(WEBHOOK_URL_PATH, methods=['POST'])
49+
def webhook():
50+
if flask.request.headers.get('content-type') == 'application/json':
51+
json_string = flask.request.get_data()
52+
update = telebot.types.Update.de_json(json_string)
53+
bot.process_new_messages([update.message])
54+
return ''
55+
else:
56+
flask.abort(403)
57+
58+
59+
# Handle '/start' and '/help'
60+
@bot.message_handler(commands=['help', 'start'])
61+
def send_welcome(message):
62+
bot.reply_to(message,
63+
("Hi there, I am EchoBot.\n"
64+
"I am here to echo your kind words back to you."))
65+
66+
67+
# Handle all other messages
68+
@bot.message_handler(func=lambda message: True, content_types=['text'])
69+
def echo_message(message):
70+
bot.reply_to(message, message.text)
71+
72+
73+
# Remove webhook, it fails sometimes the set if there is a previous webhook
74+
bot.remove_webhook()
75+
76+
# Set webhook
77+
bot.set_webhook(url=WEBHOOK_URL_BASE+WEBHOOK_URL_PATH,
78+
certificate=open(WEBHOOK_SSL_CERT, 'r'))
79+
80+
# Start flask server
81+
app.run(host=WEBHOOK_LISTEN,
82+
port=WEBHOOK_PORT,
83+
ssl_context=(WEBHOOK_SSL_CERT, WEBHOOK_SSL_PRIV),
84+
debug=True)

0 commit comments

Comments
 (0)