Skip to Content

Telegram API Rate Limit – Revealed

Telegram API Rate Limit – Revealed

Telegram introduced new bots within its API in 2015 to let developers create landing pages in their messenger, but these chatbots come with a rate limit for sending requests.

For your information, we’ll discuss this limit to help you understand how to send your requests or messages effectively to gain more users for your bot. 

What is the rate limit for Telegram bot?

Telegram API rate limit is the number of messages/requests you can send to different users or groups per second. While the exact limit may depend on the type of request, here’s the general list: 

  • Individual chats: The platform has set the limit of sending one message per second to a particular individual. 
  • Groups and Channels: You are not allowed to send more than 20 requests/messages per minute to the same group. Additionally, you can only create 50 groups or channels in a day. 
  • Overall: Telegram allows you to send only 30 messages per second to multiple users. For a single account, you cannot have more than 10 public usernames,

Telegram has set these limitations to avoid spam and keep the service running smoothly. Keep in mind that you’ll receive the 429 error code if you exceed it. This means that you will no longer be allowed to send any requests and may need to try again later. 

NOTE: If Telegram notices any spam activity, it may block your account forever.

How do I avoid the Telegram API rate limit?

Spread Notifications Over Longer Intervals

To send a large number of requests/messages to gain more users, try to spread them over longer intervals. This can be 8 – 12 hours and will help you not to exceed the API rate limit.

For instance, you can send 10 requests per second, then wait for 3 seconds before sending new ones, instead of 30 in 1 second.

NOTE: If you are sending messages to the same chat or individual, try limiting your rate to one message per second. This way, the platform won’t detect any spam activity on its server, and you won’t get the 429 error message, which indicates you’ve hit the API rate limit. 

Use Queue to Manage Requests

The next solution is to use a queue code in your bot to delay your requests. To do this, simply add the following code to your API:

lock_queue = Queue(1)
requests_queue = Queue(3)
def api_request(argument):
    if lock_queue.empty():
        try:
            requests_queue.put_nowait(time.time())
        except queue.Full:
            lock_queue.put(1)
            first_request_time = requests_queue.get()
            logger.info(‘First request time: ‘ + str(first_request_time))
            current_time = time.time()
            passed_time = current_time – first_request_time
            if passed_time >= 1:
                requests_queue.put_nowait(time.time())
                lock_queue.get()
            else:
                logger.info(passed_time)
                time.sleep(1 – passed_time)
                requests_queue.put_nowait(time.time())
                lock_queue.get()
    else:
        lock_queue.put(1)
        first_request_time = vk_requests_queue.get()
        logger.info(‘First request time: ‘ + str(first_request_time))
        current_time = time.time()
        passed_time = current_time – first_request_time
        if passed_time >= 1:
            requests_queue.put_nowait(time.time())
            lock_queue.get()
        else:
            logger.info(passed_time)
            time.sleep(1 – passed_time)
            requests_queue.put_nowait(time.time())
            lock_queue.get()
    result = make_api_request(argument) # requests are made too by external module.
    return result

If this code doesn’t help, you can try this one: 

import redis

r_db = redis.Redis(port=port, db=db)

def limit_request(request_to_make, limit=3, per=1, request_name=‘test’, **kwargs):
    over_limit_lua_ = ”’
    local key_name = KEYS[1]
    local limit = tonumber(ARGV[1])
    local duration = ARGV[2]

    local key = key_name .. ‘_num_of_requests
    local count = redis.call(‘INCR‘, key)
    if tonumber(count) > limit then
        local time_left = redis.call(‘PTTL‘, key)
        return time_left
    end
    redis.call(‘EXPIRE‘, key, duration)
    return -2
    ”’

    if not hasattr(r_db, ‘over_limit_lua’):
        r_db.over_limit_lua = r_db.register_script(over_limit_lua_)

    request_possibility = int(r_db.over_limit_lua(keys=request_name, args=[limit, per]))
    if request_possibility > 0:
        time.sleep(request_possibility / 1000.0)
        return limit_request(request_to_make, limit, per, request_name, **kwargs)
    else:
        request_result = request_to_make(**kwargs)
        return request_result

Once you add the code to your Telegram bot API, try sending the requests to users and see if you are still getting the error code.

Set Timeouts Before Sending Messages

You can also set a timeout or timer in your Telegram bot API to delay the messages and avoid exceeding the rate limit. For this, add the following code:

const delay = interval => new Promise(resolve => setTimeout(resolve, interval));
const sendMessage = async params => {
  await delay(1000);
 
  return axios(params);
};

Here is another way to do this: 

const RateLimiter = require(‘request-rate-limiter’);
const limiter = new RateLimiter(120); // 120 requests per minute
const sendMessage = params => limiter.request(params);
sendMessage(‘/sendMessage?text=hi’)
  .then(response => {
    console.log(‘hello!’, response);
  }).catch(err => {
    console.log(‘oh my’, err);
  });

Afterward, confirm if you still get the error 429 code while sending messages to users on Telegram.

Use Your Own Server API

If you are over the rate limit, use your own API server to access the features to send more messages or requests. 

For this, specify the option – – local in the bot API. This will enable features that are unavailable at https://api.telegram.org, such as: 

  • File download size limit: None
  • Files upload size limit: 2000MB
  • Webhook URL: HTTP URL
  • File Upload Path: Local and USL scheme
  • Webhook IP: Any local IP address
  • Webhook port: Any 
  • Max_webhook_connections: can be set up to 100000.

Moreover, you also get the absolute local path directly in the “file_path” field without the getFile request for downloading it.

Conclusion

In this comprehensive guide, we’ve discussed what the Telegram API rate limit is and how you can avoid getting its 429 error code. 

Hopefully, this article provided you with a clear understanding of the rate limit while sending requests/messages through your Telegram bots.

Author

  • Tauqeer Ahmed

    Tauqeer Ahmed is a technology expert with over 10 years of experience in the industry. He has a degree in Computer Science and specializes in network security and software troubleshooting. You can find out more about him at https://helpfixthat.com/tauqeer-ahmed/