telepulse 0.1.0__py3-none-any.whl

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/__init__.py ADDED
@@ -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
telepulse/limiter.py ADDED
@@ -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]
telepulse/timers.py ADDED
@@ -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,9 @@
1
+ telepulse/__init__.py,sha256=sN1N5avJssFtsD7dQICbibeby9k2uGFLIHfa87JT9fM,346
2
+ telepulse/decorators.py,sha256=dQvEmy6IJ8ZXQYJQfmsVmVc6WptnMpuAcWuQmx8h1To,2401
3
+ telepulse/limiter.py,sha256=8R5V-khh1vOzBSn6SDQNrkH0ljxtwxmknlYLGpPjCT8,3307
4
+ telepulse/timers.py,sha256=rnnCEz8kUZLsQM80s8Jp57Ro2dSeenrfXHXk07hu2No,2973
5
+ telepulse-0.1.0.dist-info/licenses/LICENSE,sha256=Xb4cFlciTTdXYwBWMH178eclJLjdx2HM5QZPn8YTTR8,1077
6
+ telepulse-0.1.0.dist-info/METADATA,sha256=p5PaMAgWfbdMaFPGajtu3FUSE9ZoBJTGfwD4dmNdMXs,3091
7
+ telepulse-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ telepulse-0.1.0.dist-info/top_level.txt,sha256=C5enYxsZdUQOmdVbYhO4--DjgdA8tsqLvG7AzWCL2Mo,10
9
+ telepulse-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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.
@@ -0,0 +1 @@
1
+ telepulse