async def convert(self): tags = set() user = None for arg in self.argument.split(): if arg.startswith('#'): tags.add(arg.lower()) elif user is None: user = commands.UserConverter(self.ctx, arg).convert() else: err_msg = "There can only be 1 user argument. All others should be '#'" await self.ctx.bot.say(err_msg) raise commands.BadArgument(err_msg) if user is None: user = self.ctx.message.author chmp_rstr = ChampionRoster(self.ctx.bot, user) await chmp_rstr.load_champions() if not chmp_rstr: # try: # embeds = await Hook.roster_kickback(self.ctx, user.color) # await Hook.pages_menu(self.ctx.bot, self.ctx, embeds) # except: await self.ctx.bot.say( 'No roster detected. \nUse ``/profile`` for import instructions.' ) # em = discord.Embed(color=discord.Color.green(),title='[????] {}'.format(user.name)) # em.add_field(name='Missing Roster', # value='Load up a "champ*.csv" file from Hook to import your roster') # em.add_field(name='Hook Web App', value=HOOK_URL) # em.set_footer(text='hook/champions for Collector',icon_url=GITHUB_ICON) # await self.ctx.bot.say(embed=em) raise MissingRosterError('No Roster found for {}'.format( user.name)) return types.SimpleNamespace(tags=tags, roster=chmp_rstr)
def __init__(self, bot): self.bot = bot self._conn = None # initialized in on_ready self._model = None self._model_attrib = None self._user_converter = commands.UserConverter() self._pool = concurrent.futures.ProcessPoolExecutor()
async def r(self, ctx, *, message): async for history_message in ctx.channel.history(limit=10): if history_message.author.discriminator == "0000": converter = commands.UserConverter() todm = await converter.convert(ctx, history_message.author.name) return await self.dm(ctx, todm, message=message) await ctx.send("Webhook not found")
def get_converter(self, field_name: str, field: FieldSchema): if field.converter: return field.converter if field.nullable: yield NoneConverter() if "url" in field_name: yield UrlConverter() elif field.python_type is db_utils.File: # field_name.endswith("file_attached"): yield FileConverter() elif field.python_type is comics.Author: yield comics.AuthorConverter() elif field.python_type is discord.Colour: yield commands.ColourConverter() elif field.python_type is discord.User: yield commands.UserConverter() elif field.python_type is str: yield StrConverter() elif field.python_type is int: yield IntConverter() elif issubclass(field.python_type, Model): yield ModelConverter(self.fk_dict[field_name]) else: raise ValueError(f"No converter found for {field_name}!") if field.unique: yield EnsureUniqueConverter(self.model, field_name)
async def convert(self): tags = set() user = None for arg in self.argument.split(): if arg.startswith('#'): tags.add(arg.lower()) elif user is None: user = commands.UserConverter(self.ctx, arg).convert() else: err_msg = "There can only be 1 user argument. All others should be '#'" await self.ctx.bot.say(err_msg) raise commands.BadArgument(err_msg) if user is None: user = self.ctx.message.author chmp_rstr = ChampionRoster(self.ctx.bot, user) await chmp_rstr.load_champions() if not chmp_rstr: menu = PagesMenu(self.ctx.bot, timeout=120, delete_onX=True, add_pageof=True) hook = Hook(self.ctx.bot) try: color = user.color except: color = discord.Color.gold() embeds = await hook.roster_kickback(color) await menu.menu_start(pages=embeds) raise MissingRosterError('No Roster found for {}'.format( user.name)) return types.SimpleNamespace(tags=tags, roster=chmp_rstr)
async def massban(self, ctx, *, users): """remove all members passed in, space delimited. may take a few """ \ """moments to complete due to rate limiting. requires manage server and ban perms to use""" converter = commands.UserConverter() message = "```diff\n" confirmation = await ctx.reply("Attempting mass ban...") embed = discord.Embed(title="Mass ban") for user in users.split(): try: user = await converter.convert(ctx, user) except commands.UserNotFound: message += f"- User {user} not found.\n" continue if user := discord.utils.get(ctx.guild.members, id=user.id): if user.id == ctx.bot.user.id or user.id == ctx.guild.owner.id \ or self.member_remove_fail(ctx, user): message += f"- Could not ban {user}.\n" continue message += f"+ Banned {user}.\n" embed.description = message + "\n```" await confirmation.edit(content="", embed=embed) await ctx.guild.ban(discord.Object(id=user.id)) await asyncio.sleep(0.5)
async def convert(self): user = None if self.argument: user = commands.UserConverter(self.ctx, self.argument).convert() else: user = self.ctx.message.author chmp_rstr = ChampionRoster(self.ctx.bot, user) await chmp_rstr.load_champions() return chmp_rstr
async def post_new_apps(self): log.info('Checking for new applications') checklist_urls = { 'cmp': 'https://docs.google.com/spreadsheets/d/e/2PACX-1vShlqb3iFZL5HpvWe62-hXeRJ_j6CtSo_TUzjCE2h-lou4bHdFQJKcmDx97VvzjFAze2i9vIzl2ErEs/pub?gid=181078935&single=true&output=csv', 'smp': 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRTqR018lkhKqOf4ToC5RJC4WBFP31Sv7hPD0-eZMXLQf5mmPCo5STU4v1z6s3HIvT2rIG4F1IRqC7N/pub?gid=1666125740&single=true&output=csv' } new_apps = await get_applications(checklist_urls['cmp']) cid = 676429957827788800 app_channel = self.bot.get_channel(cid) userconverter = commands.UserConverter() for new_app in new_apps: app = [ 'None' if value == '' else str(value) for value in new_app.values() ] app_embed = Embed(colour=Colours.techrock) # Get user try: app_user = await userconverter.convert(app_channel, app[2]) app_embed.set_author(name='CMP Application', icon_url=app_user.avatar_url) except: app_embed.set_author(name='CMP Application') app_embed.add_field(name='Discord Username', value=app[2]) app_embed.add_field(name='GamerTag', value=app[3]) app_embed.add_field(name='Age', value=app[4]) app_embed.add_field(name='Technical Niches', value=app[5]) app_embed.add_field(name='Minecraft Experience', value=app[7], inline=False) app_embed.add_field(name='Social Media', value=app[8]) app_embed.add_field(name='Links', value=app[9]) # Split uploads into hyperlinks if app[6] == 'None': media_links = 'None' else: media_links = '' media_links_list = app[6].split(', ') for i, link in enumerate(media_links_list, 1): media_links += f'[{i}]({link}) ' app_embed.add_field(name='Pictures/Videos', value=media_links) msg = await app_channel.send(embed=app_embed) await msg.add_reaction(Emojis.thumbs_up) await msg.add_reaction(Emojis.thumbs_down)
async def convert(self, context, argument): try: convert = beans.UserConverter() user = await convert.convert(context,argument) except beans.BadArgument: try: user = await context.bot.fetch_user(int(argument)) except: #HTTPException or not a integer await context.send("User not found!") raise BadArgument("User not found") return user
async def rank(self, ctx, ranks_to_show: int = 5): user_ranks = economy_col.find() user_ranks = user_ranks.sort([("balance", -1), ("id", 1)]) rank_embed = discord.Embed(colour=Colours.base, title=f"Leaderboard for {ctx.message.guild}") count = 0 conv = commands.UserConverter() ranks = [] users = [] balances = [] do_add_author, author_count, author_balance = None, None, None guild = self.bot.get_guild(ctx.message.guild.id) for item in user_ranks: if guild.get_member(int(item["id"])) is not None: try: count += 1 user = await conv.convert(ctx=ctx, argument=str(item["id"])) except: continue if count <= ranks_to_show: ranks.append(f"{count}.") users.append(str(user)) balances.append(f"<:EmojiCoins:732598961558388817> {item['balance']}") if str(user.id) == str(ctx.message.author.id): do_add_author = True author_count = count author_balance = item["balance"] if str(ctx.message.author) not in users and do_add_author: ranks.append("**...**") users.append("\u200b") balances.append("\u200b") ranks.append(f"{author_count}.") users.append(f"**{ctx.message.author}**") balances.append(f"<:EmojiCoins:732598961558388817> {author_balance}") count = 0 for username in users: if username == str(ctx.message.author): ranks[count] = f"**{ranks[count]}**" users[count] = f"**{users[count]}**" balances[count] = f"**{balances[count]}**" count += 1 rank_embed.add_field(name="#", value="\n".join(ranks), inline=True) rank_embed.add_field(name="User", value="\n".join(users), inline=True) rank_embed.add_field(name="Balance", value="\n".join(balances), inline=True) await ctx.send(embed=rank_embed)
async def get_intro_dm(ctx, *, target_user): print("get_intro_dm", target_user) try: if is_mention(target_user): converter = commands.UserConverter() target_user = await converter.convert(ctx, target_user) else: target_user = await string_to_user(target_user ) #target user can be a string await send_intro_by_dm(ctx, target_user) except Exception as e: print(e) if is_intro_channel(ctx): await ctx.channel.send(content="Could not fetch intro.")
async def info(self, ctx, user=None): try: converter = commands.UserConverter() user = await converter.convert(ctx, user) except commands.BadArgument: pass if user is None: user = ctx.author if isinstance(user, discord.abc.User): user_db = await self.connections.find_one({"id": user.id}) if user_db: embed = await self.get_info_embed(ctx, user, user_db) return await ctx.send(embed=embed) if user != ctx.author: return await ctx.send("This user is not linked to the bot.") return await ctx.send("You are not linked to the bot.") if isinstance(user, str): uname, uuid = await skypy.fetch_uuid_uname(user) dc_users = self.connections.find({"uuid": uuid}) dc_users = await dc_users.to_list(length=1000) if len(dc_users) > 0: embeds = [] for dc_user in dc_users: embed = await self.get_info_embed( ctx, self.bot.get_user(dc_user["id"]), dc_user) embeds.append(embed) msg = await ctx.send(embed=embeds[0]) if len(embeds) > 1: paginator = Paginator(self.bot, msg, embeds=embeds, timeout=60, use_more=True, only=ctx.author) await paginator.start() return return await ctx.send(embed=await self.get_info_embed( ctx, None, { "uuid": uuid, "verified": False }, linked=False)) raise commands.BadArgument( message="Discord User or Minecraft username")
def __init__(self, bot): self.bot = bot self.arrow = "➤" self.empty_image = io.BytesIO() Image.new("RGB", (1, 1)).save(self.empty_image, format="png") self.empty_image.seek(0) self.star = "✫" self.separator = "------------------------------" self.startup_time = self.time() self.user_converter = commands.UserConverter() self.admin = discord.Permissions(8) self.STARTUP_TIME_FORMAT = "%A, %b %d, %Y - %m/%d/%Y - %I:%M:%S %p" self.CREATION_TIME_FORMAT = "%m/%d/%Y - %I:%M:%S %p" self.crafthead = Crafthead() self.paginators = Paginators()
async def whoadd(self, ctx, bot: BotAdded): data = bot author = await try_call(commands.UserConverter().convert, ctx, str(data.author), exception=UserNotFound) embed = discord.Embed(title=str(data.bot)) embed.set_thumbnail(url=data.bot.avatar_url) def or_none(condition, func): if condition: return func(condition) fields = (("Added by", f"{author.mention} (`{author.id}`)"), ("Reason", data.reason), ("Requested", or_none(data.requested_at, default_date)), ("Joined", or_none(data.joined_at, default_date)), ("Message Request", or_none(data.jump_url, "[jump]({})".format))) await ctx.embed(embed=embed, fields=fields)
async def convert(self, ctx, arg): """Converter function for the lookup command""" try: match = commands.UserConverter()._get_id_match(arg) or re.match(r'<@!?([0-9]+)>$', arg) user = None if match is not None: user_id = int(match.group(1)) result = ctx.bot.get_user(user_id) if result: user = result else: user = await ctx.bot.get_user_info(match.group(1)) assert isinstance(user, discord.User) return user except (AssertionError, discord.DiscordException): raise discord.NotFound
async def convert(self, ctx: utils.CustomContext, argument: str): converters = { commands.TextChannelConverter(): "Text Channel", commands.VoiceChannelConverter(): "Voice Channel", commands.MemberConverter(): "Server Member", commands.UserConverter(): "Discord User", commands.PartialEmojiConverter(): "Emoji", utils.RoleConverter(): "Server Role", } for converter, title in converters.items(): try: convert = await converter.convert(ctx, argument) return convert.id, title except Exception as e: continue raise commands.BadArgument("Couldn't find anything that matches that.")
async def whoadd(self, ctx, bot: BotAdded): data = bot author = await try_call(commands.UserConverter().convert, ctx, str(data.author), exception=UserNotFound) embed = discord.Embed(title=f"{data.bot}", color=self.bot.color) request = default_date(data.requested_at) if data.requested_at else None join = default_date(data.joined_at) if data.joined_at else None embed.set_thumbnail(url=data.bot.avatar_url) fields = (("Reason", data.reason), ("Requested", request), ("Joined", join), ("Message Request", f"[jump]({data.jump_url})" if data.jump_url else None)) if author: embed.set_author(name=author, icon_url=author.avatar_url) for name, value in fields: if value: embed.add_field(name=name, value=value, inline=False) await ctx.maybe_reply(embed=embed)
async def balance(self, ctx): msg = ctx.message.content.replace("!!balance ", "").replace( "!!balance", "").replace("!!bal ", "").replace("!!bal", "") user = ctx.author if msg != "": userConvert = commands.UserConverter() try: user = await commands.UserConverter().convert(ctx, msg) except Exception: pass amount = await self.getb(user.id) if amount == 1: emerald = "emerald" else: emerald = "emeralds" balEmbed = discord.Embed(color=discord.Color.green(), description=user.mention + " has a total of " + str(amount) + " <:emerald:653729877698150405>") await ctx.send(embed=balEmbed)
async def on_message(self, message): if message.channel in (self.bot.channels["dm_logs"],self.bot.channels["suggestions"]) and not message.author.bot and message.reference: referenced_message = await message.channel.fetch_message(message.reference.message_id) reference_author = referenced_message.author if reference_author.discriminator == "0000": todm= reference_author.name converter = commands.UserConverter() todm = await converter.convert(message.channel, todm) dm = self.bot.get_command("dm") ctx = await self.bot.get_context(message) await dm(ctx, todm, message=message.content) if message.channel.id == 749971061843558440 and message.embeds and str(message.author) == "GitHub#0000": if " new commit" in message.embeds[0].title: update_for_main = message.embeds[0].title.startswith("[Discord-TTS-Bot:master]") and self.bot.user.id == 513423712582762502 update_for_dev = message.embeds[0].title.startswith("[Discord-TTS-Bot:dev]") and self.bot.user.id == 698218518335848538 if update_for_main or update_for_dev: await self.bot.channels['logs'].send("Detected new bot commit! Pulling changes") call(['git', 'pull']) print("===============================================") await self.bot.channels['logs'].send("Restarting bot...") await self.bot.close()
async def college(self, ctx): """View your college. Colleges are a politically oriented association. Its members gain a passive amount of gravitas depending on its level. They also gain access to the `usurp` command. `college help` will show all other commands related to this association type. """ info = await AssetCreation.getGuildFromPlayer(self.client.pg_con, ctx.author.id) getLeader = commands.UserConverter() leader = await getLeader.convert(ctx, str(info['Leader'])) level, progress = await AssetCreation.getGuildLevel(self.client.pg_con, info['ID'], returnline=True) members = await AssetCreation.getGuildMemberCount( self.client.pg_con, info['ID']) capacity = await AssetCreation.getGuildCapacity( self.client.pg_con, info['ID']) embed = discord.Embed(title=f"{info['Name']}", color=self.client.ayesha_blue) embed.set_thumbnail(url=f"{info['Icon']}") embed.add_field(name='Leader', value=f"{leader.mention}") embed.add_field(name='Members', value=f"{members}/{capacity}") embed.add_field(name='Level', value=f"{level}") embed.add_field(name='EXP Progress', value=f'{progress}') embed.add_field(name='Base', value=f"{info['Base']}") if info['Join'] != 'open': # Alert level requirements if open embed.add_field( name=f"This {info['Type']} is {info['Join']} to new members.", value=f"{info['Desc']}", inline=False) else: embed.add_field(name=( f"This {info['Type']} is {info['Join']} to new members at or " f"above level {info['Min_Level']}."), value=f"{info['Desc']}", inline=False) embed.set_footer(text=f"College ID: {info['ID']}") await ctx.reply(embed=embed)
async def send_reaction(ctx, image_url, action, *, target_user=None): try: conv = commands.UserConverter() user = await conv.convert(ctx=ctx, argument="".join(target_user)) user = user.display_name except: user = target_user if target_user is None: react_embed = discord.Embed( colour=Colours.base, title= f"{ctx.message.author.display_name} {action} somebody in the chat!" ) else: react_embed = discord.Embed( colour=Colours.base, title=f"{ctx.message.author.display_name} {action} {user}!") react_embed.set_image(url=image_url) await ctx.send(embed=react_embed)
async def quote(self, ctx: commands.Context, *, arg: str): # Retrieve a new UserConverter converter = commands.UserConverter() # Strip leading/trailing spaces arg = arg.strip() try: # Split the args by spaces content = arg.split(' ') # Check if there is less than 2 args if len(content) < 2: self.currentMessages = [await ctx.send_help()] return # try to convert the first argument into a user user: discord.User = await converter.convert(ctx=ctx, argument=content[0]) except commands.CommandError: self.currentMessages = [await ctx.send("Invalid user")] return # Finds the end of the quote author's @ qMessage = arg[arg.find('>') + 1:] qMessage = qMessage.strip() # Set JSON output jOuput = [user.id, getCurrentTime(), qMessage] # Write the JSON to file try: with open(QUOTE_LOG, mode='a') as f: f.write(f'{json.dumps(jOuput)}\n') except OSError: self.bot.addErrorLog( f"Error writing quote, author: {ctx.author.name}, channel: {ctx.channel.name}:" f" {ctx.message.content}") # TOFIX raise an error await ctx.message.add_reaction(THUMBS_UP)
async def snowballfight(self, ctx, enemy: discord.Member): _("""Make a snowball fights against another guild.""") if enemy is ctx.author: return await ctx.send(_("You may not fight yourself.")) async with self.bot.pool.acquire() as conn: guild1, rank1 = await conn.fetchval( 'SELECT (guild, guildrank) FROM profile WHERE "user"=$1;', ctx.author.id) guild2, rank2 = await conn.fetchval( 'SELECT (guild, guildrank) FROM profile WHERE "user"=$1;', enemy.id) if rank2 == "Member": return await ctx.send( _("The enemy must be an officer or higher.")) guild1 = await conn.fetchrow('SELECT * FROM guild WHERE "id"=$1;', guild1) guild2 = await conn.fetchrow('SELECT * FROM guild WHERE "id"=$1;', guild2) guild1_members = [ r["user"] for r in await conn.fetch( 'SELECT "user" FROM profile WHERE "guild"=$1;', guild1["id"]) ] guild2_members = [ r["user"] for r in await conn.fetch( 'SELECT "user" FROM profile WHERE "guild"=$1;', guild2["id"]) ] msg = await ctx.send( _("{enemy}, {author} has challenged you for an epic snowball fight! If you want to accept, react ⚔\n**IMPORTANT: This is very spammy, make sure you are using a dedicated channel!**" ).format(enemy=enemy.mention, author=ctx.author.mention)) def check(r, u): return (r.message.id == msg.id and u == enemy and str(r.emoji) == "\U00002744") await msg.add_reaction("\U00002744") try: await self.bot.wait_for("reaction_add", check=check, timeout=30) except asyncio.TimeoutError: return await ctx.send(_("Timed out...")) conv = commands.UserConverter() team1 = [ctx.author] team2 = [enemy] def check1(msg): return (msg.content.startswith("snowballfight nominate") and msg.author == ctx.author) def check2(msg): return (msg.content.startswith("snowballfight nominate") and msg.author == enemy) await ctx.send( _("{author}, type `snowballfight nominate @user` to add one of your guild members to the fight!" ).format(author=ctx.author.mention)) while len(team1) == 1: try: msg = await self.bot.wait_for("message", check=check1, timeout=30) except asyncio.TimeoutError: return await ctx.send(_("Timed out...")) try: u = await conv.convert(ctx, msg.content.split()[-1]) except commands.BadArgument: continue if u.id not in guild1_members: await ctx.send(_("Not one of your guild members...")) elif u in team1: await ctx.send(_("That's you!")) else: team1.append(u) await ctx.send( _("{enemy}, use `snowballfight nominate @user` to add one of your guild members to the fight!" ).format(enemy=enemy.mention)) while len(team2) == 1: try: msg = await self.bot.wait_for("message", check=check2, timeout=30) except asyncio.TimeoutError: return await ctx.send(_("Timed out...")) try: u = await conv.convert(ctx, msg.content.split()[-1]) except commands.BadArgument: continue if u.id not in guild2_members: await ctx.send(_("Not one of your guild members...")) elif u in team2: await ctx.send(_("That's you!")) else: team2.append(u) points1 = 1 points2 = 1 while points1 < 10 and points2 < 10: t1 = (":black_large_square:" * (points1 - 1) + ":snowflake:" + ":black_large_square:" * (10 - points1)) t2 = (":black_large_square:" * (points2 - 1) + ":snowflake:" + ":black_large_square:" * (10 - points2)) await ctx.send( _(""" {author.mention}'s team vs {enemy.mention}'s team {t1} - {author} {t2} - {enemy} Next round starts in 5 seconds! """).format(author=ctx.author, enemy=enemy, t1=t1, t2=t2)) await asyncio.sleep(5) game_mode = random.choice(["typeit", "maths", "hangman"]) if game_mode == "typeit": w = random.sample(string.ascii_letters, 15) w.insert(random.randint(1, 14), "\u200b") word = "".join(w) real = word.replace("\u200b", "") def corr(msg): return (msg.author in team1 or msg.author in team2) and msg.content == real await ctx.send( _("It's word typing time! In 3 seconds, I will send a word. Whoever types it fastest gets one point!" )) await asyncio.sleep(3) await ctx.send(f"`{word}`") try: msg = await self.bot.wait_for("message", check=corr, timeout=45) except asyncio.TimeoutError: return await ctx.send( _("Noone managed to get it right, I'll cancel the fight!" )) if msg.author in team1: points1 += 1 else: points2 += 1 await ctx.send( _("{author} got it right!").format( author=ctx.author.mention)) elif game_mode == "maths": m = random.randint(1, 20) x = random.randint(1, 30) c = random.choice([2, 4, 5]) d = random.randint(1, 100) res = (m * x) / c + d if int(res) == res: res = str(int(res)) else: res = str(res) def corr(msg): return (msg.author in team1 or msg.author in team2) and msg.content == res await ctx.send( _("It's maths time! In 3 seconds, I'll send a simple maths task to solve! Type the answer to get a point!" )) await asyncio.sleep(3) await ctx.send(f"`({m} * {x}) / {c} + {d}`") try: msg = await self.bot.wait_for("message", check=corr, timeout=45) except asyncio.TimeoutError: return await ctx.send( _("Noone managed to get it right, I'll cancel the fight!" )) if msg.author in team1: points1 += 1 else: points2 += 1 await ctx.send( _("{user} got it right!").format(user=msg.author)) elif game_mode == "hangman": word = random.choice(self.words).strip() def corr(msg): return (msg.author in team1 or msg.author in team2) and ( msg.content == word or len(msg.content) == 1) disp = "_ " * len(word) guessed = [] await ctx.send( _("It's hangman time! In 3 seconds, I'll send a hangman-style word and you will have to either send your full word as the guess or a letter to check for!" )) await asyncio.sleep(3) q = await ctx.send(f"`{disp}`") while True: try: msg = await self.bot.wait_for("message", check=corr, timeout=20) except asyncio.TimeoutError: return await ctx.send( _("Noone participated, I'll cancel the fight!")) if msg.content == word: if msg.author in team1: points1 += 1 else: points2 += 1 await ctx.send( _("{user} got it right!").format(user=msg.author)) break else: try: await msg.delete() except discord.Forbidden: pass if msg.content in guessed: continue if msg.content not in word: continue guessed.append(msg.content) disp = " ".join( [i if (i in guessed) else "_" for i in word]) await q.edit(content=f"`{disp}`") if points1 > points2: await ctx.send( _("Team 1 ({user}) won!").format(user=ctx.author.mention)) else: await ctx.send( _("Team 2 ({user}) won!").format(user=enemy.mention))
def __init__(self, bot): self.bot = bot self.blue = discord.Color.blue() self.user_conv = commands.UserConverter()
async def battle(self, ctx, enemy: discord.Member, amount: int, fightercount: int): if amount < 0: return await ctx.send("Don't scam!") if enemy is ctx.author: return await ctx.send("Poor kiddo having no friendos.") async with self.bot.pool.acquire() as conn: guild1, rank1 = await conn.fetchval( 'SELECT (guild, guildrank) FROM profile WHERE "user"=$1;', ctx.author.id ) guild2, rank2 = await conn.fetchval( 'SELECT (guild, guildrank) FROM profile WHERE "user"=$1;', enemy.id ) if guild1 == 0 or guild2 == 0: return await ctx.send("One of you both doesn't have a guild.") guild1 = await conn.fetchrow('SELECT * FROM guild WHERE "id"=$1;', guild1) guild2 = await conn.fetchrow('SELECT * FROM guild WHERE "id"=$1;', guild2) if rank1 == "Member" or rank2 == "Member": return await ctx.send( "One of you both isn't an officer of their guild." ) if guild1[5] < amount or guild2[5] < amount: return await ctx.send("One of the guilds can't pay the price.") size1 = await conn.fetchval( 'SELECT count(user) FROM profile WHERE "guild"=$1;', guild1[0] ) size2 = await conn.fetchval( 'SELECT count(user) FROM profile WHERE "guild"=$1;', guild2[0] ) if size1 < fightercount or size2 < fightercount: return await ctx.send("One of the guilds is too small.") def msgcheck(amsg): return ( amsg.author == enemy and amsg.content.lower() == "guild battle accept" ) await ctx.send( f"{enemy.mention}, {ctx.author.mention} invites you to fight in a guild battle. Type `guild battle accept` to join the battle. You got **1 Minute to accept**." ) try: res = await self.bot.wait_for("message", timeout=60, check=msgcheck) except: return await ctx.send( f"{enemy.mention} didn't want to join your battle, {ctx.author.mention}." ) await ctx.send( f"{enemy.mention} accepted the challenge by {ctx.author.mention}. Please now nominate members, {ctx.author.mention}. Use `battle nominate @user` to add someone to your team." ) team1 = [] team2 = [] converter = commands.UserConverter() async def guildcheck(already, guildid, user): try: member = await converter.convert(ctx, user) except: return False guild = await self.bot.pool.fetchval( 'SELECT guild FROM profile WHERE "user"=$1;', member.id ) if guild != guildid: await ctx.send("That person isn't in your guild.") return False if member in already: return False return member def simple1(msg): return msg.author == ctx.author and msg.content.startswith( "battle nominate" ) def simple2(msg): return msg.author == enemy and msg.content.startswith("battle nominate") while len(team1) != fightercount: try: res = await self.bot.wait_for("message", timeout=30, check=simple1) guild1check = await guildcheck( team1, guild1["id"], res.content.split()[-1] ) if guild1check: team1.append(guild1check) await ctx.send( f"{guild1check} has been added to your team, {ctx.author.mention}." ) else: await ctx.send("User not found.") continue except asyncio.TimeoutError: return await ctx.send("Took to long to add members. Fight cancelled.") await ctx.send( f"Please now nominate members, {enemy.mention}. Use `battle nominate @user` to add someone to your team." ) while len(team2) != fightercount: try: res = await self.bot.wait_for("message", timeout=30, check=simple2) guild2check = await guildcheck( team2, guild2["id"], res.content.split()[-1] ) if guild2check: team2.append(guild2check) await ctx.send( f"{guild2check} has been added to your team, {enemy.mention}." ) else: await ctx.send("User not found.") continue except asyncio.TimeoutError: return await ctx.send("Took to long to add members. Fight cancelled.") msg = await ctx.send("Fight started!\nGenerating battles...") await asyncio.sleep(3) await msg.edit(content="Fight started!\nGenerating battles... Done.") wins1 = 0 wins2 = 0 for user in team1: user2 = team2[team1.index(user)] msg = await ctx.send( f"Guild Battle Fight **{team1.index(user)+1}** of **{len(team1)}**.\n**{user.name}** vs **{user2.name}**!\nBattle running..." ) async with self.bot.pool.acquire() as conn: sw1 = ( await conn.fetchval( "SELECT ai.damage FROM profile p JOIN allitems ai ON (p.user=ai.owner) JOIN inventory i ON (ai.id=i.item) WHERE i.equipped IS TRUE AND p.user=$1 AND type='Sword';", user.id, ) or 0 ) sh1 = ( await conn.fetchval( "SELECT ai.armor FROM profile p JOIN allitems ai ON (p.user=ai.owner) JOIN inventory i ON (ai.id=i.item) WHERE i.equipped IS TRUE AND p.user=$1 AND type='Shield';", user.id, ) or 0 ) sw2 = ( await conn.fetchval( "SELECT ai.damage FROM profile p JOIN allitems ai ON (p.user=ai.owner) JOIN inventory i ON (ai.id=i.item) WHERE i.equipped IS TRUE AND p.user=$1 AND type='Sword';", user2.id, ) or 0 ) sh2 = ( await conn.fetchval( "SELECT ai.armor FROM profile p JOIN allitems ai ON (p.user=ai.owner) JOIN inventory i ON (ai.id=i.item) WHERE i.equipped IS TRUE AND p.user=$1 AND type='Shield';", user2.id, ) or 0 ) val1 = sw1 + sh1 + random.randint(1, 7) val2 = sw2 + sh2 + random.randint(1, 7) if val1 > val2: winner = user wins1 += 1 elif val2 > val1: winner = user2 wins2 += 1 else: winner = random.choice(user, user2) if winner == user: wins1 += 1 else: wins2 += 1 await asyncio.sleep(5) await ctx.send( f"Winner of **{user}** vs **{user2}** is **{winner}**! Current points: **{wins1}** to **{wins2}**." ) async with self.bot.pool.acquire() as conn: money1 = await conn.fetchval( 'SELECT money FROM guild WHERE "id"=$1;', guild1["id"] ) money2 = await conn.fetchval( 'SELECT money FROM guild WHERE "id"=$1;', guild2["id"] ) if money1 < amount or money2 < amount: return await ctx.send("Some guild spent the money??? Bad looser!") if wins1 > wins2: await conn.execute( 'UPDATE guild SET money=money+$1 WHERE "id"=$2;', amount, guild1["id"], ) await conn.execute( 'UPDATE guild SET money=money-$1 WHERE "id"=$2;', amount, guild2["id"], ) await conn.execute( 'UPDATE guild SET wins=wins+1 WHERE "id"=$1;', guild1["id"] ) await ctx.send(f"{guild1['name']} won the battle! Congratulations!") elif wins2 > wins1: await conn.execute( 'UPDATE guild SET money=money+$1 WHERE "id"=$2;', amount, guild2["id"], ) await conn.execute( 'UPDATE guild SET money=money-$1 WHERE "id"=$2;', amount, guild1["id"], ) await conn.execute( 'UPDATE guild SET wins=wins+1 WHERE "id"=$1;', guild2["id"] ) await ctx.send(f"{guild2['name']} won the battle! Congratulations!") else: await ctx.send("It's a tie!")
async def blacklist(self, ctx): """ Blacklist users from using the bot. Send with no args to see who's blacklisted.""" conv = commands.UserConverter() users = await asyncio.gather(*[conv.convert(ctx, str(_id)) for _id in self.blacklist]) names = [user.name for user in users] await ctx.send('\t'.join(names) or 'No one has been blacklisted')
async def divorce(self, ctx, user: typing.Union[discord.User, discord.Member, int]): """Divorce somebody that you are married to, can be from an mention, their name or an id""" _ = await self._get_text(ctx) if isinstance(user, int): try: converter = commands.UserConverter() user = await converter.convert(ctx, str(user)) except commands.BadArgument: user_re_match = re.match("[0-9]{12,22}", str(user)) if user_re_match is None: return await self.bot.send_cmd_help(ctx) user = await self.bot.get_user_info(int(user_re_match.group(0)) ) if user.id == ctx.author.id: return await ctx.send(_("You can't divorce yourself")) author_data = await r.table("marriage").get(str(ctx.author.id) ).run(self.bot.r_conn) if not author_data: return await ctx.send(bold(_("You are not married"))) user_data = await r.table("marriage").get(str(user.id) ).run(self.bot.r_conn) if not user_data: return await ctx.send(_("That user is not married to anyone")) if not str(ctx.author.id) in user_data.get("marriedTo", []): return await ctx.send(_("That user is not married to you")) await ctx.send( _("**Are you sure you want to divorce %s?**") % user.name.replace("@", "@\u200B")) try: msg = await self.bot.wait_for( "message", check=lambda x: x.channel == ctx.message.channel and x.author == ctx.author, timeout=15.0) if msg.content.lower() != "yes": return await ctx.send(_("**Cancelled.**")) except asyncio.TimeoutError: return await ctx.send(_("**Cancelled.**")) new_author_married = [] for u in author_data.get("marriedTo", []): if u != str(user.id): new_author_married.append(u) new_user_married = [] for u in user_data.get("marriedTo", []): if u != str(ctx.author.id): new_user_married.append(u) await r.table("marriage").get(str(user.id)).update({ "marriedTo": new_user_married }).run(self.bot.r_conn) await r.table("marriage").get(str(ctx.author.id)).update({ "marriedTo": new_author_married }).run(self.bot.r_conn) await ctx.send("%s divorced %s 😦😢" % (ctx.author.name.replace( "@", "@\u200B"), user.name.replace("@", "@\u200B")))
id=user_id) or discord.utils.get( guild.members, id=user_id) if result is None: results = await guild.query_members(user_ids=[user_id], limit=1) if results: result = results[0] if result is None: raise commands.BadArgument(f'Member "{argument}" not found') return result _member_converter = MemberConverter() _user_converter = commands.UserConverter() class NotInRange(commands.BadArgument): def __init__(self, text: str, from_: int, to_: int) -> None: self.text = text self.from_ = from_ self.to_ = to_ class InvalidCrateRarity(commands.BadArgument): pass class InvalidCoinSide(commands.BadArgument): pass
SOFTWARE. """ from typing import Any import re from contextlib import suppress from collections import namedtuple from io import BytesIO import discord from discord.ext import commands BetterUser = namedtuple('BetterUser', ['obj', 'http_dict']) u_conv = commands.UserConverter() m_conv = commands.MemberConverter() emoji_regex = "(?:\U0001f1e6[\U0001f1e8-\U0001f1ec\U0001f1ee\U0001f1f1\U0001f1f2\U0001f1f4\U0001f1f6-\U0001f1fa\U0001f1fc\U0001f1fd\U0001f1ff])|(?:\U0001f1e7[\U0001f1e6\U0001f1e7\U0001f1e9-\U0001f1ef\U0001f1f1-\U0001f1f4\U0001f1f6-\U0001f1f9\U0001f1fb\U0001f1fc\U0001f1fe\U0001f1ff])|(?:\U0001f1e8[\U0001f1e6\U0001f1e8\U0001f1e9\U0001f1eb-\U0001f1ee\U0001f1f0-\U0001f1f5\U0001f1f7\U0001f1fa-\U0001f1ff])|(?:\U0001f1e9[\U0001f1ea\U0001f1ec\U0001f1ef\U0001f1f0\U0001f1f2\U0001f1f4\U0001f1ff])|(?:\U0001f1ea[\U0001f1e6\U0001f1e8\U0001f1ea\U0001f1ec\U0001f1ed\U0001f1f7-\U0001f1fa])|(?:\U0001f1eb[\U0001f1ee-\U0001f1f0\U0001f1f2\U0001f1f4\U0001f1f7])|(?:\U0001f1ec[\U0001f1e6\U0001f1e7\U0001f1e9-\U0001f1ee\U0001f1f1-\U0001f1f3\U0001f1f5-\U0001f1fa\U0001f1fc\U0001f1fe])|(?:\U0001f1ed[\U0001f1f0\U0001f1f2\U0001f1f3\U0001f1f7\U0001f1f9\U0001f1fa])|(?:\U0001f1ee[\U0001f1e8-\U0001f1ea\U0001f1f1-\U0001f1f4\U0001f1f6-\U0001f1f9])|(?:\U0001f1ef[\U0001f1ea\U0001f1f2\U0001f1f4\U0001f1f5])|(?:\U0001f1f0[\U0001f1ea\U0001f1ec-\U0001f1ee\U0001f1f2\U0001f1f3\U0001f1f5\U0001f1f7\U0001f1fc\U0001f1fe\U0001f1ff])|(?:\U0001f1f1[\U0001f1e6-\U0001f1e8\U0001f1ee\U0001f1f0\U0001f1f7-\U0001f1fb\U0001f1fe])|(?:\U0001f1f2[\U0001f1e6\U0001f1e8-\U0001f1ed\U0001f1f0-\U0001f1ff])|(?:\U0001f1f3[\U0001f1e6\U0001f1e8\U0001f1ea-\U0001f1ec\U0001f1ee\U0001f1f1\U0001f1f4\U0001f1f5\U0001f1f7\U0001f1fa\U0001f1ff])|\U0001f1f4\U0001f1f2|(?:\U0001f1f4[\U0001f1f2])|(?:\U0001f1f5[\U0001f1e6\U0001f1ea-\U0001f1ed\U0001f1f0-\U0001f1f3\U0001f1f7-\U0001f1f9\U0001f1fc\U0001f1fe])|\U0001f1f6\U0001f1e6|(?:\U0001f1f6[\U0001f1e6])|(?:\U0001f1f7[\U0001f1ea\U0001f1f4\U0001f1f8\U0001f1fa\U0001f1fc])|(?:\U0001f1f8[\U0001f1e6-\U0001f1ea\U0001f1ec-\U0001f1f4\U0001f1f7-\U0001f1f9\U0001f1fb\U0001f1fd-\U0001f1ff])|(?:\U0001f1f9[\U0001f1e6\U0001f1e8\U0001f1e9\U0001f1eb-\U0001f1ed\U0001f1ef-\U0001f1f4\U0001f1f7\U0001f1f9\U0001f1fb\U0001f1fc\U0001f1ff])|(?:\U0001f1fa[\U0001f1e6\U0001f1ec\U0001f1f2\U0001f1f8\U0001f1fe\U0001f1ff])|(?:\U0001f1fb[\U0001f1e6\U0001f1e8\U0001f1ea\U0001f1ec\U0001f1ee\U0001f1f3\U0001f1fa])|(?:\U0001f1fc[\U0001f1eb\U0001f1f8])|\U0001f1fd\U0001f1f0|(?:\U0001f1fd[\U0001f1f0])|(?:\U0001f1fe[\U0001f1ea\U0001f1f9])|(?:\U0001f1ff[\U0001f1e6\U0001f1f2\U0001f1fc])|(?:\U0001f3f3\ufe0f\u200d\U0001f308)|(?:\U0001f441\u200d\U0001f5e8)|(?:[\U0001f468\U0001f469]\u200d\u2764\ufe0f\u200d(?:\U0001f48b\u200d)?[\U0001f468\U0001f469])|(?:(?:(?:\U0001f468\u200d[\U0001f468\U0001f469])|(?:\U0001f469\u200d\U0001f469))(?:(?:\u200d\U0001f467(?:\u200d[\U0001f467\U0001f466])?)|(?:\u200d\U0001f466\u200d\U0001f466)))|(?:(?:(?:\U0001f468\u200d\U0001f468)|(?:\U0001f469\u200d\U0001f469))\u200d\U0001f466)|[\u2194-\u2199]|[\u23e9-\u23f3]|[\u23f8-\u23fa]|[\u25fb-\u25fe]|[\u2600-\u2604]|[\u2638-\u263a]|[\u2648-\u2653]|[\u2692-\u2694]|[\u26f0-\u26f5]|[\u26f7-\u26fa]|[\u2708-\u270d]|[\u2753-\u2755]|[\u2795-\u2797]|[\u2b05-\u2b07]|[\U0001f191-\U0001f19a]|[\U0001f1e6-\U0001f1ff]|[\U0001f232-\U0001f23a]|[\U0001f300-\U0001f321]|[\U0001f324-\U0001f393]|[\U0001f399-\U0001f39b]|[\U0001f39e-\U0001f3f0]|[\U0001f3f3-\U0001f3f5]|[\U0001f3f7-\U0001f3fa]|[\U0001f400-\U0001f4fd]|[\U0001f4ff-\U0001f53d]|[\U0001f549-\U0001f54e]|[\U0001f550-\U0001f567]|[\U0001f573-\U0001f57a]|[\U0001f58a-\U0001f58d]|[\U0001f5c2-\U0001f5c4]|[\U0001f5d1-\U0001f5d3]|[\U0001f5dc-\U0001f5de]|[\U0001f5fa-\U0001f64f]|[\U0001f680-\U0001f6c5]|[\U0001f6cb-\U0001f6d2]|[\U0001f6e0-\U0001f6e5]|[\U0001f6f3-\U0001f6f6]|[\U0001f910-\U0001f91e]|[\U0001f920-\U0001f927]|[\U0001f933-\U0001f93a]|[\U0001f93c-\U0001f93e]|[\U0001f940-\U0001f945]|[\U0001f947-\U0001f94b]|[\U0001f950-\U0001f95e]|[\U0001f980-\U0001f991]|\u00a9|\u00ae|\u203c|\u2049|\u2122|\u2139|\u21a9|\u21aa|\u231a|\u231b|\u2328|\u23cf|\u24c2|\u25aa|\u25ab|\u25b6|\u25c0|\u260e|\u2611|\u2614|\u2615|\u2618|\u261d|\u2620|\u2622|\u2623|\u2626|\u262a|\u262e|\u262f|\u2660|\u2663|\u2665|\u2666|\u2668|\u267b|\u267f|\u2696|\u2697|\u2699|\u269b|\u269c|\u26a0|\u26a1|\u26aa|\u26ab|\u26b0|\u26b1|\u26bd|\u26be|\u26c4|\u26c5|\u26c8|\u26ce|\u26cf|\u26d1|\u26d3|\u26d4|\u26e9|\u26ea|\u26fd|\u2702|\u2705|\u270f|\u2712|\u2714|\u2716|\u271d|\u2721|\u2728|\u2733|\u2734|\u2744|\u2747|\u274c|\u274e|\u2757|\u2763|\u2764|\u27a1|\u27b0|\u27bf|\u2934|\u2935|\u2b1b|\u2b1c|\u2b50|\u2b55|\u3030|\u303d|\u3297|\u3299|\U0001f004|\U0001f0cf|\U0001f170|\U0001f171|\U0001f17e|\U0001f17f|\U0001f18e|\U0001f201|\U0001f202|\U0001f21a|\U0001f22f|\U0001f250|\U0001f251|\U0001f396|\U0001f397|\U0001f56f|\U0001f570|\U0001f587|\U0001f590|\U0001f595|\U0001f596|\U0001f5a4|\U0001f5a5|\U0001f5a8|\U0001f5b1|\U0001f5b2|\U0001f5bc|\U0001f5e1|\U0001f5e3|\U0001f5e8|\U0001f5ef|\U0001f5f3|\U0001f6e9|\U0001f6eb|\U0001f6ec|\U0001f6f0|\U0001f930|\U0001f9c0|[#|0-9]\u20e3" class BetterUserConverter(commands.Converter): async def convert(self, ctx, argument): out = ctx.author if not argument else None for converter in (m_conv, u_conv): if out: break with suppress(Exception): out = await converter.convert(ctx, argument) if out is None: try: out = await ctx.bot.fetch_user(argument)
except Exception as exc: raise commands.CommandError( f'Conversion of "{argument}" to {target_type.__class__.__name__} failed: {exc}' ) return converter type_to_converter = { # Builtins bool: commands.core._convert_to_bool, int: built_in_converter(int), str: str, # Discord objects Role: commands.RoleConverter(), User: commands.UserConverter(), Member: commands.MemberConverter(), Color: commands.ColorConverter(), Invite: commands.InviteConverter(), Emoji: commands.EmojiConverter(), Message: commands.MessageConverter(), PartialEmoji: commands.PartialEmojiConverter(), TextChannel: commands.TextChannelConverter(), VoiceChannel: commands.VoiceChannelConverter(), CategoryChannel: commands.CategoryChannelConverter(), } _to_str = { Message: lambda m: f"Message with id {m.id} in {m.channel.mention}", }