-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlog.py
113 lines (86 loc) · 3.13 KB
/
log.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# Fly-telegram UserBot
# this code is licensed by cc-by-nc (https://creativecommons.org/share-your-work/cclicenses)
import contextlib
import threading
import logging
import asyncio
import functools
import html
from pyrogram import Client
from pyrogram.errors import exceptions
from aiogram import types
from aiogram.utils.keyboard import InlineKeyboardBuilder
from inline.types import inline
def fix_task_error(task: asyncio.Task):
"""
Fixes task errors by canceling the task and ignoring any exceptions.
Args:
task (asyncio.Task): The task to fix.
"""
def no_error(task: asyncio.Task):
try:
task.cancel()
except Exception:
pass
task.add_done_callback(functools.partial(no_error))
class UserbotHandler(logging.StreamHandler):
"""
A custom logging handler for the userbot.
Args:
client (Client): The Telegram client instance.
"""
def __init__(self, client: Client):
"""
Initializes the handler.
Args:
client (Client): The Telegram client instance.
"""
self.buffer = []
self.client = client
self.filters = []
self.lock = threading.RLock()
super().__init__()
def emit(self, record: logging.LogRecord):
"""
Emits a log record.
Args:
record (logging.LogRecord): The log record.
"""
super().emit(record)
with contextlib.suppress(Exception):
task = asyncio.ensure_future(self.inlinelog(record))
async def inlinelog(self, record: logging.LogRecord):
"""
Logs an error message to the Telegram bot.
Args:
record (logging.LogRecord): The log record.
"""
if record.levelname == "ERROR" and inline.bot:
builder = InlineKeyboardBuilder()
builder.row(types.InlineKeyboardButton(
text="⚠️ Issues", url="https://github.com/fly-telegram/userbot/issues"))
text = f"<code>{html.escape(self.format(record))}</code>\n"
if self.buffer:
for x in self.buffer:
text += f"<code>{html.escape(x)}</code>\n"
await inline.bot.send_message(self.client.me.id, text,
reply_markup=builder.as_markup())
def load(client: Client) -> logging.Logger:
"""
Loads the logging configuration for the userbot.
Returns:
logging.Logger: The logger instance.
"""
format = logging.Formatter(
"%(asctime)s [%(levelname)s] %(funcName)s: %(lineno)d - %(message)s",
"%m-%d %H:%M:%S")
logger = logging.getLogger()
logger.handlers = []
logger.setLevel(logging.INFO)
telegram_handler = UserbotHandler(client)
logger.addHandler(telegram_handler)
telegram_handler.setFormatter(format)
logging.getLogger("pyrogram").setLevel(logging.WARNING)
logging.getLogger("aiogram").setLevel(logging.WARNING)
logging.getLogger("aiohttp").setLevel(logging.WARNING)
return logger