We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Webhook Broken Pipe after connection reset, kills dispatcher
### Steps to reproduce
1.
Standard Webhook with updater and dispatcher:
```
updater = Updater(TOKEN) PORT = int(os.environ.get('PORT', '5000')) # add handlers 
updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN) 
updater.bot.set_webhook("https://home.co.za/" + TOKEN) 
dp = updater.dispatcher dp.add_error_handler(error) 
updater.idle()
```


### Expected behaviour
Bot should run and remain responsive

### Actual behaviour
It runs,  but after a few hours becomes unresponsive.

### Configuration
**Operating System:**
Linux Cappucino 4.4.0-104-generic #127-Ubuntu SMP Mon Dec 11 12:16:50 UTC 2017 i686 athlon i686 GNU/Linux

**Version of Python, python-telegram-bot & dependencies:**

```
python-telegram-bot 9.0.0
certifi 2017.11.05
future 0.16.0
Python 3.5.2 (default, Nov 23 2017, 16:37:01)  [GCC 5.4.0 20160609]
```

### Logs
```
2018-01-10 03:54:56,480 - telegram.ext.updater - ERROR - unhandled exception
Traceback (most recent call last):
  File "/usr/lib/python3.5/socketserver.py", line 313, in _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib/python3.5/socketserver.py", line 341, in process_request
    self.finish_request(request, client_address)
  File "/usr/lib/python3.5/socketserver.py", line 354, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/local/lib/python3.5/dist-packages/telegram/utils/webhookhandler.py", line 62, in __init__
    super(WebhookHandler, self).__init__(request, client_address, server)
  File "/usr/lib/python3.5/socketserver.py", line 681, in __init__
    self.handle()
  File "/usr/lib/python3.5/http/server.py", line 422, in handle
    self.handle_one_request()
  File "/usr/lib/python3.5/http/server.py", line 390, in handle_one_request
    self.raw_requestline = self.rfile.readline(65537)
  File "/usr/lib/python3.5/socket.py", line 575, in readinto
    return self._sock.recv_into(b)
ConnectionResetError: [Errno 104] Connection reset by peer

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/telegram/ext/updater.py", line 149, in _thread_wrapper
    target(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/telegram/ext/updater.py", line 353, in _start_webhook
    self.httpd.serve_forever(poll_interval=1)
  File "/usr/local/lib/python3.5/dist-packages/telegram/utils/webhookhandler.py", line 41, in serve_forever
    super(WebhookServer, self).serve_forever(poll_interval)
  File "/usr/lib/python3.5/socketserver.py", line 234, in serve_forever
    self._handle_request_noblock()
  File "/usr/lib/python3.5/socketserver.py", line 315, in _handle_request_noblock
    self.handle_error(request, client_address)
  File "/usr/lib/python3.5/socketserver.py", line 371, in handle_error
    print('Exception happened during processing of request from', end=' ')
BrokenPipeError: [Errno 32] Broken pipe
Exception in thread updater:
Traceback (most recent call last):
  File "/usr/lib/python3.5/socketserver.py", line 313, in _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib/python3.5/socketserver.py", line 341, in process_request
    self.finish_request(request, client_address)
  File "/usr/lib/python3.5/socketserver.py", line 354, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/local/lib/python3.5/dist-packages/telegram/utils/webhookhandler.py", line 62, in __init__
    super(WebhookHandler, self).__init__(request, client_address, server)
  File "/usr/lib/python3.5/socketserver.py", line 681, in __init__
    self.handle()
  File "/usr/lib/python3.5/http/server.py", line 422, in handle
    self.handle_one_request()
  File "/usr/lib/python3.5/http/server.py", line 390, in handle_one_request
    self.raw_requestline = self.rfile.readline(65537)
  File "/usr/lib/python3.5/socket.py", line 575, in readinto
    return self._sock.recv_into(b)
ConnectionResetError: [Errno 104] Connection reset by peer

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/local/lib/python3.5/dist-packages/telegram/ext/updater.py", line 149, in _thread_wrapper
    target(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/telegram/ext/updater.py", line 353, in _start_webhook
    self.httpd.serve_forever(poll_interval=1)
  File "/usr/local/lib/python3.5/dist-packages/telegram/utils/webhookhandler.py", line 41, in serve_forever
    super(WebhookServer, self).serve_forever(poll_interval)
  File "/usr/lib/python3.5/socketserver.py", line 234, in serve_forever
    self._handle_request_noblock()
  File "/usr/lib/python3.5/socketserver.py", line 315, in _handle_request_noblock
    self.handle_error(request, client_address)
  File "/usr/lib/python3.5/socketserver.py", line 371, in handle_error
    print('Exception happened during processing of request from', end=' ')
BrokenPipeError: [Errno 32] Broken pipe

2018-01-10 03:54:56,601 - telegram.ext.dispatcher - CRITICAL - stopping due to exception in another thread
2018-01-10 03:54:56,601 - telegram.ext.dispatcher - DEBUG - Dispatcher thread stopped
2018-01-10 03:54:56,601 - telegram.ext.updater - DEBUG - dispatcher - ended
```

  

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `telegram/utils/webhookhandler.py`
Content:
```
1 #!/usr/bin/env python
2 #
3 # A library that provides a Python interface to the Telegram Bot API
4 # Copyright (C) 2015-2018
5 # Leandro Toledo de Souza <devs@python-telegram-bot.org>
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Lesser Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU Lesser Public License for more details.
16 #
17 # You should have received a copy of the GNU Lesser Public License
18 # along with this program.  If not, see [http://www.gnu.org/licenses/].
19 import logging
20 
21 from telegram import Update
22 from future.utils import bytes_to_native_str
23 from threading import Lock
24 try:
25     import ujson as json
26 except ImportError:
27     import json
28 try:
29     import BaseHTTPServer
30 except ImportError:
31     import http.server as BaseHTTPServer
32 
33 logging.getLogger(__name__).addHandler(logging.NullHandler())
34 
35 
36 class _InvalidPost(Exception):
37 
38     def __init__(self, http_code):
39         self.http_code = http_code
40         super(_InvalidPost, self).__init__()
41 
42 
43 class WebhookServer(BaseHTTPServer.HTTPServer, object):
44 
45     def __init__(self, server_address, RequestHandlerClass, update_queue, webhook_path, bot):
46         super(WebhookServer, self).__init__(server_address, RequestHandlerClass)
47         self.logger = logging.getLogger(__name__)
48         self.update_queue = update_queue
49         self.webhook_path = webhook_path
50         self.bot = bot
51         self.is_running = False
52         self.server_lock = Lock()
53         self.shutdown_lock = Lock()
54 
55     def serve_forever(self, poll_interval=0.5):
56         with self.server_lock:
57             self.is_running = True
58             self.logger.debug('Webhook Server started.')
59             super(WebhookServer, self).serve_forever(poll_interval)
60             self.logger.debug('Webhook Server stopped.')
61 
62     def shutdown(self):
63         with self.shutdown_lock:
64             if not self.is_running:
65                 self.logger.warn('Webhook Server already stopped.')
66                 return
67             else:
68                 super(WebhookServer, self).shutdown()
69                 self.is_running = False
70 
71 
72 # WebhookHandler, process webhook calls
73 # Based on: https://github.com/eternnoir/pyTelegramBotAPI/blob/master/
74 # examples/webhook_examples/webhook_cpython_echo_bot.py
75 class WebhookHandler(BaseHTTPServer.BaseHTTPRequestHandler, object):
76     server_version = 'WebhookHandler/1.0'
77 
78     def __init__(self, request, client_address, server):
79         self.logger = logging.getLogger(__name__)
80         super(WebhookHandler, self).__init__(request, client_address, server)
81 
82     def do_HEAD(self):
83         self.send_response(200)
84         self.end_headers()
85 
86     def do_GET(self):
87         self.send_response(200)
88         self.end_headers()
89 
90     def do_POST(self):
91         self.logger.debug('Webhook triggered')
92         try:
93             self._validate_post()
94             clen = self._get_content_len()
95         except _InvalidPost as e:
96             self.send_error(e.http_code)
97             self.end_headers()
98         else:
99             buf = self.rfile.read(clen)
100             json_string = bytes_to_native_str(buf)
101 
102             self.send_response(200)
103             self.end_headers()
104 
105             self.logger.debug('Webhook received data: ' + json_string)
106 
107             update = Update.de_json(json.loads(json_string), self.server.bot)
108 
109             self.logger.debug('Received Update with ID %d on Webhook' % update.update_id)
110             self.server.update_queue.put(update)
111 
112     def _validate_post(self):
113         if not (self.path == self.server.webhook_path and 'content-type' in self.headers and
114                 self.headers['content-type'] == 'application/json'):
115             raise _InvalidPost(403)
116 
117     def _get_content_len(self):
118         clen = self.headers.get('content-length')
119         if clen is None:
120             raise _InvalidPost(411)
121         try:
122             clen = int(clen)
123         except ValueError:
124             raise _InvalidPost(403)
125         if clen < 0:
126             raise _InvalidPost(403)
127         return clen
128 
129     def log_message(self, format, *args):
130         """Log an arbitrary message.
131 
132         This is used by all other logging functions.
133 
134         It overrides ``BaseHTTPRequestHandler.log_message``, which logs to ``sys.stderr``.
135 
136         The first argument, FORMAT, is a format string for the message to be logged.  If the format
137         string contains any % escapes requiring parameters, they should be specified as subsequent
138         arguments (it's just like printf!).
139 
140         The client ip is prefixed to every message.
141 
142         """
143         self.logger.debug("%s - - %s" % (self.address_string(), format % args))
144
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/telegram/utils/webhookhandler.py b/telegram/utils/webhookhandler.py
--- a/telegram/utils/webhookhandler.py
+++ b/telegram/utils/webhookhandler.py
@@ -62,12 +62,17 @@
     def shutdown(self):
         with self.shutdown_lock:
             if not self.is_running:
-                self.logger.warn('Webhook Server already stopped.')
+                self.logger.warning('Webhook Server already stopped.')
                 return
             else:
                 super(WebhookServer, self).shutdown()
                 self.is_running = False
 
+    def handle_error(self, request, client_address):
+        """Handle an error gracefully."""
+        self.logger.debug('Exception happened during processing of request from %s',
+                          client_address, exc_info=True)
+
 
 # WebhookHandler, process webhook calls
 # Based on: https://github.com/eternnoir/pyTelegramBotAPI/blob/master/

{"golden_diff": "diff --git a/telegram/utils/webhookhandler.py b/telegram/utils/webhookhandler.py\n--- a/telegram/utils/webhookhandler.py\n+++ b/telegram/utils/webhookhandler.py\n@@ -62,12 +62,17 @@\n     def shutdown(self):\n         with self.shutdown_lock:\n             if not self.is_running:\n-                self.logger.warn('Webhook Server already stopped.')\n+                self.logger.warning('Webhook Server already stopped.')\n                 return\n             else:\n                 super(WebhookServer, self).shutdown()\n                 self.is_running = False\n \n+    def handle_error(self, request, client_address):\n+        \"\"\"Handle an error gracefully.\"\"\"\n+        self.logger.debug('Exception happened during processing of request from %s',\n+                          client_address, exc_info=True)\n+\n \n # WebhookHandler, process webhook calls\n # Based on: https://github.com/eternnoir/pyTelegramBotAPI/blob/master/\n", "issue": "Webhook Broken Pipe after connection reset, kills dispatcher\n### Steps to reproduce\r\n1.\r\nStandard Webhook with updater and dispatcher:\r\n```\r\nupdater = Updater(TOKEN) PORT = int(os.environ.get('PORT', '5000')) # add handlers \r\nupdater.start_webhook(listen=\"0.0.0.0\", port=PORT, url_path=TOKEN) \r\nupdater.bot.set_webhook(\"https://home.co.za/\" + TOKEN) \r\ndp = updater.dispatcher dp.add_error_handler(error) \r\nupdater.idle()\r\n```\r\n\r\n\r\n### Expected behaviour\r\nBot should run and remain responsive\r\n\r\n### Actual behaviour\r\nIt runs,  but after a few hours becomes unresponsive.\r\n\r\n### Configuration\r\n**Operating System:**\r\nLinux Cappucino 4.4.0-104-generic #127-Ubuntu SMP Mon Dec 11 12:16:50 UTC 2017 i686 athlon i686 GNU/Linux\r\n\r\n**Version of Python, python-telegram-bot & dependencies:**\r\n\r\n```\r\npython-telegram-bot 9.0.0\r\ncertifi 2017.11.05\r\nfuture 0.16.0\r\nPython 3.5.2 (default, Nov 23 2017, 16:37:01)  [GCC 5.4.0 20160609]\r\n```\r\n\r\n### Logs\r\n```\r\n2018-01-10 03:54:56,480 - telegram.ext.updater - ERROR - unhandled exception\r\nTraceback (most recent call last):\r\n  File \"/usr/lib/python3.5/socketserver.py\", line 313, in _handle_request_noblock\r\n    self.process_request(request, client_address)\r\n  File \"/usr/lib/python3.5/socketserver.py\", line 341, in process_request\r\n    self.finish_request(request, client_address)\r\n  File \"/usr/lib/python3.5/socketserver.py\", line 354, in finish_request\r\n    self.RequestHandlerClass(request, client_address, self)\r\n  File \"/usr/local/lib/python3.5/dist-packages/telegram/utils/webhookhandler.py\", line 62, in __init__\r\n    super(WebhookHandler, self).__init__(request, client_address, server)\r\n  File \"/usr/lib/python3.5/socketserver.py\", line 681, in __init__\r\n    self.handle()\r\n  File \"/usr/lib/python3.5/http/server.py\", line 422, in handle\r\n    self.handle_one_request()\r\n  File \"/usr/lib/python3.5/http/server.py\", line 390, in handle_one_request\r\n    self.raw_requestline = self.rfile.readline(65537)\r\n  File \"/usr/lib/python3.5/socket.py\", line 575, in readinto\r\n    return self._sock.recv_into(b)\r\nConnectionResetError: [Errno 104] Connection reset by peer\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n  File \"/usr/local/lib/python3.5/dist-packages/telegram/ext/updater.py\", line 149, in _thread_wrapper\r\n    target(*args, **kwargs)\r\n  File \"/usr/local/lib/python3.5/dist-packages/telegram/ext/updater.py\", line 353, in _start_webhook\r\n    self.httpd.serve_forever(poll_interval=1)\r\n  File \"/usr/local/lib/python3.5/dist-packages/telegram/utils/webhookhandler.py\", line 41, in serve_forever\r\n    super(WebhookServer, self).serve_forever(poll_interval)\r\n  File \"/usr/lib/python3.5/socketserver.py\", line 234, in serve_forever\r\n    self._handle_request_noblock()\r\n  File \"/usr/lib/python3.5/socketserver.py\", line 315, in _handle_request_noblock\r\n    self.handle_error(request, client_address)\r\n  File \"/usr/lib/python3.5/socketserver.py\", line 371, in handle_error\r\n    print('Exception happened during processing of request from', end=' ')\r\nBrokenPipeError: [Errno 32] Broken pipe\r\nException in thread updater:\r\nTraceback (most recent call last):\r\n  File \"/usr/lib/python3.5/socketserver.py\", line 313, in _handle_request_noblock\r\n    self.process_request(request, client_address)\r\n  File \"/usr/lib/python3.5/socketserver.py\", line 341, in process_request\r\n    self.finish_request(request, client_address)\r\n  File \"/usr/lib/python3.5/socketserver.py\", line 354, in finish_request\r\n    self.RequestHandlerClass(request, client_address, self)\r\n  File \"/usr/local/lib/python3.5/dist-packages/telegram/utils/webhookhandler.py\", line 62, in __init__\r\n    super(WebhookHandler, self).__init__(request, client_address, server)\r\n  File \"/usr/lib/python3.5/socketserver.py\", line 681, in __init__\r\n    self.handle()\r\n  File \"/usr/lib/python3.5/http/server.py\", line 422, in handle\r\n    self.handle_one_request()\r\n  File \"/usr/lib/python3.5/http/server.py\", line 390, in handle_one_request\r\n    self.raw_requestline = self.rfile.readline(65537)\r\n  File \"/usr/lib/python3.5/socket.py\", line 575, in readinto\r\n    return self._sock.recv_into(b)\r\nConnectionResetError: [Errno 104] Connection reset by peer\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n  File \"/usr/lib/python3.5/threading.py\", line 914, in _bootstrap_inner\r\n    self.run()\r\n  File \"/usr/lib/python3.5/threading.py\", line 862, in run\r\n    self._target(*self._args, **self._kwargs)\r\n  File \"/usr/local/lib/python3.5/dist-packages/telegram/ext/updater.py\", line 149, in _thread_wrapper\r\n    target(*args, **kwargs)\r\n  File \"/usr/local/lib/python3.5/dist-packages/telegram/ext/updater.py\", line 353, in _start_webhook\r\n    self.httpd.serve_forever(poll_interval=1)\r\n  File \"/usr/local/lib/python3.5/dist-packages/telegram/utils/webhookhandler.py\", line 41, in serve_forever\r\n    super(WebhookServer, self).serve_forever(poll_interval)\r\n  File \"/usr/lib/python3.5/socketserver.py\", line 234, in serve_forever\r\n    self._handle_request_noblock()\r\n  File \"/usr/lib/python3.5/socketserver.py\", line 315, in _handle_request_noblock\r\n    self.handle_error(request, client_address)\r\n  File \"/usr/lib/python3.5/socketserver.py\", line 371, in handle_error\r\n    print('Exception happened during processing of request from', end=' ')\r\nBrokenPipeError: [Errno 32] Broken pipe\r\n\r\n2018-01-10 03:54:56,601 - telegram.ext.dispatcher - CRITICAL - stopping due to exception in another thread\r\n2018-01-10 03:54:56,601 - telegram.ext.dispatcher - DEBUG - Dispatcher thread stopped\r\n2018-01-10 03:54:56,601 - telegram.ext.updater - DEBUG - dispatcher - ended\r\n```\r\n\r\n  \n", "before_files": [{"content": "#!/usr/bin/env python\n#\n# A library that provides a Python interface to the Telegram Bot API\n# Copyright (C) 2015-2018\n# Leandro Toledo de Souza <devs@python-telegram-bot.org>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU Lesser Public License for more details.\n#\n# You should have received a copy of the GNU Lesser Public License\n# along with this program.  If not, see [http://www.gnu.org/licenses/].\nimport logging\n\nfrom telegram import Update\nfrom future.utils import bytes_to_native_str\nfrom threading import Lock\ntry:\n    import ujson as json\nexcept ImportError:\n    import json\ntry:\n    import BaseHTTPServer\nexcept ImportError:\n    import http.server as BaseHTTPServer\n\nlogging.getLogger(__name__).addHandler(logging.NullHandler())\n\n\nclass _InvalidPost(Exception):\n\n    def __init__(self, http_code):\n        self.http_code = http_code\n        super(_InvalidPost, self).__init__()\n\n\nclass WebhookServer(BaseHTTPServer.HTTPServer, object):\n\n    def __init__(self, server_address, RequestHandlerClass, update_queue, webhook_path, bot):\n        super(WebhookServer, self).__init__(server_address, RequestHandlerClass)\n        self.logger = logging.getLogger(__name__)\n        self.update_queue = update_queue\n        self.webhook_path = webhook_path\n        self.bot = bot\n        self.is_running = False\n        self.server_lock = Lock()\n        self.shutdown_lock = Lock()\n\n    def serve_forever(self, poll_interval=0.5):\n        with self.server_lock:\n            self.is_running = True\n            self.logger.debug('Webhook Server started.')\n            super(WebhookServer, self).serve_forever(poll_interval)\n            self.logger.debug('Webhook Server stopped.')\n\n    def shutdown(self):\n        with self.shutdown_lock:\n            if not self.is_running:\n                self.logger.warn('Webhook Server already stopped.')\n                return\n            else:\n                super(WebhookServer, self).shutdown()\n                self.is_running = False\n\n\n# WebhookHandler, process webhook calls\n# Based on: https://github.com/eternnoir/pyTelegramBotAPI/blob/master/\n# examples/webhook_examples/webhook_cpython_echo_bot.py\nclass WebhookHandler(BaseHTTPServer.BaseHTTPRequestHandler, object):\n    server_version = 'WebhookHandler/1.0'\n\n    def __init__(self, request, client_address, server):\n        self.logger = logging.getLogger(__name__)\n        super(WebhookHandler, self).__init__(request, client_address, server)\n\n    def do_HEAD(self):\n        self.send_response(200)\n        self.end_headers()\n\n    def do_GET(self):\n        self.send_response(200)\n        self.end_headers()\n\n    def do_POST(self):\n        self.logger.debug('Webhook triggered')\n        try:\n            self._validate_post()\n            clen = self._get_content_len()\n        except _InvalidPost as e:\n            self.send_error(e.http_code)\n            self.end_headers()\n        else:\n            buf = self.rfile.read(clen)\n            json_string = bytes_to_native_str(buf)\n\n            self.send_response(200)\n            self.end_headers()\n\n            self.logger.debug('Webhook received data: ' + json_string)\n\n            update = Update.de_json(json.loads(json_string), self.server.bot)\n\n            self.logger.debug('Received Update with ID %d on Webhook' % update.update_id)\n            self.server.update_queue.put(update)\n\n    def _validate_post(self):\n        if not (self.path == self.server.webhook_path and 'content-type' in self.headers and\n                self.headers['content-type'] == 'application/json'):\n            raise _InvalidPost(403)\n\n    def _get_content_len(self):\n        clen = self.headers.get('content-length')\n        if clen is None:\n            raise _InvalidPost(411)\n        try:\n            clen = int(clen)\n        except ValueError:\n            raise _InvalidPost(403)\n        if clen < 0:\n            raise _InvalidPost(403)\n        return clen\n\n    def log_message(self, format, *args):\n        \"\"\"Log an arbitrary message.\n\n        This is used by all other logging functions.\n\n        It overrides ``BaseHTTPRequestHandler.log_message``, which logs to ``sys.stderr``.\n\n        The first argument, FORMAT, is a format string for the message to be logged.  If the format\n        string contains any % escapes requiring parameters, they should be specified as subsequent\n        arguments (it's just like printf!).\n\n        The client ip is prefixed to every message.\n\n        \"\"\"\n        self.logger.debug(\"%s - - %s\" % (self.address_string(), format % args))\n", "path": "telegram/utils/webhookhandler.py"}], "after_files": [{"content": "#!/usr/bin/env python\n#\n# A library that provides a Python interface to the Telegram Bot API\n# Copyright (C) 2015-2018\n# Leandro Toledo de Souza <devs@python-telegram-bot.org>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU Lesser Public License for more details.\n#\n# You should have received a copy of the GNU Lesser Public License\n# along with this program.  If not, see [http://www.gnu.org/licenses/].\nimport logging\n\nfrom telegram import Update\nfrom future.utils import bytes_to_native_str\nfrom threading import Lock\ntry:\n    import ujson as json\nexcept ImportError:\n    import json\ntry:\n    import BaseHTTPServer\nexcept ImportError:\n    import http.server as BaseHTTPServer\n\nlogging.getLogger(__name__).addHandler(logging.NullHandler())\n\n\nclass _InvalidPost(Exception):\n\n    def __init__(self, http_code):\n        self.http_code = http_code\n        super(_InvalidPost, self).__init__()\n\n\nclass WebhookServer(BaseHTTPServer.HTTPServer, object):\n\n    def __init__(self, server_address, RequestHandlerClass, update_queue, webhook_path, bot):\n        super(WebhookServer, self).__init__(server_address, RequestHandlerClass)\n        self.logger = logging.getLogger(__name__)\n        self.update_queue = update_queue\n        self.webhook_path = webhook_path\n        self.bot = bot\n        self.is_running = False\n        self.server_lock = Lock()\n        self.shutdown_lock = Lock()\n\n    def serve_forever(self, poll_interval=0.5):\n        with self.server_lock:\n            self.is_running = True\n            self.logger.debug('Webhook Server started.')\n            super(WebhookServer, self).serve_forever(poll_interval)\n            self.logger.debug('Webhook Server stopped.')\n\n    def shutdown(self):\n        with self.shutdown_lock:\n            if not self.is_running:\n                self.logger.warning('Webhook Server already stopped.')\n                return\n            else:\n                super(WebhookServer, self).shutdown()\n                self.is_running = False\n\n    def handle_error(self, request, client_address):\n        \"\"\"Handle an error gracefully.\"\"\"\n        self.logger.debug('Exception happened during processing of request from %s',\n                          client_address, exc_info=True)\n\n\n# WebhookHandler, process webhook calls\n# Based on: https://github.com/eternnoir/pyTelegramBotAPI/blob/master/\n# examples/webhook_examples/webhook_cpython_echo_bot.py\nclass WebhookHandler(BaseHTTPServer.BaseHTTPRequestHandler, object):\n    server_version = 'WebhookHandler/1.0'\n\n    def __init__(self, request, client_address, server):\n        self.logger = logging.getLogger(__name__)\n        super(WebhookHandler, self).__init__(request, client_address, server)\n\n    def do_HEAD(self):\n        self.send_response(200)\n        self.end_headers()\n\n    def do_GET(self):\n        self.send_response(200)\n        self.end_headers()\n\n    def do_POST(self):\n        self.logger.debug('Webhook triggered')\n        try:\n            self._validate_post()\n            clen = self._get_content_len()\n        except _InvalidPost as e:\n            self.send_error(e.http_code)\n            self.end_headers()\n        else:\n            buf = self.rfile.read(clen)\n            json_string = bytes_to_native_str(buf)\n\n            self.send_response(200)\n            self.end_headers()\n\n            self.logger.debug('Webhook received data: ' + json_string)\n\n            update = Update.de_json(json.loads(json_string), self.server.bot)\n\n            self.logger.debug('Received Update with ID %d on Webhook' % update.update_id)\n            self.server.update_queue.put(update)\n\n    def _validate_post(self):\n        if not (self.path == self.server.webhook_path and 'content-type' in self.headers and\n                self.headers['content-type'] == 'application/json'):\n            raise _InvalidPost(403)\n\n    def _get_content_len(self):\n        clen = self.headers.get('content-length')\n        if clen is None:\n            raise _InvalidPost(411)\n        try:\n            clen = int(clen)\n        except ValueError:\n            raise _InvalidPost(403)\n        if clen < 0:\n            raise _InvalidPost(403)\n        return clen\n\n    def log_message(self, format, *args):\n        \"\"\"Log an arbitrary message.\n\n        This is used by all other logging functions.\n\n        It overrides ``BaseHTTPRequestHandler.log_message``, which logs to ``sys.stderr``.\n\n        The first argument, FORMAT, is a format string for the message to be logged.  If the format\n        string contains any % escapes requiring parameters, they should be specified as subsequent\n        arguments (it's just like printf!).\n\n        The client ip is prefixed to every message.\n\n        \"\"\"\n        self.logger.debug(\"%s - - %s\" % (self.address_string(), format % args))\n", "path": "telegram/utils/webhookhandler.py"}]}