Skip to content
This repository has been archived by the owner on May 10, 2024. It is now read-only.

Commit

Permalink
Switch to new sentry-sdk
Browse files Browse the repository at this point in the history
  • Loading branch information
Nukesor committed Aug 3, 2020
1 parent a235bf0 commit 1861f54
Show file tree
Hide file tree
Showing 20 changed files with 313 additions and 299 deletions.
380 changes: 205 additions & 175 deletions poetry.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ repository = "https://github.com/nukesor/sticker-finder"

[tool.poetry.dependencies]
python = ">=3.7"
raven = "^6"
sentry-sdk = "0.16.0"
alembic = "^1"
python-telegram-bot = "^12"
SQLAlchemy = "^1"
Expand Down
2 changes: 1 addition & 1 deletion stickerfinder/logic/sticker_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def extract_text(tg_sticker):
logger.info(f"Failed to open image {tg_sticker.file_unique_id}")
pass
except:
sentry.captureException()
sentry.capture_exception(tags={"context": "text_extraction"})
pass

return text
3 changes: 1 addition & 2 deletions stickerfinder/logic/tag.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,9 +254,8 @@ def tag_sticker(
achievement_message = i18n.t(f"text.tagging.achievements.{len(user.changes)}")
tg_chat.send_message(achievement_message)

sentry.captureMessage(
sentry.capture_message(
f"User hit {len(user.changes)} changes!",
level="info",
extra={
"user": user.username,
"user_id": user.id,
Expand Down
57 changes: 39 additions & 18 deletions stickerfinder/sentry.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
"""Simple wrapper around sentry that allows for lazy initilization."""
from raven import Client
import sentry_sdk
from sentry_sdk import configure_scope

from stickerfinder.config import config
from telegram.error import TimedOut


class Sentry(object):
"""Sentry wrapper class that allows this app to work without a sentry token.
"""Sentry wrapper class.
This class offers some convenience classes and functions for adding
additional information to sentry calls.
If no token is specified in the config, the messages used for logging are simply not called.
The extra level of abstraction ensures that everything will still work,
if sentry hasn't been initialized.
"""

initialized = False
Expand All @@ -15,27 +22,41 @@ def __init__(self):
"""Construct new sentry wrapper."""
if config["logging"]["sentry_enabled"]:
self.initialized = True
self.sentry = Client(config["logging"]["sentry_token"])
sentry_sdk.init(config["logging"]["sentry_token"],)

def captureMessage(self, *args, **kwargs):
def capture_message(self, message, level="info", tags=None, extra=None):
"""Capture message with sentry."""
if self.initialized:
if "tags" not in kwargs:
kwargs["tags"] = {}
if not self.initialized:
return

with configure_scope() as scope:
if tags is not None:
for key, tag in tags.items():
scope.set_tag(key, tag)

# Tag it as stickerfinder
kwargs["tags"]["bot"] = "stickerfinder"
self.sentry.captureMessage(*args, **kwargs)
if extra is not None:
for key, extra in extra.items():
scope.set_extra(key, extra)

def captureException(self, *args, **kwargs):
scope.set_tag("bot", "StickerFinder")
sentry_sdk.capture_message(message, level)

def capture_exception(self, tags=None, extra=None):
"""Capture exception with sentry."""
if self.initialized:
if "tags" not in kwargs:
kwargs["tags"] = {}
if not self.initialized:
return

with configure_scope() as scope:
if tags is not None:
for key, tag in tags.items():
scope.set_tag(key, tag)

if extra is not None:
for key, extra in extra.items():
scope.set_extra(key, extra)

# Tag it as stickerfinder
kwargs["tags"]["bot"] = "stickerfinder"
self.sentry.captureException(*args, **kwargs)
scope.set_tag("bot", "StickerFinder")
sentry_sdk.capture_exception()


sentry = Sentry()
30 changes: 17 additions & 13 deletions stickerfinder/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from stickerfinder.i18n import i18n


def job_session_wrapper():
def job_wrapper():
"""Create a session, handle permissions and exceptions for jobs."""

def real_decorator(func):
Expand All @@ -34,7 +34,7 @@ def wrapper(context):
# Capture all exceptions from jobs.
# We need to handle those inside the jobs
traceback.print_exc()
sentry.captureException()
sentry.capture_exception(tags={"handler": "job"})
finally:
context.job.enabled = True
session.close()
Expand All @@ -44,7 +44,7 @@ def wrapper(context):
return real_decorator


def inline_session_wrapper():
def inline_query_wrapper():
"""Create a session, handle permissions and exceptions."""

def real_decorator(func):
Expand All @@ -69,7 +69,7 @@ def wrapper(update, context):
except Exception as e:
if not ignore_exception(e):
traceback.print_exc()
sentry.captureException()
sentry.capture_exception(tags={"handler": "inline_query"})

finally:
session.close()
Expand All @@ -79,7 +79,7 @@ def wrapper(update, context):
return real_decorator


def callback_session_wrapper():
def callback_query_wrapper():
"""Create a session, handle permissions and exceptions."""

def real_decorator(func):
Expand All @@ -104,8 +104,11 @@ def wrapper(update, context):
except Exception as e:
if not ignore_exception(e):
traceback.print_exc()
sentry.captureException()

sentry.capture_exception(
tags={"handler": "callback_query",},
extra={"query": update.callback_query,},
)
finally:
session.close()

Expand All @@ -114,7 +117,7 @@ def wrapper(update, context):
return real_decorator


def session_wrapper(
def message_wrapper(
send_message=True, allow_edit=False, admin_only=False,
):
"""Create a session, handle permissions, handle exceptions and prepare some entities."""
Expand Down Expand Up @@ -175,12 +178,13 @@ def wrapper(update, context):
except Exception as e:
if not ignore_exception(e):
traceback.print_exc()
sentry.captureException()
if send_message and message:
session.close()
error_message = i18n.t("text.misc.error")
message.chat.send_message(error_message)
raise
sentry.capture_exception(
tags={"handler": "message",},
extra={"update": update.to_dict(), "function": func.__name__},
)

error_message = i18n.t("text.misc.error")
message.chat.send_message(error_message)
finally:
session.close()

Expand Down
4 changes: 0 additions & 4 deletions stickerfinder/stickerfinder.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@
from stickerfinder.telegram.callback_handlers import handle_callback_query
from stickerfinder.telegram.inline_query import search
from stickerfinder.telegram.inline_query.result import handle_chosen_inline_result
from stickerfinder.telegram.error_handler import error_callback


logging.basicConfig(
Expand Down Expand Up @@ -182,6 +181,3 @@
# Inline callback handler
dispatcher.add_handler(CallbackQueryHandler(handle_callback_query))
dispatcher.add_handler(ChosenInlineResultHandler(handle_chosen_inline_result))

# Error handling
dispatcher.add_error_handler(error_callback)
4 changes: 2 additions & 2 deletions stickerfinder/telegram/callback_handlers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from telegram.ext import run_async

from stickerfinder.db import get_session
from stickerfinder.session import callback_session_wrapper
from stickerfinder.session import callback_query_wrapper
from stickerfinder.helper.callback import CallbackType
from stickerfinder.models import Chat

Expand Down Expand Up @@ -87,7 +87,7 @@ def __init__(self, session, bot, query, user):


@run_async
@callback_session_wrapper()
@callback_query_wrapper()
def handle_callback_query(bot, update, session, user):
"""Handle callback queries from inline keyboards."""
context = CallbackContext(session, bot, update.callback_query, user)
Expand Down
28 changes: 14 additions & 14 deletions stickerfinder/telegram/commands/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@

from stickerfinder.config import config
from stickerfinder.models import User, StickerSet, Chat, Sticker
from stickerfinder.session import session_wrapper
from stickerfinder.session import message_wrapper


@run_async
@session_wrapper(admin_only=True)
@message_wrapper(admin_only=True)
def ban_user(bot, update, session, chat, user):
"""Send a help text."""
name_to_ban = update.message.text.split(" ", 1)[1].lower()
Expand All @@ -29,7 +29,7 @@ def ban_user(bot, update, session, chat, user):


@run_async
@session_wrapper(admin_only=True)
@message_wrapper(admin_only=True)
def unban_user(bot, update, session, chat, user):
"""Send a help text."""
name_to_unban = update.message.text.split(" ", 1)[1].lower()
Expand All @@ -51,7 +51,7 @@ def unban_user(bot, update, session, chat, user):


@run_async
@session_wrapper(admin_only=True)
@message_wrapper(admin_only=True)
def authorize_user(bot, update, session, chat, user):
"""Send a help text."""
name_to_ban = update.message.text.split(" ", 1)[1].lower()
Expand All @@ -70,7 +70,7 @@ def authorize_user(bot, update, session, chat, user):


@run_async
@session_wrapper(admin_only=True)
@message_wrapper(admin_only=True)
def make_admin(bot, update, session, chat, user):
"""Send a help text."""
identifier = update.message.text.split(" ", 1)[1].lower()
Expand All @@ -93,7 +93,7 @@ def make_admin(bot, update, session, chat, user):


@run_async
@session_wrapper(admin_only=True)
@message_wrapper(admin_only=True)
def add_sets(bot, update, session, chat, user):
"""Get random sticker_set."""
text = update.message.text[9:]
Expand All @@ -119,7 +119,7 @@ def add_sets(bot, update, session, chat, user):


@run_async
@session_wrapper(admin_only=True)
@message_wrapper(admin_only=True)
def delete_set(bot, update, session, chat, user):
"""Delete a specific set."""
name = update.message.text[11:].strip().lower()
Expand All @@ -134,7 +134,7 @@ def delete_set(bot, update, session, chat, user):


@run_async
@session_wrapper(admin_only=True)
@message_wrapper(admin_only=True)
def broadcast(bot, update, session, chat, user):
"""Broadcast a message to all users."""
message = update.message.text.split(" ", 1)[1].strip()
Expand Down Expand Up @@ -184,7 +184,7 @@ def broadcast(bot, update, session, chat, user):


@run_async
@session_wrapper(admin_only=True)
@message_wrapper(admin_only=True)
def test_broadcast(bot, update, session, chat, user):
"""Broadcast a message to all users."""
message = update.message.text.split(" ", 1)[1].strip()
Expand All @@ -195,7 +195,7 @@ def test_broadcast(bot, update, session, chat, user):


@run_async
@session_wrapper(admin_only=True)
@message_wrapper(admin_only=True)
def fix_stuff(bot, update, session, chat, user):
"""Entry point for quick fixes."""
bot.send_message(chat.id, "starting to fix")
Expand Down Expand Up @@ -226,7 +226,7 @@ def fix_stuff(bot, update, session, chat, user):


@run_async
@session_wrapper()
@message_wrapper()
def show_sticker(bot, update, session, chat, user):
"""Show the sticker for the given file id."""
file_id = update.message.text.split(" ", 1)[1].strip()
Expand All @@ -237,7 +237,7 @@ def show_sticker(bot, update, session, chat, user):


@run_async
@session_wrapper()
@message_wrapper()
def show_sticker_file_id(bot, update, session, chat, user):
"""Give the file id for a sticker."""
if update.message.reply_to_message is None:
Expand All @@ -251,7 +251,7 @@ def show_sticker_file_id(bot, update, session, chat, user):


@run_async
@session_wrapper(admin_only=True)
@message_wrapper(admin_only=True)
def ban_sticker(bot, update, session, chat, user):
"""Broadcast a message to all users."""
chat.current_sticker.banned = True
Expand All @@ -261,7 +261,7 @@ def ban_sticker(bot, update, session, chat, user):


@run_async
@session_wrapper(admin_only=True)
@message_wrapper(admin_only=True)
def unban_sticker(bot, update, session, chat, user):
"""Broadcast a message to all users."""
chat.current_sticker.banned = True
Expand Down
4 changes: 2 additions & 2 deletions stickerfinder/telegram/commands/chat.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
"""Chat related commands."""
from telegram.ext import run_async
from stickerfinder.session import session_wrapper
from stickerfinder.session import message_wrapper
from stickerfinder.telegram.keyboard import get_main_keyboard
from stickerfinder.logic.tag import send_tagged_count_message


@run_async
@session_wrapper()
@message_wrapper()
def cancel(bot, update, session, chat, user):
"""Send a help text."""
if not send_tagged_count_message(session, bot, user, chat):
Expand Down
6 changes: 3 additions & 3 deletions stickerfinder/telegram/commands/maintenance.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
"""Maintenance related commands."""
from telegram.ext import run_async

from stickerfinder.session import session_wrapper
from stickerfinder.session import message_wrapper
from stickerfinder.logic.maintenance import check_maintenance_chat, check_newsfeed_chat


@run_async
@session_wrapper(admin_only=True)
@message_wrapper(admin_only=True)
def flag_chat(bot, update, session, chat, user):
"""Flag a chat as maintenance or ban chat."""
chat_type = update.message.text.split(" ", 1)[1].strip()
Expand All @@ -25,7 +25,7 @@ def flag_chat(bot, update, session, chat, user):


@run_async
@session_wrapper(admin_only=True)
@message_wrapper(admin_only=True)
def start_tasks(bot, update, session, chat, user):
"""Start the handling of tasks."""
if not chat.is_maintenance and not chat.is_newsfeed:
Expand Down
Loading

0 comments on commit 1861f54

Please # to comment.