puragram 1.0.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.
- puragram-1.0.0/LICENSE +21 -0
- puragram-1.0.0/PKG-INFO +93 -0
- puragram-1.0.0/README.md +67 -0
- puragram-1.0.0/puragram/__init__.py +67 -0
- puragram-1.0.0/puragram/api.py +123 -0
- puragram-1.0.0/puragram/bot.py +397 -0
- puragram-1.0.0/puragram/exceptions.py +23 -0
- puragram-1.0.0/puragram/filters.py +177 -0
- puragram-1.0.0/puragram/fsm/__init__.py +8 -0
- puragram-1.0.0/puragram/fsm/context.py +22 -0
- puragram-1.0.0/puragram/fsm/state.py +17 -0
- puragram-1.0.0/puragram/fsm/storage.py +159 -0
- puragram-1.0.0/puragram/keyboards.py +157 -0
- puragram-1.0.0/puragram/logger.py +46 -0
- puragram-1.0.0/puragram/middleware.py +81 -0
- puragram-1.0.0/puragram/security.py +136 -0
- puragram-1.0.0/puragram/types.py +181 -0
- puragram-1.0.0/puragram/utils.py +81 -0
- puragram-1.0.0/puragram/webhook.py +128 -0
- puragram-1.0.0/puragram.egg-info/PKG-INFO +93 -0
- puragram-1.0.0/puragram.egg-info/SOURCES.txt +28 -0
- puragram-1.0.0/puragram.egg-info/dependency_links.txt +1 -0
- puragram-1.0.0/puragram.egg-info/requires.txt +4 -0
- puragram-1.0.0/puragram.egg-info/top_level.txt +1 -0
- puragram-1.0.0/pyproject.toml +39 -0
- puragram-1.0.0/setup.cfg +4 -0
- puragram-1.0.0/tests/test_filters.py +60 -0
- puragram-1.0.0/tests/test_fsm.py +39 -0
- puragram-1.0.0/tests/test_security.py +320 -0
- puragram-1.0.0/tests/test_utils.py +19 -0
puragram-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 <Maxim Zhovner>
|
|
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.
|
puragram-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: puragram
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Fast, dependency-light Telegram Bot API framework built on urllib3
|
|
5
|
+
Author-email: Maxim Zhovner <zovnercukmaksim197@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Keywords: telegram,bot,api,urllib3,framework
|
|
8
|
+
Classifier: Development Status :: 4 - Beta
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Topic :: Communications :: Chat
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
19
|
+
Requires-Python: >=3.9
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: urllib3>=2.0
|
|
23
|
+
Provides-Extra: test
|
|
24
|
+
Requires-Dist: pytest>=7; extra == "test"
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# puragram
|
|
28
|
+
|
|
29
|
+
A fast, dependency-light Telegram Bot API framework for Python.
|
|
30
|
+
Built on urllib3 — no aiohttp, no requests, no httpx.
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install puragram
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Quick start
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
from puragram import Bot
|
|
42
|
+
|
|
43
|
+
bot = Bot("YOUR_TOKEN", parse_mode="HTML")
|
|
44
|
+
|
|
45
|
+
@bot.message_handler(commands=["start"])
|
|
46
|
+
def start(msg):
|
|
47
|
+
bot.send_message(msg.chat.id, f"Hi, <b>{msg.from_user.first_name}</b>!")
|
|
48
|
+
|
|
49
|
+
@bot.message_handler(content_types=["text"])
|
|
50
|
+
def echo(msg):
|
|
51
|
+
bot.send_message(msg.chat.id, f"You said: <b>{msg.text}</b>")
|
|
52
|
+
|
|
53
|
+
if __name__ == "__main__":
|
|
54
|
+
bot.run_polling()
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Features
|
|
58
|
+
|
|
59
|
+
- Fast: direct urllib3 pool, JSON bodies, keep-alive
|
|
60
|
+
- Built-in FSM: State, StatesGroup, MemoryStorage, FileStorage, SQLiteStorage
|
|
61
|
+
- Middleware: logging, throttling, timing
|
|
62
|
+
- Filters: Command, Text, Regexp, ContentTypes, ChatType, ChatId, UserId, CallbackData, Func
|
|
63
|
+
- Webhook server on stdlib http.server
|
|
64
|
+
- Secure: path traversal guard, size limits, ReDoS filter, webhook secret, token redaction, dedup
|
|
65
|
+
- Zero dependencies except urllib3
|
|
66
|
+
|
|
67
|
+
## FSM example
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from puragram import Bot, State, StatesGroup
|
|
71
|
+
|
|
72
|
+
bot = Bot("YOUR_TOKEN")
|
|
73
|
+
|
|
74
|
+
class Form(StatesGroup):
|
|
75
|
+
name = State()
|
|
76
|
+
|
|
77
|
+
@bot.message_handler(commands=["start"])
|
|
78
|
+
def start(msg, data):
|
|
79
|
+
data["state"].set_state(Form.name)
|
|
80
|
+
bot.send_message(msg.chat.id, "Your name?")
|
|
81
|
+
|
|
82
|
+
@bot.message_handler(state=Form.name)
|
|
83
|
+
def on_name(msg, data):
|
|
84
|
+
data["state"].update_data(name=msg.text)
|
|
85
|
+
data["state"].clear()
|
|
86
|
+
bot.send_message(msg.chat.id, f"Hi, {msg.text}!")
|
|
87
|
+
|
|
88
|
+
bot.run_polling()
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## License
|
|
92
|
+
|
|
93
|
+
MIT — see LICENSE.
|
puragram-1.0.0/README.md
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# puragram
|
|
2
|
+
|
|
3
|
+
A fast, dependency-light Telegram Bot API framework for Python.
|
|
4
|
+
Built on urllib3 — no aiohttp, no requests, no httpx.
|
|
5
|
+
|
|
6
|
+
## Install
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
pip install puragram
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Quick start
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
from puragram import Bot
|
|
16
|
+
|
|
17
|
+
bot = Bot("YOUR_TOKEN", parse_mode="HTML")
|
|
18
|
+
|
|
19
|
+
@bot.message_handler(commands=["start"])
|
|
20
|
+
def start(msg):
|
|
21
|
+
bot.send_message(msg.chat.id, f"Hi, <b>{msg.from_user.first_name}</b>!")
|
|
22
|
+
|
|
23
|
+
@bot.message_handler(content_types=["text"])
|
|
24
|
+
def echo(msg):
|
|
25
|
+
bot.send_message(msg.chat.id, f"You said: <b>{msg.text}</b>")
|
|
26
|
+
|
|
27
|
+
if __name__ == "__main__":
|
|
28
|
+
bot.run_polling()
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Features
|
|
32
|
+
|
|
33
|
+
- Fast: direct urllib3 pool, JSON bodies, keep-alive
|
|
34
|
+
- Built-in FSM: State, StatesGroup, MemoryStorage, FileStorage, SQLiteStorage
|
|
35
|
+
- Middleware: logging, throttling, timing
|
|
36
|
+
- Filters: Command, Text, Regexp, ContentTypes, ChatType, ChatId, UserId, CallbackData, Func
|
|
37
|
+
- Webhook server on stdlib http.server
|
|
38
|
+
- Secure: path traversal guard, size limits, ReDoS filter, webhook secret, token redaction, dedup
|
|
39
|
+
- Zero dependencies except urllib3
|
|
40
|
+
|
|
41
|
+
## FSM example
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from puragram import Bot, State, StatesGroup
|
|
45
|
+
|
|
46
|
+
bot = Bot("YOUR_TOKEN")
|
|
47
|
+
|
|
48
|
+
class Form(StatesGroup):
|
|
49
|
+
name = State()
|
|
50
|
+
|
|
51
|
+
@bot.message_handler(commands=["start"])
|
|
52
|
+
def start(msg, data):
|
|
53
|
+
data["state"].set_state(Form.name)
|
|
54
|
+
bot.send_message(msg.chat.id, "Your name?")
|
|
55
|
+
|
|
56
|
+
@bot.message_handler(state=Form.name)
|
|
57
|
+
def on_name(msg, data):
|
|
58
|
+
data["state"].update_data(name=msg.text)
|
|
59
|
+
data["state"].clear()
|
|
60
|
+
bot.send_message(msg.chat.id, f"Hi, {msg.text}!")
|
|
61
|
+
|
|
62
|
+
bot.run_polling()
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## License
|
|
66
|
+
|
|
67
|
+
MIT — see LICENSE.
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
from .api import TelegramAPI
|
|
2
|
+
from .bot import Bot
|
|
3
|
+
from .exceptions import (
|
|
4
|
+
TelegramError, GrambotError, SecurityError,
|
|
5
|
+
ValidationError, WebhookError,
|
|
6
|
+
)
|
|
7
|
+
from .logger import get_logger, setup_logging, quiet
|
|
8
|
+
|
|
9
|
+
from .types import (
|
|
10
|
+
CallbackQuery, Chat, Message, Update, User,
|
|
11
|
+
)
|
|
12
|
+
from .keyboards import (
|
|
13
|
+
ForceReply, InlineKeyboardBuilder, InlineKeyboardButton,
|
|
14
|
+
InlineKeyboardMarkup, KeyboardButton, RemoveKeyboard,
|
|
15
|
+
ReplyKeyboardMarkup,
|
|
16
|
+
)
|
|
17
|
+
from .filters import (
|
|
18
|
+
BaseFilter, CallbackData, ChatId, ChatType, Command,
|
|
19
|
+
ContentTypes, Func, Regexp, Text, UserId,
|
|
20
|
+
)
|
|
21
|
+
from .fsm import (
|
|
22
|
+
BaseStorage, FileStorage, FSMContext, MemoryStorage,
|
|
23
|
+
SQLiteStorage, State, StatesGroup,
|
|
24
|
+
)
|
|
25
|
+
from .middleware import (
|
|
26
|
+
BaseMiddleware, LoggingMiddleware, ThrottlingMiddleware,
|
|
27
|
+
TimingMiddleware,
|
|
28
|
+
)
|
|
29
|
+
from .webhook import WebhookServer
|
|
30
|
+
from .utils import (
|
|
31
|
+
chunked, escape_html, escape_markdown, safe_text,
|
|
32
|
+
split_message, truncate, user_mention,
|
|
33
|
+
)
|
|
34
|
+
from .security import (
|
|
35
|
+
constant_time_eq, mask_token, redact, safe_filename,
|
|
36
|
+
safe_path, validate_callback_data, validate_text,
|
|
37
|
+
compile_safe_regex, check_size,
|
|
38
|
+
MAX_MESSAGE_LEN, MAX_CAPTION_LEN, MAX_CALLBACK_DATA,
|
|
39
|
+
MAX_UPLOAD_BYTES, MAX_WEBHOOK_BYTES, MAX_REGEX_LEN,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
__version__ = "1.0.0"
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"Bot", "TelegramAPI",
|
|
46
|
+
"GrambotError", "TelegramError", "SecurityError",
|
|
47
|
+
"ValidationError", "WebhookError",
|
|
48
|
+
"Update", "Message", "Chat", "User", "CallbackQuery",
|
|
49
|
+
"InlineKeyboardMarkup", "InlineKeyboardButton",
|
|
50
|
+
"ReplyKeyboardMarkup", "KeyboardButton",
|
|
51
|
+
"ForceReply", "RemoveKeyboard", "InlineKeyboardBuilder",
|
|
52
|
+
"BaseFilter", "Func", "Command", "Text", "ContentTypes",
|
|
53
|
+
"ChatType", "ChatId", "UserId", "Regexp", "CallbackData",
|
|
54
|
+
"FSMContext", "State", "StatesGroup",
|
|
55
|
+
"BaseStorage", "MemoryStorage", "FileStorage", "SQLiteStorage",
|
|
56
|
+
"BaseMiddleware", "LoggingMiddleware", "ThrottlingMiddleware",
|
|
57
|
+
"TimingMiddleware",
|
|
58
|
+
"WebhookServer",
|
|
59
|
+
"escape_html", "escape_markdown", "safe_text",
|
|
60
|
+
"split_message", "chunked", "user_mention", "truncate",
|
|
61
|
+
"redact", "mask_token", "safe_path", "safe_filename",
|
|
62
|
+
"validate_callback_data", "validate_text",
|
|
63
|
+
"compile_safe_regex", "check_size", "constant_time_eq",
|
|
64
|
+
"MAX_MESSAGE_LEN", "MAX_CAPTION_LEN", "MAX_CALLBACK_DATA",
|
|
65
|
+
"MAX_UPLOAD_BYTES", "MAX_WEBHOOK_BYTES", "MAX_REGEX_LEN",
|
|
66
|
+
"get_logger", "setup_logging", "quiet",
|
|
67
|
+
]
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import urllib3
|
|
3
|
+
|
|
4
|
+
from .exceptions import TelegramError, SecurityError
|
|
5
|
+
from .security import MAX_UPLOAD_BYTES, safe_filename
|
|
6
|
+
from .logger import get_logger
|
|
7
|
+
|
|
8
|
+
log = get_logger("puragram.api")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _camel(name):
|
|
12
|
+
head, *tail = name.split("_")
|
|
13
|
+
return head + "".join(p.capitalize() for p in tail)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class TelegramAPI:
|
|
17
|
+
def __init__(self, token, pool_size=10, timeout=30.0, retries=2):
|
|
18
|
+
if not token or not isinstance(token, str):
|
|
19
|
+
raise SecurityError("Token must be a non-empty string")
|
|
20
|
+
if ":" not in token:
|
|
21
|
+
raise SecurityError("Token has invalid format")
|
|
22
|
+
self.token = token
|
|
23
|
+
self.base_url = f"https://api.telegram.org/bot{token}"
|
|
24
|
+
self.file_url = f"https://api.telegram.org/file/bot{token}"
|
|
25
|
+
self._http = urllib3.PoolManager(
|
|
26
|
+
num_pools=pool_size,
|
|
27
|
+
maxsize=pool_size,
|
|
28
|
+
block=False,
|
|
29
|
+
timeout=urllib3.Timeout(connect=5.0, read=timeout),
|
|
30
|
+
retries=urllib3.Retry(
|
|
31
|
+
retries,
|
|
32
|
+
backoff_factor=0.3,
|
|
33
|
+
status_forcelist=[500, 502, 503, 504],
|
|
34
|
+
allowed_methods=frozenset(["GET", "POST"]),
|
|
35
|
+
raise_on_status=False,
|
|
36
|
+
),
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
def call(self, method, files=None, **params):
|
|
40
|
+
url = f"{self.base_url}/{_camel(method)}"
|
|
41
|
+
try:
|
|
42
|
+
if files:
|
|
43
|
+
fields = self._build_multipart(files, params)
|
|
44
|
+
resp = self._http.request("POST", url, fields=fields)
|
|
45
|
+
else:
|
|
46
|
+
body = json.dumps(
|
|
47
|
+
params, ensure_ascii=False, separators=(",", ":")
|
|
48
|
+
).encode("utf-8")
|
|
49
|
+
resp = self._http.request(
|
|
50
|
+
"POST", url, body=body,
|
|
51
|
+
headers={"Content-Type": "application/json"},
|
|
52
|
+
)
|
|
53
|
+
except urllib3.exceptions.HTTPError as e:
|
|
54
|
+
log.error("HTTP error calling %s: %s", method, e)
|
|
55
|
+
raise TelegramError(f"HTTP error: {e}") from e
|
|
56
|
+
|
|
57
|
+
return self._parse(resp.data)
|
|
58
|
+
|
|
59
|
+
def stream_file(self, file_path, chunk_size=64 * 1024):
|
|
60
|
+
url = f"{self.file_url}/{file_path}"
|
|
61
|
+
resp = self._http.request("GET", url, preload_content=False)
|
|
62
|
+
try:
|
|
63
|
+
while True:
|
|
64
|
+
chunk = resp.read(chunk_size)
|
|
65
|
+
if not chunk:
|
|
66
|
+
break
|
|
67
|
+
yield chunk
|
|
68
|
+
finally:
|
|
69
|
+
resp.release_conn()
|
|
70
|
+
|
|
71
|
+
def close(self):
|
|
72
|
+
self._http.clear()
|
|
73
|
+
|
|
74
|
+
@staticmethod
|
|
75
|
+
def _parse(raw):
|
|
76
|
+
try:
|
|
77
|
+
payload = json.loads(raw)
|
|
78
|
+
except json.JSONDecodeError:
|
|
79
|
+
raise TelegramError(f"Invalid JSON from Telegram: {raw[:200]!r}")
|
|
80
|
+
if not payload.get("ok"):
|
|
81
|
+
raise TelegramError(
|
|
82
|
+
payload.get("description", "Unknown error"),
|
|
83
|
+
payload.get("error_code"),
|
|
84
|
+
payload,
|
|
85
|
+
)
|
|
86
|
+
return payload["result"]
|
|
87
|
+
|
|
88
|
+
@staticmethod
|
|
89
|
+
def _build_multipart(files, params):
|
|
90
|
+
fields = {}
|
|
91
|
+
for k, v in params.items():
|
|
92
|
+
if v is None:
|
|
93
|
+
continue
|
|
94
|
+
if isinstance(v, (dict, list)):
|
|
95
|
+
fields[k] = json.dumps(v, ensure_ascii=False)
|
|
96
|
+
elif isinstance(v, bool):
|
|
97
|
+
fields[k] = "true" if v else "false"
|
|
98
|
+
else:
|
|
99
|
+
fields[k] = str(v)
|
|
100
|
+
|
|
101
|
+
for k, v in files.items():
|
|
102
|
+
if hasattr(v, "read"):
|
|
103
|
+
data = v.read()
|
|
104
|
+
if isinstance(data, str):
|
|
105
|
+
data = data.encode()
|
|
106
|
+
if len(data) > MAX_UPLOAD_BYTES:
|
|
107
|
+
raise SecurityError(f"File too large: {len(data)} bytes")
|
|
108
|
+
name = safe_filename(getattr(v, "name", k))
|
|
109
|
+
fields[k] = (name, data, "application/octet-stream")
|
|
110
|
+
elif isinstance(v, (bytes, bytearray)):
|
|
111
|
+
if len(v) > MAX_UPLOAD_BYTES:
|
|
112
|
+
raise SecurityError(f"File too large: {len(v)} bytes")
|
|
113
|
+
fields[k] = (f"{safe_filename(k)}.bin", bytes(v),
|
|
114
|
+
"application/octet-stream")
|
|
115
|
+
elif isinstance(v, str) and v.startswith("https://"):
|
|
116
|
+
fields[k] = v
|
|
117
|
+
elif isinstance(v, str) and v.startswith("http://"):
|
|
118
|
+
raise SecurityError("Only HTTPS URLs allowed")
|
|
119
|
+
else:
|
|
120
|
+
raise SecurityError(
|
|
121
|
+
f"Unsupported file for {k!r}: {type(v).__name__}"
|
|
122
|
+
)
|
|
123
|
+
return fields
|