Skip to content

Instantly share code, notes, and snippets.

@nwunderly
Last active January 21, 2021 20:11
Show Gist options
  • Save nwunderly/a8c3e09973d7042969451f89de235e8d to your computer and use it in GitHub Desktop.
Save nwunderly/a8c3e09973d7042969451f89de235e8d to your computer and use it in GitHub Desktop.
helpful discord.py converters
import re
import discord
from discord.ext import commands
class FetchedUser(commands.Converter):
async def convert(self, ctx, argument):
if not argument.isdigit():
raise commands.BadArgument('Not a valid user ID.')
try:
return await ctx.bot.fetch_user(argument)
except discord.NotFound:
raise commands.BadArgument('User not found.')
except discord.HTTPException:
raise commands.BadArgument('An error occurred while fetching the user.')
class GlobalChannel(commands.Converter):
async def convert(self, ctx, argument):
try:
return await commands.TextChannelConverter().convert(ctx, argument)
except commands.BadArgument:
# Not found... so fall back to ID + global lookup
try:
channel_id = int(argument, base=10)
except ValueError:
raise commands.BadArgument(f'Could not find a channel by ID {argument!r}.')
else:
channel = ctx.bot.get_channel(channel_id)
if channel is None:
raise commands.BadArgument(f'Could not find a channel by ID {argument!r}.')
return channel
class Guild(commands.Converter):
async def convert(self, ctx, argument):
if not argument.isdigit():
raise commands.BadArgument('Not a valid guild ID.')
try:
return ctx.bot.get_guild(argument)
except discord.NotFound:
raise commands.BadArgument('Guild not found.')
except discord.HTTPException:
raise commands.BadArgument('An error occurred while fetching the guild.')
class OptionFlags(commands.Converter):
pattern = re.compile(r"""--(\S+)(?:\s+(?!--)((?:.(?!--))*\S))?""")
async def convert(self, ctx, argument):
result = {}
matches = self.pattern.finditer(argument)
for match in matches:
key = match.group(1)
value = match.group(2) or True
result[key] = value
return result
class Command(commands.Converter):
async def convert(self, ctx, argument):
command = ctx.bot.get_command(argument)
if command:
return command
else:
raise commands.BadArgument("A command with this name could not be found.")
class Cog(commands.Converter):
async def convert(self, ctx, argument):
cog = ctx.bot.get_cog(argument)
if cog:
return cog
else:
raise commands.BadArgument("A cog with this name could not be found.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment