telegram-async 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.
@@ -0,0 +1,27 @@
1
+
2
+ ---
3
+
4
+ # 📄 `LICENSE` (MIT)
5
+
6
+ ```text
7
+ MIT License
8
+
9
+ Copyright (c) 2026 Denys
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
@@ -0,0 +1,32 @@
1
+ Metadata-Version: 2.4
2
+ Name: telegram-async
3
+ Version: 0.1.0
4
+ Summary: Asynchronous Telegram bot framework with throttling, callbacks, and middleware
5
+ Author-email: Denys <ostrovskyidenys30@gmail.com>
6
+ License: MIT
7
+ Keywords: telegram,async,bot,framework
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: aiohttp>=3.13.3
14
+ Requires-Dist: rich>=14.2.0
15
+ Dynamic: license-file
16
+
17
+ # telegram-async
18
+
19
+ **Asynchronous Telegram bot framework** z middleware, throttlingiem, callbackami i pseudo-przyciskami.
20
+
21
+ Framework ułatwia tworzenie botów Telegram w Pythonie z wykorzystaniem `asyncio` i `aiohttp`. Wspiera:
22
+
23
+ - Komendy `/start`, `/help`, `/confirm`
24
+ - Throttling wiadomości użytkownika
25
+ - Middleware logger (Rich)
26
+ - Callbacki i pseudo-przyciski (`/ok`)
27
+ - Background task działający w pętli co X sekund
28
+
29
+ ## Instalacja
30
+
31
+ ```bash
32
+ pip install telegram-async
@@ -0,0 +1,16 @@
1
+ # telegram-async
2
+
3
+ **Asynchronous Telegram bot framework** z middleware, throttlingiem, callbackami i pseudo-przyciskami.
4
+
5
+ Framework ułatwia tworzenie botów Telegram w Pythonie z wykorzystaniem `asyncio` i `aiohttp`. Wspiera:
6
+
7
+ - Komendy `/start`, `/help`, `/confirm`
8
+ - Throttling wiadomości użytkownika
9
+ - Middleware logger (Rich)
10
+ - Callbacki i pseudo-przyciski (`/ok`)
11
+ - Background task działający w pętli co X sekund
12
+
13
+ ## Instalacja
14
+
15
+ ```bash
16
+ pip install telegram-async
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "telegram-async"
7
+ version = "0.1.0"
8
+ description = "Asynchronous Telegram bot framework with throttling, callbacks, and middleware"
9
+ readme = "README.md"
10
+ license = {text = "MIT"}
11
+ authors = [
12
+ {name = "Denys", email = "ostrovskyidenys30@gmail.com"}
13
+ ]
14
+ dependencies = [
15
+ "aiohttp>=3.13.3",
16
+ "rich>=14.2.0"
17
+ ]
18
+ keywords = ["telegram", "async", "bot", "framework"]
19
+ classifiers = [
20
+ "Programming Language :: Python :: 3",
21
+ "License :: OSI Approved :: MIT License",
22
+ "Operating System :: OS Independent"
23
+ ]
24
+
25
+ [tool.setuptools.packages.find]
26
+ where = ["."]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,11 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name="telegram_async",
5
+ version="0.1.0",
6
+ packages=find_packages(),
7
+ install_requires=[
8
+ "aiohttp",
9
+ "rich"
10
+ ],
11
+ )
@@ -0,0 +1,2 @@
1
+ from .bot import Bot
2
+ from .roles import Role
@@ -0,0 +1,60 @@
1
+ from .client import TelegramClient
2
+ from .dispatcher import Dispatcher
3
+ from .server import WebhookServer
4
+ from .roles import Role
5
+ from .logger import logger
6
+ from .decorators import command as command_deco, on_message, middleware, role_required
7
+
8
+ class Bot:
9
+ def __init__(self, token, role_provider=None, session_store=None):
10
+ self.client = TelegramClient(token)
11
+ self.role_provider = role_provider or (lambda _: Role.GUEST)
12
+ self.dispatcher = Dispatcher(self.client, self.role_provider, session_store=session_store)
13
+
14
+ def command(self, name: str):
15
+ def wrapper(func):
16
+ func = command_deco(name)(func)
17
+ self.dispatcher.register(func)
18
+ logger.info(f"Registered command {name}")
19
+ return func
20
+ return wrapper
21
+
22
+ def on_message(self, **filters):
23
+ def wrapper(func):
24
+ func = on_message(**filters)(func)
25
+ self.dispatcher.register(func)
26
+ return func
27
+ return wrapper
28
+
29
+ def middleware(self):
30
+ def wrapper(func):
31
+ func = middleware()(func)
32
+ self.dispatcher.register(func)
33
+ return func
34
+ return wrapper
35
+
36
+ def require(self, role: Role):
37
+ def wrapper(func):
38
+ func = role_required(role)(func)
39
+ return func
40
+ return wrapper
41
+
42
+ def run_webhook(self, host="0.0.0.0", port=8080):
43
+ server = WebhookServer(self.dispatcher)
44
+ server.run(host, port)
45
+
46
+ async def run_polling(self):
47
+ import asyncio
48
+ from aiohttp import ClientSession
49
+ offset = None
50
+ while True:
51
+ async with ClientSession() as session:
52
+ params = {"timeout": 30}
53
+ if offset:
54
+ params["offset"] = offset
55
+ async with session.get(f"{self.client.base}/getUpdates", params=params) as r:
56
+ updates = await r.json()
57
+ for update in updates.get("result", []):
58
+ await self.dispatcher.dispatch(update)
59
+ offset = update["update_id"] + 1
60
+ await asyncio.sleep(1)
@@ -0,0 +1,25 @@
1
+ from collections import defaultdict
2
+
3
+ class CallbackRegistry:
4
+ def __init__(self):
5
+ # pattern -> handler
6
+ self.handlers = {}
7
+
8
+ def register(self, pattern: str, handler):
9
+ self.handlers[pattern] = handler
10
+
11
+ async def dispatch(self, ctx, callback_data: str):
12
+ for pattern, handler in self.handlers.items():
13
+ if pattern == callback_data:
14
+ await handler(ctx)
15
+ return
16
+
17
+ # Singleton do użytku w frameworku
18
+ callback_registry = CallbackRegistry()
19
+
20
+ # dekorator do bot.py
21
+ def on_callback(pattern: str):
22
+ def wrapper(func):
23
+ callback_registry.register(pattern, func)
24
+ return func
25
+ return wrapper
@@ -0,0 +1,19 @@
1
+ import aiohttp
2
+
3
+ class TelegramClient:
4
+ def __init__(self, token: str):
5
+ self.base = f"https://api.telegram.org/bot{token}"
6
+
7
+ async def send_message(self, chat_id: int, text: str):
8
+ async with aiohttp.ClientSession() as s:
9
+ await s.post(
10
+ f"{self.base}/sendMessage",
11
+ json={"chat_id": chat_id, "text": text}
12
+ )
13
+
14
+ async def answer_callback(self, callback_id: str, text: str = None):
15
+ async with aiohttp.ClientSession() as s:
16
+ await s.post(
17
+ f"{self.base}/answerCallbackQuery",
18
+ json={"callback_query_id": callback_id, "text": text or ""}
19
+ )
@@ -0,0 +1,16 @@
1
+ from typing import Any
2
+
3
+ class Context:
4
+ def __init__(self, client, update: dict, role: Any, session=None):
5
+ self.client = client
6
+ self.update = update
7
+ self.message = update.get("message") or {}
8
+ self.chat_id = self.message.get("chat", {}).get("id")
9
+ self.user_id = self.message.get("from", {}).get("id")
10
+ self.text = self.message.get("text", "")
11
+ self.role = role
12
+ self.session = session or {}
13
+
14
+ async def reply(self, text: str):
15
+ if self.chat_id:
16
+ await self.client.send_message(self.chat_id, text)
@@ -0,0 +1,31 @@
1
+ from functools import wraps
2
+ from .roles import Role
3
+
4
+ def role_required(role: Role):
5
+ def decorator(func):
6
+ func.__required_role__ = role
7
+ return func
8
+ return decorator
9
+
10
+ def command(name: str):
11
+ def decorator(func):
12
+ func.__command__ = name
13
+ return func
14
+ return decorator
15
+
16
+ def on_message(text_contains=None, from_user=None, chat_id=None):
17
+ def decorator(func):
18
+ func.__on_message__ = True
19
+ func.__filter__ = {
20
+ "text_contains": text_contains,
21
+ "from_user": from_user,
22
+ "chat_id": chat_id
23
+ }
24
+ return func
25
+ return decorator
26
+
27
+ def middleware():
28
+ def decorator(func):
29
+ func.__middleware__ = True
30
+ return func
31
+ return decorator
@@ -0,0 +1,61 @@
1
+ from .context import Context
2
+ from .roles import Role
3
+
4
+ class Dispatcher:
5
+ def __init__(self, client, role_provider, session_store=None):
6
+ self.client = client
7
+ self.role_provider = role_provider
8
+ self.session_store = session_store or {}
9
+ self.command_handlers = {}
10
+ self.message_handlers = []
11
+ self.middlewares = []
12
+
13
+ def register(self, func):
14
+ if hasattr(func, "__command__"):
15
+ role = getattr(func, "__required_role__", Role.GUEST)
16
+ self.command_handlers[func.__command__] = (func, role)
17
+
18
+ if hasattr(func, "__on_message__"):
19
+ self.message_handlers.append(func)
20
+
21
+ if hasattr(func, "__middleware__"):
22
+ self.middlewares.append(func)
23
+
24
+ async def _run_middlewares(self, ctx, handler):
25
+ async def call(index):
26
+ if index < len(self.middlewares):
27
+ await self.middlewares[index](ctx, lambda: call(index + 1))
28
+ else:
29
+ await handler(ctx)
30
+ await call(0)
31
+
32
+ async def dispatch(self, update: dict):
33
+ msg = update.get("message")
34
+ if not msg:
35
+ return
36
+
37
+ user_id = msg.get("from", {}).get("id")
38
+ role = self.role_provider(user_id)
39
+ session = self.session_store.get(user_id, {})
40
+
41
+ ctx = Context(self.client, update, role, session)
42
+
43
+ text = msg.get("text", "")
44
+
45
+ if text.startswith("/"):
46
+ command = text.split()[0]
47
+ if command in self.command_handlers:
48
+ handler, min_role = self.command_handlers[command]
49
+ if role >= min_role:
50
+ await self._run_middlewares(ctx, handler)
51
+ return
52
+
53
+ for handler in self.message_handlers:
54
+ filt = getattr(handler, "__filter__", {})
55
+ if filt.get("text_contains") and filt["text_contains"] not in text:
56
+ continue
57
+ if filt.get("from_user") and filt["from_user"] != user_id:
58
+ continue
59
+ if filt.get("chat_id") and filt["chat_id"] != ctx.chat_id:
60
+ continue
61
+ await self._run_middlewares(ctx, handler)
@@ -0,0 +1,14 @@
1
+ from telegram_async.decorators import command
2
+
3
+ def generate_help(dispatcher) -> str:
4
+ """
5
+ Generuje tekst help z listą komend i minimalną info
6
+ """
7
+ lines = ["📖 Lista komend:"]
8
+ for cmd, (handler, role) in dispatcher.command_handlers.items():
9
+ lines.append(f"{cmd} - minimalna rola: {role.name}")
10
+ return "\n".join(lines)
11
+
12
+ async def send_help(ctx, dispatcher):
13
+ help_text = generate_help(dispatcher)
14
+ await ctx.reply(help_text)
@@ -0,0 +1,10 @@
1
+ import logging
2
+ from rich.logging import RichHandler
3
+
4
+ logging.basicConfig(
5
+ level=logging.INFO,
6
+ format="%(message)s",
7
+ handlers=[RichHandler()]
8
+ )
9
+
10
+ logger = logging.getLogger("telegram_async")
@@ -0,0 +1,13 @@
1
+ from telegram_async import Bot
2
+ from telegram_async.throttling import Throttle
3
+
4
+ bot = Bot(token="TOKEN")
5
+ throttle = Throttle()
6
+
7
+ @bot.middleware()
8
+ async def rate_limit(ctx, next):
9
+ allowed = await throttle.check(ctx.user_id, rate=5, per=10)
10
+ if not allowed:
11
+ await ctx.reply("⛔ Too many attempts. Please wait a moment.")
12
+ return
13
+ await next()
@@ -0,0 +1,6 @@
1
+ from enum import IntEnum
2
+
3
+ class Role(IntEnum):
4
+ GUEST = 0
5
+ USER = 1
6
+ ADMIN = 2
@@ -0,0 +1,15 @@
1
+ from aiohttp import web
2
+
3
+ class WebhookServer:
4
+ def __init__(self, dispatcher):
5
+ self.dispatcher = dispatcher
6
+ self.app = web.Application()
7
+ self.app.router.add_post("/webhook", self.handle)
8
+
9
+ async def handle(self, request):
10
+ update = await request.json()
11
+ await self.dispatcher.dispatch(update)
12
+ return web.Response(text="ok")
13
+
14
+ def run(self, host="0.0.0.0", port=8080):
15
+ web.run_app(self.app, host=host, port=port)
@@ -0,0 +1,9 @@
1
+ class SessionStorage:
2
+ def __init__(self):
3
+ self.store = {}
4
+
5
+ def get(self, user_id):
6
+ return self.store.get(user_id, {})
7
+
8
+ def set(self, user_id, data):
9
+ self.store[user_id] = data
@@ -0,0 +1,19 @@
1
+ import asyncio
2
+
3
+ class TaskManager:
4
+ def __init__(self):
5
+ self.tasks = []
6
+
7
+ def add_task(self, coro, interval: int = None):
8
+ """Dodaje zadanie async, opcjonalnie z interwałem (sekundy)"""
9
+ async def looped():
10
+ while True:
11
+ await coro()
12
+ if not interval:
13
+ break
14
+ await asyncio.sleep(interval)
15
+ t = asyncio.create_task(looped())
16
+ self.tasks.append(t)
17
+ return t
18
+
19
+ task_manager = TaskManager()
@@ -0,0 +1,21 @@
1
+ import time
2
+ from collections import defaultdict
3
+ from asyncio import Lock
4
+
5
+ class Throttle:
6
+ def __init__(self):
7
+ # user_id -> [timestamp1, timestamp2, ...]
8
+ self.calls = defaultdict(list)
9
+ self.lock = Lock()
10
+
11
+ async def check(self, user_id: int, rate: int = 5, per: int = 10) -> bool:
12
+ """Zwraca True jeśli użytkownik może wykonać akcję"""
13
+ now = time.time()
14
+ async with self.lock:
15
+ timestamps = self.calls[user_id]
16
+ # usuwamy stare
17
+ self.calls[user_id] = [t for t in timestamps if now - t < per]
18
+ if len(self.calls[user_id]) >= rate:
19
+ return False
20
+ self.calls[user_id].append(now)
21
+ return True
@@ -0,0 +1,32 @@
1
+ Metadata-Version: 2.4
2
+ Name: telegram-async
3
+ Version: 0.1.0
4
+ Summary: Asynchronous Telegram bot framework with throttling, callbacks, and middleware
5
+ Author-email: Denys <ostrovskyidenys30@gmail.com>
6
+ License: MIT
7
+ Keywords: telegram,async,bot,framework
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: aiohttp>=3.13.3
14
+ Requires-Dist: rich>=14.2.0
15
+ Dynamic: license-file
16
+
17
+ # telegram-async
18
+
19
+ **Asynchronous Telegram bot framework** z middleware, throttlingiem, callbackami i pseudo-przyciskami.
20
+
21
+ Framework ułatwia tworzenie botów Telegram w Pythonie z wykorzystaniem `asyncio` i `aiohttp`. Wspiera:
22
+
23
+ - Komendy `/start`, `/help`, `/confirm`
24
+ - Throttling wiadomości użytkownika
25
+ - Middleware logger (Rich)
26
+ - Callbacki i pseudo-przyciski (`/ok`)
27
+ - Background task działający w pętli co X sekund
28
+
29
+ ## Instalacja
30
+
31
+ ```bash
32
+ pip install telegram-async
@@ -0,0 +1,24 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ setup.py
5
+ telegram_async/__init__.py
6
+ telegram_async/bot.py
7
+ telegram_async/callback.py
8
+ telegram_async/client.py
9
+ telegram_async/context.py
10
+ telegram_async/decorators.py
11
+ telegram_async/dispatcher.py
12
+ telegram_async/docs.py
13
+ telegram_async/logger.py
14
+ telegram_async/middleware.py
15
+ telegram_async/roles.py
16
+ telegram_async/server.py
17
+ telegram_async/storage.py
18
+ telegram_async/tasks.py
19
+ telegram_async/throttling.py
20
+ telegram_async.egg-info/PKG-INFO
21
+ telegram_async.egg-info/SOURCES.txt
22
+ telegram_async.egg-info/dependency_links.txt
23
+ telegram_async.egg-info/requires.txt
24
+ telegram_async.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ aiohttp>=3.13.3
2
+ rich>=14.2.0
@@ -0,0 +1,2 @@
1
+ dist
2
+ telegram_async