Skip to content

Commit 2f32236

Browse files
Added run_webhooks for asynctelebot
1 parent f8f147f commit 2f32236

6 files changed

Lines changed: 278 additions & 7 deletions

File tree

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#!/usr/bin/python
2+
3+
# This is a simple echo bot using the decorator mechanism.
4+
# It echoes any incoming text messages.
5+
# Example on built-in function to receive and process webhooks.
6+
7+
from telebot.async_telebot import AsyncTeleBot
8+
import asyncio
9+
bot = AsyncTeleBot('TOKEN')
10+
11+
12+
WEBHOOK_SSL_CERT = './webhook_cert.pem' # Path to the ssl certificate
13+
WEBHOOK_SSL_PRIV = './webhook_pkey.pem' # Path to the ssl private key
14+
DOMAIN = '123.12.33.22' # either domain, or ip address of vps
15+
16+
# Quick'n'dirty SSL certificate generation:
17+
#
18+
# openssl genrsa -out webhook_pkey.pem 2048
19+
# openssl req -new -x509 -days 3650 -key webhook_pkey.pem -out webhook_cert.pem
20+
#
21+
# When asked for "Common Name (e.g. server FQDN or YOUR name)" you should reply
22+
# with the same value in you put in WEBHOOK_HOST
23+
24+
25+
# Handle '/start' and '/help'
26+
@bot.message_handler(commands=['help', 'start'])
27+
async def send_welcome(message):
28+
await bot.reply_to(message, """\
29+
Hi there, I am EchoBot.
30+
I am here to echo your kind words back to you. Just say anything nice and I'll say the exact same thing to you!\
31+
""")
32+
33+
34+
# Handle all other messages with content_type 'text' (content_types defaults to ['text'])
35+
@bot.message_handler(func=lambda message: True)
36+
async def echo_message(message):
37+
await bot.reply_to(message, message.text)
38+
39+
40+
# it uses fastapi + uvicorn
41+
asyncio.run(bot.run_webhooks(
42+
listen=DOMAIN,
43+
certificate=WEBHOOK_SSL_CERT,
44+
certificate_key=WEBHOOK_SSL_PRIV
45+
))
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#!/usr/bin/python
2+
3+
# This is a simple echo bot using the decorator mechanism.
4+
# It echoes any incoming text messages.
5+
# Example on built-in function to receive and process webhooks.
6+
7+
import telebot
8+
9+
API_TOKEN = 'TOKEN'
10+
11+
bot = telebot.TeleBot(API_TOKEN)
12+
13+
WEBHOOK_SSL_CERT = './webhook_cert.pem' # Path to the ssl certificate
14+
WEBHOOK_SSL_PRIV = './webhook_pkey.pem' # Path to the ssl private key
15+
DOMAIN = '123.12.33.22' # either domain, or ip address of vps
16+
17+
# Quick'n'dirty SSL certificate generation:
18+
#
19+
# openssl genrsa -out webhook_pkey.pem 2048
20+
# openssl req -new -x509 -days 3650 -key webhook_pkey.pem -out webhook_cert.pem
21+
#
22+
# When asked for "Common Name (e.g. server FQDN or YOUR name)" you should reply
23+
# with the same value in you put in WEBHOOK_HOST
24+
25+
26+
# Handle '/start' and '/help'
27+
@bot.message_handler(commands=['help', 'start'])
28+
def send_welcome(message):
29+
bot.reply_to(message, """\
30+
Hi there, I am EchoBot.
31+
I am here to echo your kind words back to you. Just say anything nice and I'll say the exact same thing to you!\
32+
""")
33+
34+
35+
# Handle all other messages with content_type 'text' (content_types defaults to ['text'])
36+
@bot.message_handler(func=lambda message: True)
37+
def echo_message(message):
38+
bot.reply_to(message, message.text)
39+
40+
41+
bot.run_webhooks(
42+
listen=DOMAIN,
43+
certificate=WEBHOOK_SSL_CERT,
44+
certificate_key=WEBHOOK_SSL_PRIV
45+
)

‎telebot/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -375,7 +375,7 @@ def run_webhooks(self,
375375
ssl_context = (certificate, certificate_key) if certificate else None
376376
self.webhook_listener = SyncWebhookListener(self, secret_token, listen, port, ssl_context, '/'+url_path, debug)
377377
self.webhook_listener.run_app()
378-
return self.webhook_listener
378+
379379

380380

381381
def delete_webhook(self, drop_pending_updates=None, timeout=None):

‎telebot/async_telebot.py‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,13 @@
3030
types.ReplyKeyboardRemove, types.ForceReply]
3131

3232

33+
# for webhooks
34+
from telebot.extensions import AsyncWebhookListener
35+
import string
36+
import random
37+
import ssl
38+
39+
3340
"""
3441
Module : telebot
3542
"""
@@ -1438,6 +1445,82 @@ async def set_webhook(self, url=None, certificate=None, max_connections=None, al
14381445
drop_pending_updates, timeout, secret_token)
14391446

14401447

1448+
async def run_webhooks(self,
1449+
listen: Optional[str]="127.0.0.1",
1450+
port: Optional[int]=443,
1451+
url_path: Optional[str]=None,
1452+
certificate: Optional[str]=None,
1453+
certificate_key: Optional[str]=None,
1454+
webhook_url: Optional[str]=None,
1455+
max_connections: Optional[int]=None,
1456+
allowed_updates: Optional[List]=None,
1457+
ip_address: Optional[str]=None,
1458+
drop_pending_updates: Optional[bool] = None,
1459+
timeout: Optional[int]=None,
1460+
secret_token: Optional[str]=None,
1461+
secret_token_length: Optional[int]=20,
1462+
debug: Optional[bool]=False):
1463+
"""
1464+
This class sets webhooks and listens to a given url and port.
1465+
1466+
:param listen: IP address to listen to. Defaults to
1467+
0.0.0.0
1468+
:param port: A port which will be used to listen to webhooks.
1469+
:param url_path: Path to the webhook. Defaults to /token
1470+
:param certificate: Path to the certificate file.
1471+
:param certificate_key: Path to the certificate key file.
1472+
:param webhook_url: Webhook URL.
1473+
:param max_connections: Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, and higher values to increase your bot's throughput.
1474+
:param allowed_updates: A JSON-serialized list of the update types you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default). If not specified, the previous setting will be used.
1475+
:param ip_address: The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS
1476+
:param drop_pending_updates: Pass True to drop all pending updates
1477+
:param timeout: Integer. Request connection timeout
1478+
:param secret_token: Secret token to be used to verify the webhook request.
1479+
:return:
1480+
"""
1481+
1482+
# generate secret token if not set
1483+
if not secret_token:
1484+
secret_token = ''.join(random.choices(string.ascii_uppercase + string.digits, k=secret_token_length))
1485+
1486+
1487+
if not url_path:
1488+
url_path = self.token + '/'
1489+
if url_path[-1] != '/': url_path += '/'
1490+
1491+
1492+
1493+
protocol = "https" if certificate else "http"
1494+
if not webhook_url:
1495+
webhook_url = "{}://{}:{}/{}".format(protocol, listen, port, url_path)
1496+
1497+
if certificate and certificate_key:
1498+
ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
1499+
ssl_ctx.load_cert_chain(certificate, certificate_key)
1500+
else:
1501+
ssl_ctx = None
1502+
1503+
# open certificate if it exists
1504+
cert_file = open(certificate, 'rb') if certificate else None
1505+
await self.set_webhook(
1506+
url=webhook_url,
1507+
certificate=cert_file,
1508+
max_connections=max_connections,
1509+
allowed_updates=allowed_updates,
1510+
ip_address=ip_address,
1511+
drop_pending_updates=drop_pending_updates,
1512+
timeout=timeout,
1513+
secret_token=secret_token
1514+
)
1515+
if cert_file: cert_file.close()
1516+
1517+
ssl_context = (certificate, certificate_key) if certificate else (None, None)
1518+
self.webhook_listener = AsyncWebhookListener(self, secret_token, listen, port, ssl_context, '/'+url_path, debug)
1519+
# create a new loop, set it, and pass it
1520+
asyncio.set_event_loop(asyncio.new_event_loop())
1521+
await self.webhook_listener.run_app()
1522+
1523+
14411524

14421525
async def delete_webhook(self, drop_pending_updates=None, timeout=None):
14431526
"""

‎telebot/extensions/__init__.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
from .webhooks import SyncWebhookListener
1+
from .webhooks import SyncWebhookListener, AsyncWebhookListener
22

33

44

55
__all__ = [
6-
'SyncWebhookListener'
7-
]
6+
'SyncWebhookListener',
7+
'AsyncWebhookListener'
8+
]

‎telebot/extensions/webhooks.py‎

Lines changed: 100 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,35 @@
22
This file is used by TeleBot.run_webhooks() &
33
AsyncTeleBot.run_webhooks() functions.
44
5-
Flask/Aiohttp is required to run this script.
5+
Flask/fastapi is required to run this script.
66
"""
77

8-
8+
# modules required
99
flask_installed = True
10+
fastapi_installed = True
11+
uvicorn_installed = True
12+
1013
try:
1114
import flask
1215
from werkzeug.serving import _TSSLContextArg
1316
except ImportError:
1417
flask_installed = False
1518
_TSSLContextArg = None
1619

20+
try:
21+
import fastapi
22+
from fastapi.responses import JSONResponse
23+
except ImportError:
24+
fastapi_installed = False
25+
26+
27+
try:
28+
from uvicorn import Server, Config
29+
except ImportError:
30+
uvicorn_installed = False
31+
1732

33+
import asyncio
1834
from telebot.types import Update
1935

2036

@@ -85,4 +101,85 @@ def run_app(self):
85101
ssl_context=self._ssl_context,
86102
debug=self._debug
87103
)
88-
return self
104+
105+
106+
107+
108+
class AsyncWebhookListener:
109+
def __init__(self, bot,
110+
secret_token: str, host: Optional[str]="127.0.0.1",
111+
port: Optional[int]=8000,
112+
ssl_context: Optional[_TSSLContextArg]=None,
113+
url_path: Optional[str]=None,
114+
debug: Optional[bool]=False
115+
) -> None:
116+
"""
117+
Synchronous implementation of webhook listener
118+
for synchronous version of telebot.
119+
120+
:param bot: TeleBot instance
121+
:param secret_token: Telegram secret token
122+
:param host: Webhook host
123+
:param port: Webhook port
124+
:param ssl_context: SSL context
125+
"""
126+
self._check_dependencies()
127+
128+
self.app = fastapi.FastAPI()
129+
self._secret_token = secret_token
130+
self._bot = bot
131+
self._port = port
132+
self._host = host
133+
self._ssl_context = ssl_context
134+
self._url_path = url_path
135+
self._debug = debug
136+
self._prepare_endpoint_urls()
137+
138+
139+
def _check_dependencies(self):
140+
if not fastapi_installed:
141+
raise ImportError('Fastapi is not installed. Please install it via pip.')
142+
if not uvicorn_installed:
143+
raise ImportError('Uvicorn is not installed. Please install it via pip.')
144+
145+
import starlette
146+
if starlette.__version__ < '0.20.2':
147+
raise ImportError('Starlette version is too old. Please upgrade it.')
148+
return
149+
150+
151+
def _prepare_endpoint_urls(self):
152+
self.app.add_api_route(endpoint=self.process_update,path= self._url_path, methods=["POST"])
153+
154+
155+
async def process_update(self, request: fastapi.Request):
156+
"""
157+
Processes updates.
158+
"""
159+
# header containsX-Telegram-Bot-Api-Secret-Token
160+
if request.headers.get('X-Telegram-Bot-Api-Secret-Token') != self._secret_token:
161+
# secret token didn't match
162+
return JSONResponse(status_code=403, content={"error": "Forbidden"})
163+
if request.headers.get('content-type') == 'application/json':
164+
json_string = await request.json()
165+
asyncio.create_task(self._bot.process_new_updates([Update.de_json(json_string)]))
166+
return JSONResponse('', status_code=200)
167+
168+
return JSONResponse(status_code=403, content={"error": "Forbidden"})
169+
170+
171+
async def run_app(self):
172+
"""
173+
Run app with the given parameters.
174+
"""
175+
176+
config = Config(app=self.app,
177+
host=self._host,
178+
port=self._port,
179+
debug=self._debug,
180+
ssl_certfile=self._ssl_context[0],
181+
ssl_keyfile=self._ssl_context[1]
182+
)
183+
server = Server(config)
184+
await server.serve()
185+
await self._bot.close_session()

0 commit comments

Comments
 (0)