2015-09-05 16:56:06 +02:00
|
|
|
#!/usr/bin/env python
|
|
|
|
#
|
|
|
|
# A library that provides a Python interface to the Telegram Bot API
|
2018-01-04 16:16:06 +01:00
|
|
|
# Copyright (C) 2015-2018
|
2016-01-05 14:12:03 +01:00
|
|
|
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
2015-09-05 16:56:06 +02:00
|
|
|
#
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU Lesser Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU Lesser Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU Lesser Public License
|
|
|
|
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
2017-09-01 08:43:08 +02:00
|
|
|
"""This module contains methods to make POST and GET requests."""
|
2017-01-06 22:48:34 +01:00
|
|
|
import os
|
|
|
|
import socket
|
2017-07-29 13:30:27 +02:00
|
|
|
import sys
|
2017-01-06 22:48:34 +01:00
|
|
|
import logging
|
2017-05-22 23:21:51 +02:00
|
|
|
import warnings
|
2015-09-05 16:56:06 +02:00
|
|
|
|
2016-08-26 09:40:46 +02:00
|
|
|
try:
|
|
|
|
import ujson as json
|
|
|
|
except ImportError:
|
|
|
|
import json
|
2015-09-05 16:56:06 +02:00
|
|
|
|
2016-05-29 23:49:29 +02:00
|
|
|
import certifi
|
2017-09-25 20:58:10 +02:00
|
|
|
|
2017-05-22 23:21:51 +02:00
|
|
|
try:
|
|
|
|
import telegram.vendor.ptb_urllib3.urllib3 as urllib3
|
|
|
|
import telegram.vendor.ptb_urllib3.urllib3.contrib.appengine as appengine
|
|
|
|
from telegram.vendor.ptb_urllib3.urllib3.connection import HTTPConnection
|
|
|
|
from telegram.vendor.ptb_urllib3.urllib3.util.timeout import Timeout
|
2017-08-11 23:58:41 +02:00
|
|
|
except ImportError: # pragma: no cover
|
2017-05-22 23:21:51 +02:00
|
|
|
warnings.warn("python-telegram-bot wasn't properly installed. Please refer to README.rst on "
|
|
|
|
"how to properly install.")
|
|
|
|
raise
|
2015-09-14 18:13:22 +02:00
|
|
|
|
2015-09-05 16:56:06 +02:00
|
|
|
from telegram import (InputFile, TelegramError)
|
2016-12-19 23:07:35 +01:00
|
|
|
from telegram.error import (Unauthorized, NetworkError, TimedOut, BadRequest, ChatMigrated,
|
|
|
|
RetryAfter, InvalidToken)
|
2015-09-05 16:56:06 +02:00
|
|
|
|
2016-06-19 23:40:34 +02:00
|
|
|
logging.getLogger('urllib3').setLevel(logging.WARNING)
|
|
|
|
|
2015-09-05 16:56:06 +02:00
|
|
|
|
2016-09-06 15:38:07 +02:00
|
|
|
class Request(object):
|
2015-09-05 16:56:06 +02:00
|
|
|
"""
|
2016-09-06 15:38:07 +02:00
|
|
|
Helper class for python-telegram-bot which provides methods to perform POST & GET towards
|
|
|
|
telegram servers.
|
2015-09-07 20:54:12 +02:00
|
|
|
|
2015-09-05 16:56:06 +02:00
|
|
|
Args:
|
2017-01-06 22:48:34 +01:00
|
|
|
con_pool_size (int): Number of connections to keep in the connection pool.
|
2016-09-06 15:38:07 +02:00
|
|
|
proxy_url (str): The URL to the proxy server. For example: `http://127.0.0.1:3128`.
|
|
|
|
urllib3_proxy_kwargs (dict): Arbitrary arguments passed as-is to `urllib3.ProxyManager`.
|
|
|
|
This value will be ignored if proxy_url is not set.
|
2017-01-06 22:48:34 +01:00
|
|
|
connect_timeout (int|float): The maximum amount of time (in seconds) to wait for a
|
|
|
|
connection attempt to a server to succeed. None will set an infinite timeout for
|
|
|
|
connection attempts. (default: 5.)
|
|
|
|
read_timeout (int|float): The maximum amount of time (in seconds) to wait between
|
|
|
|
consecutive read operations for a response from the server. None will set an infinite
|
|
|
|
timeout. This value is usually overridden by the various ``telegram.Bot`` methods.
|
|
|
|
(default: 5.)
|
2016-05-29 23:26:18 +02:00
|
|
|
|
2015-09-05 16:56:06 +02:00
|
|
|
"""
|
2015-09-07 20:54:12 +02:00
|
|
|
|
2017-01-06 22:48:34 +01:00
|
|
|
def __init__(self,
|
|
|
|
con_pool_size=1,
|
|
|
|
proxy_url=None,
|
|
|
|
urllib3_proxy_kwargs=None,
|
|
|
|
connect_timeout=5.,
|
|
|
|
read_timeout=5.):
|
2016-09-06 15:38:07 +02:00
|
|
|
if urllib3_proxy_kwargs is None:
|
|
|
|
urllib3_proxy_kwargs = dict()
|
|
|
|
|
2017-01-06 22:48:34 +01:00
|
|
|
self._connect_timeout = connect_timeout
|
|
|
|
|
2017-07-29 13:30:27 +02:00
|
|
|
sockopts = HTTPConnection.default_socket_options + [
|
|
|
|
(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)]
|
|
|
|
|
|
|
|
# TODO: Support other platforms like mac and windows.
|
|
|
|
if 'linux' in sys.platform:
|
|
|
|
sockopts.append((socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 120))
|
|
|
|
sockopts.append((socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 30))
|
|
|
|
sockopts.append((socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 8))
|
|
|
|
|
2017-08-12 15:45:38 +02:00
|
|
|
self._con_pool_size = con_pool_size
|
|
|
|
|
2016-09-06 15:38:07 +02:00
|
|
|
kwargs = dict(
|
|
|
|
maxsize=con_pool_size,
|
|
|
|
cert_reqs='CERT_REQUIRED',
|
|
|
|
ca_certs=certifi.where(),
|
2017-07-29 13:30:27 +02:00
|
|
|
socket_options=sockopts,
|
2017-01-06 22:48:34 +01:00
|
|
|
timeout=urllib3.Timeout(
|
2017-03-11 15:23:43 +01:00
|
|
|
connect=self._connect_timeout, read=read_timeout, total=None))
|
2016-09-06 15:38:07 +02:00
|
|
|
|
|
|
|
# Set a proxy according to the following order:
|
|
|
|
# * proxy defined in proxy_url (+ urllib3_proxy_kwargs)
|
|
|
|
# * proxy set in `HTTPS_PROXY` env. var.
|
|
|
|
# * proxy set in `https_proxy` env. var.
|
|
|
|
# * None (if no proxy is configured)
|
|
|
|
|
|
|
|
if not proxy_url:
|
|
|
|
proxy_url = os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy')
|
|
|
|
|
|
|
|
if not proxy_url:
|
2017-05-22 23:21:51 +02:00
|
|
|
if appengine.is_appengine_sandbox():
|
2017-04-27 10:59:35 +02:00
|
|
|
# Use URLFetch service if running in App Engine
|
2017-05-22 23:21:51 +02:00
|
|
|
mgr = appengine.AppEngineManager()
|
2017-04-27 10:59:35 +02:00
|
|
|
else:
|
|
|
|
mgr = urllib3.PoolManager(**kwargs)
|
2016-09-06 15:38:07 +02:00
|
|
|
else:
|
|
|
|
kwargs.update(urllib3_proxy_kwargs)
|
2017-02-25 19:47:56 +01:00
|
|
|
if proxy_url.startswith('socks'):
|
2017-04-29 13:42:36 +02:00
|
|
|
try:
|
2017-05-22 23:21:51 +02:00
|
|
|
from telegram.vendor.ptb_urllib3.urllib3.contrib.socks import SOCKSProxyManager
|
2017-04-29 13:42:36 +02:00
|
|
|
except ImportError:
|
2017-02-25 19:47:56 +01:00
|
|
|
raise RuntimeError('PySocks is missing')
|
|
|
|
mgr = SOCKSProxyManager(proxy_url, **kwargs)
|
|
|
|
else:
|
|
|
|
mgr = urllib3.proxy_from_url(proxy_url, **kwargs)
|
|
|
|
if mgr.proxy.auth:
|
|
|
|
# TODO: what about other auth types?
|
|
|
|
auth_hdrs = urllib3.make_headers(proxy_basic_auth=mgr.proxy.auth)
|
|
|
|
mgr.proxy_headers.update(auth_hdrs)
|
2016-09-06 15:38:07 +02:00
|
|
|
|
|
|
|
self._con_pool = mgr
|
|
|
|
|
2017-08-12 15:45:38 +02:00
|
|
|
@property
|
|
|
|
def con_pool_size(self):
|
|
|
|
"""The size of the connection pool used."""
|
|
|
|
return self._con_pool_size
|
|
|
|
|
2016-09-06 15:38:07 +02:00
|
|
|
def stop(self):
|
|
|
|
self._con_pool.clear()
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _parse(json_data):
|
|
|
|
"""Try and parse the JSON returned from Telegram.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
dict: A JSON parsed as Python dict with results - on error this dict will be empty.
|
|
|
|
|
|
|
|
"""
|
2018-04-17 06:40:02 +02:00
|
|
|
|
2016-09-06 15:38:07 +02:00
|
|
|
try:
|
2018-04-17 06:40:02 +02:00
|
|
|
decoded_s = json_data.decode('utf-8')
|
2016-09-06 15:38:07 +02:00
|
|
|
data = json.loads(decoded_s)
|
2018-04-17 06:40:02 +02:00
|
|
|
except UnicodeDecodeError:
|
|
|
|
logging.getLogger(__name__).debug(
|
|
|
|
'Logging raw invalid UTF-8 response:\n%r', json_data)
|
|
|
|
raise TelegramError('Server response could not be decoded using UTF-8')
|
2016-09-06 15:38:07 +02:00
|
|
|
except ValueError:
|
|
|
|
raise TelegramError('Invalid server response')
|
|
|
|
|
2017-09-25 20:58:10 +02:00
|
|
|
if not data.get('ok'): # pragma: no cover
|
2016-09-06 15:38:07 +02:00
|
|
|
description = data.get('description')
|
|
|
|
parameters = data.get('parameters')
|
|
|
|
if parameters:
|
|
|
|
migrate_to_chat_id = parameters.get('migrate_to_chat_id')
|
|
|
|
if migrate_to_chat_id:
|
|
|
|
raise ChatMigrated(migrate_to_chat_id)
|
2016-10-04 00:27:45 +02:00
|
|
|
retry_after = parameters.get('retry_after')
|
|
|
|
if retry_after:
|
|
|
|
raise RetryAfter(retry_after)
|
2016-09-06 15:38:07 +02:00
|
|
|
if description:
|
|
|
|
return description
|
|
|
|
|
|
|
|
return data['result']
|
|
|
|
|
|
|
|
def _request_wrapper(self, *args, **kwargs):
|
|
|
|
"""Wraps urllib3 request for handling known exceptions.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
args: unnamed arguments, passed to urllib3 request.
|
|
|
|
kwargs: keyword arguments, passed tp urllib3 request.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
str: A non-parsed JSON text.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
TelegramError
|
|
|
|
|
|
|
|
"""
|
2017-01-03 22:41:52 +01:00
|
|
|
# Make sure to hint Telegram servers that we reuse connections by sending
|
|
|
|
# "Connection: keep-alive" in the HTTP headers.
|
|
|
|
if 'headers' not in kwargs:
|
|
|
|
kwargs['headers'] = {}
|
|
|
|
kwargs['headers']['connection'] = 'keep-alive'
|
|
|
|
|
2016-09-06 15:38:07 +02:00
|
|
|
try:
|
|
|
|
resp = self._con_pool.request(*args, **kwargs)
|
|
|
|
except urllib3.exceptions.TimeoutError:
|
|
|
|
raise TimedOut()
|
|
|
|
except urllib3.exceptions.HTTPError as error:
|
|
|
|
# HTTPError must come last as its the base urllib3 exception class
|
|
|
|
# TODO: do something smart here; for now just raise NetworkError
|
|
|
|
raise NetworkError('urllib3 HTTPError {0}'.format(error))
|
|
|
|
|
|
|
|
if 200 <= resp.status <= 299:
|
|
|
|
# 200-299 range are HTTP success statuses
|
|
|
|
return resp.data
|
|
|
|
|
|
|
|
try:
|
|
|
|
message = self._parse(resp.data)
|
|
|
|
except ValueError:
|
2017-06-21 22:34:35 +02:00
|
|
|
message = 'Unknown HTTPError'
|
2016-09-06 15:38:07 +02:00
|
|
|
|
|
|
|
if resp.status in (401, 403):
|
2017-05-12 17:38:36 +02:00
|
|
|
raise Unauthorized(message)
|
2016-09-06 15:38:07 +02:00
|
|
|
elif resp.status == 400:
|
2017-01-07 22:09:06 +01:00
|
|
|
raise BadRequest(message)
|
2016-11-09 14:36:42 +01:00
|
|
|
elif resp.status == 404:
|
|
|
|
raise InvalidToken()
|
2017-06-15 17:44:39 +02:00
|
|
|
elif resp.status == 413:
|
2017-06-21 22:34:35 +02:00
|
|
|
raise NetworkError('File too large. Check telegram api limits '
|
|
|
|
'https://core.telegram.org/bots/api#senddocument')
|
|
|
|
|
2016-09-06 15:38:07 +02:00
|
|
|
elif resp.status == 502:
|
|
|
|
raise NetworkError('Bad Gateway')
|
|
|
|
else:
|
|
|
|
raise NetworkError('{0} ({1})'.format(message, resp.status))
|
|
|
|
|
2017-01-06 22:48:34 +01:00
|
|
|
def get(self, url, timeout=None):
|
2016-09-06 15:38:07 +02:00
|
|
|
"""Request an URL.
|
2017-01-06 22:48:34 +01:00
|
|
|
|
2016-09-06 15:38:07 +02:00
|
|
|
Args:
|
2017-08-02 04:56:07 +02:00
|
|
|
url (:obj:`str`): The web location we want to retrieve.
|
|
|
|
timeout (:obj:`int` | :obj:`float`): If this value is specified, use it as the read
|
|
|
|
timeout from the server (instead of the one specified during creation of the
|
|
|
|
connection pool).
|
2016-09-06 15:38:07 +02:00
|
|
|
|
|
|
|
Returns:
|
|
|
|
A JSON object.
|
|
|
|
|
|
|
|
"""
|
2017-01-06 22:48:34 +01:00
|
|
|
urlopen_kwargs = {}
|
|
|
|
|
|
|
|
if timeout is not None:
|
|
|
|
urlopen_kwargs['timeout'] = Timeout(read=timeout, connect=self._connect_timeout)
|
|
|
|
|
|
|
|
result = self._request_wrapper('GET', url, **urlopen_kwargs)
|
2016-09-06 15:38:07 +02:00
|
|
|
return self._parse(result)
|
|
|
|
|
|
|
|
def post(self, url, data, timeout=None):
|
|
|
|
"""Request an URL.
|
2018-03-05 12:17:56 +01:00
|
|
|
|
2016-09-06 15:38:07 +02:00
|
|
|
Args:
|
2017-08-02 04:56:07 +02:00
|
|
|
url (:obj:`str`): The web location we want to retrieve.
|
2017-06-18 12:14:24 +02:00
|
|
|
data (dict[str, str|int]): A dict of key/value pairs. Note: On py2.7 value is unicode.
|
2017-08-02 04:56:07 +02:00
|
|
|
timeout (:obj:`int` | :obj:`float`): If this value is specified, use it as the read
|
|
|
|
timeout from the server (instead of the one specified during creation of the
|
|
|
|
connection pool).
|
2016-09-06 15:38:07 +02:00
|
|
|
|
|
|
|
Returns:
|
|
|
|
A JSON object.
|
|
|
|
|
|
|
|
"""
|
|
|
|
urlopen_kwargs = {}
|
|
|
|
|
|
|
|
if timeout is not None:
|
2017-01-06 22:48:34 +01:00
|
|
|
urlopen_kwargs['timeout'] = Timeout(read=timeout, connect=self._connect_timeout)
|
2016-09-06 15:38:07 +02:00
|
|
|
|
|
|
|
if InputFile.is_inputfile(data):
|
|
|
|
data = InputFile(data)
|
2017-01-03 22:41:52 +01:00
|
|
|
result = self._request_wrapper(
|
|
|
|
'POST', url, body=data.to_form(), headers=data.headers, **urlopen_kwargs)
|
2016-09-06 15:38:07 +02:00
|
|
|
else:
|
|
|
|
data = json.dumps(data)
|
|
|
|
result = self._request_wrapper(
|
|
|
|
'POST',
|
|
|
|
url,
|
|
|
|
body=data.encode(),
|
|
|
|
headers={'Content-Type': 'application/json'},
|
|
|
|
**urlopen_kwargs)
|
|
|
|
|
|
|
|
return self._parse(result)
|
|
|
|
|
2017-01-06 22:48:34 +01:00
|
|
|
def retrieve(self, url, timeout=None):
|
2016-12-18 03:05:00 +01:00
|
|
|
"""Retrieve the contents of a file by its URL.
|
2017-01-06 22:48:34 +01:00
|
|
|
|
2016-12-18 03:05:00 +01:00
|
|
|
Args:
|
2017-08-02 04:56:07 +02:00
|
|
|
url (:obj:`str`): The web location we want to retrieve.
|
|
|
|
timeout (:obj:`int` | :obj:`float`): If this value is specified, use it as the read
|
|
|
|
timeout from the server (instead of the one specified during creation of the
|
|
|
|
connection pool).
|
2017-01-06 22:48:34 +01:00
|
|
|
|
2016-12-18 03:05:00 +01:00
|
|
|
"""
|
2017-01-06 22:48:34 +01:00
|
|
|
urlopen_kwargs = {}
|
|
|
|
if timeout is not None:
|
|
|
|
urlopen_kwargs['timeout'] = Timeout(read=timeout, connect=self._connect_timeout)
|
|
|
|
|
|
|
|
return self._request_wrapper('GET', url, **urlopen_kwargs)
|
2016-12-18 03:05:00 +01:00
|
|
|
|
2017-01-06 22:48:34 +01:00
|
|
|
def download(self, url, filename, timeout=None):
|
2016-09-06 15:38:07 +02:00
|
|
|
"""Download a file by its URL.
|
2018-03-05 12:17:56 +01:00
|
|
|
|
2016-09-06 15:38:07 +02:00
|
|
|
Args:
|
2017-01-06 22:48:34 +01:00
|
|
|
url (str): The web location we want to retrieve.
|
2017-08-02 04:56:07 +02:00
|
|
|
timeout (:obj:`int` | :obj:`float`): If this value is specified, use it as the read
|
|
|
|
timeout from the server (instead of the one specified during creation of the
|
|
|
|
connection pool).
|
2016-09-06 15:38:07 +02:00
|
|
|
|
|
|
|
filename:
|
|
|
|
The filename within the path to download the file.
|
|
|
|
|
|
|
|
"""
|
2017-01-06 22:48:34 +01:00
|
|
|
buf = self.retrieve(url, timeout=timeout)
|
2016-09-06 15:38:07 +02:00
|
|
|
with open(filename, 'wb') as fobj:
|
|
|
|
fobj.write(buf)
|