def find_target(self, ctx, arg):
"""Returns the ID of the given target"""
if arg.casefold() in ('everyone', 'all'):
return discord.Object(id=0)
try:
return await MemberConverter().convert(ctx, arg)
except BadArgument:
pass
try:
return await RoleConverter().convert(ctx, arg)
except BadArgument:
pass
return None
python类MemberConverter()的实例源码
def _get_quote(self, ctx, author_or_num=None):
sid = ctx.message.server.id
if type(author_or_num) is discord.Member:
return self._get_random_author_quote(ctx, author_or_num)
if author_or_num:
try:
quote_id = int(author_or_num)
if quote_id > 0 and quote_id <= len(self.quotes[sid]):
return (quote_id - 1, self.quotes[sid][quote_id - 1])
else:
raise commands.BadArgument("Quote #%i does not exist." % quote_id)
except ValueError:
pass
try:
author = commands.MemberConverter(ctx, author_or_num).convert()
except commands.errors.BadArgument:
author = author_or_num.strip(' \t\n\r\x0b\x0c-–—') # whitespace + dashes
return self._get_random_author_quote(ctx, author)
return self._get_random_quote(ctx)
def convert(self, ctx: DogbotContext, argument: str) -> str:
cog: 'Time' = ctx.command.instance
# resolve another user's timezone
try:
member = await MemberConverter().convert(ctx, argument)
timezone = await cog.get_timezone_for(member)
if timezone:
return timezone
except BadArgument:
pass
# hippo checking
blacklisted = list('`\\<>@')
if any(character in argument for character in blacklisted) or len(argument) > 30:
raise BadArgument("That doesn't look like a timezone.")
# actually check if it's a valid timezone with arrow's parser
try:
arrow.utcnow().to(argument)
except arrow.parser.ParserError:
raise BadArgument('Invalid timezone.')
return argument
def convert(self, ctx, argument):
try:
m = await commands.MemberConverter().convert(ctx, argument)
can_execute = ctx.author.id == ctx.bot.owner_id or \
ctx.author == ctx.guild.owner or \
ctx.author.top_role > m.top_role
if not can_execute:
raise commands.BadArgument('You cannot do this action on this user due to role hierarchy.')
return m.id
except commands.BadArgument:
try:
return int(argument, base=10)
except ValueError:
raise commands.BadArgument(f"{argument} is not a valid member or member ID.") from None
def addquote(self, ctx, message: str, *, author: str = None):
"""Adds a quote to the server quote list. The quote must be enclosed
in \"double quotes\". If a member mention or name is the last argument,
the quote will be stored as theirs. If not, the last argument will
be stored as the quote's author. If left empty, "Unknown" is used.
"""
if author:
try:
author = commands.MemberConverter(ctx, author).convert()
except commands.errors.BadArgument:
author = author.strip(' \t\n\r\x0b\x0c-–—') # whitespace + dashes
pass
self._add_quote(ctx, author, message)
await self.bot.say("Quote added.")
def convert(self, ctx, argument):
for converter in (MemberConverter, UserConverter):
try:
return await converter().convert(ctx, argument)
except commands.BadArgument:
pass
try:
return await ctx.bot.get_user_info(argument)
except discord.HTTPException:
raise commands.BadArgument("That user wasn't found.")
def convert(self, ctx, argument):
try:
return await MemberConverter().convert(ctx, argument)
except commands.BadArgument:
try:
return discord.Object(id=int(argument))
except ValueError:
raise commands.BadArgument('Invalid member ID. I also couldn\'t find the user by username.')
def convert(self, ctx, argument):
try:
return await commands.TextChannelConverter().convert(ctx, argument)
except commands.BadArgument:
return await commands.MemberConverter().convert(ctx, argument)
def magik(self, ctx, target, *args):
""" Add some magik to your boring-ass images """
try:
member = await commands.MemberConverter().convert(ctx, target)
url = member.avatar_url
except:
url = target
url = url.replace("gif", "png").strip("<>")
if args:
opt = args[0]
else:
opt = 0.5
multi = parsers.as_number(opt, 0.5)
if multi > 10:
return await ctx.send('Maximum multiplier is 10')
m = await ctx.send("pls wait am generating")
try:
b = BytesIO()
async with aiohttp.ClientSession() as session:
async with session.get(url) as r:
with wand.image.Image(file=BytesIO(await r.read())) as img:
img.transform(resize="400x400")
img.liquid_rescale(width=int(img.width * 0.5),
height=int(img.height * 0.5),
delta_x=multi,
rigidity=0)
img.liquid_rescale(width=int(img.width * 1.5),
height=int(img.height * 1.5),
delta_x=2,
rigidity=0)
img.save(file=b)
b.seek(0)
await ctx.send(file=discord.File(b, filename="magik.png"))
await m.delete()
except:
await m.edit(content="Unable to generate image. Provide a mention or valid URL.")
def invert(self, ctx, target):
""" Ever wanted to see the stuff of nightmares? """
try:
member = await commands.MemberConverter().convert(ctx, target)
url = member.avatar_url
except:
url = target
url = url.replace("gif", "png").strip("<>")
m = await ctx.send("pls wait am generating")
try:
b = BytesIO()
async with aiohttp.ClientSession() as session:
async with session.get(url) as r:
img = Image.open(BytesIO(await r.read()))
bio = BytesIO()
if (img.mode == 'RGBA'):
r,g,b,a = img.split()
rgb_image = Image.merge('RGB', (r,g,b))
inverted = ImageOps.invert(rgb_image)
r,g,b = inverted.split()
img = Image.merge('RGBA', (r,g,b,a))
else:
img = ImageOps.invert(img)
img.save(bio, "PNG")
bio.seek(0)
await ctx.send(file=discord.File(bio, filename="invert.png"))
await m.delete()
except Exception as e:
print(e)
await m.edit(content="Unable to generate image. Provide a mention or valid URL.")
def get_check_steamid(player, ctx, mention=False, no_error=False):
is_author = player is None
if is_author:
player = ctx.message.author
try:
player = int(player)
except (ValueError, TypeError):
pass # This either this is a discord user or an invalid argument
if isinstance(player, int):
if player > 76561197960265728:
player -= 76561197960265728
# Don't have to rate limit here because this will be first query ran
player_info = await opendota_query(f"/players/{player}")
if player_info.get("profile") is None:
raise UserError("Either this person doesn't play dota, or they haven't enabled public match data")
if mention:
return player, f"[{player_info['profile']['personaname']}](https://www.opendota.com/players/{player})"
else:
return player
if not isinstance(player, discord.User):
try:
player = await commands.MemberConverter().convert(ctx, str(player))
except commands.BadArgument:
if no_error:
return None
raise UserError("Ya gotta @mention a user who has been linked to a steam id, or just give me a their steam id")
userinfo = botdata.userinfo(player.id)
if userinfo.steam32 is None:
if no_error:
return None
if is_author:
raise SteamNotLinkedError()
else:
raise SteamNotLinkedError(player)
if mention:
return userinfo.steam32, player.mention
else:
return userinfo.steam32