irubix 0.9.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.
- irubix-0.9.0/LICENSE +21 -0
- irubix-0.9.0/PKG-INFO +142 -0
- irubix-0.9.0/README.md +119 -0
- irubix-0.9.0/irubix/__init__.py +47 -0
- irubix-0.9.0/irubix/_update.py +60 -0
- irubix-0.9.0/irubix/bale/__init__.py +5 -0
- irubix-0.9.0/irubix/bale/bot.py +230 -0
- irubix-0.9.0/irubix/bot.py +384 -0
- irubix-0.9.0/irubix/soroush/__init__.py +4 -0
- irubix-0.9.0/irubix/soroush/bot.py +280 -0
- irubix-0.9.0/irubix/telegram/__init__.py +3 -0
- irubix-0.9.0/irubix/telegram/bot.py +191 -0
- irubix-0.9.0/irubix.egg-info/PKG-INFO +142 -0
- irubix-0.9.0/irubix.egg-info/SOURCES.txt +23 -0
- irubix-0.9.0/irubix.egg-info/dependency_links.txt +1 -0
- irubix-0.9.0/irubix.egg-info/top_level.txt +1 -0
- irubix-0.9.0/setup.cfg +4 -0
- irubix-0.9.0/setup.py +26 -0
- irubix-0.9.0/tests/test_bale_api.py +59 -0
- irubix-0.9.0/tests/test_lightweight_import.py +20 -0
- irubix-0.9.0/tests/test_platform_imports.py +23 -0
- irubix-0.9.0/tests/test_public_api.py +154 -0
- irubix-0.9.0/tests/test_soroush_api.py +59 -0
- irubix-0.9.0/tests/test_telegram_api.py +47 -0
- irubix-0.9.0/tests/test_update_check.py +22 -0
irubix-0.9.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 mahdishami
|
|
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.
|
irubix-0.9.0/PKG-INFO
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: irubix
|
|
3
|
+
Version: 0.9.0
|
|
4
|
+
Summary: Async Python bot clients for Rubika, Bale, Soroush Plus and Telegram
|
|
5
|
+
Home-page: https://github.com/adminVIPZEXNET/irubix
|
|
6
|
+
Author: mahdishami
|
|
7
|
+
License: MIT
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Requires-Python: >=3.10
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Dynamic: author
|
|
15
|
+
Dynamic: classifier
|
|
16
|
+
Dynamic: description
|
|
17
|
+
Dynamic: description-content-type
|
|
18
|
+
Dynamic: home-page
|
|
19
|
+
Dynamic: license
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
Dynamic: requires-python
|
|
22
|
+
Dynamic: summary
|
|
23
|
+
|
|
24
|
+
# IRubix
|
|
25
|
+
|
|
26
|
+
کتابخانهای سبک برای ساخت ربات در **روبیکا، بله، سروشپلاس و تلگرام** با Python و `async/await`.
|
|
27
|
+
|
|
28
|
+
## نصب
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
python -m pip install --upgrade irubix
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
برای نصب آخرین نسخه مخزن:
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
python -m pip install --upgrade git+https://github.com/adminVIPZEXNET/irubix.git
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## شروع سریع
|
|
41
|
+
|
|
42
|
+
فقط ماژول پیامرسان و توکن همان ربات را انتخاب کنید.
|
|
43
|
+
|
|
44
|
+
**روبیکا**
|
|
45
|
+
```python
|
|
46
|
+
from irubix import rubika
|
|
47
|
+
|
|
48
|
+
bot = rubika.IRubix("BOT_TOKEN")
|
|
49
|
+
|
|
50
|
+
@bot.command("start")
|
|
51
|
+
async def start(bot, event):
|
|
52
|
+
await event.reply("سلام! ربات فعاله.")
|
|
53
|
+
|
|
54
|
+
bot.run()
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
**بله**
|
|
58
|
+
```python
|
|
59
|
+
from irubix import bale
|
|
60
|
+
|
|
61
|
+
bot = bale.IRubix("BOT_TOKEN")
|
|
62
|
+
|
|
63
|
+
@bot.command("start")
|
|
64
|
+
async def start(bot, event):
|
|
65
|
+
await event.reply("سلام! ربات فعاله.")
|
|
66
|
+
|
|
67
|
+
bot.run()
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
**سروشپلاس**
|
|
71
|
+
```python
|
|
72
|
+
from irubix import soroush
|
|
73
|
+
|
|
74
|
+
bot = soroush.IRubix("BOT_TOKEN")
|
|
75
|
+
|
|
76
|
+
@bot.command("start")
|
|
77
|
+
async def start(bot, event):
|
|
78
|
+
await event.reply("سلام! ربات فعاله.")
|
|
79
|
+
|
|
80
|
+
bot.run()
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
**تلگرام**
|
|
84
|
+
```python
|
|
85
|
+
from irubix import telegram
|
|
86
|
+
|
|
87
|
+
bot = telegram.IRubix("BOT_TOKEN")
|
|
88
|
+
|
|
89
|
+
@bot.command("start")
|
|
90
|
+
async def start(bot, event):
|
|
91
|
+
await event.reply("سلام! ربات فعاله.")
|
|
92
|
+
|
|
93
|
+
bot.run()
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## مستندات
|
|
97
|
+
|
|
98
|
+
- [راهنمای کامل همه کلاسها و نمونهکدها](https://adminvipzexnet.github.io/irubix/classes/)
|
|
99
|
+
|
|
100
|
+
| پیامرسان | راهنما | متدها |
|
|
101
|
+
|---|---|---|
|
|
102
|
+
| روبیکا | [شروع سریع](https://adminvipzexnet.github.io/irubix/bot-guide/) | [فهرست متدها](https://adminvipzexnet.github.io/irubix/bot-methods/) |
|
|
103
|
+
| بله | [شروع سریع](https://adminvipzexnet.github.io/irubix/bale-guide/) | [فهرست متدها](https://adminvipzexnet.github.io/irubix/bale-methods/) |
|
|
104
|
+
| سروشپلاس | [شروع سریع](https://adminvipzexnet.github.io/irubix/soroush-guide/) | [فهرست متدها](https://adminvipzexnet.github.io/irubix/soroush-methods/) |
|
|
105
|
+
| تلگرام | [شروع سریع](https://adminvipzexnet.github.io/irubix/telegram-guide/) | [فهرست متدها](https://adminvipzexnet.github.io/irubix/telegram-methods/) |
|
|
106
|
+
|
|
107
|
+
- [وبسایت مستندات](https://adminvipzexnet.github.io/irubix/)
|
|
108
|
+
- [نمونه خروجیها](https://adminvipzexnet.github.io/irubix/outputs/)
|
|
109
|
+
- [سؤالات متداول](https://adminvipzexnet.github.io/irubix/faq/)
|
|
110
|
+
|
|
111
|
+
## ساختار پروژه
|
|
112
|
+
|
|
113
|
+
```text
|
|
114
|
+
irubix/
|
|
115
|
+
├── __init__.py # ورودی اصلی کتابخانه
|
|
116
|
+
├── bot.py # کلاینت روبیکا
|
|
117
|
+
├── _update.py # بررسی نسخه جدید
|
|
118
|
+
├── bale/ # کلاینت بله
|
|
119
|
+
├── soroush/ # کلاینت سروشپلاس
|
|
120
|
+
└── telegram/ # کلاینت تلگرام
|
|
121
|
+
|
|
122
|
+
docs/ # مستندات
|
|
123
|
+
examples/ # نمونهکدها
|
|
124
|
+
tests/ # تستها
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## نکات
|
|
128
|
+
|
|
129
|
+
- تمام درخواستهای API بهصورت async اجرا میشوند.
|
|
130
|
+
- هسته کتابخانه به کتابخانه جانبی نیاز ندارد.
|
|
131
|
+
- هر پیامرسان فقط API و قابلیتهای رسمی خودش را ارائه میکند.
|
|
132
|
+
- برای غیرفعالکردن بررسی نسخه جدید، متغیر محیطی `IRUBIX_DISABLE_UPDATE_CHECK=1` را تنظیم کنید.
|
|
133
|
+
|
|
134
|
+
## اجرای تستها
|
|
135
|
+
|
|
136
|
+
```bash
|
|
137
|
+
python -m unittest discover -s tests -v
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
## مجوز
|
|
141
|
+
|
|
142
|
+
MIT
|
irubix-0.9.0/README.md
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# IRubix
|
|
2
|
+
|
|
3
|
+
کتابخانهای سبک برای ساخت ربات در **روبیکا، بله، سروشپلاس و تلگرام** با Python و `async/await`.
|
|
4
|
+
|
|
5
|
+
## نصب
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
python -m pip install --upgrade irubix
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
برای نصب آخرین نسخه مخزن:
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
python -m pip install --upgrade git+https://github.com/adminVIPZEXNET/irubix.git
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## شروع سریع
|
|
18
|
+
|
|
19
|
+
فقط ماژول پیامرسان و توکن همان ربات را انتخاب کنید.
|
|
20
|
+
|
|
21
|
+
**روبیکا**
|
|
22
|
+
```python
|
|
23
|
+
from irubix import rubika
|
|
24
|
+
|
|
25
|
+
bot = rubika.IRubix("BOT_TOKEN")
|
|
26
|
+
|
|
27
|
+
@bot.command("start")
|
|
28
|
+
async def start(bot, event):
|
|
29
|
+
await event.reply("سلام! ربات فعاله.")
|
|
30
|
+
|
|
31
|
+
bot.run()
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
**بله**
|
|
35
|
+
```python
|
|
36
|
+
from irubix import bale
|
|
37
|
+
|
|
38
|
+
bot = bale.IRubix("BOT_TOKEN")
|
|
39
|
+
|
|
40
|
+
@bot.command("start")
|
|
41
|
+
async def start(bot, event):
|
|
42
|
+
await event.reply("سلام! ربات فعاله.")
|
|
43
|
+
|
|
44
|
+
bot.run()
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
**سروشپلاس**
|
|
48
|
+
```python
|
|
49
|
+
from irubix import soroush
|
|
50
|
+
|
|
51
|
+
bot = soroush.IRubix("BOT_TOKEN")
|
|
52
|
+
|
|
53
|
+
@bot.command("start")
|
|
54
|
+
async def start(bot, event):
|
|
55
|
+
await event.reply("سلام! ربات فعاله.")
|
|
56
|
+
|
|
57
|
+
bot.run()
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
**تلگرام**
|
|
61
|
+
```python
|
|
62
|
+
from irubix import telegram
|
|
63
|
+
|
|
64
|
+
bot = telegram.IRubix("BOT_TOKEN")
|
|
65
|
+
|
|
66
|
+
@bot.command("start")
|
|
67
|
+
async def start(bot, event):
|
|
68
|
+
await event.reply("سلام! ربات فعاله.")
|
|
69
|
+
|
|
70
|
+
bot.run()
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## مستندات
|
|
74
|
+
|
|
75
|
+
- [راهنمای کامل همه کلاسها و نمونهکدها](https://adminvipzexnet.github.io/irubix/classes/)
|
|
76
|
+
|
|
77
|
+
| پیامرسان | راهنما | متدها |
|
|
78
|
+
|---|---|---|
|
|
79
|
+
| روبیکا | [شروع سریع](https://adminvipzexnet.github.io/irubix/bot-guide/) | [فهرست متدها](https://adminvipzexnet.github.io/irubix/bot-methods/) |
|
|
80
|
+
| بله | [شروع سریع](https://adminvipzexnet.github.io/irubix/bale-guide/) | [فهرست متدها](https://adminvipzexnet.github.io/irubix/bale-methods/) |
|
|
81
|
+
| سروشپلاس | [شروع سریع](https://adminvipzexnet.github.io/irubix/soroush-guide/) | [فهرست متدها](https://adminvipzexnet.github.io/irubix/soroush-methods/) |
|
|
82
|
+
| تلگرام | [شروع سریع](https://adminvipzexnet.github.io/irubix/telegram-guide/) | [فهرست متدها](https://adminvipzexnet.github.io/irubix/telegram-methods/) |
|
|
83
|
+
|
|
84
|
+
- [وبسایت مستندات](https://adminvipzexnet.github.io/irubix/)
|
|
85
|
+
- [نمونه خروجیها](https://adminvipzexnet.github.io/irubix/outputs/)
|
|
86
|
+
- [سؤالات متداول](https://adminvipzexnet.github.io/irubix/faq/)
|
|
87
|
+
|
|
88
|
+
## ساختار پروژه
|
|
89
|
+
|
|
90
|
+
```text
|
|
91
|
+
irubix/
|
|
92
|
+
├── __init__.py # ورودی اصلی کتابخانه
|
|
93
|
+
├── bot.py # کلاینت روبیکا
|
|
94
|
+
├── _update.py # بررسی نسخه جدید
|
|
95
|
+
├── bale/ # کلاینت بله
|
|
96
|
+
├── soroush/ # کلاینت سروشپلاس
|
|
97
|
+
└── telegram/ # کلاینت تلگرام
|
|
98
|
+
|
|
99
|
+
docs/ # مستندات
|
|
100
|
+
examples/ # نمونهکدها
|
|
101
|
+
tests/ # تستها
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## نکات
|
|
105
|
+
|
|
106
|
+
- تمام درخواستهای API بهصورت async اجرا میشوند.
|
|
107
|
+
- هسته کتابخانه به کتابخانه جانبی نیاز ندارد.
|
|
108
|
+
- هر پیامرسان فقط API و قابلیتهای رسمی خودش را ارائه میکند.
|
|
109
|
+
- برای غیرفعالکردن بررسی نسخه جدید، متغیر محیطی `IRUBIX_DISABLE_UPDATE_CHECK=1` را تنظیم کنید.
|
|
110
|
+
|
|
111
|
+
## اجرای تستها
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
python -m unittest discover -s tests -v
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## مجوز
|
|
118
|
+
|
|
119
|
+
MIT
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""IRubix: lightweight async clients for messaging platforms."""
|
|
2
|
+
|
|
3
|
+
from importlib import import_module
|
|
4
|
+
|
|
5
|
+
from .bot import Bot, Event, IRubix, RubikaAPIError
|
|
6
|
+
|
|
7
|
+
__author__ = "mahdishami"
|
|
8
|
+
__version__ = "0.9.0"
|
|
9
|
+
|
|
10
|
+
from ._update import check_for_updates
|
|
11
|
+
|
|
12
|
+
check_for_updates(__version__)
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"IRubix",
|
|
16
|
+
"Bot",
|
|
17
|
+
"Event",
|
|
18
|
+
"RubikaAPIError",
|
|
19
|
+
"rubika",
|
|
20
|
+
"bale",
|
|
21
|
+
"soroush",
|
|
22
|
+
"telegram",
|
|
23
|
+
"__version__",
|
|
24
|
+
"__author__",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
_PLATFORM_MODULES = {
|
|
28
|
+
"rubika": ".bot",
|
|
29
|
+
"bale": ".bale",
|
|
30
|
+
"soroush": ".soroush",
|
|
31
|
+
"telegram": ".telegram",
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def __getattr__(name):
|
|
36
|
+
"""Import a platform client only when it is requested."""
|
|
37
|
+
module_path = _PLATFORM_MODULES.get(name)
|
|
38
|
+
if module_path is None:
|
|
39
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
40
|
+
|
|
41
|
+
module = import_module(module_path, __name__)
|
|
42
|
+
globals()[name] = module
|
|
43
|
+
return module
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def __dir__():
|
|
47
|
+
return sorted(set(globals()) | set(__all__))
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Non-blocking PyPI update notifications for IRubix."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
import threading
|
|
9
|
+
from urllib.request import Request, urlopen
|
|
10
|
+
|
|
11
|
+
_PYPI_JSON = "https://pypi.org/pypi/irubix/json"
|
|
12
|
+
_TIMEOUT = 3.0
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _version_key(version: str) -> tuple[int, ...]:
|
|
16
|
+
"""Compare ordinary numeric release versions without extra dependencies."""
|
|
17
|
+
parts = tuple(int(part) for part in re.findall(r"\d+", str(version)))
|
|
18
|
+
return parts or (0,)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _is_newer(latest: str, installed: str) -> bool:
|
|
22
|
+
return _version_key(latest) > _version_key(installed)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _check(installed: str) -> None:
|
|
26
|
+
try:
|
|
27
|
+
request = Request(
|
|
28
|
+
_PYPI_JSON,
|
|
29
|
+
headers={"Accept": "application/json", "User-Agent": "IRubix-update-check"},
|
|
30
|
+
)
|
|
31
|
+
with urlopen(request, timeout=_TIMEOUT) as response:
|
|
32
|
+
data = json.loads(response.read().decode("utf-8"))
|
|
33
|
+
latest = str(data["info"]["version"])
|
|
34
|
+
if _is_newer(latest, installed):
|
|
35
|
+
print(
|
|
36
|
+
"\n[IRubix] نسخه جدید در دسترس است! "
|
|
37
|
+
f"(نسخه شما: {installed} | نسخه جدید: {latest})\n"
|
|
38
|
+
"برای بهروزرسانی اجرا کنید:\n"
|
|
39
|
+
"python -m pip install --upgrade irubix\n",
|
|
40
|
+
file=sys.stderr,
|
|
41
|
+
flush=True,
|
|
42
|
+
)
|
|
43
|
+
except Exception:
|
|
44
|
+
# Update checks must never interrupt or slow down the user's program.
|
|
45
|
+
return
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def check_for_updates(installed_version: str) -> None:
|
|
49
|
+
"""Check PyPI in a daemon thread; never block application startup."""
|
|
50
|
+
if os.environ.get("IRUBIX_DISABLE_UPDATE_CHECK", "").lower() in {
|
|
51
|
+
"1", "true", "yes", "on"
|
|
52
|
+
}:
|
|
53
|
+
return
|
|
54
|
+
thread = threading.Thread(
|
|
55
|
+
target=_check,
|
|
56
|
+
args=(installed_version,),
|
|
57
|
+
name="irubix-update-check",
|
|
58
|
+
daemon=True,
|
|
59
|
+
)
|
|
60
|
+
thread.start()
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
"""Async client for the Bale Bot API (stdlib only)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import json
|
|
6
|
+
import urllib.error
|
|
7
|
+
import urllib.parse
|
|
8
|
+
import urllib.request
|
|
9
|
+
from typing import Any, Callable
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class BaleAPIError(RuntimeError):
|
|
13
|
+
"""Raised when Bale returns an API or transport error."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Event:
|
|
17
|
+
"""Incoming Bale update exposed to registered handlers."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, bot: "IRubix", raw: dict[str, Any]):
|
|
20
|
+
self.bot = bot
|
|
21
|
+
self.raw = raw
|
|
22
|
+
self.update = raw
|
|
23
|
+
self.message = raw.get("message") or raw.get("edited_message") or {}
|
|
24
|
+
self.chat = self.message.get("chat") or {}
|
|
25
|
+
self.chat_id = self.chat.get("id") or self.message.get("chat_id")
|
|
26
|
+
self.message_id = self.message.get("message_id")
|
|
27
|
+
self.text = self.message.get("text") or self.message.get("caption") or ""
|
|
28
|
+
self.sender = self.message.get("from") or {}
|
|
29
|
+
self.sender_id = self.sender.get("id")
|
|
30
|
+
self.callback_query = raw.get("callback_query") or {}
|
|
31
|
+
self.button_id = self.callback_query.get("data")
|
|
32
|
+
self.type = "callback_query" if self.callback_query else (
|
|
33
|
+
"message" if self.message else "unknown"
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
async def reply(self, text: str, **kwargs: Any):
|
|
37
|
+
"""Reply to the message that triggered this event."""
|
|
38
|
+
if self.callback_query:
|
|
39
|
+
chat = (self.callback_query.get("message") or {}).get("chat") or {}
|
|
40
|
+
message_id = (self.callback_query.get("message") or {}).get("message_id")
|
|
41
|
+
chat_id = chat.get("id")
|
|
42
|
+
else:
|
|
43
|
+
chat_id, message_id = self.chat_id, self.message_id
|
|
44
|
+
if chat_id is None:
|
|
45
|
+
raise BaleAPIError("Chat ID was not found in this update.")
|
|
46
|
+
if message_id is not None:
|
|
47
|
+
kwargs.setdefault("reply_to_message_id", message_id)
|
|
48
|
+
return await self.bot.send_message(chat_id, text, **kwargs)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class IRubix:
|
|
52
|
+
"""Async Bale Bot API client with a small, decorator-based interface."""
|
|
53
|
+
|
|
54
|
+
API_URL = "https://tapi.bale.ai"
|
|
55
|
+
__version__ = "0.4.0"
|
|
56
|
+
|
|
57
|
+
def __init__(self, token: str, *, timeout: float = 40, base_url: str | None = None):
|
|
58
|
+
if not isinstance(token, str) or not token.strip():
|
|
59
|
+
raise ValueError("Bale bot token must not be empty.")
|
|
60
|
+
self.token = token.strip()
|
|
61
|
+
self.base_url = (base_url or self.API_URL).rstrip("/")
|
|
62
|
+
self.timeout = timeout
|
|
63
|
+
self._handlers: list[tuple[str, Any, Callable]] = []
|
|
64
|
+
self._running = False
|
|
65
|
+
self._offset = 0
|
|
66
|
+
|
|
67
|
+
def _request_sync(self, method: str, payload: dict | None = None):
|
|
68
|
+
url = f"{self.base_url}/bot{self.token}/{method}"
|
|
69
|
+
data = json.dumps(payload or {}, ensure_ascii=False).encode("utf-8")
|
|
70
|
+
request = urllib.request.Request(
|
|
71
|
+
url, data=data,
|
|
72
|
+
headers={"Content-Type": "application/json", "Accept": "application/json",
|
|
73
|
+
"User-Agent": f"IRubix-Bale/{self.__version__}"},
|
|
74
|
+
method="POST",
|
|
75
|
+
)
|
|
76
|
+
try:
|
|
77
|
+
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
|
78
|
+
body = response.read().decode("utf-8")
|
|
79
|
+
except urllib.error.HTTPError as exc:
|
|
80
|
+
detail = exc.read().decode("utf-8", "replace")
|
|
81
|
+
raise BaleAPIError(f"HTTP {exc.code}: {detail}") from exc
|
|
82
|
+
except (urllib.error.URLError, TimeoutError, OSError) as exc:
|
|
83
|
+
raise BaleAPIError(f"Connection error: {exc}") from exc
|
|
84
|
+
try:
|
|
85
|
+
result = json.loads(body)
|
|
86
|
+
except json.JSONDecodeError as exc:
|
|
87
|
+
raise BaleAPIError("Bale returned invalid JSON.") from exc
|
|
88
|
+
if not isinstance(result, dict):
|
|
89
|
+
raise BaleAPIError("Unexpected Bale API response.")
|
|
90
|
+
if result.get("ok") is False:
|
|
91
|
+
raise BaleAPIError(result.get("description") or "Bale API request failed.")
|
|
92
|
+
return result.get("result", result)
|
|
93
|
+
|
|
94
|
+
async def request(self, method: str, payload: dict | None = None):
|
|
95
|
+
"""Call a Bale Bot API method."""
|
|
96
|
+
if not method or "/" in method:
|
|
97
|
+
raise ValueError("Invalid API method name.")
|
|
98
|
+
return await asyncio.to_thread(self._request_sync, method, payload)
|
|
99
|
+
|
|
100
|
+
async def get_me(self):
|
|
101
|
+
return await self.request("getMe")
|
|
102
|
+
|
|
103
|
+
async def get_updates(self, *, offset: int | None = None, limit: int = 100,
|
|
104
|
+
timeout: int = 30):
|
|
105
|
+
payload = {"limit": limit, "timeout": timeout}
|
|
106
|
+
if offset is not None:
|
|
107
|
+
payload["offset"] = offset
|
|
108
|
+
return await self.request("getUpdates", payload)
|
|
109
|
+
|
|
110
|
+
async def send_message(self, chat_id: int | str, text: str, **kwargs):
|
|
111
|
+
payload = {"chat_id": chat_id, "text": text}
|
|
112
|
+
for key in ("reply_to_message_id", "reply_markup", "parse_mode",
|
|
113
|
+
"disable_notification", "protect_content", "message_thread_id"):
|
|
114
|
+
if kwargs.get(key) is not None:
|
|
115
|
+
payload[key] = kwargs[key]
|
|
116
|
+
return await self.request("sendMessage", payload)
|
|
117
|
+
|
|
118
|
+
async def send_photo(self, chat_id: int | str, photo: str, caption: str | None = None,
|
|
119
|
+
**kwargs):
|
|
120
|
+
payload = {"chat_id": chat_id, "photo": photo}
|
|
121
|
+
if caption is not None:
|
|
122
|
+
payload["caption"] = caption
|
|
123
|
+
if kwargs.get("reply_to_message_id") is not None:
|
|
124
|
+
payload["reply_to_message_id"] = kwargs["reply_to_message_id"]
|
|
125
|
+
return await self.request("sendPhoto", payload)
|
|
126
|
+
|
|
127
|
+
async def send_document(self, chat_id: int | str, document: str,
|
|
128
|
+
caption: str | None = None, **kwargs):
|
|
129
|
+
payload = {"chat_id": chat_id, "document": document}
|
|
130
|
+
if caption is not None:
|
|
131
|
+
payload["caption"] = caption
|
|
132
|
+
if kwargs.get("reply_to_message_id") is not None:
|
|
133
|
+
payload["reply_to_message_id"] = kwargs["reply_to_message_id"]
|
|
134
|
+
return await self.request("sendDocument", payload)
|
|
135
|
+
|
|
136
|
+
async def edit_message_text(self, chat_id: int | str, message_id: int | str,
|
|
137
|
+
text: str, **kwargs):
|
|
138
|
+
payload = {"chat_id": chat_id, "message_id": message_id, "text": text}
|
|
139
|
+
if kwargs.get("reply_markup") is not None:
|
|
140
|
+
payload["reply_markup"] = kwargs["reply_markup"]
|
|
141
|
+
return await self.request("editMessageText", payload)
|
|
142
|
+
|
|
143
|
+
async def delete_message(self, chat_id: int | str, message_id: int | str):
|
|
144
|
+
return await self.request("deleteMessage", {
|
|
145
|
+
"chat_id": chat_id, "message_id": message_id
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
def command(self, names: str | list[str]):
|
|
149
|
+
commands = [names] if isinstance(names, str) else list(names)
|
|
150
|
+
commands = [str(name).lstrip("/") for name in commands]
|
|
151
|
+
def decorator(function):
|
|
152
|
+
self._handlers.append(("command", commands, function))
|
|
153
|
+
return function
|
|
154
|
+
return decorator
|
|
155
|
+
|
|
156
|
+
def message(self, flt=None):
|
|
157
|
+
def decorator(function):
|
|
158
|
+
self._handlers.append(("message", flt, function))
|
|
159
|
+
return function
|
|
160
|
+
return decorator
|
|
161
|
+
|
|
162
|
+
def callback(self):
|
|
163
|
+
def decorator(function):
|
|
164
|
+
self._handlers.append(("callback", None, function))
|
|
165
|
+
return function
|
|
166
|
+
return decorator
|
|
167
|
+
|
|
168
|
+
async def _dispatch(self, raw: dict):
|
|
169
|
+
event = Event(self, raw)
|
|
170
|
+
for kind, value, handler in tuple(self._handlers):
|
|
171
|
+
if kind == "command":
|
|
172
|
+
first = event.text.strip().split(maxsplit=1)[0].split("@", 1)[0].lstrip("/") if event.text.strip() else ""
|
|
173
|
+
if not event.text.startswith("/") or first not in value:
|
|
174
|
+
continue
|
|
175
|
+
elif kind == "callback":
|
|
176
|
+
if not event.callback_query:
|
|
177
|
+
continue
|
|
178
|
+
elif kind == "message":
|
|
179
|
+
if not event.message:
|
|
180
|
+
continue
|
|
181
|
+
if callable(value) and not value(event):
|
|
182
|
+
continue
|
|
183
|
+
try:
|
|
184
|
+
result = handler(self, event)
|
|
185
|
+
if hasattr(result, "__await__"):
|
|
186
|
+
await result
|
|
187
|
+
except Exception as exc:
|
|
188
|
+
print(f"[IRubix:Bale] Handler error: {exc}")
|
|
189
|
+
|
|
190
|
+
async def start(self, *, timeout: int = 30, retry_delay: float = 2):
|
|
191
|
+
"""Start long polling until stop() is called."""
|
|
192
|
+
if not 0 <= timeout <= 50:
|
|
193
|
+
raise ValueError("timeout must be between 0 and 50 seconds.")
|
|
194
|
+
self._running = True
|
|
195
|
+
print("[IRubix:Bale] Bot started.")
|
|
196
|
+
while self._running:
|
|
197
|
+
try:
|
|
198
|
+
updates = await self.get_updates(offset=self._offset, timeout=timeout)
|
|
199
|
+
for update in updates or []:
|
|
200
|
+
if not isinstance(update, dict):
|
|
201
|
+
continue
|
|
202
|
+
update_id = update.get("update_id")
|
|
203
|
+
if isinstance(update_id, int):
|
|
204
|
+
self._offset = max(self._offset, update_id + 1)
|
|
205
|
+
await self._dispatch(update)
|
|
206
|
+
except asyncio.CancelledError:
|
|
207
|
+
raise
|
|
208
|
+
except Exception as exc:
|
|
209
|
+
print(f"[IRubix:Bale] Polling error: {exc}")
|
|
210
|
+
await asyncio.sleep(retry_delay)
|
|
211
|
+
print("[IRubix:Bale] Bot stopped.")
|
|
212
|
+
|
|
213
|
+
def stop(self):
|
|
214
|
+
"""Stop the polling loop after the current request."""
|
|
215
|
+
self._running = False
|
|
216
|
+
|
|
217
|
+
def run(self, *, timeout: int = 30, retry_delay: float = 2):
|
|
218
|
+
"""Run polling; await the result if called inside an active event loop."""
|
|
219
|
+
try:
|
|
220
|
+
asyncio.get_running_loop()
|
|
221
|
+
except RuntimeError:
|
|
222
|
+
try:
|
|
223
|
+
asyncio.run(self.start(timeout=timeout, retry_delay=retry_delay))
|
|
224
|
+
except KeyboardInterrupt:
|
|
225
|
+
self.stop()
|
|
226
|
+
return None
|
|
227
|
+
return self.start(timeout=timeout, retry_delay=retry_delay)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
Bot = IRubix
|