|
3 | 3 |
|
4 | 4 | import html |
5 | 5 | import io |
| 6 | +import os |
| 7 | +import sys |
| 8 | +import time |
6 | 9 | from subprocess import PIPE |
7 | | -from typing import Any, TypedDict |
| 10 | +from typing import Any, Never, TypedDict |
8 | 11 |
|
9 | 12 | from anyio import run_process |
10 | 13 | from hydrogram.types import Message |
11 | 14 |
|
| 15 | +from korone import constants |
| 16 | +from korone.utils.caching import cache |
| 17 | + |
12 | 18 |
|
13 | 19 | class CommitInfo(TypedDict): |
14 | 20 | title: str |
15 | 21 |
|
16 | 22 |
|
| 23 | +class RebootCache(TypedDict): |
| 24 | + chat_id: int |
| 25 | + message_id: int |
| 26 | + time: float |
| 27 | + |
| 28 | + |
17 | 29 | async def generate_document(output: Any, message: Message) -> None: |
18 | 30 | with io.BytesIO(str.encode(str(output))) as file: |
19 | 31 | file.name = "output.txt" |
@@ -56,3 +68,34 @@ def generate_changelog(commits: dict[str, CommitInfo]) -> str: |
56 | 68 | async def perform_update() -> str: |
57 | 69 | commands = ["git reset --hard origin/main", "pybabel compile -d locales -D bot", "uv sync"] |
58 | 70 | return "".join([await run_command(command) for command in commands]) |
| 71 | + |
| 72 | + |
| 73 | +async def restart_bot(message: Message, text: str) -> Never: |
| 74 | + await cache.delete(constants.REBOOT_CACHE_KEY) |
| 75 | + await message.edit_text(text) |
| 76 | + |
| 77 | + value: RebootCache = { |
| 78 | + "chat_id": message.chat.id, |
| 79 | + "message_id": message.id, |
| 80 | + "time": time.time(), |
| 81 | + } |
| 82 | + await cache.set(constants.REBOOT_CACHE_KEY, value=value, expire=constants.REBOOT_CACHE_TTL) |
| 83 | + |
| 84 | + main_module = sys.modules.get("__main__") |
| 85 | + module_name = None |
| 86 | + |
| 87 | + if main_module is not None: |
| 88 | + if package_name := getattr(main_module, "__package__", None): |
| 89 | + module_name = package_name |
| 90 | + elif (spec := getattr(main_module, "__spec__", None)) and ( |
| 91 | + spec_name := getattr(spec, "name", None) |
| 92 | + ): |
| 93 | + module_name = spec_name.removesuffix(".__main__") |
| 94 | + |
| 95 | + if module_name: |
| 96 | + args = [sys.executable, "-m", module_name, *sys.argv[1:]] |
| 97 | + else: |
| 98 | + script_candidate = sys.argv[0] or getattr(main_module, "__file__", "") |
| 99 | + args = [sys.executable, script_candidate, *sys.argv[1:]] |
| 100 | + |
| 101 | + os.execv(sys.executable, args) |
0 commit comments