Created
October 3, 2020 13:53
-
-
Save dob9601/34b16d9bd74b695d202a02e5a295de6f to your computer and use it in GitHub Desktop.
A sample implementation of sentry user context with discord.py. A better solution would be to override the on_error function which I realised after writing this beast..
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """Decorators, primarily related to sentry logging.""" | |
| import functools | |
| import sentry_sdk | |
| import discord | |
| from discord.ext import commands | |
| def sentry_user_context(payload_position: int, payload_type: object, bot: commands.Bot = None): | |
| """Provide user context for sentry logging.""" | |
| def decorator(function): | |
| @functools.wraps(function) | |
| async def wrapper(*args, **kwargs): | |
| user_object: discord.User = None | |
| user = {} | |
| payload = args[payload_position] | |
| if payload_type == commands.Context: | |
| user_object = payload.message.author | |
| elif payload_type == discord.RawReactionActionEvent: | |
| if bot is None: | |
| raise ValueError('RawReactionActionEvent payload requires bot object') | |
| user_object = bot.get_user(payload.user_id) | |
| else: | |
| raise ValueError('Unsupported payload type.') | |
| with sentry_sdk.configure_scope() as scope: | |
| scope.user = { | |
| 'id': user_object.id, | |
| 'username': f'{user_object.name}#{user_object.discriminator}' | |
| } | |
| return await function(*args, **kwargs) | |
| return wrapper | |
| return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment