umaxbot 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.
umaxbot-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,69 @@
1
+ Metadata-Version: 2.4
2
+ Name: umaxbot
3
+ Version: 0.1.0
4
+ Summary: Async framework for building bots for MAX messenger (aiogram-style)
5
+ Home-page: https://github.com/werdset/maxbot
6
+ Author: werdset
7
+ Author-email: vladimirwerdset@gmail.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Framework :: AsyncIO
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.8
13
+ Description-Content-Type: text/markdown
14
+ Requires-Dist: httpx>=0.24.0
15
+ Requires-Dist: pydantic>=1.10.0
16
+ Dynamic: author
17
+ Dynamic: author-email
18
+ Dynamic: classifier
19
+ Dynamic: description
20
+ Dynamic: description-content-type
21
+ Dynamic: home-page
22
+ Dynamic: requires-dist
23
+ Dynamic: requires-python
24
+ Dynamic: summary
25
+
26
+ # maxbot
27
+
28
+ Асинхронный Python-фреймворк для создания ботов в мессенджере [MAX](https://max.ru).
29
+
30
+ 🎯 Синтаксис как у `aiogram`
31
+ 🚀 Поддержка polling
32
+ 💬 Inline-кнопки
33
+ 📦 Простая отправка сообщений
34
+
35
+ ## Установка
36
+
37
+ ```bash
38
+ pip install maxbot
39
+ ```
40
+
41
+ ## Пример
42
+
43
+ ```python
44
+ from maxbot.bot import Bot
45
+ from maxbot.dispatcher import Dispatcher
46
+ from maxbot.types import InlineKeyboardMarkup, InlineKeyboardButton, Message
47
+
48
+ bot = Bot("YourToken")
49
+ dp = Dispatcher(bot)
50
+
51
+ @dp.message()
52
+ async def on_message(message: Message):
53
+ keyboard = InlineKeyboardMarkup(inline_keyboard=[
54
+ [InlineKeyboardButton(text="👋 Поздороваться", callback_data="hello")]
55
+ ])
56
+ await bot.send_message(
57
+ chat_id = message.sender.id,
58
+ text="Привет! Нажми на кнопку ниже:",
59
+ notify=True,
60
+ reply_markup=keyboard,
61
+ format="markdown"
62
+ )
63
+
64
+ @dp.callback()
65
+ async def on_callback(cb):
66
+ if cb.payload == "hello":
67
+ await bot.send_message(cb.user.id, "Приятно познакомиться!")
68
+
69
+ ```
@@ -0,0 +1,44 @@
1
+ # maxbot
2
+
3
+ Асинхронный Python-фреймворк для создания ботов в мессенджере [MAX](https://max.ru).
4
+
5
+ 🎯 Синтаксис как у `aiogram`
6
+ 🚀 Поддержка polling
7
+ 💬 Inline-кнопки
8
+ 📦 Простая отправка сообщений
9
+
10
+ ## Установка
11
+
12
+ ```bash
13
+ pip install maxbot
14
+ ```
15
+
16
+ ## Пример
17
+
18
+ ```python
19
+ from maxbot.bot import Bot
20
+ from maxbot.dispatcher import Dispatcher
21
+ from maxbot.types import InlineKeyboardMarkup, InlineKeyboardButton, Message
22
+
23
+ bot = Bot("YourToken")
24
+ dp = Dispatcher(bot)
25
+
26
+ @dp.message()
27
+ async def on_message(message: Message):
28
+ keyboard = InlineKeyboardMarkup(inline_keyboard=[
29
+ [InlineKeyboardButton(text="👋 Поздороваться", callback_data="hello")]
30
+ ])
31
+ await bot.send_message(
32
+ chat_id = message.sender.id,
33
+ text="Привет! Нажми на кнопку ниже:",
34
+ notify=True,
35
+ reply_markup=keyboard,
36
+ format="markdown"
37
+ )
38
+
39
+ @dp.callback()
40
+ async def on_callback(cb):
41
+ if cb.payload == "hello":
42
+ await bot.send_message(cb.user.id, "Приятно познакомиться!")
43
+
44
+ ```
File without changes
@@ -0,0 +1,216 @@
1
+ import mimetypes
2
+
3
+ import httpx
4
+ from typing import Optional
5
+ from .types import InlineKeyboardMarkup
6
+
7
+ class Bot:
8
+ BASE_URL = "https://botapi.max.ru"
9
+
10
+ def __init__(self, token: str):
11
+ self.token = token
12
+ self.base_url = self.BASE_URL
13
+ self.client = httpx.AsyncClient()
14
+
15
+ async def _request(self, method: str, path: str, params=None, json=None):
16
+ if params is None:
17
+ params = {}
18
+ params["access_token"] = self.token # 👈 всегда добавляем токен
19
+ headers = {"Content-Type": "application/json"}
20
+ try:
21
+ response = await self.client.request(
22
+ method=method,
23
+ url=self.base_url + path,
24
+ params=params,
25
+ json=json,
26
+ headers=headers,
27
+ timeout=httpx.Timeout(30.0)
28
+ )
29
+ response.raise_for_status()
30
+ return response.json()
31
+ except httpx.HTTPStatusError as e:
32
+ print(f"[Bot] Ошибка запроса: {e}")
33
+ print(f"[Bot] Ответ сервера: {e.response.status_code} {e.response.text}") # 👈 вот это ключ
34
+ raise
35
+ except httpx.ReadTimeout:
36
+ print("[Bot] Таймаут при ожидании ответа (нормально для long polling)")
37
+ return {}
38
+
39
+ async def get_me(self):
40
+ return await self._request("GET", "/me")
41
+
42
+ async def send_message(
43
+ self,
44
+ chat_id: int,
45
+ text: str,
46
+ reply_markup: Optional[InlineKeyboardMarkup] = None,
47
+ notify: bool = True,
48
+ format: Optional[str] = None
49
+ ):
50
+ params = {
51
+ "access_token": self.token,
52
+ "user_id": chat_id,
53
+ # API может ожидать "true"/"false"
54
+ }
55
+
56
+ json_body = {
57
+ "text": text,
58
+ "notify": notify,
59
+ }
60
+
61
+ if format:
62
+ json_body["format"] = format
63
+
64
+ if reply_markup:
65
+ json_body["attachments"] = [reply_markup.to_attachment()]
66
+
67
+ print("[send_message] params:", params)
68
+ print("[send_message] json:", json_body)
69
+
70
+ return await self.client.post(
71
+ f"{self.base_url}/messages",
72
+ params=params,
73
+ json=json_body,
74
+ headers={"Content-Type": "application/json"},
75
+ timeout=httpx.Timeout(30.0)
76
+ )
77
+
78
+ async def answer_callback(self, callback_id: str, notification: str):
79
+ print("[Bot] ➤ Ответ на callback:", {
80
+ "callback_id": callback_id,
81
+ "notification": notification
82
+ })
83
+ return await self._request(
84
+ "POST",
85
+ "/answers",
86
+ params={"callback_id": callback_id},
87
+ json={"notification": notification}
88
+ )
89
+
90
+ async def update_message(self,
91
+ message_id: str,
92
+ text: str,
93
+ reply_markup: Optional[InlineKeyboardMarkup] = None,
94
+ notify: bool = True,
95
+ format: Optional[str] = None):
96
+
97
+ params = {
98
+ "access_token": self.token,
99
+ "message_id": message_id,
100
+ # API может ожидать "true"/"false"
101
+ }
102
+
103
+ json_body = {
104
+ "text": text,
105
+ "notify": notify,
106
+ }
107
+
108
+ if format:
109
+ json_body["format"] = format
110
+
111
+ if reply_markup:
112
+ json_body["attachments"] = [reply_markup.to_attachment()]
113
+
114
+ print("[send_message] params:", params)
115
+ print("[send_message] json:", json_body)
116
+
117
+ return await self.client.put(
118
+ f"{self.base_url}/messages",
119
+ params=params,
120
+ json=json_body,
121
+ headers={"Content-Type": "application/json"},
122
+ timeout=httpx.Timeout(30.0)
123
+ )
124
+
125
+
126
+ async def delete_message(self, message_id: str):
127
+ params = {
128
+ "access_token": self.token,
129
+ "message_id": message_id,
130
+ # API может ожидать "true"/"false"
131
+ }
132
+
133
+ return await self.client.delete(
134
+ f"{self.base_url}/messages",
135
+ params=params,
136
+ headers={"Content-Type": "application/json"},
137
+ timeout=httpx.Timeout(30.0)
138
+ )
139
+
140
+
141
+ async def upload_file(self, file_path: str, media_type: str) -> str:
142
+ # 1. Получаем URL загрузки
143
+ resp = await self._request(
144
+ "POST",
145
+ "/uploads",
146
+ params={"type": media_type}
147
+ )
148
+ upload_url = resp["url"]
149
+
150
+ # 2. Загружаем файл по upload_url
151
+ mime_type, _ = mimetypes.guess_type(file_path)
152
+ files = {"data": (file_path, open(file_path, "rb"), mime_type or "application/octet-stream")}
153
+
154
+ async with httpx.AsyncClient() as client:
155
+ upload_resp = await client.post(upload_url, files=files)
156
+ upload_resp.raise_for_status()
157
+ result = upload_resp.json()
158
+ return result["token"]
159
+
160
+ async def send_file(
161
+ self,
162
+ chat_id: int,
163
+ file_path: str,
164
+ media_type: str,
165
+ text: str = "",
166
+ reply_markup: Optional[InlineKeyboardMarkup] = None,
167
+ notify: bool = True,
168
+ format: Optional[str] = None
169
+ ):
170
+ # Загрузка файла на сервер
171
+ token = await self.upload_file(file_path, media_type)
172
+
173
+ # Базовое вложение — медиафайл
174
+ attachments = [
175
+ {
176
+ "type": media_type,
177
+ "payload": {"token": token}
178
+ }
179
+ ]
180
+
181
+ # Если передана клавиатура — добавляем её как вложение
182
+ if reply_markup:
183
+ attachments.append(reply_markup.to_attachment())
184
+
185
+ # Параметры и тело запроса — как в send_message
186
+ params = {
187
+ "access_token": self.token,
188
+ "user_id": chat_id,
189
+ }
190
+
191
+ json_body = {
192
+ "text": text,
193
+ "notify": notify,
194
+ "attachments": attachments,
195
+ }
196
+
197
+ if format:
198
+ json_body["format"] = format
199
+
200
+ print("[send_file] params:", params)
201
+ print("[send_file] json:", json_body)
202
+
203
+ return await self.client.post(
204
+ f"{self.base_url}/messages",
205
+ params=params,
206
+ json=json_body,
207
+ headers={"Content-Type": "application/json"},
208
+ timeout=httpx.Timeout(30.0)
209
+ )
210
+
211
+
212
+
213
+
214
+
215
+
216
+
@@ -0,0 +1,95 @@
1
+ import asyncio
2
+
3
+ from filters import FilterExpression
4
+ from .router import Router
5
+ from .types import Message, Callback
6
+ from maxbot.bot import Bot
7
+ from typing import Callable, List
8
+
9
+ class Dispatcher:
10
+ def __init__(self, bot: Bot):
11
+ self.bot = bot
12
+ self.message_handlers: List[tuple[Callable, FilterExpression | None]] = []
13
+ self.callback_handlers: List[tuple[Callable, FilterExpression | None]] = []
14
+ self.routers: list[Router] = []
15
+
16
+ def message(self, filter: FilterExpression = None):
17
+ def decorator(func):
18
+ self.message_handlers.append((func, filter))
19
+ return func
20
+
21
+ return decorator
22
+
23
+ def include_router(self, router):
24
+ self.routers.append(router)
25
+
26
+ def callback(self, filter: FilterExpression = None):
27
+ def decorator(func):
28
+ self.callback_handlers.append((func, filter))
29
+ return func
30
+
31
+ return decorator
32
+
33
+ async def _polling(self):
34
+ marker = 0
35
+ while True:
36
+ try:
37
+ response = await self.bot._request("GET", "/updates", params={
38
+ "access_token": self.bot.token,
39
+ "offset": marker,
40
+ })
41
+
42
+ updates = response.get("updates", [])
43
+ for update in updates:
44
+ print(f"🔔 Update: {update}")
45
+ update_type = update.get("update_type")
46
+
47
+ if update_type == "message_created":
48
+ msg = Message.from_raw(update["message"])
49
+ for func, flt in self.message_handlers:
50
+ if flt is None or flt.check(msg):
51
+ await func(msg)
52
+
53
+ for router in self.routers:
54
+ for func, flt in router.message_handlers:
55
+ if flt is None or flt.check(msg):
56
+ await func(msg)
57
+
58
+
59
+ elif update_type == "message_callback":
60
+
61
+ try:
62
+
63
+ cb = Callback(**update["callback"])
64
+
65
+ for func, flt in self.callback_handlers:
66
+ if flt is None or flt.check(cb):
67
+ await func(cb)
68
+
69
+ for router in self.routers:
70
+ for func, flt in router.callback_handlers:
71
+ if flt is None or flt.check(cb):
72
+ await func(cb)
73
+
74
+ except Exception as e:
75
+
76
+ print(f"[Dispatcher] Ошибка в обработке callback: {e}")
77
+
78
+ print(f"[Dispatcher] Payload:\n{update}")
79
+
80
+ elif update_type == "bot_started":
81
+ print("🚀 Бот запущен новым пользователем!")
82
+ # можешь тут вызывать специальные хендлеры
83
+
84
+ # обновляем offset/marker
85
+ marker = response.get("marker", marker)
86
+
87
+ except Exception as e:
88
+ print(f"[Dispatcher] Ошибка: {type(e).__name__}: {e}")
89
+ import traceback
90
+ traceback.print_exc()
91
+
92
+ await asyncio.sleep(1)
93
+
94
+ def run_polling(self):
95
+ asyncio.run(self._polling())
@@ -0,0 +1,26 @@
1
+ class FilterExpression:
2
+ def __init__(self, attr: str):
3
+ self.attr = attr
4
+ self.op = None
5
+ self.value = None
6
+
7
+ def __eq__(self, other):
8
+ self.op = "eq"
9
+ self.value = other
10
+ return self
11
+
12
+ def check(self, data):
13
+ value = data
14
+ for part in self.attr.split("."):
15
+ value = getattr(value, part, None)
16
+ if self.op == "eq":
17
+ return value == self.value
18
+ return False
19
+
20
+
21
+ class FMeta:
22
+ def __getattr__(self, item):
23
+ return FilterExpression(item)
24
+
25
+
26
+ F = FMeta()
@@ -0,0 +1,19 @@
1
+ from typing import Callable, Union, List, Tuple
2
+ from .filters import FilterExpression
3
+
4
+ class Router:
5
+ def __init__(self):
6
+ self.message_handlers: List[Tuple[Callable, Union[FilterExpression, None]]] = []
7
+ self.callback_handlers: List[Tuple[Callable, Union[FilterExpression, None]]] = []
8
+
9
+ def message(self, filter: FilterExpression = None):
10
+ def decorator(func):
11
+ self.message_handlers.append((func, filter))
12
+ return func
13
+ return decorator
14
+
15
+ def callback(self, filter: FilterExpression = None):
16
+ def decorator(func):
17
+ self.callback_handlers.append((func, filter))
18
+ return func
19
+ return decorator
@@ -0,0 +1,60 @@
1
+ from pydantic import BaseModel, Field
2
+ from typing import List, Optional
3
+
4
+ class User(BaseModel):
5
+ id: int = Field(alias="user_id")
6
+ first_name: str = ""
7
+ last_name: str = ""
8
+ name: str = ""
9
+
10
+ class Config:
11
+ populate_by_name = True
12
+
13
+ class Chat(BaseModel):
14
+ id: int
15
+ type: str
16
+
17
+ class Message(BaseModel):
18
+ id: str
19
+ text: str
20
+ chat: Chat
21
+ sender: User
22
+
23
+ @classmethod
24
+ def from_raw(cls, raw: dict):
25
+ return cls(
26
+ id=raw["body"]["mid"],
27
+ text=raw["body"]["text"],
28
+ chat=Chat(id=raw["recipient"]["chat_id"], type=raw["recipient"]["chat_type"]),
29
+ sender=User(user_id=raw["sender"]["user_id"], name=raw["sender"]["name"])
30
+ )
31
+
32
+ class Callback(BaseModel):
33
+ callback_id: str
34
+ payload: str
35
+ user: User
36
+
37
+ class InlineKeyboardButton(BaseModel):
38
+ text: str
39
+ callback_data: str
40
+
41
+ def to_dict(self):
42
+ return {
43
+ "type": "callback",
44
+ "text": self.text,
45
+ "payload": self.callback_data
46
+ }
47
+
48
+ class InlineKeyboardMarkup(BaseModel):
49
+ inline_keyboard: List[List[InlineKeyboardButton]]
50
+
51
+ def to_attachment(self):
52
+ return {
53
+ "type": "inline_keyboard",
54
+ "payload": {
55
+ "buttons": [
56
+ [button.to_dict() for button in row]
57
+ for row in self.inline_keyboard
58
+ ]
59
+ }
60
+ }
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
umaxbot-0.1.0/setup.py ADDED
@@ -0,0 +1,25 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name="umaxbot",
5
+ version="0.1.0",
6
+ description="Async framework for building bots for MAX messenger (aiogram-style)",
7
+ long_description=open("README.md", encoding="utf-8").read(),
8
+ long_description_content_type="text/markdown",
9
+ author="werdset",
10
+ author_email="vladimirwerdset@gmail.com",
11
+ url="https://github.com/werdset/maxbot",
12
+ packages=find_packages(),
13
+ install_requires=[
14
+ "httpx>=0.24.0",
15
+ "pydantic>=1.10.0"
16
+ ],
17
+ python_requires=">=3.8",
18
+ classifiers=[
19
+ "Programming Language :: Python :: 3",
20
+ "Framework :: AsyncIO",
21
+ "License :: OSI Approved :: MIT License",
22
+ "Operating System :: OS Independent",
23
+ ],
24
+ )
25
+
@@ -0,0 +1,69 @@
1
+ Metadata-Version: 2.4
2
+ Name: umaxbot
3
+ Version: 0.1.0
4
+ Summary: Async framework for building bots for MAX messenger (aiogram-style)
5
+ Home-page: https://github.com/werdset/maxbot
6
+ Author: werdset
7
+ Author-email: vladimirwerdset@gmail.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Framework :: AsyncIO
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.8
13
+ Description-Content-Type: text/markdown
14
+ Requires-Dist: httpx>=0.24.0
15
+ Requires-Dist: pydantic>=1.10.0
16
+ Dynamic: author
17
+ Dynamic: author-email
18
+ Dynamic: classifier
19
+ Dynamic: description
20
+ Dynamic: description-content-type
21
+ Dynamic: home-page
22
+ Dynamic: requires-dist
23
+ Dynamic: requires-python
24
+ Dynamic: summary
25
+
26
+ # maxbot
27
+
28
+ Асинхронный Python-фреймворк для создания ботов в мессенджере [MAX](https://max.ru).
29
+
30
+ 🎯 Синтаксис как у `aiogram`
31
+ 🚀 Поддержка polling
32
+ 💬 Inline-кнопки
33
+ 📦 Простая отправка сообщений
34
+
35
+ ## Установка
36
+
37
+ ```bash
38
+ pip install maxbot
39
+ ```
40
+
41
+ ## Пример
42
+
43
+ ```python
44
+ from maxbot.bot import Bot
45
+ from maxbot.dispatcher import Dispatcher
46
+ from maxbot.types import InlineKeyboardMarkup, InlineKeyboardButton, Message
47
+
48
+ bot = Bot("YourToken")
49
+ dp = Dispatcher(bot)
50
+
51
+ @dp.message()
52
+ async def on_message(message: Message):
53
+ keyboard = InlineKeyboardMarkup(inline_keyboard=[
54
+ [InlineKeyboardButton(text="👋 Поздороваться", callback_data="hello")]
55
+ ])
56
+ await bot.send_message(
57
+ chat_id = message.sender.id,
58
+ text="Привет! Нажми на кнопку ниже:",
59
+ notify=True,
60
+ reply_markup=keyboard,
61
+ format="markdown"
62
+ )
63
+
64
+ @dp.callback()
65
+ async def on_callback(cb):
66
+ if cb.payload == "hello":
67
+ await bot.send_message(cb.user.id, "Приятно познакомиться!")
68
+
69
+ ```
@@ -0,0 +1,13 @@
1
+ README.md
2
+ setup.py
3
+ maxbot/__init__.py
4
+ maxbot/bot.py
5
+ maxbot/dispatcher.py
6
+ maxbot/filters.py
7
+ maxbot/router.py
8
+ maxbot/types.py
9
+ umaxbot.egg-info/PKG-INFO
10
+ umaxbot.egg-info/SOURCES.txt
11
+ umaxbot.egg-info/dependency_links.txt
12
+ umaxbot.egg-info/requires.txt
13
+ umaxbot.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ httpx>=0.24.0
2
+ pydantic>=1.10.0
@@ -0,0 +1 @@
1
+ maxbot