ertebat 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.
- ertebat-0.1.0/PKG-INFO +174 -0
- ertebat-0.1.0/README.md +160 -0
- ertebat-0.1.0/ertebat/__init__.py +62 -0
- ertebat-0.1.0/ertebat/_bot_api.py +166 -0
- ertebat-0.1.0/ertebat/_token.py +110 -0
- ertebat-0.1.0/ertebat/_update.py +116 -0
- ertebat-0.1.0/ertebat/api_methods.py +146 -0
- ertebat-0.1.0/ertebat/bale/__init__.py +5 -0
- ertebat-0.1.0/ertebat/bale/bot.py +272 -0
- ertebat-0.1.0/ertebat/bot.py +587 -0
- ertebat-0.1.0/ertebat/filters.py +30 -0
- ertebat-0.1.0/ertebat/models.py +220 -0
- ertebat-0.1.0/ertebat/multibot.py +102 -0
- ertebat-0.1.0/ertebat/soroush/__init__.py +4 -0
- ertebat-0.1.0/ertebat/soroush/bot.py +313 -0
- ertebat-0.1.0/ertebat/telegram/__init__.py +3 -0
- ertebat-0.1.0/ertebat/telegram/bot.py +230 -0
- ertebat-0.1.0/ertebat.egg-info/PKG-INFO +174 -0
- ertebat-0.1.0/ertebat.egg-info/SOURCES.txt +32 -0
- ertebat-0.1.0/ertebat.egg-info/dependency_links.txt +1 -0
- ertebat-0.1.0/ertebat.egg-info/top_level.txt +1 -0
- ertebat-0.1.0/pyproject.toml +20 -0
- ertebat-0.1.0/setup.cfg +4 -0
- ertebat-0.1.0/setup.py +22 -0
- ertebat-0.1.0/tests/test_bale_api.py +59 -0
- ertebat-0.1.0/tests/test_lightweight_import.py +20 -0
- ertebat-0.1.0/tests/test_multibot.py +62 -0
- ertebat-0.1.0/tests/test_platform_api_dispatch.py +68 -0
- ertebat-0.1.0/tests/test_platform_imports.py +33 -0
- ertebat-0.1.0/tests/test_public_api.py +169 -0
- ertebat-0.1.0/tests/test_rubika_api_methods.py +151 -0
- ertebat-0.1.0/tests/test_soroush_api.py +59 -0
- ertebat-0.1.0/tests/test_telegram_api.py +47 -0
- ertebat-0.1.0/tests/test_update_check.py +71 -0
ertebat-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ertebat
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Async multi-platform bot clients for Rubika, Bale, Soroush Plus and Telegram
|
|
5
|
+
Home-page: https://github.com/adminVIPZEXNET/ertebat
|
|
6
|
+
Author: mahdishami
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
Dynamic: home-page
|
|
13
|
+
Dynamic: requires-python
|
|
14
|
+
|
|
15
|
+
# Ertebat
|
|
16
|
+
|
|
17
|
+
کتابخانهای سبک برای ساخت ربات در **روبیکا، بله، سروشپلاس و تلگرام** با Python و `async/await`.
|
|
18
|
+
|
|
19
|
+
## نصب
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
python -m pip install --upgrade ertebat
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
برای نصب آخرین نسخه مخزن (بدون نیاز به Git):
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
python -m pip install --upgrade ertebat
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## شروع سریع
|
|
32
|
+
|
|
33
|
+
در همه پیامرسانها کلاینت مستقیماً ساخته میشود؛ کافی است ماژول پیامرسان موردنظر را وارد کنید. واردکردن توکن اختیاری است: اگر توکن را ننویسید، Ertebat آن را بهصورت مخفی در ترمینال درخواست میکند.
|
|
34
|
+
|
|
35
|
+
فقط ماژول پیامرسان موردنظر را انتخاب کنید.
|
|
36
|
+
|
|
37
|
+
**روبیکا**
|
|
38
|
+
```python
|
|
39
|
+
from ertebat import Rubika
|
|
40
|
+
|
|
41
|
+
bot = Rubika() # توکن در ترمینال پرسیده میشود
|
|
42
|
+
|
|
43
|
+
@bot.command("start")
|
|
44
|
+
async def start(bot, event):
|
|
45
|
+
await event.reply("سلام! ربات فعاله.")
|
|
46
|
+
|
|
47
|
+
bot.run()
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
**بله**
|
|
51
|
+
```python
|
|
52
|
+
from ertebat import bale
|
|
53
|
+
|
|
54
|
+
bot = bale() # توکن در ترمینال پرسیده میشود
|
|
55
|
+
|
|
56
|
+
@bot.command("start")
|
|
57
|
+
async def start(bot, event):
|
|
58
|
+
await event.reply("سلام! ربات فعاله.")
|
|
59
|
+
|
|
60
|
+
bot.run()
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
**سروشپلاس**
|
|
64
|
+
```python
|
|
65
|
+
from ertebat import soroush
|
|
66
|
+
|
|
67
|
+
bot = soroush() # توکن در ترمینال پرسیده میشود
|
|
68
|
+
|
|
69
|
+
@bot.command("start")
|
|
70
|
+
async def start(bot, event):
|
|
71
|
+
await event.reply("سلام! ربات فعاله.")
|
|
72
|
+
|
|
73
|
+
bot.run()
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
**تلگرام**
|
|
77
|
+
```python
|
|
78
|
+
from ertebat import telegram
|
|
79
|
+
|
|
80
|
+
bot = telegram() # توکن در ترمینال پرسیده میشود
|
|
81
|
+
|
|
82
|
+
@bot.command("start")
|
|
83
|
+
async def start(bot, event):
|
|
84
|
+
await event.reply("سلام! ربات فعاله.")
|
|
85
|
+
|
|
86
|
+
bot.run()
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## اجرای چند ربات همزمان
|
|
90
|
+
|
|
91
|
+
با `MultiBot` میتوانید چند ربات از پیامرسانهای مختلف را در یک برنامه اجرا کنید:
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
from ertebat import MultiBot
|
|
95
|
+
|
|
96
|
+
app = MultiBot()
|
|
97
|
+
rubika = app.add("rubika", "RUBIKA_TOKEN")
|
|
98
|
+
telegram = app.add("telegram", "TELEGRAM_TOKEN")
|
|
99
|
+
bale = app.add("bale", "BALE_TOKEN")
|
|
100
|
+
|
|
101
|
+
@rubika.command("start")
|
|
102
|
+
async def rubika_start(bot, event):
|
|
103
|
+
await event.reply("Hello from Rubika!")
|
|
104
|
+
|
|
105
|
+
@telegram.command("start")
|
|
106
|
+
async def telegram_start(bot, event):
|
|
107
|
+
await event.reply("Hello from Telegram!")
|
|
108
|
+
|
|
109
|
+
app.run() # همه رباتها بهصورت همزمان اجرا میشوند
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
برای افزودن چند ربات از یک پیامرسان، نام یکتا تعیین کنید:
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
first = app.add("bale", "TOKEN_1", name="bale_main")
|
|
116
|
+
second = app.add("bale", "TOKEN_2", name="bale_backup")
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
`app.stop()` همه رباتها را متوقف میکند و `app.get("rubika")` یک ربات ثبتشده را برمیگرداند.
|
|
120
|
+
|
|
121
|
+
## مستندات
|
|
122
|
+
|
|
123
|
+
- [راهنمای کامل همه کلاسها و نمونهکدها](https://adminvipzexnet.github.io/ertebat/classes/)
|
|
124
|
+
- [مستندات کامل API روبیکا v3، متدها و مدلها](docs/rubika-api-v3.md)
|
|
125
|
+
- [دسترسی به متدهای API بله، سروشپلاس و تلگرام](docs/platform-api-methods.md)
|
|
126
|
+
|
|
127
|
+
| پیامرسان | راهنما | متدها |
|
|
128
|
+
|---|---|---|
|
|
129
|
+
| روبیکا | [شروع سریع](https://adminvipzexnet.github.io/ertebat/bot-guide/) | [فهرست متدها](https://adminvipzexnet.github.io/ertebat/bot-methods/) |
|
|
130
|
+
| بله | [شروع سریع](https://adminvipzexnet.github.io/ertebat/bale-guide/) | [فهرست متدها](https://adminvipzexnet.github.io/ertebat/bale-methods/) |
|
|
131
|
+
| سروشپلاس | [شروع سریع](https://adminvipzexnet.github.io/ertebat/soroush-guide/) | [فهرست متدها](https://adminvipzexnet.github.io/ertebat/soroush-methods/) |
|
|
132
|
+
| تلگرام | [شروع سریع](https://adminvipzexnet.github.io/ertebat/telegram-guide/) | [فهرست متدها](https://adminvipzexnet.github.io/ertebat/telegram-methods/) |
|
|
133
|
+
|
|
134
|
+
- [وبسایت مستندات](https://adminvipzexnet.github.io/ertebat/)
|
|
135
|
+
- [نمونه خروجیها](https://adminvipzexnet.github.io/ertebat/outputs/)
|
|
136
|
+
- [سؤالات متداول](https://adminvipzexnet.github.io/ertebat/faq/)
|
|
137
|
+
|
|
138
|
+
## ساختار پروژه
|
|
139
|
+
|
|
140
|
+
```text
|
|
141
|
+
ertebat/
|
|
142
|
+
├── __init__.py # ورودی اصلی کتابخانه
|
|
143
|
+
├── bot.py # پیادهسازی کلاینت روبیکا
|
|
144
|
+
├── _update.py # بررسی نسخه جدید
|
|
145
|
+
├── multibot.py # اجرای چند ربات
|
|
146
|
+
├── bale/ # کلاینت بله
|
|
147
|
+
├── soroush/ # کلاینت سروشپلاس
|
|
148
|
+
└── telegram/ # کلاینت تلگرام
|
|
149
|
+
|
|
150
|
+
docs/ # مستندات
|
|
151
|
+
examples/ # نمونهکدها
|
|
152
|
+
tests/ # تستها
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
## نکات
|
|
156
|
+
|
|
157
|
+
- سازنده مستقیم هر پیامرسان: `Rubika("TOKEN")`، `bale("TOKEN")`، `soroush("TOKEN")` و `telegram("TOKEN")`.
|
|
158
|
+
- برای سازگاری با کدهای قبلی، ویژگیهای `.Ertebat` و `.Bot` همچنان بهعنوان alias در دسترساند.
|
|
159
|
+
|
|
160
|
+
- تمام درخواستهای API بهصورت async اجرا میشوند.
|
|
161
|
+
- هسته کتابخانه به کتابخانه جانبی نیاز ندارد.
|
|
162
|
+
- هر پیامرسان فقط API و قابلیتهای رسمی خودش را ارائه میکند.
|
|
163
|
+
- برای غیرفعالکردن بررسی نسخه جدید، متغیر محیطی `ERTEBAT_DISABLE_UPDATE_CHECK=1` را تنظیم کنید.
|
|
164
|
+
|
|
165
|
+
## اجرای تستها
|
|
166
|
+
|
|
167
|
+
```bash
|
|
168
|
+
python -m unittest discover -s tests -v
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
## مجوز
|
|
172
|
+
|
|
173
|
+
MIT
|
|
174
|
+
|
ertebat-0.1.0/README.md
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
# Ertebat
|
|
2
|
+
|
|
3
|
+
کتابخانهای سبک برای ساخت ربات در **روبیکا، بله، سروشپلاس و تلگرام** با Python و `async/await`.
|
|
4
|
+
|
|
5
|
+
## نصب
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
python -m pip install --upgrade ertebat
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
برای نصب آخرین نسخه مخزن (بدون نیاز به Git):
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
python -m pip install --upgrade ertebat
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## شروع سریع
|
|
18
|
+
|
|
19
|
+
در همه پیامرسانها کلاینت مستقیماً ساخته میشود؛ کافی است ماژول پیامرسان موردنظر را وارد کنید. واردکردن توکن اختیاری است: اگر توکن را ننویسید، Ertebat آن را بهصورت مخفی در ترمینال درخواست میکند.
|
|
20
|
+
|
|
21
|
+
فقط ماژول پیامرسان موردنظر را انتخاب کنید.
|
|
22
|
+
|
|
23
|
+
**روبیکا**
|
|
24
|
+
```python
|
|
25
|
+
from ertebat import Rubika
|
|
26
|
+
|
|
27
|
+
bot = Rubika() # توکن در ترمینال پرسیده میشود
|
|
28
|
+
|
|
29
|
+
@bot.command("start")
|
|
30
|
+
async def start(bot, event):
|
|
31
|
+
await event.reply("سلام! ربات فعاله.")
|
|
32
|
+
|
|
33
|
+
bot.run()
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
**بله**
|
|
37
|
+
```python
|
|
38
|
+
from ertebat import bale
|
|
39
|
+
|
|
40
|
+
bot = bale() # توکن در ترمینال پرسیده میشود
|
|
41
|
+
|
|
42
|
+
@bot.command("start")
|
|
43
|
+
async def start(bot, event):
|
|
44
|
+
await event.reply("سلام! ربات فعاله.")
|
|
45
|
+
|
|
46
|
+
bot.run()
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
**سروشپلاس**
|
|
50
|
+
```python
|
|
51
|
+
from ertebat import soroush
|
|
52
|
+
|
|
53
|
+
bot = soroush() # توکن در ترمینال پرسیده میشود
|
|
54
|
+
|
|
55
|
+
@bot.command("start")
|
|
56
|
+
async def start(bot, event):
|
|
57
|
+
await event.reply("سلام! ربات فعاله.")
|
|
58
|
+
|
|
59
|
+
bot.run()
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
**تلگرام**
|
|
63
|
+
```python
|
|
64
|
+
from ertebat import telegram
|
|
65
|
+
|
|
66
|
+
bot = telegram() # توکن در ترمینال پرسیده میشود
|
|
67
|
+
|
|
68
|
+
@bot.command("start")
|
|
69
|
+
async def start(bot, event):
|
|
70
|
+
await event.reply("سلام! ربات فعاله.")
|
|
71
|
+
|
|
72
|
+
bot.run()
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## اجرای چند ربات همزمان
|
|
76
|
+
|
|
77
|
+
با `MultiBot` میتوانید چند ربات از پیامرسانهای مختلف را در یک برنامه اجرا کنید:
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
from ertebat import MultiBot
|
|
81
|
+
|
|
82
|
+
app = MultiBot()
|
|
83
|
+
rubika = app.add("rubika", "RUBIKA_TOKEN")
|
|
84
|
+
telegram = app.add("telegram", "TELEGRAM_TOKEN")
|
|
85
|
+
bale = app.add("bale", "BALE_TOKEN")
|
|
86
|
+
|
|
87
|
+
@rubika.command("start")
|
|
88
|
+
async def rubika_start(bot, event):
|
|
89
|
+
await event.reply("Hello from Rubika!")
|
|
90
|
+
|
|
91
|
+
@telegram.command("start")
|
|
92
|
+
async def telegram_start(bot, event):
|
|
93
|
+
await event.reply("Hello from Telegram!")
|
|
94
|
+
|
|
95
|
+
app.run() # همه رباتها بهصورت همزمان اجرا میشوند
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
برای افزودن چند ربات از یک پیامرسان، نام یکتا تعیین کنید:
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
first = app.add("bale", "TOKEN_1", name="bale_main")
|
|
102
|
+
second = app.add("bale", "TOKEN_2", name="bale_backup")
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
`app.stop()` همه رباتها را متوقف میکند و `app.get("rubika")` یک ربات ثبتشده را برمیگرداند.
|
|
106
|
+
|
|
107
|
+
## مستندات
|
|
108
|
+
|
|
109
|
+
- [راهنمای کامل همه کلاسها و نمونهکدها](https://adminvipzexnet.github.io/ertebat/classes/)
|
|
110
|
+
- [مستندات کامل API روبیکا v3، متدها و مدلها](docs/rubika-api-v3.md)
|
|
111
|
+
- [دسترسی به متدهای API بله، سروشپلاس و تلگرام](docs/platform-api-methods.md)
|
|
112
|
+
|
|
113
|
+
| پیامرسان | راهنما | متدها |
|
|
114
|
+
|---|---|---|
|
|
115
|
+
| روبیکا | [شروع سریع](https://adminvipzexnet.github.io/ertebat/bot-guide/) | [فهرست متدها](https://adminvipzexnet.github.io/ertebat/bot-methods/) |
|
|
116
|
+
| بله | [شروع سریع](https://adminvipzexnet.github.io/ertebat/bale-guide/) | [فهرست متدها](https://adminvipzexnet.github.io/ertebat/bale-methods/) |
|
|
117
|
+
| سروشپلاس | [شروع سریع](https://adminvipzexnet.github.io/ertebat/soroush-guide/) | [فهرست متدها](https://adminvipzexnet.github.io/ertebat/soroush-methods/) |
|
|
118
|
+
| تلگرام | [شروع سریع](https://adminvipzexnet.github.io/ertebat/telegram-guide/) | [فهرست متدها](https://adminvipzexnet.github.io/ertebat/telegram-methods/) |
|
|
119
|
+
|
|
120
|
+
- [وبسایت مستندات](https://adminvipzexnet.github.io/ertebat/)
|
|
121
|
+
- [نمونه خروجیها](https://adminvipzexnet.github.io/ertebat/outputs/)
|
|
122
|
+
- [سؤالات متداول](https://adminvipzexnet.github.io/ertebat/faq/)
|
|
123
|
+
|
|
124
|
+
## ساختار پروژه
|
|
125
|
+
|
|
126
|
+
```text
|
|
127
|
+
ertebat/
|
|
128
|
+
├── __init__.py # ورودی اصلی کتابخانه
|
|
129
|
+
├── bot.py # پیادهسازی کلاینت روبیکا
|
|
130
|
+
├── _update.py # بررسی نسخه جدید
|
|
131
|
+
├── multibot.py # اجرای چند ربات
|
|
132
|
+
├── bale/ # کلاینت بله
|
|
133
|
+
├── soroush/ # کلاینت سروشپلاس
|
|
134
|
+
└── telegram/ # کلاینت تلگرام
|
|
135
|
+
|
|
136
|
+
docs/ # مستندات
|
|
137
|
+
examples/ # نمونهکدها
|
|
138
|
+
tests/ # تستها
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
## نکات
|
|
142
|
+
|
|
143
|
+
- سازنده مستقیم هر پیامرسان: `Rubika("TOKEN")`، `bale("TOKEN")`، `soroush("TOKEN")` و `telegram("TOKEN")`.
|
|
144
|
+
- برای سازگاری با کدهای قبلی، ویژگیهای `.Ertebat` و `.Bot` همچنان بهعنوان alias در دسترساند.
|
|
145
|
+
|
|
146
|
+
- تمام درخواستهای API بهصورت async اجرا میشوند.
|
|
147
|
+
- هسته کتابخانه به کتابخانه جانبی نیاز ندارد.
|
|
148
|
+
- هر پیامرسان فقط API و قابلیتهای رسمی خودش را ارائه میکند.
|
|
149
|
+
- برای غیرفعالکردن بررسی نسخه جدید، متغیر محیطی `ERTEBAT_DISABLE_UPDATE_CHECK=1` را تنظیم کنید.
|
|
150
|
+
|
|
151
|
+
## اجرای تستها
|
|
152
|
+
|
|
153
|
+
```bash
|
|
154
|
+
python -m unittest discover -s tests -v
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
## مجوز
|
|
158
|
+
|
|
159
|
+
MIT
|
|
160
|
+
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Ertebat: lightweight async clients for supported messaging platforms."""
|
|
2
|
+
from importlib import import_module
|
|
3
|
+
from types import ModuleType
|
|
4
|
+
|
|
5
|
+
from .bot import Bot, Event, Ertebat as _RubikaClient, RubikaAPIError
|
|
6
|
+
from .multibot import MultiBot
|
|
7
|
+
from .filters import Filter, Text, ChatTypeFilter, FromUser, IsImage, IsVideo, IsVoice, Command
|
|
8
|
+
from .models import (APIModel, AuxData, Bot as BotModel, BotCommand, ButtonType, Chat, ChatKeypadType, ChatType, ContactMessage, File, FileType, ForwardedFrom, InlineMessage, Keypad, KeypadRow, Location, Message, Metadata, MetadataPart, Poll, PollStatus, Update, UpdateType)
|
|
9
|
+
__author__ = "mahdishami"
|
|
10
|
+
__version__ = "0.1.0"
|
|
11
|
+
|
|
12
|
+
from ._update import check_for_updates
|
|
13
|
+
check_for_updates(__version__)
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"Rubika", "Bot", "Event", "RubikaAPIError", "Filter", "Text", "ChatTypeFilter", "FromUser", "IsImage", "IsVideo", "IsVoice", "Command",
|
|
17
|
+
"rubika", "bale", "soroush", "telegram",
|
|
18
|
+
"__version__", "__author__", "MultiBot", "APIModel", "File", "Chat",
|
|
19
|
+
"AuxData", "Location", "BotModel", "BotCommand", "ForwardedFrom",
|
|
20
|
+
"ContactMessage", "PollStatus", "Poll", "Message", "Update",
|
|
21
|
+
"InlineMessage", "MetadataPart", "Metadata", "KeypadRow", "Keypad",
|
|
22
|
+
"ChatType", "FileType", "ChatKeypadType", "UpdateType", "ButtonType",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
_PLATFORM_MODULES = {
|
|
26
|
+
"rubika": ".bot",
|
|
27
|
+
"bale": ".bale",
|
|
28
|
+
"soroush": ".soroush",
|
|
29
|
+
"telegram": ".telegram",
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class _CallablePlatformModule(ModuleType):
|
|
34
|
+
"""Allow a platform namespace to be called directly with its bot token."""
|
|
35
|
+
|
|
36
|
+
def __call__(self, *args, **kwargs):
|
|
37
|
+
return self.Ertebat(*args, **kwargs)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class Rubika(_RubikaClient):
|
|
41
|
+
"""Create a Rubika bot directly: Rubika("TOKEN")."""
|
|
42
|
+
|
|
43
|
+
Ertebat = _RubikaClient
|
|
44
|
+
Bot = _RubikaClient
|
|
45
|
+
Event = Event
|
|
46
|
+
RubikaAPIError = RubikaAPIError
|
|
47
|
+
APIError = RubikaAPIError
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def __getattr__(name):
|
|
51
|
+
"""Load a platform namespace only when it is requested."""
|
|
52
|
+
module_path = _PLATFORM_MODULES.get(name)
|
|
53
|
+
if module_path is None:
|
|
54
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
55
|
+
module = import_module(module_path, __name__)
|
|
56
|
+
module.__class__ = _CallablePlatformModule
|
|
57
|
+
globals()[name] = module
|
|
58
|
+
return module
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def __dir__():
|
|
62
|
+
return sorted(set(globals()) | set(__all__))
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""Shared helpers for Telegram-compatible Bot API clients.
|
|
2
|
+
|
|
3
|
+
The clients intentionally keep platform-specific HTTP and response handling,
|
|
4
|
+
while this module provides generic endpoint dispatch and multipart encoding.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import mimetypes
|
|
9
|
+
import uuid
|
|
10
|
+
import urllib.request
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
from urllib.parse import quote
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def encode_request_payload(payload: dict[str, Any]):
|
|
17
|
+
"""Return (body, content_type), using multipart for Path/bytes file values."""
|
|
18
|
+
files: dict[str, tuple[str, bytes, str]] = {}
|
|
19
|
+
for key, value in payload.items():
|
|
20
|
+
if isinstance(value, Path):
|
|
21
|
+
data = value.read_bytes()
|
|
22
|
+
filename = value.name
|
|
23
|
+
mime = mimetypes.guess_type(filename)[0] or "application/octet-stream"
|
|
24
|
+
files[key] = (filename, data, mime)
|
|
25
|
+
elif isinstance(value, bytes):
|
|
26
|
+
files[key] = (f"{key}.bin", value, "application/octet-stream")
|
|
27
|
+
elif isinstance(value, tuple) and len(value) == 2 and isinstance(value[1], bytes):
|
|
28
|
+
filename, data = value
|
|
29
|
+
filename = str(filename)
|
|
30
|
+
mime = mimetypes.guess_type(filename)[0] or "application/octet-stream"
|
|
31
|
+
files[key] = (filename, data, mime)
|
|
32
|
+
|
|
33
|
+
if not files:
|
|
34
|
+
import json
|
|
35
|
+
return json.dumps(payload or {}, ensure_ascii=False).encode("utf-8"), "application/json"
|
|
36
|
+
|
|
37
|
+
boundary = "----Ertebat" + uuid.uuid4().hex
|
|
38
|
+
chunks: list[bytes] = []
|
|
39
|
+
for key, value in payload.items():
|
|
40
|
+
chunks.append(f"--{boundary}\r\n".encode("ascii"))
|
|
41
|
+
if key in files:
|
|
42
|
+
filename, data, mime = files[key]
|
|
43
|
+
safe_name = filename.replace('"', "")
|
|
44
|
+
chunks.append(
|
|
45
|
+
(
|
|
46
|
+
f'Content-Disposition: form-data; name="{key}"; filename="{safe_name}"\r\n'
|
|
47
|
+
f"Content-Type: {mime}\r\n\r\n"
|
|
48
|
+
).encode("utf-8")
|
|
49
|
+
)
|
|
50
|
+
chunks.extend((data, b"\r\n"))
|
|
51
|
+
else:
|
|
52
|
+
import json
|
|
53
|
+
if isinstance(value, (dict, list, tuple)):
|
|
54
|
+
field_value = json.dumps(value, ensure_ascii=False)
|
|
55
|
+
elif isinstance(value, bool):
|
|
56
|
+
field_value = "true" if value else "false"
|
|
57
|
+
elif value is None:
|
|
58
|
+
field_value = ""
|
|
59
|
+
else:
|
|
60
|
+
field_value = str(value)
|
|
61
|
+
chunks.extend((
|
|
62
|
+
f'Content-Disposition: form-data; name="{key}"\r\n\r\n'.encode("utf-8"),
|
|
63
|
+
field_value.encode("utf-8"),
|
|
64
|
+
b"\r\n",
|
|
65
|
+
))
|
|
66
|
+
chunks.append(f"--{boundary}--\r\n".encode("ascii"))
|
|
67
|
+
return b"".join(chunks), f"multipart/form-data; boundary={boundary}"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class BotAPIMethods:
|
|
71
|
+
"""Generic access to platform Bot API endpoints.
|
|
72
|
+
|
|
73
|
+
Every endpoint can be called by snake_case or native camelCase name.
|
|
74
|
+
Parameters are passed as keyword arguments; use call_api for exact names.
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
async def call_api(self, method: str, **params: Any):
|
|
78
|
+
"""Call any endpoint supported by the selected messaging platform."""
|
|
79
|
+
if not isinstance(method, str) or not method or "/" in method:
|
|
80
|
+
raise ValueError("method must be a non-empty API method name.")
|
|
81
|
+
return await self.request(method, params or None)
|
|
82
|
+
|
|
83
|
+
_POSITIONAL_PARAMETERS = {
|
|
84
|
+
"getMe": (),
|
|
85
|
+
"getChat": ("chat_id",),
|
|
86
|
+
"getChatMember": ("chat_id", "user_id"),
|
|
87
|
+
"getFile": ("file_id",),
|
|
88
|
+
"sendMessage": ("chat_id", "text"),
|
|
89
|
+
"sendPhoto": ("chat_id", "photo"),
|
|
90
|
+
"sendAudio": ("chat_id", "audio"),
|
|
91
|
+
"sendDocument": ("chat_id", "document"),
|
|
92
|
+
"sendVideo": ("chat_id", "video"),
|
|
93
|
+
"sendAnimation": ("chat_id", "animation"),
|
|
94
|
+
"sendVoice": ("chat_id", "voice"),
|
|
95
|
+
"sendVideoNote": ("chat_id", "video_note"),
|
|
96
|
+
"sendSticker": ("chat_id", "sticker"),
|
|
97
|
+
"sendLocation": ("chat_id", "latitude", "longitude"),
|
|
98
|
+
"sendContact": ("chat_id", "phone_number", "first_name"),
|
|
99
|
+
"sendPoll": ("chat_id", "question", "options"),
|
|
100
|
+
"sendChatAction": ("chat_id", "action"),
|
|
101
|
+
"forwardMessage": ("chat_id", "from_chat_id", "message_id"),
|
|
102
|
+
"copyMessage": ("chat_id", "from_chat_id", "message_id"),
|
|
103
|
+
"editMessageText": ("chat_id", "message_id", "text"),
|
|
104
|
+
"deleteMessage": ("chat_id", "message_id"),
|
|
105
|
+
"answerCallbackQuery": ("callback_query_id",),
|
|
106
|
+
"setWebhook": ("url",),
|
|
107
|
+
"setMyCommands": ("commands",),
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
def __getattr__(self, name: str):
|
|
111
|
+
# Resolve otherwise-unimplemented API methods dynamically. This keeps
|
|
112
|
+
# the SDK forward-compatible with new endpoints without pretending the
|
|
113
|
+
# remote platform supports endpoints it has not implemented.
|
|
114
|
+
if not name or name.startswith("_"):
|
|
115
|
+
raise AttributeError(name)
|
|
116
|
+
endpoint = name.split("_")[0] + "".join(
|
|
117
|
+
part[:1].upper() + part[1:] for part in name.split("_")[1:]
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
async def invoke(*args: Any, **kwargs: Any):
|
|
121
|
+
if args:
|
|
122
|
+
parameter_names = self._POSITIONAL_PARAMETERS.get(endpoint)
|
|
123
|
+
if parameter_names is None or len(args) > len(parameter_names):
|
|
124
|
+
raise TypeError(
|
|
125
|
+
f"{name}() accepts keyword arguments for this endpoint; "
|
|
126
|
+
"use call_api(method, **params) for full API access."
|
|
127
|
+
)
|
|
128
|
+
for key, value in zip(parameter_names, args):
|
|
129
|
+
if key in kwargs:
|
|
130
|
+
raise TypeError(f"{name}() got multiple values for {key!r}.")
|
|
131
|
+
kwargs[key] = value
|
|
132
|
+
return await self.request(endpoint, kwargs or None)
|
|
133
|
+
|
|
134
|
+
invoke.__name__ = name
|
|
135
|
+
invoke.__doc__ = f"Call the {endpoint} endpoint using keyword parameters."
|
|
136
|
+
return invoke
|
|
137
|
+
|
|
138
|
+
async def download_file(self, file_id: str, destination: str | Path | None = None):
|
|
139
|
+
"""Download a file by ID; return bytes or save it and return its Path."""
|
|
140
|
+
info = await self.request("getFile", {"file_id": file_id})
|
|
141
|
+
if not isinstance(info, dict):
|
|
142
|
+
raise RuntimeError("The platform did not return file metadata.")
|
|
143
|
+
file_path = info.get("file_path") or info.get("path")
|
|
144
|
+
direct_url = info.get("download_url") or info.get("file_url") or info.get("url")
|
|
145
|
+
if direct_url:
|
|
146
|
+
url = direct_url
|
|
147
|
+
elif file_path:
|
|
148
|
+
base = getattr(self, "FILE_URL", "").rstrip("/")
|
|
149
|
+
if not base:
|
|
150
|
+
base = getattr(self, "base_url", "").rstrip("/") + "/file"
|
|
151
|
+
url = f"{base}/bot{self.token}/{quote(str(file_path), safe='/')}"
|
|
152
|
+
else:
|
|
153
|
+
raise RuntimeError("File metadata does not contain a downloadable path or URL.")
|
|
154
|
+
|
|
155
|
+
def fetch():
|
|
156
|
+
request = urllib.request.Request(url, headers={"User-Agent": "Ertebat/0.13"})
|
|
157
|
+
with urllib.request.urlopen(request, timeout=getattr(self, "timeout", 40)) as response:
|
|
158
|
+
return response.read()
|
|
159
|
+
|
|
160
|
+
data = await asyncio.to_thread(fetch)
|
|
161
|
+
if destination is None:
|
|
162
|
+
return data
|
|
163
|
+
target = Path(destination)
|
|
164
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
165
|
+
target.write_bytes(data)
|
|
166
|
+
return target
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Shared terminal helpers for Ertebat."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
_GREEN = "\033[92m"
|
|
9
|
+
_CYAN = "\033[96m"
|
|
10
|
+
_RESET = "\033[0m"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _color(value: str, code: str) -> str:
|
|
14
|
+
if os.environ.get("NO_COLOR") is not None or os.environ.get("TERM", "").lower() == "dumb":
|
|
15
|
+
return value
|
|
16
|
+
return f"{code}{value}{_RESET}"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _read_masked(prompt: str) -> str:
|
|
20
|
+
"""Read terminal input while displaying one green asterisk per character."""
|
|
21
|
+
sys.stdout.write(_color(prompt, _CYAN))
|
|
22
|
+
sys.stdout.flush()
|
|
23
|
+
chars: list[str] = []
|
|
24
|
+
|
|
25
|
+
if os.name == "nt":
|
|
26
|
+
import msvcrt
|
|
27
|
+
|
|
28
|
+
while True:
|
|
29
|
+
char = msvcrt.getwch()
|
|
30
|
+
if char in ("\r", "\n"):
|
|
31
|
+
sys.stdout.write("\n")
|
|
32
|
+
break
|
|
33
|
+
if char == "\003":
|
|
34
|
+
raise KeyboardInterrupt
|
|
35
|
+
if char in ("\b", "\x7f"):
|
|
36
|
+
if chars:
|
|
37
|
+
chars.pop()
|
|
38
|
+
sys.stdout.write("\b \b")
|
|
39
|
+
sys.stdout.flush()
|
|
40
|
+
continue
|
|
41
|
+
if char == "\x00":
|
|
42
|
+
msvcrt.getwch()
|
|
43
|
+
continue
|
|
44
|
+
if char.isprintable():
|
|
45
|
+
chars.append(char)
|
|
46
|
+
sys.stdout.write(_color("*", _GREEN))
|
|
47
|
+
sys.stdout.flush()
|
|
48
|
+
return "".join(chars)
|
|
49
|
+
|
|
50
|
+
import termios
|
|
51
|
+
import tty
|
|
52
|
+
|
|
53
|
+
fd = sys.stdin.fileno()
|
|
54
|
+
old_settings = termios.tcgetattr(fd)
|
|
55
|
+
try:
|
|
56
|
+
tty.setraw(fd)
|
|
57
|
+
while True:
|
|
58
|
+
char = sys.stdin.read(1)
|
|
59
|
+
if char in ("\r", "\n"):
|
|
60
|
+
sys.stdout.write("\n")
|
|
61
|
+
sys.stdout.flush()
|
|
62
|
+
break
|
|
63
|
+
if char in ("\x03",):
|
|
64
|
+
raise KeyboardInterrupt
|
|
65
|
+
if char in ("\x04",):
|
|
66
|
+
sys.stdout.write("\n")
|
|
67
|
+
sys.stdout.flush()
|
|
68
|
+
break
|
|
69
|
+
if char in ("\x7f", "\b"):
|
|
70
|
+
if chars:
|
|
71
|
+
chars.pop()
|
|
72
|
+
sys.stdout.write("\b \b")
|
|
73
|
+
sys.stdout.flush()
|
|
74
|
+
continue
|
|
75
|
+
if char.isprintable():
|
|
76
|
+
chars.append(char)
|
|
77
|
+
sys.stdout.write(_color("*", _GREEN))
|
|
78
|
+
sys.stdout.flush()
|
|
79
|
+
finally:
|
|
80
|
+
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
|
|
81
|
+
|
|
82
|
+
return "".join(chars)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def resolve_token(token: str | None, platform: str) -> str:
|
|
86
|
+
"""Return a supplied token or securely request one from the terminal."""
|
|
87
|
+
if isinstance(token, str) and token.strip():
|
|
88
|
+
return token.strip()
|
|
89
|
+
|
|
90
|
+
if not sys.stdin or not sys.stdin.isatty():
|
|
91
|
+
raise ValueError(
|
|
92
|
+
f"{platform} bot token is missing. Pass it to the constructor "
|
|
93
|
+
"or run the program in an interactive terminal."
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
prompt = (
|
|
97
|
+
f"[Ertebat:{platform}] Bot token is missing.\n"
|
|
98
|
+
f"[Ertebat:{platform}] Enter your bot token: "
|
|
99
|
+
)
|
|
100
|
+
try:
|
|
101
|
+
entered = _read_masked(prompt)
|
|
102
|
+
except (EOFError, OSError, AttributeError) as exc:
|
|
103
|
+
raise RuntimeError(
|
|
104
|
+
f"Could not read the {platform} bot token from this terminal."
|
|
105
|
+
) from exc
|
|
106
|
+
|
|
107
|
+
if not entered or not entered.strip():
|
|
108
|
+
raise ValueError(f"{platform} bot token cannot be empty.")
|
|
109
|
+
|
|
110
|
+
return entered.strip()
|