maxbot-chatbot-python 1.1.0__tar.gz → 1.1.1__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.
Files changed (18) hide show
  1. maxbot_chatbot_python-1.1.1/PKG-INFO +17 -0
  2. {maxbot_chatbot_python-1.1.0 → maxbot_chatbot_python-1.1.1}/README.md +4 -1
  3. {maxbot_chatbot_python-1.1.0 → maxbot_chatbot_python-1.1.1}/maxbot_chatbot_python/bot.py +7 -4
  4. {maxbot_chatbot_python-1.1.0 → maxbot_chatbot_python-1.1.1}/maxbot_chatbot_python/notification.py +18 -11
  5. maxbot_chatbot_python-1.1.1/maxbot_chatbot_python.egg-info/PKG-INFO +17 -0
  6. maxbot_chatbot_python-1.1.1/maxbot_chatbot_python.egg-info/requires.txt +3 -0
  7. {maxbot_chatbot_python-1.1.0 → maxbot_chatbot_python-1.1.1}/setup.py +3 -8
  8. maxbot_chatbot_python-1.1.0/PKG-INFO +0 -237
  9. maxbot_chatbot_python-1.1.0/maxbot_chatbot_python.egg-info/PKG-INFO +0 -237
  10. maxbot_chatbot_python-1.1.0/maxbot_chatbot_python.egg-info/requires.txt +0 -3
  11. {maxbot_chatbot_python-1.1.0 → maxbot_chatbot_python-1.1.1}/LICENSE +0 -0
  12. {maxbot_chatbot_python-1.1.0 → maxbot_chatbot_python-1.1.1}/maxbot_chatbot_python/__init__.py +0 -0
  13. {maxbot_chatbot_python-1.1.0 → maxbot_chatbot_python-1.1.1}/maxbot_chatbot_python/router.py +0 -0
  14. {maxbot_chatbot_python-1.1.0 → maxbot_chatbot_python-1.1.1}/maxbot_chatbot_python/state.py +0 -0
  15. {maxbot_chatbot_python-1.1.0 → maxbot_chatbot_python-1.1.1}/maxbot_chatbot_python.egg-info/SOURCES.txt +0 -0
  16. {maxbot_chatbot_python-1.1.0 → maxbot_chatbot_python-1.1.1}/maxbot_chatbot_python.egg-info/dependency_links.txt +0 -0
  17. {maxbot_chatbot_python-1.1.0 → maxbot_chatbot_python-1.1.1}/maxbot_chatbot_python.egg-info/top_level.txt +0 -0
  18. {maxbot_chatbot_python-1.1.0 → maxbot_chatbot_python-1.1.1}/setup.cfg +0 -0
@@ -0,0 +1,17 @@
1
+ Metadata-Version: 2.4
2
+ Name: maxbot-chatbot-python
3
+ Version: 1.1.1
4
+ Summary: Python SDK and Chatbot Framework for MAX API
5
+ Home-page: https://github.com/green-api/maxbot-chatbot-python
6
+ Author: Green-API
7
+ Requires-Python: >=3.12
8
+ License-File: LICENSE
9
+ Requires-Dist: maxbot-api-client-python>=1.1.1
10
+ Requires-Dist: httpx>=0.24.0
11
+ Requires-Dist: pydantic>=2.0.0
12
+ Dynamic: author
13
+ Dynamic: home-page
14
+ Dynamic: license-file
15
+ Dynamic: requires-dist
16
+ Dynamic: requires-python
17
+ Dynamic: summary
@@ -1,4 +1,4 @@
1
- # maxbot-chatbot-python
1
+ # MAX BOT API Chatbot (Python)
2
2
 
3
3
  `maxbot-chatbot-python` — это асинхронный фреймворк для создания масштабируемых ботов для **MAX BOT API** на языке **Python**.
4
4
 
@@ -152,6 +152,9 @@ class PasswordScene(Scene):
152
152
 
153
153
  @bot.router.register("message_created")
154
154
  async def fsm_handler(notification):
155
+ if not notification.state_manager.get(notification.state_id):
156
+ notification.state_manager.create(notification.state_id)
157
+
155
158
  current_scene = notification.get_current_scene()
156
159
  if current_scene:
157
160
  await current_scene.start(notification)
@@ -1,4 +1,5 @@
1
1
  import asyncio
2
+ from maxbot_api_client_python.types.models import GetUpdatesReq
2
3
  from maxbot_chatbot_python.router import Router
3
4
  from maxbot_chatbot_python.notification import Notification
4
5
 
@@ -14,9 +15,11 @@ class Bot:
14
15
 
15
16
  while True:
16
17
  try:
17
- resp = await self.api.subscriptions.GetUpdatesAsync(
18
- marker=self.marker,
19
- timeout=25
18
+ resp = await self.api.subscriptions.get_updates_async(
19
+ GetUpdatesReq(
20
+ marker=self.marker,
21
+ timeout=25
22
+ )
20
23
  )
21
24
 
22
25
  if getattr(resp, 'marker', 0) != 0:
@@ -36,7 +39,7 @@ class Bot:
36
39
  async def process_update(self, update):
37
40
  notif = Notification(
38
41
  update=update,
39
- bot_api=self.api,
42
+ bot=self.api,
40
43
  state_manager=self.state_manager
41
44
  )
42
45
  await self.router.publish(notif)
@@ -1,14 +1,17 @@
1
1
  import asyncio, logging
2
2
 
3
3
  from maxbot_api_client_python import utils
4
- from maxbot_api_client_python.types.models import Attachment, KeyboardButton
4
+ from maxbot_api_client_python.types.models import (
5
+ Attachment, KeyboardButton, SendMessageReq, SendFileReq,
6
+ AnswerCallbackReq, SendActionReq
7
+ )
5
8
 
6
9
  logger = logging.getLogger(__name__)
7
10
 
8
11
  class Notification:
9
- def __init__(self, update, bot_api, state_manager=None):
12
+ def __init__(self, update, bot, state_manager=None):
10
13
  self.update = update
11
- self.bot_api = bot_api
14
+ self.bot = bot
12
15
  self.state_manager = state_manager
13
16
  self.state_id = "global"
14
17
  self.create_state_id()
@@ -21,7 +24,7 @@ class Notification:
21
24
  kwargs["chat_id"] = self.chat_id()
22
25
 
23
26
  try:
24
- await self.bot_api.messages.SendMessageAsync(**kwargs)
27
+ await self.bot.messages.send_message_async(SendMessageReq(**kwargs))
25
28
  logger.info(f"Reply sent to {kwargs['chat_id']}")
26
29
  except Exception as e:
27
30
  logger.error(f"Sending reply error: {e}, target_id: {kwargs['chat_id']}")
@@ -104,7 +107,7 @@ class Notification:
104
107
 
105
108
  for i in range(5):
106
109
  try:
107
- await self.bot_api.helpers.SendFileAsync(**kwargs)
110
+ await self.bot.helpers.send_file_async(SendFileReq(**kwargs))
108
111
  logger.info(f"Media reply sent successfully to {target_id}")
109
112
  return
110
113
  except Exception as e:
@@ -168,9 +171,11 @@ class Notification:
168
171
  raise ValueError("cannot answer callback: update is not a callback")
169
172
 
170
173
  try:
171
- await self.bot_api.messages.AnswerCallbackAsync(
172
- callback_id=self.update.callback.callback_id,
173
- notification=text if text else " "
174
+ await self.bot.messages.answer_callback_async(
175
+ AnswerCallbackReq(
176
+ callback_id=self.update.callback.callback_id,
177
+ notification=text if text else " "
178
+ )
174
179
  )
175
180
  except Exception as e:
176
181
  logger.error(f"AnswerCallback error: {e}")
@@ -182,9 +187,11 @@ class Notification:
182
187
  if chat_id == 0:
183
188
  raise ValueError("missing chat ID")
184
189
 
185
- res = await self.bot_api.chats.SendActionAsync(
186
- chat_id=chat_id,
187
- action=action
190
+ res = await self.bot.chats.send_action_async(
191
+ SendActionReq(
192
+ chat_id=chat_id,
193
+ action=action
194
+ )
188
195
  )
189
196
 
190
197
  if res and not getattr(res, 'success', True):
@@ -0,0 +1,17 @@
1
+ Metadata-Version: 2.4
2
+ Name: maxbot-chatbot-python
3
+ Version: 1.1.1
4
+ Summary: Python SDK and Chatbot Framework for MAX API
5
+ Home-page: https://github.com/green-api/maxbot-chatbot-python
6
+ Author: Green-API
7
+ Requires-Python: >=3.12
8
+ License-File: LICENSE
9
+ Requires-Dist: maxbot-api-client-python>=1.1.1
10
+ Requires-Dist: httpx>=0.24.0
11
+ Requires-Dist: pydantic>=2.0.0
12
+ Dynamic: author
13
+ Dynamic: home-page
14
+ Dynamic: license-file
15
+ Dynamic: requires-dist
16
+ Dynamic: requires-python
17
+ Dynamic: summary
@@ -0,0 +1,3 @@
1
+ maxbot-api-client-python>=1.1.1
2
+ httpx>=0.24.0
3
+ pydantic>=2.0.0
@@ -1,21 +1,16 @@
1
1
  from setuptools import setup, find_packages
2
2
 
3
- with open("README.md", encoding="UTF-8") as file:
4
- long_description = file.read()
5
-
6
3
  setup(
7
4
  name="maxbot-chatbot-python",
8
- version="1.1.0",
5
+ version="1.1.1",
9
6
  description="Python SDK and Chatbot Framework for MAX API",
10
- long_description=long_description,
11
- long_description_content_type="text/markdown",
12
7
  author="Green-API",
13
8
  url="https://github.com/green-api/maxbot-chatbot-python",
14
9
  packages=find_packages(exclude=["examples*"]),
15
10
  install_requires=[
16
- "maxbot-api-client-python>=1.1.0",
11
+ "maxbot-api-client-python>=1.1.1",
17
12
  "httpx>=0.24.0",
18
13
  "pydantic>=2.0.0"
19
14
  ],
20
15
  python_requires=">=3.12",
21
- )
16
+ )
@@ -1,237 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: maxbot-chatbot-python
3
- Version: 1.1.0
4
- Summary: Python SDK and Chatbot Framework for MAX API
5
- Home-page: https://github.com/green-api/maxbot-chatbot-python
6
- Author: Green-API
7
- Requires-Python: >=3.12
8
- Description-Content-Type: text/markdown
9
- License-File: LICENSE
10
- Requires-Dist: maxbot-api-client-python>=1.1.0
11
- Requires-Dist: httpx>=0.24.0
12
- Requires-Dist: pydantic>=2.0.0
13
- Dynamic: author
14
- Dynamic: description
15
- Dynamic: description-content-type
16
- Dynamic: home-page
17
- Dynamic: license-file
18
- Dynamic: requires-dist
19
- Dynamic: requires-python
20
- Dynamic: summary
21
-
22
- # maxbot-chatbot-python
23
-
24
- `maxbot-chatbot-python` — это асинхронный фреймворк для создания масштабируемых ботов для **MAX BOT API** на языке **Python**.
25
-
26
- Построенная на основе [`maxbot_api_client_python`](https://github.com/green-api/maxbot-api-client-python), эта библиотека предоставляет чистый маршрутизатор, автоматическое получение обновлений (*Long Polling*) и надежный менеджер состояний (*FSM*) для построения многошаговых диалоговых сценариев.
27
-
28
- Для использования библиотеки требуется получить токен бота в консоли разработчика **MAX API**.
29
- Ознакомиться с инструкцией можно [по ссылке](https://green-api.com/max-bot-api/docs/before-start/).
30
-
31
- ## API
32
-
33
- Документацию по **REST API MAX** можно найти по ссылке [dev.max.ru/docs-api](https://dev.max.ru/docs-api). Библиотека является оберткой для REST API, поэтому документация по указанной выше ссылке также применима к используемым здесь моделям.
34
-
35
- Документацию по **MAX BOT API** можно найти по ссылке [green-api.com/max-bot-api/docs](https://green-api.com/max-bot-api/docs/).
36
-
37
- ## Поддержка
38
-
39
- [![Support](https://img.shields.io/badge/support@green--api.com-D14836?style=for-the-badge&logo=gmail&logoColor=white)](mailto:support@green-api.com)
40
- [![Support](https://img.shields.io/badge/Telegram-2CA5E0?style=for-the-badge&logo=telegram&logoColor=white)](https://t.me/greenapi_support_ru_bot)
41
- [![Support](https://img.shields.io/badge/WhatsApp-25D366?style=for-the-badge&logo=whatsapp&logoColor=white)](https://wa.me/77780739095)
42
-
43
- ## Руководства и новости
44
-
45
- [![Guides](https://img.shields.io/badge/YouTube-%23FF0000.svg?style=for-the-badge&logo=YouTube&logoColor=white)](https://www.youtube.com/@green-api)
46
- [![News](https://img.shields.io/badge/Telegram-2CA5E0?style=for-the-badge&logo=telegram&logoColor=white)](https://t.me/green_api)
47
- [![News](https://img.shields.io/badge/WhatsApp-25D366?style=for-the-badge&logo=whatsapp&logoColor=white)](https://whatsapp.com/channel/0029VaHUM5TBA1f7cG29nO1C)
48
-
49
- ## Установка
50
-
51
- **Убедитесь, что у вас установлен Python версии 3.12 или выше.**
52
-
53
- ```bash
54
- python --version
55
- ```
56
-
57
- **Установите библиотеку:**
58
-
59
- ```bash
60
- pip install maxbot-chatbot-python
61
- ```
62
-
63
- ---
64
-
65
- ## Использование и примеры
66
-
67
- **Параметры конфигурации:**
68
-
69
- - `base_url` - Базовый URL-адрес серверов платформы MaxBot. Все методы API будут маршрутизироваться по этому корневому адресу. Актуальный адрес указан в [официальной документации](https://dev.max.ru/docs-api).
70
- - `token` - Уникальный секретный ключ авторизации (API-ключ) вашего бота. Получить его можно в личном кабинете после [регистрации или создании бота](https://green-api.com/max-bot-api/docs/before-start/) на платформе [business.max.ru](https://business.max.ru/).
71
- - `ratelimiter` - Встроенный ограничитель частоты запросов. Он контролирует количество исходящих запросов в секунду (RPS), защищая бота от блокировки со стороны сервера за превышение лимитов. Рекомендуемое значение — не менее 25.
72
- - `timeout` - Максимальное время ожидания ответа от сервера (в секундах). Если сервер не ответит в течение этого времени, запрос будет завершен с ошибкой. Оптимальное значение — 30 секунд.
73
-
74
- ### Инициализация бота
75
-
76
- Использование асинхронного контекстного менеджера (`async with API(...)`) гарантирует безопасное закрытие сетевых соединений при остановке бота.
77
-
78
- ```python
79
- import asyncio
80
-
81
- from maxbot_api_client_python import API, Config
82
- from maxbot_chatbot_python import Bot, MapStateManager
83
-
84
- async def main():
85
- cfg = Config(
86
- base_url="https://platform-api.max.ru/",
87
- token="YOUR_BOT_TOKEN",
88
- ratelimiter=25,
89
- timeout=35
90
- )
91
-
92
- async with API(cfg) as api_client:
93
- bot = Bot(api_client)
94
- bot.state_manager = MapStateManager(init_data={})
95
-
96
- polling_task = asyncio.create_task(bot.start_polling())
97
-
98
- try:
99
- await polling_task
100
- except asyncio.CancelledError:
101
- pass
102
-
103
- if __name__ == "__main__":
104
- try:
105
- asyncio.run(main())
106
- except KeyboardInterrupt:
107
- print("Bot stopped by user")
108
- ```
109
-
110
- ### Маршрутизация команд, сообщений и коллбэков
111
-
112
- Встроенный **маршрутизатор** (`Router`) позволяет легко обрабатывать конкретные команды (начинающиеся со слэша `/`) и нажатия на **inline-кнопки** (коллбэки).
113
-
114
- ```python
115
- @bot.router.command("/start")
116
- async def start_command(notification):
117
- await notification.reply("Hello! Welcome to the MAX Bot.")
118
-
119
- @bot.router.register("message_created")
120
- async def ping_handler(notification):
121
- try:
122
- if notification.text() == "ping":
123
- await notification.reply("pong")
124
- except ValueError:
125
- pass
126
-
127
- @bot.router.callback("accept_rules")
128
- async def rules_callback(notification):
129
- await notification.reply("*Thank you for accepting the rules!*", format_type="markdown")
130
- await notification.answer_callback("Success!")
131
- ```
132
-
133
- ### Управление состояниями и Сцены (FSM)
134
-
135
- Для сложных многошаговых диалогов (например, регистрация или анкетирование) используйте **Менеджер состояний** (`StateManager`) и **Сцены** (`Scene`).
136
-
137
- ```python
138
- from maxbot_chatbot_python import Scene
139
-
140
- class RegistrationScene(Scene):
141
- async def start(self, notification):
142
- try:
143
- text = notification.text()
144
- except ValueError:
145
- return
146
-
147
- if text == "/start":
148
- await notification.reply("Let's register! What is your *login*?", "markdown")
149
- return
150
-
151
- if len(text) >= 4:
152
- if notification.state_manager:
153
- notification.state_manager.update_state_data(notification.state_id, {"login": text})
154
-
155
- await notification.reply(f"**Login** `{text}` accepted. Now enter your **password**:", "markdown")
156
- notification.activate_next_scene(PasswordScene())
157
- else:
158
- await notification.reply("Login must be **at least 4 characters long**.", "markdown")
159
-
160
- class PasswordScene(Scene):
161
- async def start(self, notification):
162
- try:
163
- password = notification.text()
164
- except ValueError:
165
- return
166
-
167
- state_data = notification.state_manager.get_state_data(notification.state_id)
168
- login = state_data.get("login", "Unknown")
169
-
170
- await notification.reply(f"Success! Profile created.\nLogin: `{login}`\nPass: `{password}`", "markdown")
171
-
172
- notification.activate_next_scene(RegistrationScene())
173
-
174
- @bot.router.register("message_created")
175
- async def fsm_handler(notification):
176
- current_scene = notification.get_current_scene()
177
- if current_scene:
178
- await current_scene.start(notification)
179
- ```
180
-
181
- ### Ответ с медиафайлами
182
-
183
- Обертка `Notification` содержит готовые асинхронные методы для отправки файлов, геолокаций, стикеров и статусов набора текста.
184
-
185
- ```python
186
- @bot.router.command("/photo")
187
- async def send_photo(notification):
188
- await notification.show_action("sending_photo")
189
-
190
- await notification.reply_with_media(
191
- text="Check out this image!",
192
- format_type="markdown",
193
- file_source="https://storage.yandexcloud.net/sw-prod-03-test/ChatBot/corgi.jpg"
194
- )
195
- ```
196
-
197
- ### Эхо-бот
198
-
199
- ```python
200
- import asyncio
201
-
202
- from maxbot_api_client_python import API, Config
203
- from maxbot_chatbot_python import Bot, MapStateManager
204
-
205
- async def main():
206
- cfg = Config(
207
- base_url="https://platform-api.max.ru/",
208
- token="YOUR_BOT_TOKEN",
209
- ratelimiter=25
210
- )
211
-
212
- async with API(cfg) as api_client:
213
- bot = Bot(api_client)
214
- bot.state_manager = MapStateManager(init_data={})
215
-
216
- @bot.router.register("message_created")
217
- async def echo_handler(notification):
218
- try:
219
- text = notification.text()
220
- await notification.reply(f"**Echo:** {text}", "markdown")
221
- except Exception as e:
222
- print(f"Error handling message: {e}")
223
-
224
- polling_task = asyncio.create_task(bot.start_polling())
225
-
226
- try:
227
- await polling_task
228
- except asyncio.CancelledError:
229
- pass
230
-
231
- if __name__ == "__main__":
232
- try:
233
- asyncio.run(main())
234
- except KeyboardInterrupt:
235
- print("Bot stopped by user (KeyboardInterrupt)")
236
- ```
237
- ```
@@ -1,237 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: maxbot-chatbot-python
3
- Version: 1.1.0
4
- Summary: Python SDK and Chatbot Framework for MAX API
5
- Home-page: https://github.com/green-api/maxbot-chatbot-python
6
- Author: Green-API
7
- Requires-Python: >=3.12
8
- Description-Content-Type: text/markdown
9
- License-File: LICENSE
10
- Requires-Dist: maxbot-api-client-python>=1.1.0
11
- Requires-Dist: httpx>=0.24.0
12
- Requires-Dist: pydantic>=2.0.0
13
- Dynamic: author
14
- Dynamic: description
15
- Dynamic: description-content-type
16
- Dynamic: home-page
17
- Dynamic: license-file
18
- Dynamic: requires-dist
19
- Dynamic: requires-python
20
- Dynamic: summary
21
-
22
- # maxbot-chatbot-python
23
-
24
- `maxbot-chatbot-python` — это асинхронный фреймворк для создания масштабируемых ботов для **MAX BOT API** на языке **Python**.
25
-
26
- Построенная на основе [`maxbot_api_client_python`](https://github.com/green-api/maxbot-api-client-python), эта библиотека предоставляет чистый маршрутизатор, автоматическое получение обновлений (*Long Polling*) и надежный менеджер состояний (*FSM*) для построения многошаговых диалоговых сценариев.
27
-
28
- Для использования библиотеки требуется получить токен бота в консоли разработчика **MAX API**.
29
- Ознакомиться с инструкцией можно [по ссылке](https://green-api.com/max-bot-api/docs/before-start/).
30
-
31
- ## API
32
-
33
- Документацию по **REST API MAX** можно найти по ссылке [dev.max.ru/docs-api](https://dev.max.ru/docs-api). Библиотека является оберткой для REST API, поэтому документация по указанной выше ссылке также применима к используемым здесь моделям.
34
-
35
- Документацию по **MAX BOT API** можно найти по ссылке [green-api.com/max-bot-api/docs](https://green-api.com/max-bot-api/docs/).
36
-
37
- ## Поддержка
38
-
39
- [![Support](https://img.shields.io/badge/support@green--api.com-D14836?style=for-the-badge&logo=gmail&logoColor=white)](mailto:support@green-api.com)
40
- [![Support](https://img.shields.io/badge/Telegram-2CA5E0?style=for-the-badge&logo=telegram&logoColor=white)](https://t.me/greenapi_support_ru_bot)
41
- [![Support](https://img.shields.io/badge/WhatsApp-25D366?style=for-the-badge&logo=whatsapp&logoColor=white)](https://wa.me/77780739095)
42
-
43
- ## Руководства и новости
44
-
45
- [![Guides](https://img.shields.io/badge/YouTube-%23FF0000.svg?style=for-the-badge&logo=YouTube&logoColor=white)](https://www.youtube.com/@green-api)
46
- [![News](https://img.shields.io/badge/Telegram-2CA5E0?style=for-the-badge&logo=telegram&logoColor=white)](https://t.me/green_api)
47
- [![News](https://img.shields.io/badge/WhatsApp-25D366?style=for-the-badge&logo=whatsapp&logoColor=white)](https://whatsapp.com/channel/0029VaHUM5TBA1f7cG29nO1C)
48
-
49
- ## Установка
50
-
51
- **Убедитесь, что у вас установлен Python версии 3.12 или выше.**
52
-
53
- ```bash
54
- python --version
55
- ```
56
-
57
- **Установите библиотеку:**
58
-
59
- ```bash
60
- pip install maxbot-chatbot-python
61
- ```
62
-
63
- ---
64
-
65
- ## Использование и примеры
66
-
67
- **Параметры конфигурации:**
68
-
69
- - `base_url` - Базовый URL-адрес серверов платформы MaxBot. Все методы API будут маршрутизироваться по этому корневому адресу. Актуальный адрес указан в [официальной документации](https://dev.max.ru/docs-api).
70
- - `token` - Уникальный секретный ключ авторизации (API-ключ) вашего бота. Получить его можно в личном кабинете после [регистрации или создании бота](https://green-api.com/max-bot-api/docs/before-start/) на платформе [business.max.ru](https://business.max.ru/).
71
- - `ratelimiter` - Встроенный ограничитель частоты запросов. Он контролирует количество исходящих запросов в секунду (RPS), защищая бота от блокировки со стороны сервера за превышение лимитов. Рекомендуемое значение — не менее 25.
72
- - `timeout` - Максимальное время ожидания ответа от сервера (в секундах). Если сервер не ответит в течение этого времени, запрос будет завершен с ошибкой. Оптимальное значение — 30 секунд.
73
-
74
- ### Инициализация бота
75
-
76
- Использование асинхронного контекстного менеджера (`async with API(...)`) гарантирует безопасное закрытие сетевых соединений при остановке бота.
77
-
78
- ```python
79
- import asyncio
80
-
81
- from maxbot_api_client_python import API, Config
82
- from maxbot_chatbot_python import Bot, MapStateManager
83
-
84
- async def main():
85
- cfg = Config(
86
- base_url="https://platform-api.max.ru/",
87
- token="YOUR_BOT_TOKEN",
88
- ratelimiter=25,
89
- timeout=35
90
- )
91
-
92
- async with API(cfg) as api_client:
93
- bot = Bot(api_client)
94
- bot.state_manager = MapStateManager(init_data={})
95
-
96
- polling_task = asyncio.create_task(bot.start_polling())
97
-
98
- try:
99
- await polling_task
100
- except asyncio.CancelledError:
101
- pass
102
-
103
- if __name__ == "__main__":
104
- try:
105
- asyncio.run(main())
106
- except KeyboardInterrupt:
107
- print("Bot stopped by user")
108
- ```
109
-
110
- ### Маршрутизация команд, сообщений и коллбэков
111
-
112
- Встроенный **маршрутизатор** (`Router`) позволяет легко обрабатывать конкретные команды (начинающиеся со слэша `/`) и нажатия на **inline-кнопки** (коллбэки).
113
-
114
- ```python
115
- @bot.router.command("/start")
116
- async def start_command(notification):
117
- await notification.reply("Hello! Welcome to the MAX Bot.")
118
-
119
- @bot.router.register("message_created")
120
- async def ping_handler(notification):
121
- try:
122
- if notification.text() == "ping":
123
- await notification.reply("pong")
124
- except ValueError:
125
- pass
126
-
127
- @bot.router.callback("accept_rules")
128
- async def rules_callback(notification):
129
- await notification.reply("*Thank you for accepting the rules!*", format_type="markdown")
130
- await notification.answer_callback("Success!")
131
- ```
132
-
133
- ### Управление состояниями и Сцены (FSM)
134
-
135
- Для сложных многошаговых диалогов (например, регистрация или анкетирование) используйте **Менеджер состояний** (`StateManager`) и **Сцены** (`Scene`).
136
-
137
- ```python
138
- from maxbot_chatbot_python import Scene
139
-
140
- class RegistrationScene(Scene):
141
- async def start(self, notification):
142
- try:
143
- text = notification.text()
144
- except ValueError:
145
- return
146
-
147
- if text == "/start":
148
- await notification.reply("Let's register! What is your *login*?", "markdown")
149
- return
150
-
151
- if len(text) >= 4:
152
- if notification.state_manager:
153
- notification.state_manager.update_state_data(notification.state_id, {"login": text})
154
-
155
- await notification.reply(f"**Login** `{text}` accepted. Now enter your **password**:", "markdown")
156
- notification.activate_next_scene(PasswordScene())
157
- else:
158
- await notification.reply("Login must be **at least 4 characters long**.", "markdown")
159
-
160
- class PasswordScene(Scene):
161
- async def start(self, notification):
162
- try:
163
- password = notification.text()
164
- except ValueError:
165
- return
166
-
167
- state_data = notification.state_manager.get_state_data(notification.state_id)
168
- login = state_data.get("login", "Unknown")
169
-
170
- await notification.reply(f"Success! Profile created.\nLogin: `{login}`\nPass: `{password}`", "markdown")
171
-
172
- notification.activate_next_scene(RegistrationScene())
173
-
174
- @bot.router.register("message_created")
175
- async def fsm_handler(notification):
176
- current_scene = notification.get_current_scene()
177
- if current_scene:
178
- await current_scene.start(notification)
179
- ```
180
-
181
- ### Ответ с медиафайлами
182
-
183
- Обертка `Notification` содержит готовые асинхронные методы для отправки файлов, геолокаций, стикеров и статусов набора текста.
184
-
185
- ```python
186
- @bot.router.command("/photo")
187
- async def send_photo(notification):
188
- await notification.show_action("sending_photo")
189
-
190
- await notification.reply_with_media(
191
- text="Check out this image!",
192
- format_type="markdown",
193
- file_source="https://storage.yandexcloud.net/sw-prod-03-test/ChatBot/corgi.jpg"
194
- )
195
- ```
196
-
197
- ### Эхо-бот
198
-
199
- ```python
200
- import asyncio
201
-
202
- from maxbot_api_client_python import API, Config
203
- from maxbot_chatbot_python import Bot, MapStateManager
204
-
205
- async def main():
206
- cfg = Config(
207
- base_url="https://platform-api.max.ru/",
208
- token="YOUR_BOT_TOKEN",
209
- ratelimiter=25
210
- )
211
-
212
- async with API(cfg) as api_client:
213
- bot = Bot(api_client)
214
- bot.state_manager = MapStateManager(init_data={})
215
-
216
- @bot.router.register("message_created")
217
- async def echo_handler(notification):
218
- try:
219
- text = notification.text()
220
- await notification.reply(f"**Echo:** {text}", "markdown")
221
- except Exception as e:
222
- print(f"Error handling message: {e}")
223
-
224
- polling_task = asyncio.create_task(bot.start_polling())
225
-
226
- try:
227
- await polling_task
228
- except asyncio.CancelledError:
229
- pass
230
-
231
- if __name__ == "__main__":
232
- try:
233
- asyncio.run(main())
234
- except KeyboardInterrupt:
235
- print("Bot stopped by user (KeyboardInterrupt)")
236
- ```
237
- ```
@@ -1,3 +0,0 @@
1
- maxbot-api-client-python>=1.1.0
2
- httpx>=0.24.0
3
- pydantic>=2.0.0