ertebat 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.
- ertebat/__init__.py +62 -0
- ertebat/_bot_api.py +166 -0
- ertebat/_token.py +110 -0
- ertebat/_update.py +116 -0
- ertebat/api_methods.py +146 -0
- ertebat/bale/__init__.py +5 -0
- ertebat/bale/bot.py +272 -0
- ertebat/bot.py +587 -0
- ertebat/filters.py +30 -0
- ertebat/models.py +220 -0
- ertebat/multibot.py +102 -0
- ertebat/soroush/__init__.py +4 -0
- ertebat/soroush/bot.py +313 -0
- ertebat/telegram/__init__.py +3 -0
- ertebat/telegram/bot.py +230 -0
- ertebat-0.1.0.dist-info/METADATA +174 -0
- ertebat-0.1.0.dist-info/RECORD +19 -0
- ertebat-0.1.0.dist-info/WHEEL +5 -0
- ertebat-0.1.0.dist-info/top_level.txt +1 -0
ertebat/__init__.py
ADDED
|
@@ -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__))
|
ertebat/_bot_api.py
ADDED
|
@@ -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
|
ertebat/_token.py
ADDED
|
@@ -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()
|
ertebat/_update.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""PyPI update notifications for Ertebat, with Android-friendly TLS handling."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import ssl
|
|
8
|
+
import sys
|
|
9
|
+
import threading
|
|
10
|
+
from urllib.error import URLError
|
|
11
|
+
from urllib.request import Request, urlopen
|
|
12
|
+
|
|
13
|
+
_PYPI_JSON = "https://pypi.org/pypi/ertebat/json"
|
|
14
|
+
_PYPI_PROJECT = "https://pypi.org/project/ertebat/"
|
|
15
|
+
_TIMEOUT = 8.0
|
|
16
|
+
|
|
17
|
+
_CYAN = "\033[96m"
|
|
18
|
+
_GREEN = "\033[92m"
|
|
19
|
+
_RED = "\033[91m"
|
|
20
|
+
_YELLOW = "\033[93m"
|
|
21
|
+
_MAGENTA = "\033[95m"
|
|
22
|
+
_BOLD = "\033[1m"
|
|
23
|
+
_RESET = "\033[0m"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _color(text: str, color: str) -> str:
|
|
27
|
+
if os.environ.get("NO_COLOR") is not None or os.environ.get("TERM", "").lower() == "dumb":
|
|
28
|
+
return text
|
|
29
|
+
return f"{color}{text}{_RESET}"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _version_key(version: str) -> tuple[int, ...]:
|
|
33
|
+
parts = tuple(int(part) for part in re.findall(r"\d+", str(version)))
|
|
34
|
+
return parts or (0,)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _is_newer(latest: str, installed: str) -> bool:
|
|
38
|
+
return _version_key(latest) > _version_key(installed)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _read_json(context=None) -> dict:
|
|
42
|
+
request = Request(
|
|
43
|
+
_PYPI_JSON,
|
|
44
|
+
headers={"Accept": "application/json", "User-Agent": "Ertebat-update-check"},
|
|
45
|
+
)
|
|
46
|
+
with urlopen(request, timeout=_TIMEOUT, context=context) as response:
|
|
47
|
+
payload = json.loads(response.read().decode("utf-8"))
|
|
48
|
+
if not isinstance(payload, dict):
|
|
49
|
+
raise ValueError("Invalid response from PyPI")
|
|
50
|
+
return payload
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _latest_pypi_version() -> str:
|
|
54
|
+
try:
|
|
55
|
+
payload = _read_json()
|
|
56
|
+
except (URLError, ssl.SSLError, OSError):
|
|
57
|
+
# Some Android Python distributions do not configure a usable CA
|
|
58
|
+
# bundle. Use certifi when installed; never disable TLS verification.
|
|
59
|
+
try:
|
|
60
|
+
import certifi
|
|
61
|
+
except ImportError:
|
|
62
|
+
raise
|
|
63
|
+
payload = _read_json(ssl.create_default_context(cafile=certifi.where()))
|
|
64
|
+
|
|
65
|
+
info = payload.get("info")
|
|
66
|
+
version = info.get("version") if isinstance(info, dict) else None
|
|
67
|
+
if not isinstance(version, str) or not version.strip():
|
|
68
|
+
raise ValueError("Could not read Ertebat version from PyPI")
|
|
69
|
+
return version.strip()
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _check(installed: str) -> None:
|
|
73
|
+
try:
|
|
74
|
+
latest = _latest_pypi_version()
|
|
75
|
+
if _is_newer(latest, installed):
|
|
76
|
+
version_url = f"{_PYPI_PROJECT}{latest}/"
|
|
77
|
+
lines = [
|
|
78
|
+
"",
|
|
79
|
+
_color("[Ertebat] A new version is available!", _BOLD + _CYAN),
|
|
80
|
+
_color(f"Current version: {installed}", _YELLOW),
|
|
81
|
+
_color(f"Latest version: {latest}", _GREEN),
|
|
82
|
+
"",
|
|
83
|
+
_color("PyPI release:", _MAGENTA),
|
|
84
|
+
_color(version_url, _BOLD),
|
|
85
|
+
"",
|
|
86
|
+
_color("To update, run:", _MAGENTA),
|
|
87
|
+
_color("python -m pip install --upgrade ertebat", _BOLD),
|
|
88
|
+
"",
|
|
89
|
+
]
|
|
90
|
+
print("\n".join(lines), file=sys.stderr, flush=True)
|
|
91
|
+
elif _version_key(latest) == _version_key(installed):
|
|
92
|
+
print(_color(f"[Ertebat] You are using the latest version ({installed}).", _GREEN), flush=True)
|
|
93
|
+
except Exception as exc:
|
|
94
|
+
print(
|
|
95
|
+
_color(f"[Ertebat] Update check failed: {type(exc).__name__}: {exc}", _RED),
|
|
96
|
+
file=sys.stderr,
|
|
97
|
+
flush=True,
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def check_for_updates(installed_version: str) -> None:
|
|
102
|
+
"""Check PyPI during import and finish before client token prompts."""
|
|
103
|
+
if os.environ.get("ERTEBAT_DISABLE_UPDATE_CHECK", "").lower() in {
|
|
104
|
+
"1", "true", "yes", "on"
|
|
105
|
+
}:
|
|
106
|
+
return
|
|
107
|
+
thread = threading.Thread(
|
|
108
|
+
target=_check,
|
|
109
|
+
args=(installed_version,),
|
|
110
|
+
name="ertebat-update-check",
|
|
111
|
+
daemon=True,
|
|
112
|
+
)
|
|
113
|
+
thread.start()
|
|
114
|
+
# Keep startup bounded, but ensure the result appears before bot.run()
|
|
115
|
+
# or a hidden token prompt can take over the terminal.
|
|
116
|
+
thread.join(timeout=_TIMEOUT + 2)
|
ertebat/api_methods.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Convenience methods for the documented Rubika Bot API."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class RubikaAPIMethods:
|
|
8
|
+
"""Mixin implementing documented Rubika Bot API endpoints."""
|
|
9
|
+
|
|
10
|
+
async def get_updates(self, offset_id: str | None = None, limit: int = 100):
|
|
11
|
+
"""Fetch updates; pass next_offset_id as offset_id on the next call."""
|
|
12
|
+
if not 1 <= limit <= 100:
|
|
13
|
+
raise ValueError("limit must be between 1 and 100.")
|
|
14
|
+
payload: dict[str, Any] = {"limit": limit}
|
|
15
|
+
if offset_id is not None:
|
|
16
|
+
payload["offset_id"] = offset_id
|
|
17
|
+
return await self.request("getUpdates", payload)
|
|
18
|
+
|
|
19
|
+
async def send_location(
|
|
20
|
+
self, chat_id: str, latitude: str | float, longitude: str | float,
|
|
21
|
+
**kwargs: Any,
|
|
22
|
+
):
|
|
23
|
+
"""Send a geographic location to a chat."""
|
|
24
|
+
payload = {"chat_id": chat_id, "latitude": str(latitude),
|
|
25
|
+
"longitude": str(longitude)}
|
|
26
|
+
payload.update(self._rubika_optional(kwargs, {
|
|
27
|
+
"chat_keypad", "inline_keypad", "disable_notification",
|
|
28
|
+
"reply_to_message_id", "chat_keypad_type",
|
|
29
|
+
}))
|
|
30
|
+
return await self.request("sendLocation", payload)
|
|
31
|
+
|
|
32
|
+
async def send_contact(
|
|
33
|
+
self, chat_id: str, first_name: str, phone_number: str,
|
|
34
|
+
last_name: str | None = None, **kwargs: Any,
|
|
35
|
+
):
|
|
36
|
+
"""Send a contact card to a chat."""
|
|
37
|
+
payload = {"chat_id": chat_id, "first_name": first_name,
|
|
38
|
+
"phone_number": phone_number}
|
|
39
|
+
if last_name is not None:
|
|
40
|
+
payload["last_name"] = last_name
|
|
41
|
+
payload.update(self._rubika_optional(kwargs, {
|
|
42
|
+
"chat_keypad", "inline_keypad", "disable_notification",
|
|
43
|
+
"reply_to_message_id", "chat_keypad_type",
|
|
44
|
+
}))
|
|
45
|
+
return await self.request("sendContact", payload)
|
|
46
|
+
|
|
47
|
+
async def edit_inline_keypad(
|
|
48
|
+
self, chat_id: str, message_id: str, inline_keypad: dict,
|
|
49
|
+
):
|
|
50
|
+
"""Replace an existing message's inline keypad.
|
|
51
|
+
|
|
52
|
+
Rubika's documentation prose names editMessageKeypad, while its
|
|
53
|
+
request example uses editInlineKeypad. The example endpoint is used.
|
|
54
|
+
"""
|
|
55
|
+
return await self.request("editInlineKeypad", {
|
|
56
|
+
"chat_id": chat_id, "message_id": message_id,
|
|
57
|
+
"inline_keypad": inline_keypad,
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
async def edit_message_keypad(
|
|
61
|
+
self, chat_id: str, message_id: str, inline_keypad: dict,
|
|
62
|
+
):
|
|
63
|
+
"""Alias for edit_inline_keypad."""
|
|
64
|
+
return await self.edit_inline_keypad(chat_id, message_id, inline_keypad)
|
|
65
|
+
|
|
66
|
+
async def edit_chat_keypad(
|
|
67
|
+
self, chat_id: str, chat_keypad: dict | None = None,
|
|
68
|
+
chat_keypad_type: str = "New",
|
|
69
|
+
):
|
|
70
|
+
"""Set or remove a chat keypad (use chat_keypad_type='Remove')."""
|
|
71
|
+
if chat_keypad_type not in {"New", "Remove", "None"}:
|
|
72
|
+
raise ValueError("chat_keypad_type must be New, Remove or None.")
|
|
73
|
+
payload: dict[str, Any] = {
|
|
74
|
+
"chat_id": chat_id, "chat_keypad_type": chat_keypad_type,
|
|
75
|
+
}
|
|
76
|
+
if chat_keypad is not None:
|
|
77
|
+
payload["chat_keypad"] = chat_keypad
|
|
78
|
+
if chat_keypad_type == "New" and chat_keypad is None:
|
|
79
|
+
raise ValueError("chat_keypad is required when chat_keypad_type='New'.")
|
|
80
|
+
return await self.request("editChatKeypad", payload)
|
|
81
|
+
|
|
82
|
+
async def set_commands(self, bot_commands: list[dict[str, str]]):
|
|
83
|
+
"""Register the bot's slash commands."""
|
|
84
|
+
if not isinstance(bot_commands, list):
|
|
85
|
+
raise TypeError("bot_commands must be a list of command dictionaries.")
|
|
86
|
+
return await self.request("setCommands", {"bot_commands": bot_commands})
|
|
87
|
+
|
|
88
|
+
async def update_bot_endpoints(self, url: str, endpoint_type: str):
|
|
89
|
+
"""Configure a webhook endpoint; the URL must be public HTTPS."""
|
|
90
|
+
if not url.startswith("https://"):
|
|
91
|
+
raise ValueError("Rubika webhook endpoints must use HTTPS.")
|
|
92
|
+
allowed = {
|
|
93
|
+
"ReceiveUpdate", "ReceiveInlineMessage", "ReceiveQuery",
|
|
94
|
+
"GetSelectionItem", "SearchSelectionItems",
|
|
95
|
+
}
|
|
96
|
+
if endpoint_type not in allowed:
|
|
97
|
+
raise ValueError(f"type must be one of: {', '.join(sorted(allowed))}")
|
|
98
|
+
return await self.request("updateBotEndpoints", {
|
|
99
|
+
"url": url, "type": endpoint_type,
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
async def update_bot_endpoint(self, url: str, endpoint_type: str):
|
|
103
|
+
"""Singular-name alias for update_bot_endpoints."""
|
|
104
|
+
return await self.update_bot_endpoints(url, endpoint_type)
|
|
105
|
+
|
|
106
|
+
async def request_send_file(self, file_type: str = "File"):
|
|
107
|
+
"""Request an upload URL for File, Image, Voice, Video, Music or Gif."""
|
|
108
|
+
allowed = {"File", "Image", "Voice", "Video", "Music", "Gif"}
|
|
109
|
+
if file_type not in allowed:
|
|
110
|
+
raise ValueError(f"type must be one of: {', '.join(sorted(allowed))}")
|
|
111
|
+
return await self.request("requestSendFile", {"type": file_type})
|
|
112
|
+
|
|
113
|
+
async def send_file_id(
|
|
114
|
+
self, chat_id: str, file_id: str, text: str | None = None,
|
|
115
|
+
**kwargs: Any,
|
|
116
|
+
):
|
|
117
|
+
"""Send an already-uploaded Rubika file by its file_id."""
|
|
118
|
+
payload: dict[str, Any] = {"chat_id": chat_id, "file_id": file_id}
|
|
119
|
+
if text is not None:
|
|
120
|
+
payload["text"] = text
|
|
121
|
+
payload.update(self._rubika_optional(kwargs, {
|
|
122
|
+
"reply_to_message_id", "disable_notification", "chat_keypad",
|
|
123
|
+
"inline_keypad", "chat_keypad_type",
|
|
124
|
+
}))
|
|
125
|
+
return await self.request("sendFile", payload)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
async def register_all_endpoints(self, base_url: str):
|
|
129
|
+
"""Register all five documented webhook endpoint types."""
|
|
130
|
+
base = base_url.rstrip("/")
|
|
131
|
+
if not base.startswith("https://"):
|
|
132
|
+
raise ValueError("Webhook base URL must use HTTPS.")
|
|
133
|
+
routes = {"ReceiveUpdate":"update", "ReceiveInlineMessage":"inline",
|
|
134
|
+
"ReceiveQuery":"query", "GetSelectionItem":"selection",
|
|
135
|
+
"SearchSelectionItems":"search-selection"}
|
|
136
|
+
results = {}
|
|
137
|
+
for endpoint_type, suffix in routes.items():
|
|
138
|
+
results[endpoint_type] = await self.update_bot_endpoints(
|
|
139
|
+
f"{base}/{suffix}", endpoint_type)
|
|
140
|
+
return results
|
|
141
|
+
|
|
142
|
+
@staticmethod
|
|
143
|
+
def _rubika_optional(values: dict, allowed: set[str]) -> dict:
|
|
144
|
+
"""Filter optional fields and omit None values."""
|
|
145
|
+
return {key: value for key, value in values.items()
|
|
146
|
+
if key in allowed and value is not None}
|