|
1 | 1 | # SPDX-License-Identifier: BSD-3-Clause |
2 | 2 | # Copyright (c) 2025 Hitalo M. <https://github.com/HitaloM> |
3 | 3 |
|
4 | | -import operator |
| 4 | +import contextlib |
5 | 5 | from datetime import UTC, datetime |
| 6 | +from io import BytesIO |
6 | 7 |
|
| 8 | +import aiofiles |
7 | 9 | from hydrogram import Client |
| 10 | +from hydrogram.errors import MessageDeleteForbidden |
8 | 11 | from hydrogram.types import Message |
9 | 12 |
|
10 | 13 | from korone.decorators import router |
|
14 | 17 |
|
15 | 18 | @router.message(Command("logs", disableable=False) & IsSudo) |
16 | 19 | async def handle_logs_command(client: Client, message: Message) -> None: |
17 | | - if not (log_files := list(LOG_DIR.glob("korone.log*"))): |
| 20 | + log_files = list(LOG_DIR.glob("korone.log*")) |
| 21 | + if not log_files: |
18 | 22 | await message.reply("No log files found.") |
19 | 23 | return |
20 | 24 |
|
21 | | - file_times = {file: file.stat().st_mtime for file in log_files} |
22 | | - match max(file_times.items(), key=operator.itemgetter(1)): |
23 | | - case (most_recent_file, mtime): |
24 | | - file_size = round(most_recent_file.stat().st_size / (1024 * 1024), 2) |
25 | | - timestamp = datetime.fromtimestamp(mtime, UTC).strftime("%Y-%m-%d %H:%M:%S") |
26 | | - caption = ( |
27 | | - f"<b>📄 Log File</b>\n" |
28 | | - f"<b>File:</b> <code>{most_recent_file.name}</code>\n" |
29 | | - f"<b>Size:</b> <code>{file_size} MB</code>\n" |
30 | | - f"<b>Last Modified:</b> <code>{timestamp} UTC</code>" |
31 | | - ) |
| 25 | + most_recent_file = max(log_files, key=lambda f: f.stat().st_mtime) |
| 26 | + file_size = round(most_recent_file.stat().st_size / (1024 * 1024), 2) |
| 27 | + timestamp = datetime.fromtimestamp(most_recent_file.stat().st_mtime, UTC).strftime( |
| 28 | + "%Y-%m-%d %H:%M:%S" |
| 29 | + ) |
| 30 | + caption = ( |
| 31 | + f"<b>📄 Log File</b>\n" |
| 32 | + f"<b>File:</b> <code>{most_recent_file.name}</code>\n" |
| 33 | + f"<b>Size:</b> <code>{file_size} MB</code>\n" |
| 34 | + f"<b>Last Modified:</b> <code>{timestamp} UTC</code>" |
| 35 | + ) |
32 | 36 |
|
33 | 37 | status_message = await message.reply("Uploading log file...") |
34 | 38 |
|
35 | 39 | try: |
| 40 | + async with aiofiles.open(most_recent_file, "rb") as file: |
| 41 | + file_buffer = BytesIO(await file.read()) |
| 42 | + file_buffer.seek(0) |
| 43 | + |
36 | 44 | await message.reply_document( |
37 | | - document=str(most_recent_file), |
| 45 | + document=file_buffer, |
38 | 46 | caption=caption, |
39 | 47 | file_name=most_recent_file.name, |
40 | 48 | ) |
41 | | - await status_message.delete() |
| 49 | + |
| 50 | + with contextlib.suppress(MessageDeleteForbidden): |
| 51 | + await status_message.delete() |
| 52 | + |
42 | 53 | except Exception as exc: |
43 | | - await status_message.edit(f"Error sending log file: {exc!s}") |
| 54 | + await status_message.edit(f"Error sending log file: {exc}") |
0 commit comments