python-telegram-bot/telegram/utils/webhookhandler.py

79 lines
2.5 KiB
Python
Raw Normal View History

2015-11-16 13:05:57 +01:00
import logging
from telegram import Update, NullHandler
from future.utils import bytes_to_native_str as n
import json
try:
import BaseHTTPServer
except ImportError:
import http.server as BaseHTTPServer
H = NullHandler()
logging.getLogger(__name__).addHandler(H)
2015-11-16 20:35:27 +01:00
class WebhookServer(BaseHTTPServer.HTTPServer, object):
2015-11-16 13:05:57 +01:00
def __init__(self, server_address, RequestHandlerClass, update_queue,
webhook_path):
2015-11-16 20:43:35 +01:00
super(WebhookServer, self).__init__(server_address,
RequestHandlerClass)
2015-11-21 23:09:19 +01:00
self.logger = logging.getLogger(__name__)
2015-11-16 13:05:57 +01:00
self.update_queue = update_queue
self.webhook_path = webhook_path
self.is_running = False
def serve_forever(self, poll_interval=0.5):
self.is_running = True
2015-11-21 23:09:19 +01:00
self.logger.info("Webhook Server started.")
super(WebhookServer, self).serve_forever(poll_interval)
2015-11-21 23:09:19 +01:00
self.logger.info("Webhook Server stopped.")
def shutdown(self):
if not self.is_running:
return
else:
super(WebhookServer, self).shutdown()
2015-11-16 13:05:57 +01:00
# WebhookHandler, process webhook calls
# Based on: https://github.com/eternnoir/pyTelegramBotAPI/blob/master/
# examples/webhook_examples/webhook_cpython_echo_bot.py
2015-11-16 20:35:27 +01:00
class WebhookHandler(BaseHTTPServer.BaseHTTPRequestHandler, object):
2015-11-16 13:05:57 +01:00
server_version = "WebhookHandler/1.0"
def __init__(self, request, client_address, server):
2015-11-21 23:09:19 +01:00
self.logger = logging.getLogger(__name__)
2015-11-16 20:35:27 +01:00
super(WebhookHandler, self).__init__(request, client_address, server)
2015-11-16 13:05:57 +01:00
def do_HEAD(self):
self.send_response(200)
self.end_headers()
def do_GET(self):
self.send_response(200)
self.end_headers()
def do_POST(self):
2015-11-21 23:09:19 +01:00
self.logger.debug("Webhook triggered")
2015-11-16 13:05:57 +01:00
if self.path == self.server.webhook_path and \
'content-type' in self.headers and \
'content-length' in self.headers and \
self.headers['content-type'] == 'application/json':
json_string = \
n(self.rfile.read(int(self.headers['content-length'])))
self.send_response(200)
self.end_headers()
2015-11-21 23:09:19 +01:00
self.logger.debug("Webhook received data: " + json_string)
2015-11-16 13:05:57 +01:00
update = Update.de_json(json.loads(json_string))
2015-11-21 23:09:19 +01:00
self.logger.info("Received Update with ID %d on Webhook" %
update.update_id)
2015-11-16 13:05:57 +01:00
self.server.update_queue.put(update)
else:
self.send_error(403)
2015-11-16 20:35:27 +01:00
self.end_headers()