shirdal 1.0.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.
- shirdal/__init__.py +115 -0
- shirdal/cli.py +145 -0
- shirdal/client.py +156 -0
- shirdal/core/__init__.py +35 -0
- shirdal/core/adapter.py +167 -0
- shirdal/core/events.py +66 -0
- shirdal/core/hydrogram_adapter.py +329 -0
- shirdal/core/mock_adapter.py +290 -0
- shirdal/core/telethon_adapter.py +378 -0
- shirdal/engine/__init__.py +42 -0
- shirdal/engine/context.py +311 -0
- shirdal/engine/dispatcher.py +117 -0
- shirdal/engine/filters.py +151 -0
- shirdal/engine/fsm.py +95 -0
- shirdal/engine/media.py +121 -0
- shirdal/engine/scheduler.py +121 -0
- shirdal/guard/__init__.py +10 -0
- shirdal/guard/antiflood.py +322 -0
- shirdal/guard/middleware.py +16 -0
- shirdal/multi.py +116 -0
- shirdal/plugins/__init__.py +3 -0
- shirdal/plugins/loader.py +149 -0
- shirdal/py.typed +0 -0
- shirdal/storage/__init__.py +14 -0
- shirdal/storage/base.py +14 -0
- shirdal/storage/crypto.py +96 -0
- shirdal/storage/mysql.py +220 -0
- shirdal/storage/redis.py +117 -0
- shirdal/storage/sqlite.py +207 -0
- shirdal-1.0.0.dist-info/METADATA +117 -0
- shirdal-1.0.0.dist-info/RECORD +34 -0
- shirdal-1.0.0.dist-info/WHEEL +4 -0
- shirdal-1.0.0.dist-info/entry_points.txt +2 -0
- shirdal-1.0.0.dist-info/licenses/LICENSE +8 -0
shirdal/__init__.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
from shirdal.client import SelfBot
|
|
2
|
+
from shirdal.core.adapter import (
|
|
3
|
+
AdapterError,
|
|
4
|
+
DeviceProfile,
|
|
5
|
+
FloodWaitError,
|
|
6
|
+
TransportAdapter,
|
|
7
|
+
)
|
|
8
|
+
from shirdal.core.events import (
|
|
9
|
+
ChatAction,
|
|
10
|
+
ChatRef,
|
|
11
|
+
EventType,
|
|
12
|
+
MediaRef,
|
|
13
|
+
MessageEvent,
|
|
14
|
+
UpdateEvent,
|
|
15
|
+
UserRef,
|
|
16
|
+
)
|
|
17
|
+
from shirdal.core.hydrogram_adapter import HydrogramAdapter
|
|
18
|
+
from shirdal.core.mock_adapter import MockAdapter
|
|
19
|
+
from shirdal.core.telethon_adapter import TelethonAdapter
|
|
20
|
+
from shirdal.engine import (
|
|
21
|
+
Context,
|
|
22
|
+
Dispatcher,
|
|
23
|
+
Filter,
|
|
24
|
+
FSMContext,
|
|
25
|
+
FSMStorage,
|
|
26
|
+
MemoryStorage,
|
|
27
|
+
ProgressTracker,
|
|
28
|
+
ScheduledJob,
|
|
29
|
+
Scheduler,
|
|
30
|
+
State,
|
|
31
|
+
StatesGroup,
|
|
32
|
+
TransferProgress,
|
|
33
|
+
TransferQueue,
|
|
34
|
+
command,
|
|
35
|
+
group,
|
|
36
|
+
incoming,
|
|
37
|
+
outgoing,
|
|
38
|
+
private,
|
|
39
|
+
regex,
|
|
40
|
+
reply,
|
|
41
|
+
state,
|
|
42
|
+
text,
|
|
43
|
+
)
|
|
44
|
+
from shirdal.guard import (
|
|
45
|
+
AntiFloodAdapter,
|
|
46
|
+
AntiFloodConfig,
|
|
47
|
+
FloodStats,
|
|
48
|
+
Middleware,
|
|
49
|
+
NextHandler,
|
|
50
|
+
)
|
|
51
|
+
from shirdal.multi import MultiBot
|
|
52
|
+
from shirdal.plugins import PluginLoadResult, PluginManager
|
|
53
|
+
from shirdal.storage import (
|
|
54
|
+
CachedChat,
|
|
55
|
+
EncryptedStorage,
|
|
56
|
+
MySQLStorage,
|
|
57
|
+
RedisStorage,
|
|
58
|
+
SecretBox,
|
|
59
|
+
SQLiteStorage,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
__all__ = [
|
|
63
|
+
"SelfBot",
|
|
64
|
+
"MultiBot",
|
|
65
|
+
"TransportAdapter",
|
|
66
|
+
"DeviceProfile",
|
|
67
|
+
"AdapterError",
|
|
68
|
+
"FloodWaitError",
|
|
69
|
+
"EventType",
|
|
70
|
+
"ChatAction",
|
|
71
|
+
"MediaRef",
|
|
72
|
+
"UserRef",
|
|
73
|
+
"ChatRef",
|
|
74
|
+
"MessageEvent",
|
|
75
|
+
"UpdateEvent",
|
|
76
|
+
"MockAdapter",
|
|
77
|
+
"TelethonAdapter",
|
|
78
|
+
"HydrogramAdapter",
|
|
79
|
+
"Context",
|
|
80
|
+
"Dispatcher",
|
|
81
|
+
"Filter",
|
|
82
|
+
"State",
|
|
83
|
+
"StatesGroup",
|
|
84
|
+
"FSMStorage",
|
|
85
|
+
"MemoryStorage",
|
|
86
|
+
"FSMContext",
|
|
87
|
+
"Scheduler",
|
|
88
|
+
"ScheduledJob",
|
|
89
|
+
"ProgressTracker",
|
|
90
|
+
"TransferProgress",
|
|
91
|
+
"TransferQueue",
|
|
92
|
+
"command",
|
|
93
|
+
"text",
|
|
94
|
+
"outgoing",
|
|
95
|
+
"incoming",
|
|
96
|
+
"private",
|
|
97
|
+
"group",
|
|
98
|
+
"reply",
|
|
99
|
+
"regex",
|
|
100
|
+
"state",
|
|
101
|
+
"AntiFloodAdapter",
|
|
102
|
+
"AntiFloodConfig",
|
|
103
|
+
"FloodStats",
|
|
104
|
+
"Middleware",
|
|
105
|
+
"NextHandler",
|
|
106
|
+
"PluginManager",
|
|
107
|
+
"PluginLoadResult",
|
|
108
|
+
"SQLiteStorage",
|
|
109
|
+
"RedisStorage",
|
|
110
|
+
"MySQLStorage",
|
|
111
|
+
"EncryptedStorage",
|
|
112
|
+
"SecretBox",
|
|
113
|
+
"CachedChat",
|
|
114
|
+
]
|
|
115
|
+
__version__ = "1.0.0"
|
shirdal/cli.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import importlib.util
|
|
5
|
+
import os
|
|
6
|
+
import runpy
|
|
7
|
+
import sqlite3
|
|
8
|
+
import sys
|
|
9
|
+
from collections.abc import Sequence
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
_MAIN_TEMPLATE = """import os
|
|
13
|
+
from shirdal import SelfBot, SQLiteStorage{adapter_import}
|
|
14
|
+
|
|
15
|
+
{adapter_init}
|
|
16
|
+
bot = SelfBot(
|
|
17
|
+
adapter,
|
|
18
|
+
anti_flood=True,
|
|
19
|
+
plugins_dir="plugins",
|
|
20
|
+
hot_reload=True,
|
|
21
|
+
storage=SQLiteStorage("shirdal.db"),
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
if __name__ == "__main__":
|
|
25
|
+
bot.run()
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
_PLUGIN_PING_TEMPLATE = """from shirdal import Context, SelfBot, command, outgoing
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def setup(bot: SelfBot) -> None:
|
|
32
|
+
@bot.on(command("ping", prefix=".") & outgoing)
|
|
33
|
+
async def ping_cmd(ctx: Context) -> None:
|
|
34
|
+
msg = await ctx.edit("⚡ Checking...")
|
|
35
|
+
await msg.edit("🏓 Pong! Shirdal is alive.", auto_delete=10)
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
_ENV_TEMPLATE = """API_ID=123456
|
|
39
|
+
API_HASH=your_api_hash_here
|
|
40
|
+
SESSION_NAME=my_account
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _adapter_snippet(adapter: str) -> tuple[str, str]:
|
|
45
|
+
if adapter == "telethon":
|
|
46
|
+
return (
|
|
47
|
+
", TelethonAdapter",
|
|
48
|
+
'adapter = TelethonAdapter(\n'
|
|
49
|
+
' os.getenv("SESSION_NAME", "my_account"),\n'
|
|
50
|
+
' int(os.getenv("API_ID", "0")),\n'
|
|
51
|
+
' os.getenv("API_HASH", ""),\n'
|
|
52
|
+
')',
|
|
53
|
+
)
|
|
54
|
+
if adapter == "hydrogram":
|
|
55
|
+
return (
|
|
56
|
+
", HydrogramAdapter",
|
|
57
|
+
'adapter = HydrogramAdapter(\n'
|
|
58
|
+
' os.getenv("SESSION_NAME", "my_account"),\n'
|
|
59
|
+
' int(os.getenv("API_ID", "0")),\n'
|
|
60
|
+
' os.getenv("API_HASH", ""),\n'
|
|
61
|
+
')',
|
|
62
|
+
)
|
|
63
|
+
return (", MockAdapter", "adapter = MockAdapter()")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def cmd_new(args: argparse.Namespace) -> int:
|
|
67
|
+
target = Path(args.dir) / args.name
|
|
68
|
+
if target.exists() and any(target.iterdir()):
|
|
69
|
+
print(f"Error: directory '{target}' already exists and is not empty.", file=sys.stderr)
|
|
70
|
+
return 1
|
|
71
|
+
|
|
72
|
+
plugins_dir = target / "plugins"
|
|
73
|
+
plugins_dir.mkdir(parents=True, exist_ok=True)
|
|
74
|
+
|
|
75
|
+
adapter_import, adapter_init = _adapter_snippet(args.adapter)
|
|
76
|
+
(target / "main.py").write_text(
|
|
77
|
+
_MAIN_TEMPLATE.format(adapter_import=adapter_import, adapter_init=adapter_init),
|
|
78
|
+
encoding="utf-8",
|
|
79
|
+
)
|
|
80
|
+
(plugins_dir / "ping.py").write_text(_PLUGIN_PING_TEMPLATE, encoding="utf-8")
|
|
81
|
+
(target / ".env.example").write_text(_ENV_TEMPLATE, encoding="utf-8")
|
|
82
|
+
print(f"Created shirdal project at {target}")
|
|
83
|
+
return 0
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def cmd_doctor(_: argparse.Namespace) -> int:
|
|
87
|
+
py_ver = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
|
|
88
|
+
py_ok = sys.version_info >= (3, 11)
|
|
89
|
+
print(f"Python: {py_ver} ({'OK' if py_ok else 'FAIL: requires >=3.11'})")
|
|
90
|
+
print(f"SQLite: {sqlite3.sqlite_version} (OK)")
|
|
91
|
+
|
|
92
|
+
optional = ("uvloop", "msgspec", "telethon", "hydrogram", "redis", "cryptography")
|
|
93
|
+
for pkg in optional:
|
|
94
|
+
found = importlib.util.find_spec(pkg) is not None
|
|
95
|
+
print(f" - {pkg}: {'installed' if found else 'not installed'}")
|
|
96
|
+
return 0 if py_ok else 1
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def cmd_run(args: argparse.Namespace) -> int:
|
|
100
|
+
script = Path(args.target)
|
|
101
|
+
if not script.exists():
|
|
102
|
+
print(f"Error: target '{script}' not found.", file=sys.stderr)
|
|
103
|
+
return 1
|
|
104
|
+
sys.path.insert(0, str(script.parent.resolve()))
|
|
105
|
+
os.chdir(script.parent.resolve())
|
|
106
|
+
runpy.run_path(str(script.name), run_name="__main__")
|
|
107
|
+
return 0
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
111
|
+
parser = argparse.ArgumentParser(
|
|
112
|
+
prog="shirdal",
|
|
113
|
+
description="Shirdal self-bot framework CLI",
|
|
114
|
+
)
|
|
115
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
116
|
+
|
|
117
|
+
p_new = sub.add_parser("new", help="Create a new shirdal self-bot project")
|
|
118
|
+
p_new.add_argument("name", help="Project directory name")
|
|
119
|
+
p_new.add_argument(
|
|
120
|
+
"--adapter",
|
|
121
|
+
choices=("telethon", "hydrogram", "mock"),
|
|
122
|
+
default="telethon",
|
|
123
|
+
help="Default MTProto adapter",
|
|
124
|
+
)
|
|
125
|
+
p_new.add_argument("--dir", default=".", help="Parent directory")
|
|
126
|
+
p_new.set_defaults(func=cmd_new)
|
|
127
|
+
|
|
128
|
+
p_doc = sub.add_parser("doctor", help="Check Python and optional dependencies")
|
|
129
|
+
p_doc.set_defaults(func=cmd_doctor)
|
|
130
|
+
|
|
131
|
+
p_run = sub.add_parser("run", help="Run a shirdal entry script")
|
|
132
|
+
p_run.add_argument("target", nargs="?", default="main.py", help="Path to main.py")
|
|
133
|
+
p_run.set_defaults(func=cmd_run)
|
|
134
|
+
|
|
135
|
+
return parser
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
139
|
+
parser = build_parser()
|
|
140
|
+
args = parser.parse_args(argv)
|
|
141
|
+
return int(args.func(args))
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
if __name__ == "__main__":
|
|
145
|
+
raise SystemExit(main())
|
shirdal/client.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from shirdal.core.adapter import TransportAdapter
|
|
9
|
+
from shirdal.core.events import EventType, UpdateEvent
|
|
10
|
+
from shirdal.engine.dispatcher import ContextHandler, Dispatcher, ErrorHandler
|
|
11
|
+
from shirdal.engine.filters import Filter
|
|
12
|
+
from shirdal.engine.fsm import FSMStorage
|
|
13
|
+
from shirdal.engine.scheduler import JobFunc, Scheduler
|
|
14
|
+
from shirdal.guard.antiflood import AntiFloodAdapter, AntiFloodConfig
|
|
15
|
+
from shirdal.guard.middleware import Middleware
|
|
16
|
+
from shirdal.plugins.loader import PluginManager
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class SelfBot:
|
|
20
|
+
"""Main entry point for a shirdal self-bot instance."""
|
|
21
|
+
|
|
22
|
+
def __init__(
|
|
23
|
+
self,
|
|
24
|
+
adapter: TransportAdapter,
|
|
25
|
+
*,
|
|
26
|
+
use_uvloop: bool = True,
|
|
27
|
+
anti_flood: bool = True,
|
|
28
|
+
flood_config: AntiFloodConfig | None = None,
|
|
29
|
+
plugins_dir: str | Path | None = None,
|
|
30
|
+
hot_reload: bool = False,
|
|
31
|
+
reload_interval: float = 1.0,
|
|
32
|
+
storage: FSMStorage | None = None,
|
|
33
|
+
) -> None:
|
|
34
|
+
self.raw_adapter = adapter
|
|
35
|
+
self.adapter: TransportAdapter = (
|
|
36
|
+
AntiFloodAdapter(adapter, config=flood_config) if anti_flood else adapter
|
|
37
|
+
)
|
|
38
|
+
self._use_uvloop = use_uvloop
|
|
39
|
+
self._tasks: set[asyncio.Task[Any]] = set()
|
|
40
|
+
self.dispatcher = Dispatcher(task_pool=self._tasks, storage=storage)
|
|
41
|
+
self.scheduler = Scheduler(self)
|
|
42
|
+
self._running = False
|
|
43
|
+
self._active_plugin_scope: str | None = None
|
|
44
|
+
|
|
45
|
+
self.plugins: PluginManager | None = (
|
|
46
|
+
PluginManager(self, plugins_dir) if plugins_dir is not None else None
|
|
47
|
+
)
|
|
48
|
+
self._hot_reload = hot_reload
|
|
49
|
+
self._reload_interval = reload_interval
|
|
50
|
+
self._watcher_task: asyncio.Task[Any] | None = None
|
|
51
|
+
|
|
52
|
+
def use(self, middleware: Middleware) -> Middleware:
|
|
53
|
+
return self.dispatcher.add_middleware(middleware)
|
|
54
|
+
|
|
55
|
+
def on(
|
|
56
|
+
self,
|
|
57
|
+
filter_obj: Filter | None = None,
|
|
58
|
+
*,
|
|
59
|
+
event_type: EventType = EventType.NEW_MESSAGE,
|
|
60
|
+
) -> Callable[[ContextHandler], ContextHandler]:
|
|
61
|
+
def decorator(func: ContextHandler) -> ContextHandler:
|
|
62
|
+
return self.dispatcher.register(
|
|
63
|
+
filter_obj,
|
|
64
|
+
func,
|
|
65
|
+
event_type=event_type,
|
|
66
|
+
plugin_name=self._active_plugin_scope,
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
return decorator
|
|
70
|
+
|
|
71
|
+
def on_edit(
|
|
72
|
+
self, filter_obj: Filter | None = None
|
|
73
|
+
) -> Callable[[ContextHandler], ContextHandler]:
|
|
74
|
+
"""Register a handler for edited messages."""
|
|
75
|
+
return self.on(filter_obj, event_type=EventType.EDIT_MESSAGE)
|
|
76
|
+
|
|
77
|
+
def on_message(self, func: ContextHandler) -> ContextHandler:
|
|
78
|
+
return self.dispatcher.register(
|
|
79
|
+
None, func, plugin_name=self._active_plugin_scope
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
def on_error(self, func: ErrorHandler) -> ErrorHandler:
|
|
83
|
+
"""Register a global error handler receiving (ctx, exception)."""
|
|
84
|
+
return self.dispatcher.register_error_handler(func)
|
|
85
|
+
|
|
86
|
+
def every(
|
|
87
|
+
self,
|
|
88
|
+
*,
|
|
89
|
+
seconds: float = 0.0,
|
|
90
|
+
minutes: float = 0.0,
|
|
91
|
+
hours: float = 0.0,
|
|
92
|
+
run_immediately: bool = False,
|
|
93
|
+
) -> Callable[[JobFunc], JobFunc]:
|
|
94
|
+
total_seconds = seconds + (minutes * 60.0) + (hours * 3600.0)
|
|
95
|
+
|
|
96
|
+
def decorator(func: JobFunc) -> JobFunc:
|
|
97
|
+
self.scheduler.add_periodic(
|
|
98
|
+
total_seconds,
|
|
99
|
+
func,
|
|
100
|
+
run_immediately=run_immediately,
|
|
101
|
+
plugin_name=self._active_plugin_scope,
|
|
102
|
+
)
|
|
103
|
+
return func
|
|
104
|
+
|
|
105
|
+
return decorator
|
|
106
|
+
|
|
107
|
+
def after(self, delay: float, func: JobFunc) -> asyncio.Task[Any]:
|
|
108
|
+
return self.scheduler.schedule_once(delay, func)
|
|
109
|
+
|
|
110
|
+
async def start(self) -> None:
|
|
111
|
+
await self.adapter.connect()
|
|
112
|
+
self._running = True
|
|
113
|
+
if self.plugins is not None:
|
|
114
|
+
await self.plugins.load_all()
|
|
115
|
+
if self._hot_reload:
|
|
116
|
+
self._watcher_task = asyncio.create_task(
|
|
117
|
+
self.plugins.watch_loop(self._reload_interval)
|
|
118
|
+
)
|
|
119
|
+
self.scheduler.start()
|
|
120
|
+
|
|
121
|
+
async def stop(self) -> None:
|
|
122
|
+
self._running = False
|
|
123
|
+
await self.scheduler.stop()
|
|
124
|
+
if self._watcher_task is not None:
|
|
125
|
+
self._watcher_task.cancel()
|
|
126
|
+
await asyncio.gather(self._watcher_task, return_exceptions=True)
|
|
127
|
+
self._watcher_task = None
|
|
128
|
+
if self._tasks:
|
|
129
|
+
await asyncio.gather(*list(self._tasks), return_exceptions=True)
|
|
130
|
+
self._tasks.clear()
|
|
131
|
+
await self.adapter.disconnect()
|
|
132
|
+
close_fn = getattr(self.dispatcher.storage, "close", None)
|
|
133
|
+
if callable(close_fn):
|
|
134
|
+
close_fn()
|
|
135
|
+
|
|
136
|
+
async def _dispatch_update(self, update: UpdateEvent) -> None:
|
|
137
|
+
await self.dispatcher.dispatch(update, self.adapter)
|
|
138
|
+
|
|
139
|
+
async def serve(self) -> None:
|
|
140
|
+
await self.start()
|
|
141
|
+
try:
|
|
142
|
+
async for update in self.adapter.listen():
|
|
143
|
+
if not self._running:
|
|
144
|
+
break
|
|
145
|
+
await self._dispatch_update(update)
|
|
146
|
+
finally:
|
|
147
|
+
await self.stop()
|
|
148
|
+
|
|
149
|
+
def run(self) -> None:
|
|
150
|
+
if self._use_uvloop:
|
|
151
|
+
try:
|
|
152
|
+
import uvloop # type: ignore[import-not-found]
|
|
153
|
+
uvloop.install()
|
|
154
|
+
except ImportError:
|
|
155
|
+
pass
|
|
156
|
+
asyncio.run(self.serve())
|
shirdal/core/__init__.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from shirdal.core.adapter import (
|
|
2
|
+
AdapterError,
|
|
3
|
+
DeviceProfile,
|
|
4
|
+
FloodWaitError,
|
|
5
|
+
TransportAdapter,
|
|
6
|
+
)
|
|
7
|
+
from shirdal.core.events import (
|
|
8
|
+
ChatAction,
|
|
9
|
+
ChatRef,
|
|
10
|
+
EventType,
|
|
11
|
+
MediaRef,
|
|
12
|
+
MessageEvent,
|
|
13
|
+
UpdateEvent,
|
|
14
|
+
UserRef,
|
|
15
|
+
)
|
|
16
|
+
from shirdal.core.hydrogram_adapter import HydrogramAdapter
|
|
17
|
+
from shirdal.core.mock_adapter import MockAdapter
|
|
18
|
+
from shirdal.core.telethon_adapter import TelethonAdapter
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"TransportAdapter",
|
|
22
|
+
"DeviceProfile",
|
|
23
|
+
"AdapterError",
|
|
24
|
+
"FloodWaitError",
|
|
25
|
+
"EventType",
|
|
26
|
+
"ChatAction",
|
|
27
|
+
"MediaRef",
|
|
28
|
+
"UserRef",
|
|
29
|
+
"ChatRef",
|
|
30
|
+
"MessageEvent",
|
|
31
|
+
"UpdateEvent",
|
|
32
|
+
"MockAdapter",
|
|
33
|
+
"TelethonAdapter",
|
|
34
|
+
"HydrogramAdapter",
|
|
35
|
+
]
|
shirdal/core/adapter.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any, AsyncIterator, Protocol, runtime_checkable
|
|
7
|
+
|
|
8
|
+
from shirdal.core.events import ChatAction, ChatRef, MessageEvent, UpdateEvent
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class AdapterError(Exception):
|
|
12
|
+
"""Base exception for transport adapter failures."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class FloodWaitError(AdapterError):
|
|
16
|
+
"""Raised when Telegram rate-limits a request."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, seconds: float, message: str | None = None) -> None:
|
|
19
|
+
self.seconds = float(seconds)
|
|
20
|
+
super().__init__(message or f"FloodWait: retry after {self.seconds}s")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(slots=True, frozen=True)
|
|
24
|
+
class DeviceProfile:
|
|
25
|
+
"""Clean client device fingerprint sent to Telegram during session creation."""
|
|
26
|
+
|
|
27
|
+
device_model: str = "Desktop"
|
|
28
|
+
system_version: str = "Windows 11"
|
|
29
|
+
app_version: str = "5.8.3 x64"
|
|
30
|
+
lang_code: str = "en"
|
|
31
|
+
system_lang_code: str = "en-US"
|
|
32
|
+
|
|
33
|
+
@classmethod
|
|
34
|
+
def desktop(cls) -> DeviceProfile:
|
|
35
|
+
return cls()
|
|
36
|
+
|
|
37
|
+
@classmethod
|
|
38
|
+
def macos(cls) -> DeviceProfile:
|
|
39
|
+
return cls(
|
|
40
|
+
device_model="MacBook Pro",
|
|
41
|
+
system_version="macOS 15.1",
|
|
42
|
+
app_version="11.4.0",
|
|
43
|
+
lang_code="en",
|
|
44
|
+
system_lang_code="en-US",
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@runtime_checkable
|
|
49
|
+
class TransportAdapter(Protocol):
|
|
50
|
+
"""Abstract MTProto transport interface for shirdal."""
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def is_connected(self) -> bool: ...
|
|
54
|
+
|
|
55
|
+
async def connect(self) -> None: ...
|
|
56
|
+
|
|
57
|
+
async def disconnect(self) -> None: ...
|
|
58
|
+
|
|
59
|
+
async def invoke(self, method: str, **params: Any) -> Any: ...
|
|
60
|
+
|
|
61
|
+
def listen(self) -> AsyncIterator[UpdateEvent]: ...
|
|
62
|
+
|
|
63
|
+
async def send_message(
|
|
64
|
+
self,
|
|
65
|
+
chat_id: int | str,
|
|
66
|
+
text: str,
|
|
67
|
+
*,
|
|
68
|
+
reply_to: int | None = None,
|
|
69
|
+
parse_mode: str | None = "html",
|
|
70
|
+
) -> MessageEvent: ...
|
|
71
|
+
|
|
72
|
+
async def edit_message(
|
|
73
|
+
self,
|
|
74
|
+
chat_id: int | str,
|
|
75
|
+
message_id: int,
|
|
76
|
+
text: str,
|
|
77
|
+
*,
|
|
78
|
+
parse_mode: str | None = "html",
|
|
79
|
+
) -> MessageEvent: ...
|
|
80
|
+
|
|
81
|
+
async def delete_messages(
|
|
82
|
+
self,
|
|
83
|
+
chat_id: int | str,
|
|
84
|
+
message_ids: list[int],
|
|
85
|
+
*,
|
|
86
|
+
revoke: bool = True,
|
|
87
|
+
) -> int: ...
|
|
88
|
+
|
|
89
|
+
async def send_media(
|
|
90
|
+
self,
|
|
91
|
+
chat_id: int | str,
|
|
92
|
+
media: str | Path | bytes,
|
|
93
|
+
*,
|
|
94
|
+
caption: str | None = None,
|
|
95
|
+
reply_to: int | None = None,
|
|
96
|
+
parse_mode: str | None = "html",
|
|
97
|
+
progress: Any = None,
|
|
98
|
+
) -> MessageEvent: ...
|
|
99
|
+
|
|
100
|
+
async def send_album(
|
|
101
|
+
self,
|
|
102
|
+
chat_id: int | str,
|
|
103
|
+
media_items: Sequence[str | Path | bytes],
|
|
104
|
+
*,
|
|
105
|
+
caption: str | None = None,
|
|
106
|
+
reply_to: int | None = None,
|
|
107
|
+
parse_mode: str | None = "html",
|
|
108
|
+
) -> list[MessageEvent]: ...
|
|
109
|
+
|
|
110
|
+
async def download_media(
|
|
111
|
+
self,
|
|
112
|
+
message: MessageEvent,
|
|
113
|
+
*,
|
|
114
|
+
destination: str | Path | None = None,
|
|
115
|
+
progress: Any = None,
|
|
116
|
+
) -> Path | bytes: ...
|
|
117
|
+
|
|
118
|
+
async def send_reaction(
|
|
119
|
+
self,
|
|
120
|
+
chat_id: int | str,
|
|
121
|
+
message_id: int,
|
|
122
|
+
emoji: str | None,
|
|
123
|
+
) -> None: ...
|
|
124
|
+
|
|
125
|
+
async def send_chat_action(
|
|
126
|
+
self,
|
|
127
|
+
chat_id: int | str,
|
|
128
|
+
action: ChatAction | str,
|
|
129
|
+
) -> None: ...
|
|
130
|
+
|
|
131
|
+
async def pin_message(
|
|
132
|
+
self,
|
|
133
|
+
chat_id: int | str,
|
|
134
|
+
message_id: int,
|
|
135
|
+
*,
|
|
136
|
+
silent: bool = True,
|
|
137
|
+
) -> None: ...
|
|
138
|
+
|
|
139
|
+
async def ban_user(
|
|
140
|
+
self,
|
|
141
|
+
chat_id: int | str,
|
|
142
|
+
user_id: int | str,
|
|
143
|
+
*,
|
|
144
|
+
until_date: int | None = None,
|
|
145
|
+
) -> None: ...
|
|
146
|
+
|
|
147
|
+
async def unban_user(
|
|
148
|
+
self,
|
|
149
|
+
chat_id: int | str,
|
|
150
|
+
user_id: int | str,
|
|
151
|
+
) -> None: ...
|
|
152
|
+
|
|
153
|
+
async def mute_user(
|
|
154
|
+
self,
|
|
155
|
+
chat_id: int | str,
|
|
156
|
+
user_id: int | str,
|
|
157
|
+
*,
|
|
158
|
+
until_date: int | None = None,
|
|
159
|
+
) -> None: ...
|
|
160
|
+
|
|
161
|
+
async def kick_user(
|
|
162
|
+
self,
|
|
163
|
+
chat_id: int | str,
|
|
164
|
+
user_id: int | str,
|
|
165
|
+
) -> None: ...
|
|
166
|
+
|
|
167
|
+
async def get_chat(self, chat_id: int | str) -> ChatRef: ...
|
shirdal/core/events.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from datetime import datetime, timezone
|
|
5
|
+
from enum import StrEnum
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class EventType(StrEnum):
|
|
10
|
+
NEW_MESSAGE = "new_message"
|
|
11
|
+
EDIT_MESSAGE = "edit_message"
|
|
12
|
+
DELETE_MESSAGE = "delete_message"
|
|
13
|
+
RAW = "raw"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ChatAction(StrEnum):
|
|
17
|
+
TYPING = "typing"
|
|
18
|
+
UPLOAD_PHOTO = "upload_photo"
|
|
19
|
+
UPLOAD_VIDEO = "upload_video"
|
|
20
|
+
UPLOAD_DOCUMENT = "upload_document"
|
|
21
|
+
RECORD_VOICE = "record_voice"
|
|
22
|
+
CANCEL = "cancel"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(slots=True, frozen=True)
|
|
26
|
+
class MediaRef:
|
|
27
|
+
media_type: str # photo | video | document | voice | sticker | audio
|
|
28
|
+
file_id: str | None = None
|
|
29
|
+
mime_type: str | None = None
|
|
30
|
+
file_name: str | None = None
|
|
31
|
+
file_size: int | None = None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(slots=True, frozen=True)
|
|
35
|
+
class UserRef:
|
|
36
|
+
id: int
|
|
37
|
+
username: str | None = None
|
|
38
|
+
first_name: str | None = None
|
|
39
|
+
is_self: bool = False
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(slots=True, frozen=True)
|
|
43
|
+
class ChatRef:
|
|
44
|
+
id: int
|
|
45
|
+
type: str = "private" # private | group | supergroup | channel
|
|
46
|
+
title: str | None = None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(slots=True)
|
|
50
|
+
class MessageEvent:
|
|
51
|
+
id: int
|
|
52
|
+
chat: ChatRef
|
|
53
|
+
sender: UserRef | None
|
|
54
|
+
text: str = ""
|
|
55
|
+
media: MediaRef | None = None
|
|
56
|
+
reply_to_id: int | None = None
|
|
57
|
+
is_outgoing: bool = False
|
|
58
|
+
date: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
|
59
|
+
raw: Any = None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(slots=True)
|
|
63
|
+
class UpdateEvent:
|
|
64
|
+
type: EventType
|
|
65
|
+
message: MessageEvent | None = None
|
|
66
|
+
raw: Any = None
|