Skip to content

Instantly share code, notes, and snippets.

@PikalaxALT
Created December 25, 2019 15:47
Show Gist options
  • Select an option

  • Save PikalaxALT/c2c13a437fbb5387d9c28aeb8a261cd7 to your computer and use it in GitHub Desktop.

Select an option

Save PikalaxALT/c2c13a437fbb5387d9c28aeb8a261cd7 to your computer and use it in GitHub Desktop.

Revisions

  1. PikalaxALT created this gist Dec 25, 2019.
    69 changes: 69 additions & 0 deletions basic_eh.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,69 @@
    import discord
    from discord.ext import commands
    import aiohttp
    import io
    import traceback

    import config # includes the token

    # These exceptions are ignored.
    filter_excs = (commands.CommandNotFound, commands.CheckFailure)
    # These are exception types you want to handle explicitly.
    handle_excs = (commands.UserInputError,)

    bot = commands.Bot(command_prefix='!')

    async def try_hastebin(content):
    """Upload to Hastebin, if possible."""
    payload = content.encode('utf-8')
    async with aiohttp.ClientSession(raise_for_status=True) as cs:
    async with cs.post('https://hastebin.com/documents', data=payload) as res:
    post = await res.json()
    uri = post['key']
    return f'https://hastebin/{uri}'

    async def send_to_owner(content):
    """Send content to owner. If content is small enough, send directly.
    Otherwise, try Hastebin first, then upload as a File."""
    owner = bot.get_user(bot.owner_id)
    if owner is None:
    return
    if len(content) < 1990:
    await owner.send(f'```\ncontent\n```')
    else:
    try:
    await owner.send(await try_hastebin(content))
    except aiohttp.ClientResponseError:
    await owner.send(file=discord.File(io.StringIO(content), filename='traceback.txt'))

    @bot.event
    async def on_error(event, *args, **kwargs):
    """Error handler for all events."""
    s = traceback.format_exc()
    content = f'Ignoring exception in {event}\n{s}'
    print(content, file=sys.stderr)
    await send_to_owner(content)

    async def handle_command_error(ctx: commands.Context, exc: Exception):
    """Handle specific exceptions separately here"""
    pass

    @bot.event
    async def on_command_error(ctx: commands.Context, exc: Exception):
    """Error handler for commands"""
    if isinstance(exc, filter_excs):
    # These exceptions are ignored completely.
    return

    if isinstance(exc, handle_excs):
    # Explicitly handle these exceptions.
    return await handle_command_error(ctx, exc)

    # Log the error and bug the owner.
    exc = getattr(exc, 'original', exc)
    lines = ''.join(traceback.format_exception(exc.__class__, exc, exc.__traceback__))
    lines = f'Ignoring exception in command {ctx.command}:\n{lines}'
    print(lines)
    await send_to_owner(lines)

    bot.run(config.token)