maxibot 0.98.1__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.
maxibot/util.py ADDED
@@ -0,0 +1,98 @@
1
+ from io import BytesIO
2
+ from typing import Union
3
+
4
+ try:
5
+ # noinspection PyPackageRequirements
6
+ from PIL import Image
7
+ pil_imported = True
8
+ except ImportError:
9
+ pil_imported = False
10
+
11
+
12
+ def is_command(text: str) -> bool:
13
+ """
14
+ Проверка, является ли строка командой
15
+
16
+ :param text: строка
17
+ :type text: str
18
+ :return: Флаг, является ли строка командой
19
+ :rtype: bool
20
+ """
21
+ if text is None:
22
+ return False
23
+ return text.startswith('/')
24
+
25
+
26
+ def extract_command(text: str) -> Union[str, None]:
27
+ """
28
+ Вытаскивает команду из текста сообщения
29
+
30
+ :param text: Description
31
+ :type text: str
32
+ :return: Description
33
+ :rtype: Union[str, None]
34
+ """
35
+ if text is None:
36
+ return None
37
+ return text.split()[0].split('@')[0][1:] if is_command(text) else None
38
+
39
+
40
+ def is_pil_image(var) -> bool:
41
+ """
42
+ Returns True if the given object is a PIL.Image.Image object.
43
+
44
+ :param var: object to be checked
45
+ :type var: :obj:`object`
46
+
47
+ :return: True if the given object is a PIL.Image.Image object.
48
+ :rtype: :obj:`bool`
49
+ """
50
+ return pil_imported and isinstance(var, Image.Image)
51
+
52
+
53
+ def pil_image_to_bytes(image, extension='JPEG', quality='web_low') -> bool:
54
+ """
55
+ Returns True if the given object is a PIL.Image.Image object.
56
+
57
+ :param var: object to be checked
58
+ :type var: :obj:`object`
59
+
60
+ :return: True if the given object is a PIL.Image.Image object.
61
+ :rtype: :obj:`bool`
62
+ """
63
+ if pil_imported:
64
+ photoBuffer = BytesIO()
65
+ image.convert('RGB').save(photoBuffer, extension, quality=quality)
66
+ photoBuffer.seek(0)
67
+ return photoBuffer
68
+ else:
69
+ raise RuntimeError('PIL module is not imported')
70
+
71
+
72
+ def get_text(media):
73
+ """
74
+ Метод получения текста из media
75
+
76
+ :param media: Объект медиа
77
+ """
78
+ try:
79
+ text = media.caption
80
+ except Exception:
81
+ text = None
82
+ finally:
83
+ return text
84
+
85
+
86
+ def get_parce_mode(media, parse_mode: str):
87
+ """
88
+ Метод получения parce_mode из media
89
+
90
+ :param media: Объект медиа
91
+ :param parse_mode: Тип парсинга раметки
92
+ """
93
+ try:
94
+ parse_mode_res = media.parse_mode.lower()
95
+ except Exception:
96
+ parse_mode_res = parse_mode.lower()
97
+ finally:
98
+ return parse_mode_res
@@ -0,0 +1,56 @@
1
+ Metadata-Version: 2.4
2
+ Name: maxibot
3
+ Version: 0.98.1
4
+ Summary: Library for build bot in MAX
5
+ Description-Content-Type: text/markdown
6
+ Requires-Dist: requests==2.32.5
7
+
8
+ ## Быстрый старт
9
+ Необходимо установить библиотеку
10
+ ```sh
11
+ pip install -i https://test.pypi.org/simple/ maxibot
12
+ ```
13
+ ## Просто эхо-бот
14
+ Необходимо создать файл `echo_bot.py` и добавить в него следующий код.
15
+ Для начала надо проинициализировать бота, делается это следующим образом:
16
+ ```python
17
+ from maxibot import MaxiBot
18
+
19
+ bot = maxibot.Maxibot("TOKEN")
20
+ ```
21
+ После этой декларации нам нужно зарегистрировать так называемых обработчиков сообщений. Обработчики сообщений определяют фильтры, которые должно проходить сообщение. Если сообщение проходит через фильтр, вызывается декорированная функция и входящее сообщение передается в качестве аргумента.
22
+
23
+ Определите определим обработчик сообщений, который обрабатывает входящие `/start` и `/help` команды.
24
+ ```python
25
+ @bot.message_handler(commands=['start', 'help'])
26
+ def send_welcome(message):
27
+ bot.send_message(message, "Привет! Как дела?")
28
+ ```
29
+ Добавим ещё один обработчик сообщения, который будет повторять отправленный текст:
30
+ ```python
31
+ @bot.message_handler(func=lambda m: True)
32
+ def echo_all(message):
33
+ bot.send_message(message, message.text)
34
+ ```
35
+ Для того, чтобы запустить бота, запустим полинг событий следующей командой:
36
+ ```python
37
+ bot.polling()
38
+ ```
39
+ Для простого эхо-бота это всё. Наш файл теперь выглядит так:
40
+ ```python
41
+ from maxibot import MaxiBot
42
+
43
+ bot = maxibot.Maxibot("TOKEN")
44
+
45
+ @bot.message_handler(commands=['start', 'help'])
46
+ def send_welcome(message):
47
+ bot.send_message(message, "Привет! Как дела?")
48
+
49
+ @bot.message_handler(func=lambda m: True)
50
+ def echo_all(message):
51
+ bot.send_message(message, message.text)
52
+
53
+ bot.polling()
54
+ ```
55
+ Чтобы запустить бота, просто откройте терминал и введите `python echo_bot.py`, чтобы запустить бота.
56
+ Проверьте его, отправив команды (`/start` и `/help`) и произвольные текстовые сообщения.
@@ -0,0 +1,11 @@
1
+ maxibot/__init__.py,sha256=yoJtEuiyiEEMAHve9s3UNiPRMc_kqkwZz6WjX30qdTY,24534
2
+ maxibot/apihelper.py,sha256=tX5N7l77GJtCWDXEeCvW2BBDwEnRCYvi_oNm8Hytt1k,9710
3
+ maxibot/types.py,sha256=pYHk-t6pFNypREEesOtQMvOgZlOy0jGXPOwSBe6l2F0,26769
4
+ maxibot/util.py,sha256=Ps263znGfLrHODi6fvYfibhpGOYOzThoQiZoHduwBi0,2545
5
+ maxibot/core/attachments/photo.py,sha256=ZaqSHuIw4ik8bxIS3VOQyD949B2AGyY5GSKSbSvf1Dg,1472
6
+ maxibot/core/network/client.py,sha256=-k9fihDINR5tWbU3IIORE4udiliCrLPIpWfDAW1zuEU,3845
7
+ maxibot/core/network/polling.py,sha256=E7z4SWIyiuFv0UMwRpPCQ0ilhbGAQ8VQ9LBFJVdvQDU,2301
8
+ maxibot-0.98.1.dist-info/METADATA,sha256=fuu7UJvqwclY-A3pd8LG61fPmoUu6VzIGF3g8emhu6w,2808
9
+ maxibot-0.98.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
10
+ maxibot-0.98.1.dist-info/top_level.txt,sha256=WNdB_JJYD7kB8YacJAru3eguPKZ5UIlkQS_opytFaSE,8
11
+ maxibot-0.98.1.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
+ maxibot