Throttle and debounce add-on for Pyrogram

Overview

pyrothrottle

Throttle and debounce add-on for Pyrogram

Quickstart

implementation on decorators

from pyrogram import Client, filters
from pyrogram.types import Message
from pyrothrottle.decorators import personal_throttle

client = Client('client')

@client.on_message(filters.incoming & filters.text)
@personal_throttle(3)
def handler(c: Client, m: Message):
    m.reply_text(f'Message processed. You can send next in {m.request_info.interval} seconds')

@handler.on_fallback
def fallback_handler(c: Client, m: Message):
    m.reply_text(f'Too fast. Write me after {m.request_info.cooldown} seconds')

client.run()

implementation on filters

from pyrogram import Client, filters
from pyrogram.types import Message
from pyrothrottle.filters import personal_throttle

client = Client('client')
throttle = personal_throttle(3)

@client.on_message(filters.incoming & filters.text & throttle.filter)
def handler(c: Client, m: Message):
    m.reply_text(f'Message processed. You can send next in {m.request_info.interval} seconds')

@throttle.on_fallback
def fallback_handler(c: Client, m: Message):
    m.reply_text(f'Too fast. Write me after {m.request_info.cooldown} seconds')

Docs

First of all, I have to mention that package has two implementations (each was shown in Quickstart section), so, each type of antispam system would have two equal named classes, one in .filters subpackage, and one in .decorators subpackage.
Also, for convinient usage, every class (when package is initialised) named in snake case (But in declaration they're named in camel case as it should be). So, in documentation they will be named as usual classes (for example, PersonalDebounce), but in code you have to use snake case names (for example, personal_debounce).

Meaningful part

In order to choice right system, you just need to undestand 5 terms.

  • Global
    Global in class name means that chosen system would have common for all users counter.
  • Personal
    Personal in class name means that chosen system would have separate counters for each user.
  • Throttle
    Throttle system counts interval between now and last processed (not last received) event. If this interval equals to or greater than given, event would be processed. Only interval is mandatory parameter.
  • Debounce
    Debounce system counts interval between now and last received event. If this interval equals to or greater than given, event would be processed. Only interval is mandatory parameter.
  • ReqrateController
    ReqrateController system counts, how many events were processed for last interval of time with length of provided interval (from some time point till now). If amount of processed events less than given allowed amount, event would be processed. Have 2 mandatory parameters: interval and amount.

In every class name first goes scope (Global or Personal), and then technique name (for example, PersonalDebounce).

Full API explanation

Classes

class pyrothrottle.decorators.GlobalThrottle

class pyrothrottle.filters.GlobalThrottle

Parameters:

  • interval(int|float) — Interval between successfully processed events. Since it's Throttle, system would pass any event, if interval between now and last processed (not last received) event would equals to or be greater than given interval. Because it's Global, system wound have common for all users counter.
  • falback (callable, optional) — Function that will be called if passed not enough time between events. Must accept two positional arguments (client, event).

class pyrothrottle.decorators.PersonalThrottle

class pyrothrottle.filters.PersonalThrottle

Parameters:

  • interval(int|float|callable) — Interval between successfully processed events. If callable passed, it must accept one positional argument (user_id) and return int or float. Since it's Throttle, system would pass an event, if interval between now and last processed (not last received) event would equals to or be greater than given interval. Because it's Personal, system wound have separate counters for each user.
  • falback (callable, optional) — Function that will be called if passed not enough time between events. Must accept two positional arguments (client, event).

class pyrothrottle.decorators.GlobalDebounce

class pyrothrottle.filters.GlobalDebounce

Parameters:

  • interval(int|float) — Interval between successfully processed events. Since it's Debounce, system would pass an event, if interval between now and last received event would equals to or be greater than given interval. Because it's Global, system wound have common for all users counter.
  • falback (callable, optional) — Function that will be called if passed not enough time between events. Must accept two positional arguments (client, event).

class pyrothrottle.decorators.PersonalDebounce

class pyrothrottle.filters.PersonalDebounce

Parameters:

  • interval(int|float|callable) — Interval between successfully processed events. If callable passed, it must accept one positional argument (user_id) and return int or float. Since it's Debounce, system would pass an event, if interval between now and last received event would equals to or be greater than given interval. Because it's Personal, system wound have separate counters for each user.
  • falback (callable, optional) — Function that will be called if passed not enough time between events. Must accept two positional arguments (client, event).

class pyrothrottle.decorators.GlobalReqrateController

class pyrothrottle.filters.GlobalReqrateController

Parameters:

  • interval(int|float) — Interval between successfully processed events. Since it's ReqrateController, system would pass an event, if amount of processed for last interval of time with length of provided interval events less that given allowed amount. Because it's Global, system wound have common for all users counter.
  • amount(int) — Allowed amount of processed requests during given interval.
  • falback (callable, optional) — Function that will be called if passed not enough time between events. Must accept two positional arguments (client, event).

class pyrothrottle.decorators.PersonalReqrateController

class pyrothrottle.filters.PersonalReqrateController

Parameters:

  • interval(int|float|callable) — Interval between successfully processed events. If callable passed, it must accept one positional argument (user_id) and return int or float. Since it's ReqrateController, system would pass an event, if amount of processed for last interval of time with length of provided interval events less that given allowed amount. Because it's Personal, system wound have separate counters for each user.
  • amount(int|callable) — Allowed amount of processed requests during given interval. If callable passed, it must accept one positional argument (user_id) and return int.
  • falback (callable, optional) — Function that will be called if passed not enough time between events. Must accept two positional arguments (client, event).

Decorators

Decorators intended to use in next way:

@client.on_event(...) # i.e. on_message, on_callback_query, etc.
@personal_throttle(3) # I'll use personal_throttle for examples
def handler(c: Client, e: Event):
    ...

If you want to add fallback handler to your system, you have to use .on_fallback (this method would contain in variable named as function that you registered as handler) as decorator. Fallback function must accept two positional arguments (same arguments as provided to main handler)

@handler.on_fallback
def fallback_handler(c: Client, e: Event):
    ...

Please note: Event objects (i.e. Message, CallbackQuery or InlineQuery) are patched, so they have have attribute request_info with usefull info (more on RequestInfo class later).

Filters

First of all, I have to mention that filter itself contained in filter attribute. Filters have 2 major ways to use: normal and anonymous.

Normal use

throttle = personal_throttle(3)

@client.on_event(different_filters & throttle.filter) # i.e. on_message, on_callback_query, etc.
def handler(c: Client, e: Event):
    ...

@throttle.on_fallback
def fallback_handler(c: Client, e: Event):
    ...

So, instead of decorators, when using filters (in normal way), .on_fallback must be called from antispam system instance

Anonymous use

@client.on_event(different_filters & personal_throttle(3).filter) # i.e. on_message, on_callback_query, etc.
def handler(c: Client, e: Event):
    ...

So, comparing ways to use, the advantage of normal use is that you can add fallback using .on_fallback, while main advantage of anonymous usage is absence of necessity to create named instance what gives us less code. You still can specify fallback when creating anomyous instance

def fallback_handler(c: Client, e: Event):
    ...

@client.on_event(different_filters & personal_throttle(3, fallback_handler).filter)
def handler(c: Client, e: Event):
    ...

Please note: Event objects (i.e. Message, CallbackQuery or InlineQuery) are patched, so they have attribute request_info with usefull info (more on RequestInfo class later).

RequestInfo

So, as it was mentioned before, all incoming events are patched, so they have attribute request_info with RequestInfo instance.

class pyrothrottle.RequestInfo

Attributes:

  • time(float) — timestamp of the moment when the event got into antispam system.
  • last_processed(float|list) — timestamp (or list of timestamps) of last processed event(s).
  • next_successful(float) — timestamp, when incoming event would be processed.
  • interval(int|float) — user-defined interval for antispam system.
  • amount(int, optional) — user-defined amount of events that should be processed during interval (only in ReqrateController)
  • cooldown(float) — amount of time till now to next successful processed event.
Телеграм бот решающий задания ЦДЗ, написанный на библиотеке libmesh.

MESHBot-Telegram Телеграм бот решающий задания ЦДЗ. Описание: Бот написан с использованием библиотеки libmesh. Для начала работы отправьте ему ссылку

2 Jun 19, 2022
A Telegram Most Powerful Media Info Bot.

Media Info Bot Support 🚑 Demo For The Bot -Test Our Bot By Clicking The Button Below Deploy To Heroku 🗳 Press the Deploy Button to Get Your Own Bot.

Anonymous 5 May 16, 2022
Pythonic wrapper for the Aladhan prayer times API.

aladhan.py is a pythonic wrapper for the Aladhan prayer times API. Installation Python 3.6 or higher is required. To Install aladhan.py with pip: pip

HETHAT 8 Aug 17, 2022
python script to buy token from pancakeswap

pancakeswapBot python script to buy token from pancakeswap Change your privatekey!!! on line 58 (signed_txn = web3.eth.account.sign_transaction(pancak

206 Dec 31, 2022
GitGram Bot. Bot Then Message You Your Repo Starts, Forks, And Many More

Yet Another GitAlertBot Inspired From Dev-v2's GitGram Run Bot: Local Host Git Clone Repo : For Telethon Version : git clone https://github.com/TeamAl

Alina RoBot 2 Nov 24, 2021
Trabalho N1 para a materia Tecnicas de Progamação da Anhembi Morumbi

Projeto da Anhembi Morumbi - Tecnicas de Programação. RPG de Console (CMD) Trabalho proposto pelo professor André Santana, na materia Tecnicas de Prog

Leonardo Silva M de Barros 3 Sep 12, 2021
A media upload to telegraph module

A media upload to telegraph module

Fayas Noushad 5 Dec 01, 2021
🚀 An asynchronous python API wrapper meant to replace discord.py - Snappy discord api wrapper written with aiohttp & websockets

Pincer An asynchronous python API wrapper meant to replace discord.py ❗ The package is currently within the planning phase 📌 Links |Join the discord

Pincer 125 Dec 26, 2022
A working bypass for discord gc spamming

IllusionGcSpammer A working bypass for discord gc spamming Installation Run pip install pip install DiscordGcSpammer then your good to go. Usage You c

6 Sep 30, 2022
Aqui está disponível GRATUITAMENTE, um bot de discord feito em python, saiba que, terá que criar seu bot como aplicação, e utilizar seu próprio token, e lembrando, é um bot básico, não se utiliza Cogs nem slash commands nele!

BotDiscordPython Aqui está disponível GRATUITAMENTE, um bot de discord feito em python, saiba que, terá que criar seu bot como aplicação, e utilizar s

Matheus Muguet 4 Feb 05, 2022
Backlog API v2 Client Library for Python

BacklogPy - Backlog API v2 Client Library for Python BacklogPy is Backlog API v2 Client Library for Python 2/3 Install You can install the client libr

Koudai Aono 7 Dec 16, 2022
High-Resolution Differential Z-Belt Mod for V0 (with optional Kirigami support)

V0-DBM This is a high-resolution differential pulley system belt mod for the Z-axis on Voron 0 with optional Kirigami Bed support. NOTE: Alpha version

Simon Küppers 11 Jan 07, 2023
A Discord bot that may save your day by predicting it.

Sage A Discord bot that may save your day by predicting it.

1 Nov 17, 2022
This script will detect changes in your session using Discords built in Gateway.

Detect Session Gateway This script will detect changes in your session using Discords built in Gateway. What does this log? Discord build version Oper

Omega 5 Dec 18, 2021
QR login for pyrogram client

Generate Pyrogram session via QRlogin

ポキ 18 Oct 21, 2022
Twitter bot to know the number of dislikes of a YouTube video

YT_dislikes is a twitter bot that allows you to know the number of dislikes (and likes) of a YouTube video. Now it is not possible to see the number o

1 Jan 08, 2022
It is a useful project for developers that includes useful tools for Instagram

InstagramIG It is a useful project for developers that includes useful tools for Instagram Installation : pip install InstagramIG Logan Usage from In

Sidra ELEzz 14 Mar 14, 2022
A Python wrapper around the Twitter API.

Python Twitter A Python wrapper around the Twitter API. By the Python-Twitter Developers Introduction This library provides a pure Python interface fo

Mike Taylor 3.4k Jan 01, 2023
This bot will send you an email or notify you via telegram & discord if dolar/lira parity breaks a record.

Dolar Rekor Kırdı Mı? This bot will send you an email or notify you via Telegram & Discord if Dolar/Lira parity breaks a record. Mailgun can be used a

Yiğit Göktuğ Budanur 2 Oct 14, 2021
Coronavirus whatsapp chatbot to give real time info on covid

Covy Developed a coronavirus whatsapp chatbot which gives case counts in a particular district, city, state or country. It also predicts future cases

Devinco (Rachit) 0 Oct 03, 2021