Python telegram bot's `get_chat_members_count` & avoiding flood limits or how to use wrappers and decorators

Alex B

I'm checking a list of around 3000 telegram chats to get and retrieve the number of chat members in each chat using the get_chat_members_count method.

At some point I'm hitting a flood limit and getting temporarily banned by Telegram BOT.

Traceback (most recent call last):
  File "C:\Users\alexa\Desktop\ico_icobench_2.py", line 194, in <module>
    ico_tel_memb = bot.get_chat_members_count('@' + ico_tel_trim, timeout=60)
  File "C:\Python36\lib\site-packages\telegram\bot.py", line 60, in decorator
    result = func(self, *args, **kwargs)
  File "C:\Python36\lib\site-packages\telegram\bot.py", line 2006, in get_chat_members_count
    result = self._request.post(url, data, timeout=timeout)
  File "C:\Python36\lib\site-packages\telegram\utils\request.py", line 278, in post
    **urlopen_kwargs)
  File "C:\Python36\lib\site-packages\telegram\utils\request.py", line 208, in _request_wrapper
    message = self._parse(resp.data)
  File "C:\Python36\lib\site-packages\telegram\utils\request.py", line 168, in _parse
    raise RetryAfter(retry_after)
telegram.error.RetryAfter: Flood control exceeded. Retry in 85988 seconds

The python-telegram-bot wiki gives a detailed explanation and example on how to avoid flood limits here.

However, I'm struggling to implement their solution and I hope someone here has more knowledge of this than myself.

I have literally made a copy and paste of their example and can't get it to work no doubt because i'm new to python. I'm guessing I'm missing some definitions but I'm not sure which. Here is the code below and after that the first error I'm receiving. Obviously the TOKEN needs to be replaced with your token.

import telegram.bot
from telegram.ext import messagequeue as mq

class MQBot(telegram.bot.Bot):
    '''A subclass of Bot which delegates send method handling to MQ'''
    def __init__(self, *args, is_queued_def=True, mqueue=None, **kwargs):
        super(MQBot, self).__init__(*args, **kwargs)
        # below 2 attributes should be provided for decorator usage
        self._is_messages_queued_default = is_queued_def
        self._msg_queue = mqueue or mq.MessageQueue()

    def __del__(self):
        try:
            self._msg_queue.stop()
        except:
            pass
        super(MQBot, self).__del__()

    @mq.queuedmessage
    def send_message(self, *args, **kwargs):
        '''Wrapped method would accept new `queued` and `isgroup`
        OPTIONAL arguments'''
        return super(MQBot, self).send_message(*args, **kwargs)


if __name__ == '__main__':
    from telegram.ext import MessageHandler, Filters
    import os
    token = os.environ.get('TOKEN')
    # for test purposes limit global throughput to 3 messages per 3 seconds
    q = mq.MessageQueue(all_burst_limit=3, all_time_limit_ms=3000)
    testbot = MQBot(token, mqueue=q)
    upd = telegram.ext.updater.Updater(bot=testbot)

    def reply(bot, update):
        # tries to echo 10 msgs at once
        chatid = update.message.chat_id
        msgt = update.message.text
        print(msgt, chatid)
        for ix in range(10):
            bot.send_message(chat_id=chatid, text='%s) %s' % (ix + 1, msgt))

    hdl = MessageHandler(Filters.text, reply)
    upd.dispatcher.add_handler(hdl)
    upd.start_polling()

The first error I get is:

Traceback (most recent call last):
  File "C:\Users\alexa\Desktop\z test.py", line 34, in <module>
    testbot = MQBot(token, mqueue=q)
  File "C:\Users\alexa\Desktop\z test.py", line 9, in __init__
    super(MQBot, self).__init__(*args, **kwargs)
  File "C:\Python36\lib\site-packages\telegram\bot.py", line 108, in __init__
    self.token = self._validate_token(token)
  File "C:\Python36\lib\site-packages\telegram\bot.py", line 129, in _validate_token
    if any(x.isspace() for x in token):
TypeError: 'NoneType' object is not iterable

The second issue I have is how to use wrappers and decorators with get_chat_members_count.

The code I have added to the example is:

@mq.queuedmessage
def get_chat_members_count(self, *args, **kwargs):
    return super(MQBot, self).get_chat_members_count(*args, **kwargs)

But nothing happens and I don't get my count of chat members. I'm also not saying which chat I need to count so not surprising I'm getting nothing back but where am I supposed to put the telegram chat id?

Igor Persikov

You are getting this error because MQBot receives an empty token. For some reason, it does not raise a descriptive exception but instead crashes unexpectedly.

So why token is empty? It seems that you are using os.environ.get incorrectly. The os.environ part is a dictionary and its' method get allows one to access dict's contents safely. According to docs:

get(key[, default])

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

According to your question, in this part token = os.environ.get('TOKEN') you pass token itself as a key. Instead, you should've passed the name of the environmental variable which contains your token.

You can fix this either rewriting that part like this token = 'TOKEN' or by setting environmental variable correctly and accessing it from os.environ.get via correct name.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Python-telegram-bot bypass flood and 429 error using Scrapy

How to use Jobqueue in Python-telegram-bot

How to get the user's name in Telegram Bot?

How to use ForceReply in python-telegram-bot wrapper

how to use send_message() in python-telegram-bot

How to get photo description in python telegram bot api?

In python-telegram-bot how to get all participants of the group?

How to get return of InLineKeyboardButton with python-telegram-bot

How to get voice file in python-telegram-bot

How many people use my telegram bot?

How to use offset on Telegram bot API webHook

How to use URL with InlineKeyboardButton for Telegram Bot

How to pass keyboard's dynamic in telegram bot?

How to print user's message in telegram bot?

Telegram download media from chat bot in python

Python: Use of decorators v/s mixins?

how save photo in telegram python bot?

How to create unit test for a Python Telegram Bot

how to detect gif in telegram bot python

How to handle callbackquery in python telegram bot

How to create custom keyboard in telegram bot with python?

How to set webhook for telegram bot in python?

How to send a file with telegram bot in python

How to use withDefault wrappers?

How can I use the python-telegram-bot library to approve user join requests?

How should I use parse_mode='HTML' in telegram python bot?

Python telegram bot - can the bot send the first message in chat?

How to get Telegram channel users list with Telegram Bot API

How to get messages sent by members in a group using the Telegram Bot API

TOP Ranking

HotTag

Archive