PagerMaid-Pyro/pagermaid/modules/sentry.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

82 lines
2.3 KiB
Python
Raw Normal View History

2022-08-01 16:04:45 +00:00
import sentry_sdk
from subprocess import run, PIPE
import sys
2022-08-01 16:04:45 +00:00
from time import time
2022-08-02 04:57:08 +00:00
from pyrogram.errors import Unauthorized, UsernameInvalid
2022-09-07 08:16:37 +00:00
from sentry_sdk.integrations.httpx import HttpxIntegration
2022-08-01 16:04:45 +00:00
from pagermaid import Config
from pagermaid.enums import Client, Message
from pagermaid.hook import Hook
from pagermaid.single_utils import safe_remove
def sentry_before_send(event, hint):
global sentry_sdk_report_time
exc_info = hint.get("exc_info")
2022-08-02 04:57:08 +00:00
if exc_info and isinstance(exc_info[1], (Unauthorized, UsernameInvalid)):
2022-08-01 16:04:45 +00:00
# The user has been deleted/deactivated or session revoked
2023-03-12 03:56:01 +00:00
safe_remove("pagermaid.session")
sys.exit(1)
2022-08-01 16:04:45 +00:00
if time() <= sentry_sdk_report_time + 30:
sentry_sdk_report_time = time()
return None
else:
sentry_sdk_report_time = time()
return event
sentry_sdk_report_time = time()
2023-03-12 03:56:01 +00:00
sentry_sdk_git_hash = (
run("git rev-parse HEAD", stdout=PIPE, shell=True, check=True)
.stdout.decode()
.strip()
2023-03-12 03:56:01 +00:00
)
# fixme: Not enough for dynamic disable sentry,
# web server will still report if pgm start with Config.ERROR_REPORT = True
if Config.ERROR_REPORT:
sentry_sdk.init(
Config.SENTRY_API,
traces_sample_rate=1.0,
release=sentry_sdk_git_hash,
before_send=sentry_before_send,
environment="production",
integrations=[
HttpxIntegration(),
],
)
else:
sentry_sdk.init()
2022-08-01 16:04:45 +00:00
@Hook.on_startup()
async def sentry_init_id(bot: Client):
2022-09-07 08:16:37 +00:00
if not bot.me:
bot.me = await bot.get_me()
data = {"id": bot.me.id, "name": bot.me.first_name, "ip_address": "{{auto}}"}
if bot.me.username:
data["username"] = bot.me.username
sentry_sdk.set_user(data)
2022-08-01 16:04:45 +00:00
@Hook.process_error()
async def sentry_report(message: Message, command, exc_info, **_):
2023-12-29 11:40:53 +00:00
if not Config.ERROR_REPORT:
return
2022-08-01 16:04:45 +00:00
sender_id = message.from_user.id if message.from_user else ""
sender_id = message.sender_chat.id if message.sender_chat else sender_id
2023-03-12 03:56:01 +00:00
sentry_sdk.set_context(
"Target",
{
"ChatID": str(message.chat.id),
"UserID": str(sender_id),
"Msg": message.text or "",
},
)
2022-08-01 16:04:45 +00:00
if command:
sentry_sdk.set_tag("com", command)
sentry_sdk.capture_exception(exc_info)