umaxbot 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.
maxbot/__init__.py ADDED
File without changes
maxbot/bot.py ADDED
@@ -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
+
maxbot/dispatcher.py ADDED
@@ -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())
maxbot/filters.py ADDED
@@ -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()
maxbot/router.py ADDED
@@ -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
maxbot/types.py ADDED
@@ -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,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,10 @@
1
+ maxbot/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ maxbot/bot.py,sha256=jgxlOmdJpaPdkJodXtu7B_3TTtvnwZaP1qBkN6qvxP4,6544
3
+ maxbot/dispatcher.py,sha256=7lCJBUgfAJdCx5M-8ztGYOvvVr8L3wLraa4_0VmSqDg,3422
4
+ maxbot/filters.py,sha256=KmoGMlCddMKEXj_Si2GMeCV8dchjlL1pKJPBWXyY7nU,585
5
+ maxbot/router.py,sha256=jQbAh50szMAhQpa7j_J2nc7r2qbi1zAiMFy16N6bgBI,709
6
+ maxbot/types.py,sha256=jE9KCgx9dXi2PGaL2ME4QZuVyPyyJncMZSnto7HPYTk,1417
7
+ umaxbot-0.1.0.dist-info/METADATA,sha256=SsXzSubdBvcsQAQ1420IVusc_gNJ2aldpibE7aC-3R0,1974
8
+ umaxbot-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
9
+ umaxbot-0.1.0.dist-info/top_level.txt,sha256=uDZb__8IlX6OR8gSOBw1OAmd6FpoDe8tLYgVR2lwJSM,7
10
+ umaxbot-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ maxbot