Repository: python-telegram-bot/python-telegram-bot

Issue:
urllib + MessageQueue = Connection pool is full warning
### Steps to reproduce
1. Create bot with implementation of [MessageQueue](https://github.com/python-telegram-bot/python-telegram-bot/wiki/Avoiding-spam-limits) (and add logging)
2. Add simply handler for him
3. Send something to him

Code example:
```python
import logging
import telegram.bot
from telegram.ext import messagequeue as mqueue
from telegram.ext import Updater, RegexHandler

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)
logger = logging.getLogger(__name__)

TOKEN = ''


class MQBot(telegram.bot.Bot):
    def __init__(self, *args, is_queued_def=True, msg_queue=None, **kwargs):
        super().__init__(*args, **kwargs)
        # For decorator usage
        self._is_messages_queued_default = is_queued_def
        self._msg_queue = msg_queue or mqueue.MessageQueue()

    @mqueue.queuedmessage
    def send_message(self, *args, **kwargs):
        super().send_message(*args, **kwargs)


def start(bot, update):
    update.message.reply_text('start')

if __name__ == '__main__':
    msg_queue = mqueue.MessageQueue(all_burst_limit=29, all_time_limit_ms=1017)
    bot = MQBot(TOKEN, msg_queue=msg_queue)
    updater = Updater(bot=bot)
    dispatcher = updater.dispatcher

    dispatcher.add_handler(RegexHandler('\w*', start))

    updater.start_polling()
    updater.idle()
```

### Expected behaviour
No errors/warnings should appears.

### Actual behaviour
In logs appears warning:
`telegram.vendor.ptb_urllib3.urllib3.connectionpool - WARNING - Connection pool is full, discarding connection: api.telegram.org`

Mb the problem is because of [this](https://github.com/python-telegram-bot/urllib3/blob/06d04e451f6beb5562057bf793218c4e363d8bc0/urllib3/connectionpool.py#L163) (`maxsize=1`)

### Configuration
**Version of Python, python-telegram-bot & dependencies:**

```
python-telegram-bot 7.0.1
certifi 2017.07.27.1
future 0.16.0
Python 3.5.2 (default, Nov 17 2016, 17:05:23)  [GCC 5.4.0 20160609]
```



Discussion:
**bad bad bad** The problem is not with MQ. I've rechecked everything on reduced to min example, and almost always the warning still arises.
Running `Python 3.6.2 (default, Jul 20 2017, 03:52:27) [GCC 7.1.1 20170630] on linux` (Manjaro)

```
import os
import logging
import telegram.bot
from telegram.ext import Updater, RegexHandler

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)
logger = logging.getLogger(__name__)

TOKEN = os.environ.get('TOKEN') or open('token.txt').read().strip()

def start(bot, update):
    for ix in range(10):
        update.message.reply_text('start')

if __name__ == '__main__':
    bot = telegram.bot.Bot(TOKEN)
    updater = Updater(bot=bot)
    dispatcher = updater.dispatcher

    dispatcher.add_handler(RegexHandler('\w*', start))

    updater.start_polling()
```
This issue indeed happens due to too small `maxsize` parameter as @korchky suggested. And as @thodnev pointed out, it indeed doesn't have anything to do with messagequeue. Instead it stems from the fact that you are creating bot instances for use with updater instead of just passing a token. When a token is passed, updater will automatically create a connectionpool with the correct size (which is how many threads are gonna be using it). However since you're manually creating the bot you'll need to do this yourselves. 
Therefore your
``` python
bot = MQBot(TOKEN, msg_queue=msg_queue)
updater = Updater(bot=bot)
```
lines should be changed to something akin to
``` python
request = Request(con_pool_size=8)
bot = MQBot(TOKEN, request=request, msg_queue=msg_queue)
updater = Updater(bot=bot)
```
The reason for a size of 8 is that updater calculates the size `workers + 4` (see more [here](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/ext/updater.py#L101)) and workers is 4 by default. If using another count of workers then you'll need a connection pool that's larger or smaller.

I will keep this issue open for now, since we're discussing weather we should make this easier and/or emit a warning when the connection pool is too small.
In fact, I was too blind to didn't notice text about this behavior in docs. But I think that will be cool to check request's `con_pool_size` when you pass bot instance to updater.

Resolving patch:
diff --git a/telegram/ext/updater.py b/telegram/ext/updater.py
--- a/telegram/ext/updater.py
+++ b/telegram/ext/updater.py
@@ -95,8 +95,16 @@ def __init__(self,
         if (token is not None) and (bot is not None):
             raise ValueError('`token` and `bot` are mutually exclusive')
 
+        self.logger = logging.getLogger(__name__)
+
+        con_pool_size = workers + 4
+
         if bot is not None:
             self.bot = bot
+            if bot.request.con_pool_size < con_pool_size:
+                self.logger.warning(
+                    'Connection pool of Request object is smaller than optimal value (%s)',
+                    con_pool_size)
         else:
             # we need a connection pool the size of:
             # * for each of the workers
@@ -107,7 +115,7 @@ def __init__(self,
             if request_kwargs is None:
                 request_kwargs = {}
             if 'con_pool_size' not in request_kwargs:
-                request_kwargs['con_pool_size'] = workers + 4
+                request_kwargs['con_pool_size'] = con_pool_size
             self._request = Request(**request_kwargs)
             self.bot = Bot(token, base_url, request=self._request)
         self.user_sig_handler = user_sig_handler
@@ -121,7 +129,6 @@ def __init__(self,
             workers=workers,
             exception_event=self.__exception_event)
         self.last_update_id = 0
-        self.logger = logging.getLogger(__name__)
         self.running = False
         self.is_idle = False
         self.httpd = None
diff --git a/telegram/utils/request.py b/telegram/utils/request.py
--- a/telegram/utils/request.py
+++ b/telegram/utils/request.py
@@ -86,6 +86,8 @@ def __init__(self,
             sockopts.append((socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 30))
             sockopts.append((socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 8))
 
+        self._con_pool_size = con_pool_size
+
         kwargs = dict(
             maxsize=con_pool_size,
             cert_reqs='CERT_REQUIRED',
@@ -126,6 +128,11 @@ def __init__(self,
 
         self._con_pool = mgr
 
+    @property
+    def con_pool_size(self):
+        """The size of the connection pool used."""
+        return self._con_pool_size
+
     def stop(self):
         self._con_pool.clear()
 


Test patch: