telepulse 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- telepulse-0.1.0/LICENSE +21 -0
- telepulse-0.1.0/PKG-INFO +85 -0
- telepulse-0.1.0/README.md +60 -0
- telepulse-0.1.0/pyproject.toml +35 -0
- telepulse-0.1.0/setup.cfg +4 -0
- telepulse-0.1.0/src/telepulse/__init__.py +14 -0
- telepulse-0.1.0/src/telepulse/decorators.py +69 -0
- telepulse-0.1.0/src/telepulse/limiter.py +106 -0
- telepulse-0.1.0/src/telepulse/timers.py +93 -0
- telepulse-0.1.0/src/telepulse.egg-info/PKG-INFO +85 -0
- telepulse-0.1.0/src/telepulse.egg-info/SOURCES.txt +12 -0
- telepulse-0.1.0/src/telepulse.egg-info/dependency_links.txt +1 -0
- telepulse-0.1.0/src/telepulse.egg-info/top_level.txt +1 -0
- telepulse-0.1.0/tests/test_telepulse.py +80 -0
telepulse-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 aivideosuz46-creator
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
telepulse-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: telepulse
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Zero-dependency rate-limiting, anti-flood, and generation-guarded scoped timer toolkit for Python Telegram bots.
|
|
5
|
+
Author: aivideosuz46-creator
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/aivideosuz46-creator/telepulse
|
|
8
|
+
Project-URL: Repository, https://github.com/aivideosuz46-creator/telepulse
|
|
9
|
+
Project-URL: Issues, https://github.com/aivideosuz46-creator/telepulse/issues
|
|
10
|
+
Keywords: telegram,bot,aiogram,pytelegrambotapi,rate-limit,anti-flood,timer,asyncio
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: Communications :: Chat
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# TelePulse
|
|
27
|
+
|
|
28
|
+
**TelePulse** is a lightweight, zero-dependency Python toolkit providing memory-bounded **anti-flood rate limiting** and **generation-guarded scoped async timers** for Telegram bots (`aiogram`, `pyTelegramBotAPI`, `python-telegram-bot`, or custom webhook handlers).
|
|
29
|
+
|
|
30
|
+
## Why TelePulse?
|
|
31
|
+
|
|
32
|
+
Group and game Telegram bots frequently suffer from two reliability bottlenecks:
|
|
33
|
+
1. **Button & Command Spam:** Users rapidly tapping inline buttons or spamming commands, triggering Telegram `429 Too Many Requests` errors or duplicate database writes.
|
|
34
|
+
2. **Stale / Overlapping Timers:** Round or session timers that fire *after* a game has already restarted or ended, causing ghost notifications and race conditions.
|
|
35
|
+
|
|
36
|
+
TelePulse solves both with pure Python standard library primitives (`time.monotonic`, `collections.deque`, `asyncio`).
|
|
37
|
+
|
|
38
|
+
## Installation
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install telepulse
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Quick Start
|
|
45
|
+
|
|
46
|
+
### 1. Anti-Flood Decorator (`@throttle`)
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
from aiogram import Router, types
|
|
50
|
+
from telepulse import LimitResult, throttle
|
|
51
|
+
|
|
52
|
+
router = Router()
|
|
53
|
+
|
|
54
|
+
async def on_spam(message: types.Message, result: LimitResult) -> None:
|
|
55
|
+
await message.answer(f"Too fast! Try again in {result.retry_after}s.")
|
|
56
|
+
|
|
57
|
+
@router.message()
|
|
58
|
+
@throttle(rate=3, per=5.0, block_for=10.0, on_limited=on_spam)
|
|
59
|
+
async def handle_message(message: types.Message) -> None:
|
|
60
|
+
await message.answer("Action accepted!")
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### 2. Generation-Guarded Scoped Timers (`ScopedTimerManager`)
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
from telepulse import ScopedTimerManager
|
|
67
|
+
|
|
68
|
+
timers = ScopedTimerManager()
|
|
69
|
+
|
|
70
|
+
async def finish_round(chat_id: int, round_id: int) -> None:
|
|
71
|
+
print(f"Chat {chat_id}: Round {round_id} ended!")
|
|
72
|
+
|
|
73
|
+
timers.schedule("chat:-100123:round", 30.0, finish_round, -100123, 1)
|
|
74
|
+
timers.schedule("chat:-100123:round", 30.0, finish_round, -100123, 2)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Running Tests
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
PYTHONPATH=src python -m unittest discover -s tests -v
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## License
|
|
84
|
+
|
|
85
|
+
MIT License — see [LICENSE](LICENSE) for details.
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# TelePulse
|
|
2
|
+
|
|
3
|
+
**TelePulse** is a lightweight, zero-dependency Python toolkit providing memory-bounded **anti-flood rate limiting** and **generation-guarded scoped async timers** for Telegram bots (`aiogram`, `pyTelegramBotAPI`, `python-telegram-bot`, or custom webhook handlers).
|
|
4
|
+
|
|
5
|
+
## Why TelePulse?
|
|
6
|
+
|
|
7
|
+
Group and game Telegram bots frequently suffer from two reliability bottlenecks:
|
|
8
|
+
1. **Button & Command Spam:** Users rapidly tapping inline buttons or spamming commands, triggering Telegram `429 Too Many Requests` errors or duplicate database writes.
|
|
9
|
+
2. **Stale / Overlapping Timers:** Round or session timers that fire *after* a game has already restarted or ended, causing ghost notifications and race conditions.
|
|
10
|
+
|
|
11
|
+
TelePulse solves both with pure Python standard library primitives (`time.monotonic`, `collections.deque`, `asyncio`).
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pip install telepulse
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Quick Start
|
|
20
|
+
|
|
21
|
+
### 1. Anti-Flood Decorator (`@throttle`)
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from aiogram import Router, types
|
|
25
|
+
from telepulse import LimitResult, throttle
|
|
26
|
+
|
|
27
|
+
router = Router()
|
|
28
|
+
|
|
29
|
+
async def on_spam(message: types.Message, result: LimitResult) -> None:
|
|
30
|
+
await message.answer(f"Too fast! Try again in {result.retry_after}s.")
|
|
31
|
+
|
|
32
|
+
@router.message()
|
|
33
|
+
@throttle(rate=3, per=5.0, block_for=10.0, on_limited=on_spam)
|
|
34
|
+
async def handle_message(message: types.Message) -> None:
|
|
35
|
+
await message.answer("Action accepted!")
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### 2. Generation-Guarded Scoped Timers (`ScopedTimerManager`)
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
from telepulse import ScopedTimerManager
|
|
42
|
+
|
|
43
|
+
timers = ScopedTimerManager()
|
|
44
|
+
|
|
45
|
+
async def finish_round(chat_id: int, round_id: int) -> None:
|
|
46
|
+
print(f"Chat {chat_id}: Round {round_id} ended!")
|
|
47
|
+
|
|
48
|
+
timers.schedule("chat:-100123:round", 30.0, finish_round, -100123, 1)
|
|
49
|
+
timers.schedule("chat:-100123:round", 30.0, finish_round, -100123, 2)
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Running Tests
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
PYTHONPATH=src python -m unittest discover -s tests -v
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## License
|
|
59
|
+
|
|
60
|
+
MIT License — see [LICENSE](LICENSE) for details.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "telepulse"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Zero-dependency rate-limiting, anti-flood, and generation-guarded scoped timer toolkit for Python Telegram bots."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "aivideosuz46-creator" }
|
|
14
|
+
]
|
|
15
|
+
keywords = ["telegram", "bot", "aiogram", "pytelegrambotapi", "rate-limit", "anti-flood", "timer", "asyncio"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 4 - Beta",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"License :: OSI Approved :: MIT License",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3.9",
|
|
22
|
+
"Programming Language :: Python :: 3.10",
|
|
23
|
+
"Programming Language :: Python :: 3.11",
|
|
24
|
+
"Programming Language :: Python :: 3.12",
|
|
25
|
+
"Topic :: Communications :: Chat",
|
|
26
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Homepage = "https://github.com/aivideosuz46-creator/telepulse"
|
|
31
|
+
Repository = "https://github.com/aivideosuz46-creator/telepulse"
|
|
32
|
+
Issues = "https://github.com/aivideosuz46-creator/telepulse/issues"
|
|
33
|
+
|
|
34
|
+
[tool.setuptools.packages.find]
|
|
35
|
+
where = ["src"]
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""TelePulse: Zero-dependency rate-limiting and scoped timer toolkit for Telegram bots."""
|
|
2
|
+
|
|
3
|
+
from .decorators import throttle
|
|
4
|
+
from .limiter import LimitResult, SlidingWindowLimiter
|
|
5
|
+
from .timers import ScopedTimerManager
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"LimitResult",
|
|
9
|
+
"SlidingWindowLimiter",
|
|
10
|
+
"ScopedTimerManager",
|
|
11
|
+
"throttle",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import functools
|
|
4
|
+
import inspect
|
|
5
|
+
from typing import Any, Callable, Hashable, Optional
|
|
6
|
+
|
|
7
|
+
from .limiter import LimitResult, SlidingWindowLimiter
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _default_key_extractor(event: Any) -> Hashable:
|
|
11
|
+
"""Extract user ID from aiogram / pyTelegramBotAPI update objects or raw IDs."""
|
|
12
|
+
if isinstance(event, (int, str)):
|
|
13
|
+
return event
|
|
14
|
+
from_user = getattr(event, "from_user", None)
|
|
15
|
+
if from_user is not None and hasattr(from_user, "id"):
|
|
16
|
+
return from_user.id
|
|
17
|
+
chat = getattr(event, "chat", None)
|
|
18
|
+
if chat is not None and hasattr(chat, "id"):
|
|
19
|
+
return chat.id
|
|
20
|
+
return id(event)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def throttle(
|
|
24
|
+
rate: int = 3,
|
|
25
|
+
per: float = 5.0,
|
|
26
|
+
block_for: float = 0.0,
|
|
27
|
+
key_func: Optional[Callable[[Any], Hashable]] = None,
|
|
28
|
+
on_limited: Optional[Callable[[Any, LimitResult], Any]] = None,
|
|
29
|
+
) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
|
|
30
|
+
"""Decorator to rate-limit sync or async Telegram bot handlers."""
|
|
31
|
+
limiter = SlidingWindowLimiter(
|
|
32
|
+
max_calls=rate,
|
|
33
|
+
period=per,
|
|
34
|
+
block_duration=block_for,
|
|
35
|
+
)
|
|
36
|
+
extractor = key_func or _default_key_extractor
|
|
37
|
+
|
|
38
|
+
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
|
|
39
|
+
if inspect.iscoroutinefunction(func):
|
|
40
|
+
|
|
41
|
+
@functools.wraps(func)
|
|
42
|
+
async def async_wrapper(event: Any, *args: Any, **kwargs: Any) -> Any:
|
|
43
|
+
key = extractor(event)
|
|
44
|
+
result = limiter.check(key)
|
|
45
|
+
if not result.allowed:
|
|
46
|
+
if on_limited is not None:
|
|
47
|
+
res = on_limited(event, result)
|
|
48
|
+
if inspect.isawaitable(res):
|
|
49
|
+
await res
|
|
50
|
+
return None
|
|
51
|
+
return await func(event, *args, **kwargs)
|
|
52
|
+
|
|
53
|
+
async_wrapper.limiter = limiter # type: ignore[attr-defined]
|
|
54
|
+
return async_wrapper
|
|
55
|
+
|
|
56
|
+
@functools.wraps(func)
|
|
57
|
+
def sync_wrapper(event: Any, *args: Any, **kwargs: Any) -> Any:
|
|
58
|
+
key = extractor(event)
|
|
59
|
+
result = limiter.check(key)
|
|
60
|
+
if not result.allowed:
|
|
61
|
+
if on_limited is not None:
|
|
62
|
+
on_limited(event, result)
|
|
63
|
+
return None
|
|
64
|
+
return func(event, *args, **kwargs)
|
|
65
|
+
|
|
66
|
+
sync_wrapper.limiter = limiter # type: ignore[attr-defined]
|
|
67
|
+
return sync_wrapper
|
|
68
|
+
|
|
69
|
+
return decorator
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
from collections import deque
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Deque, Dict, Hashable
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class LimitResult:
|
|
11
|
+
"""Outcome of a rate-limit check."""
|
|
12
|
+
|
|
13
|
+
allowed: bool
|
|
14
|
+
retry_after: float = 0.0
|
|
15
|
+
remaining: int = 0
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class SlidingWindowLimiter:
|
|
19
|
+
"""Thread-safe, memory-bounded sliding window rate limiter."""
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
max_calls: int,
|
|
24
|
+
period: float,
|
|
25
|
+
block_duration: float = 0.0,
|
|
26
|
+
cleanup_interval: int = 256,
|
|
27
|
+
) -> None:
|
|
28
|
+
if max_calls <= 0:
|
|
29
|
+
raise ValueError("max_calls must be greater than 0")
|
|
30
|
+
if period <= 0:
|
|
31
|
+
raise ValueError("period must be greater than 0")
|
|
32
|
+
if block_duration < 0:
|
|
33
|
+
raise ValueError("block_duration cannot be negative")
|
|
34
|
+
|
|
35
|
+
self.max_calls = max_calls
|
|
36
|
+
self.period = float(period)
|
|
37
|
+
self.block_duration = float(block_duration)
|
|
38
|
+
self._cleanup_interval = max(16, cleanup_interval)
|
|
39
|
+
|
|
40
|
+
self._events: Dict[Hashable, Deque[float]] = {}
|
|
41
|
+
self._blocked_until: Dict[Hashable, float] = {}
|
|
42
|
+
self._checks = 0
|
|
43
|
+
|
|
44
|
+
def check(self, key: Hashable) -> LimitResult:
|
|
45
|
+
"""Record an attempt for `key` and return whether it is permitted."""
|
|
46
|
+
now = time.monotonic()
|
|
47
|
+
self._checks += 1
|
|
48
|
+
if self._checks % self._cleanup_interval == 0:
|
|
49
|
+
self._purge_expired(now)
|
|
50
|
+
|
|
51
|
+
blocked_until = self._blocked_until.get(key)
|
|
52
|
+
if blocked_until is not None:
|
|
53
|
+
if now < blocked_until:
|
|
54
|
+
return LimitResult(
|
|
55
|
+
allowed=False,
|
|
56
|
+
retry_after=round(blocked_until - now, 3),
|
|
57
|
+
remaining=0,
|
|
58
|
+
)
|
|
59
|
+
del self._blocked_until[key]
|
|
60
|
+
|
|
61
|
+
bucket = self._events.get(key)
|
|
62
|
+
if bucket is None:
|
|
63
|
+
bucket = deque()
|
|
64
|
+
self._events[key] = bucket
|
|
65
|
+
|
|
66
|
+
cutoff = now - self.period
|
|
67
|
+
while bucket and bucket[0] <= cutoff:
|
|
68
|
+
bucket.popleft()
|
|
69
|
+
|
|
70
|
+
if len(bucket) >= self.max_calls:
|
|
71
|
+
if self.block_duration > 0:
|
|
72
|
+
self._blocked_until[key] = now + self.block_duration
|
|
73
|
+
retry_after = self.block_duration
|
|
74
|
+
else:
|
|
75
|
+
retry_after = max(0.0, (bucket[0] + self.period) - now)
|
|
76
|
+
return LimitResult(
|
|
77
|
+
allowed=False,
|
|
78
|
+
retry_after=round(retry_after, 3),
|
|
79
|
+
remaining=0,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
bucket.append(now)
|
|
83
|
+
return LimitResult(
|
|
84
|
+
allowed=True,
|
|
85
|
+
retry_after=0.0,
|
|
86
|
+
remaining=self.max_calls - len(bucket),
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
def reset(self, key: Hashable) -> None:
|
|
90
|
+
"""Clear rate-limit history and active blocks for `key`."""
|
|
91
|
+
self._events.pop(key, None)
|
|
92
|
+
self._blocked_until.pop(key, None)
|
|
93
|
+
|
|
94
|
+
def _purge_expired(self, now: float) -> None:
|
|
95
|
+
cutoff = now - self.period
|
|
96
|
+
stale_keys = [
|
|
97
|
+
k for k, dq in self._events.items() if not dq or dq[-1] <= cutoff
|
|
98
|
+
]
|
|
99
|
+
for k in stale_keys:
|
|
100
|
+
del self._events[k]
|
|
101
|
+
|
|
102
|
+
expired_blocks = [
|
|
103
|
+
k for k, until in self._blocked_until.items() if now >= until
|
|
104
|
+
]
|
|
105
|
+
for k in expired_blocks:
|
|
106
|
+
del self._blocked_until[k]
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import time
|
|
5
|
+
from typing import Any, Awaitable, Callable, Dict
|
|
6
|
+
|
|
7
|
+
AsyncCallback = Callable[..., Awaitable[Any]]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ScopedTimerManager:
|
|
11
|
+
"""Manages cancellable, generation-guarded async timers keyed by scope ID."""
|
|
12
|
+
|
|
13
|
+
def __init__(self) -> None:
|
|
14
|
+
self._tasks: Dict[str, asyncio.Task[Any]] = {}
|
|
15
|
+
self._generations: Dict[str, int] = {}
|
|
16
|
+
self._deadlines: Dict[str, float] = {}
|
|
17
|
+
|
|
18
|
+
def schedule(
|
|
19
|
+
self,
|
|
20
|
+
scope: str,
|
|
21
|
+
delay: float,
|
|
22
|
+
callback: AsyncCallback,
|
|
23
|
+
*args: Any,
|
|
24
|
+
**kwargs: Any,
|
|
25
|
+
) -> int:
|
|
26
|
+
"""Schedule `callback` after `delay` seconds under `scope`."""
|
|
27
|
+
if delay < 0:
|
|
28
|
+
raise ValueError("delay cannot be negative")
|
|
29
|
+
|
|
30
|
+
self._cancel_task_only(scope)
|
|
31
|
+
generation = self._generations.get(scope, 0) + 1
|
|
32
|
+
self._generations[scope] = generation
|
|
33
|
+
self._deadlines[scope] = time.monotonic() + delay
|
|
34
|
+
|
|
35
|
+
task = asyncio.create_task(
|
|
36
|
+
self._runner(scope, generation, delay, callback, args, kwargs)
|
|
37
|
+
)
|
|
38
|
+
self._tasks[scope] = task
|
|
39
|
+
return generation
|
|
40
|
+
|
|
41
|
+
def cancel(self, scope: str) -> bool:
|
|
42
|
+
"""Cancel an active timer for `scope` and invalidate its generation."""
|
|
43
|
+
self._generations[scope] = self._generations.get(scope, 0) + 1
|
|
44
|
+
self._deadlines.pop(scope, None)
|
|
45
|
+
return self._cancel_task_only(scope)
|
|
46
|
+
|
|
47
|
+
def cancel_all(self) -> int:
|
|
48
|
+
"""Cancel all active timers across all scopes."""
|
|
49
|
+
scopes = list(self._tasks.keys())
|
|
50
|
+
cancelled = 0
|
|
51
|
+
for scope in scopes:
|
|
52
|
+
if self.cancel(scope):
|
|
53
|
+
cancelled += 1
|
|
54
|
+
return cancelled
|
|
55
|
+
|
|
56
|
+
def remaining(self, scope: str) -> float:
|
|
57
|
+
"""Return seconds remaining for `scope`, or 0.0 if inactive."""
|
|
58
|
+
deadline = self._deadlines.get(scope)
|
|
59
|
+
if deadline is None:
|
|
60
|
+
return 0.0
|
|
61
|
+
rem = deadline - time.monotonic()
|
|
62
|
+
return round(rem, 3) if rem > 0 else 0.0
|
|
63
|
+
|
|
64
|
+
def is_active(self, scope: str) -> bool:
|
|
65
|
+
"""Return True if `scope` currently has a pending timer."""
|
|
66
|
+
task = self._tasks.get(scope)
|
|
67
|
+
return task is not None and not task.done()
|
|
68
|
+
|
|
69
|
+
def _cancel_task_only(self, scope: str) -> bool:
|
|
70
|
+
task = self._tasks.pop(scope, None)
|
|
71
|
+
if task is not None and not task.done():
|
|
72
|
+
task.cancel()
|
|
73
|
+
return True
|
|
74
|
+
return False
|
|
75
|
+
|
|
76
|
+
async def _runner(
|
|
77
|
+
self,
|
|
78
|
+
scope: str,
|
|
79
|
+
generation: int,
|
|
80
|
+
delay: float,
|
|
81
|
+
callback: AsyncCallback,
|
|
82
|
+
args: tuple[Any, ...],
|
|
83
|
+
kwargs: dict[str, Any],
|
|
84
|
+
) -> None:
|
|
85
|
+
try:
|
|
86
|
+
await asyncio.sleep(delay)
|
|
87
|
+
if self._generations.get(scope) != generation:
|
|
88
|
+
return
|
|
89
|
+
self._tasks.pop(scope, None)
|
|
90
|
+
self._deadlines.pop(scope, None)
|
|
91
|
+
await callback(*args, **kwargs)
|
|
92
|
+
except asyncio.CancelledError:
|
|
93
|
+
return
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: telepulse
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Zero-dependency rate-limiting, anti-flood, and generation-guarded scoped timer toolkit for Python Telegram bots.
|
|
5
|
+
Author: aivideosuz46-creator
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/aivideosuz46-creator/telepulse
|
|
8
|
+
Project-URL: Repository, https://github.com/aivideosuz46-creator/telepulse
|
|
9
|
+
Project-URL: Issues, https://github.com/aivideosuz46-creator/telepulse/issues
|
|
10
|
+
Keywords: telegram,bot,aiogram,pytelegrambotapi,rate-limit,anti-flood,timer,asyncio
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: Communications :: Chat
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# TelePulse
|
|
27
|
+
|
|
28
|
+
**TelePulse** is a lightweight, zero-dependency Python toolkit providing memory-bounded **anti-flood rate limiting** and **generation-guarded scoped async timers** for Telegram bots (`aiogram`, `pyTelegramBotAPI`, `python-telegram-bot`, or custom webhook handlers).
|
|
29
|
+
|
|
30
|
+
## Why TelePulse?
|
|
31
|
+
|
|
32
|
+
Group and game Telegram bots frequently suffer from two reliability bottlenecks:
|
|
33
|
+
1. **Button & Command Spam:** Users rapidly tapping inline buttons or spamming commands, triggering Telegram `429 Too Many Requests` errors or duplicate database writes.
|
|
34
|
+
2. **Stale / Overlapping Timers:** Round or session timers that fire *after* a game has already restarted or ended, causing ghost notifications and race conditions.
|
|
35
|
+
|
|
36
|
+
TelePulse solves both with pure Python standard library primitives (`time.monotonic`, `collections.deque`, `asyncio`).
|
|
37
|
+
|
|
38
|
+
## Installation
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install telepulse
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Quick Start
|
|
45
|
+
|
|
46
|
+
### 1. Anti-Flood Decorator (`@throttle`)
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
from aiogram import Router, types
|
|
50
|
+
from telepulse import LimitResult, throttle
|
|
51
|
+
|
|
52
|
+
router = Router()
|
|
53
|
+
|
|
54
|
+
async def on_spam(message: types.Message, result: LimitResult) -> None:
|
|
55
|
+
await message.answer(f"Too fast! Try again in {result.retry_after}s.")
|
|
56
|
+
|
|
57
|
+
@router.message()
|
|
58
|
+
@throttle(rate=3, per=5.0, block_for=10.0, on_limited=on_spam)
|
|
59
|
+
async def handle_message(message: types.Message) -> None:
|
|
60
|
+
await message.answer("Action accepted!")
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### 2. Generation-Guarded Scoped Timers (`ScopedTimerManager`)
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
from telepulse import ScopedTimerManager
|
|
67
|
+
|
|
68
|
+
timers = ScopedTimerManager()
|
|
69
|
+
|
|
70
|
+
async def finish_round(chat_id: int, round_id: int) -> None:
|
|
71
|
+
print(f"Chat {chat_id}: Round {round_id} ended!")
|
|
72
|
+
|
|
73
|
+
timers.schedule("chat:-100123:round", 30.0, finish_round, -100123, 1)
|
|
74
|
+
timers.schedule("chat:-100123:round", 30.0, finish_round, -100123, 2)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Running Tests
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
PYTHONPATH=src python -m unittest discover -s tests -v
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## License
|
|
84
|
+
|
|
85
|
+
MIT License — see [LICENSE](LICENSE) for details.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/telepulse/__init__.py
|
|
5
|
+
src/telepulse/decorators.py
|
|
6
|
+
src/telepulse/limiter.py
|
|
7
|
+
src/telepulse/timers.py
|
|
8
|
+
src/telepulse.egg-info/PKG-INFO
|
|
9
|
+
src/telepulse.egg-info/SOURCES.txt
|
|
10
|
+
src/telepulse.egg-info/dependency_links.txt
|
|
11
|
+
src/telepulse.egg-info/top_level.txt
|
|
12
|
+
tests/test_telepulse.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
telepulse
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import time
|
|
3
|
+
import unittest
|
|
4
|
+
|
|
5
|
+
from telepulse import ScopedTimerManager, SlidingWindowLimiter, throttle
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class TestSlidingWindowLimiter(unittest.TestCase):
|
|
9
|
+
def test_allows_within_limit_and_blocks_excess(self) -> None:
|
|
10
|
+
limiter = SlidingWindowLimiter(max_calls=2, period=1.0)
|
|
11
|
+
self.assertTrue(limiter.check("user_1").allowed)
|
|
12
|
+
self.assertTrue(limiter.check("user_1").allowed)
|
|
13
|
+
|
|
14
|
+
blocked = limiter.check("user_1")
|
|
15
|
+
self.assertFalse(blocked.allowed)
|
|
16
|
+
self.assertGreater(blocked.retry_after, 0.0)
|
|
17
|
+
|
|
18
|
+
def test_recovers_after_window(self) -> None:
|
|
19
|
+
limiter = SlidingWindowLimiter(max_calls=1, period=0.05)
|
|
20
|
+
self.assertTrue(limiter.check(42).allowed)
|
|
21
|
+
self.assertFalse(limiter.check(42).allowed)
|
|
22
|
+
time.sleep(0.06)
|
|
23
|
+
self.assertTrue(limiter.check(42).allowed)
|
|
24
|
+
|
|
25
|
+
def test_block_duration_penalty(self) -> None:
|
|
26
|
+
limiter = SlidingWindowLimiter(max_calls=1, period=0.05, block_duration=0.15)
|
|
27
|
+
self.assertTrue(limiter.check("u").allowed)
|
|
28
|
+
res = limiter.check("u")
|
|
29
|
+
self.assertFalse(res.allowed)
|
|
30
|
+
self.assertGreaterEqual(res.retry_after, 0.1)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class TestScopedTimerManager(unittest.IsolatedAsyncioTestCase):
|
|
34
|
+
async def test_timer_executes_and_replaces_previous_scope(self) -> None:
|
|
35
|
+
timers = ScopedTimerManager()
|
|
36
|
+
log: list[str] = []
|
|
37
|
+
|
|
38
|
+
async def record(label: str) -> None:
|
|
39
|
+
log.append(label)
|
|
40
|
+
|
|
41
|
+
timers.schedule("chat:100:round", 0.08, record, "stale_round")
|
|
42
|
+
await asyncio.sleep(0.02)
|
|
43
|
+
timers.schedule("chat:100:round", 0.05, record, "active_round")
|
|
44
|
+
|
|
45
|
+
await asyncio.sleep(0.09)
|
|
46
|
+
self.assertEqual(log, ["active_round"])
|
|
47
|
+
|
|
48
|
+
async def test_cancel_prevents_callback(self) -> None:
|
|
49
|
+
timers = ScopedTimerManager()
|
|
50
|
+
fired = False
|
|
51
|
+
|
|
52
|
+
async def trigger() -> None:
|
|
53
|
+
nonlocal fired
|
|
54
|
+
fired = True
|
|
55
|
+
|
|
56
|
+
timers.schedule("game:1", 0.05, trigger)
|
|
57
|
+
self.assertTrue(timers.is_active("game:1"))
|
|
58
|
+
self.assertTrue(timers.cancel("game:1"))
|
|
59
|
+
await asyncio.sleep(0.07)
|
|
60
|
+
self.assertFalse(fired)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class TestThrottleDecorator(unittest.IsolatedAsyncioTestCase):
|
|
64
|
+
async def test_async_throttle_decorator(self) -> None:
|
|
65
|
+
calls = 0
|
|
66
|
+
|
|
67
|
+
@throttle(rate=2, per=1.0)
|
|
68
|
+
async def handle_click(user_id: int) -> str:
|
|
69
|
+
nonlocal calls
|
|
70
|
+
calls += 1
|
|
71
|
+
return "ok"
|
|
72
|
+
|
|
73
|
+
self.assertEqual(await handle_click(777), "ok")
|
|
74
|
+
self.assertEqual(await handle_click(777), "ok")
|
|
75
|
+
self.assertIsNone(await handle_click(777))
|
|
76
|
+
self.assertEqual(calls, 2)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
if __name__ == "__main__":
|
|
80
|
+
unittest.main()
|