def user_color_to_discord_color(color): if color is None: return Color.default() elif color == "random": return Color(random.randint(0x000000, 0xffffff)) else: return Color(color)
async def helpers(self, ctx): """Tag helpers, usable in #support once every 24 hours per user""" print() if (ctx.channel.name != "support"): await ctx.send(embed=Embed( title="An error occured!", color=Color(value=0xEB4634), description= f'This command is only usable in <#{discord.utils.get(ctx.guild.channels, name="support").id}>!' )) return if ctx.author in pingUsers: await ctx.send(embed=Embed( title="Cooldown", color=Color(value=0xEB4634), description="You can only use this command once every 24 hours." )) return await ctx.send( f'<@{ctx.author.id}> pinged <@&{discord.utils.get(ctx.guild.roles, name="Helpers").id}>' ) pingUsers.append(ctx.author) await asyncio.sleep(86400) pingUsers.remove(ctx.author)
async def timeout(self, ctx, member: discord.Member=None): """Put user on timeout\nExample usage: `$timeout @SlimShadyIAm#9999`""" if member is None: raise commands.BadArgument("Please supply a member, i.e `$timeout @SlimShadyIAm#9999`") role = discord.utils.get(ctx.guild.roles, name="timeout") if (role is None): await ctx.send(embed=Embed(title="An error occured!", color=Color(value=0xEB4634), description='timeout role not found!')) return await ctx.send(embed=Embed(title="Done!", color=Color(value=0x37b83b), description=f'Gave <@{member.id}> the timeout role. We\'ll let them know and remove it in 15 minutes.').set_footer(text=f'Requested by {ctx.author.name}#{ctx.author.discriminator}', icon_url=ctx.author.avatar_url)) rules_chan = discord.utils.get(ctx.guild.channels, name="rules") timeout_chan = discord.utils.get(ctx.guild.channels, name="timeout") embed = Embed(title="You have been put in timeout.", color=Color(value=0xebde34), description=f'{ctx.author.name} gave you the timeout role. We\'ll remove it in 15 minutes. Please read the message in <#{timeout_chan.id}> and review the rules in <#{rules_chan.id}>.').set_footer(text=f'Requested by {ctx.author.name}#{ctx.author.discriminator}', icon_url=ctx.author.avatar_url) try: await member.send(embed=embed) await member.add_roles(role) except discord.Forbidden: channel = discord.utils.get(ctx.guild.channels, name="general" if os.environ.get('PRODUCTION') == "false" else "off-topic") await channel.send(f'<@{member.id}> I tried to DM this to you, but your DMs are closed! You\'ll be timed out in 10 seconds.', embed=embed) await asyncio.sleep(10) await member.add_roles(role) await asyncio.sleep(900) embed=Embed(title="Timeout finished.", color=Color(value=0x37b83b), description='Removed your timeout role. Please behave, or we will have to take further action.').set_footer(text=f'Requested by {ctx.author.name}#{ctx.author.discriminator}', icon_url=ctx.author.avatar_url) try: await member.send(embed=embed) await member.remove_roles(role) except discord.Forbidden: channel = discord.utils.get(ctx.guild.channels, name="general" if os.environ.get('PRODUCTION') == "false" else "off-topic") await channel.send(f'<@{member.id}> I tried to DM this to you, but your DMs are closed!', embed=embed) await member.remove_roles(role) await ctx.author.send(embed=Embed(title="Done!", color=Color(value=0x37b83b), description=f'Removed {member.name}\'s timeout role.').set_footer(text=f'Requested by {ctx.author.name}#{ctx.author.discriminator}', icon_url=ctx.author.avatar_url))
def random(): # type: () -> Color chilipepper = Color(0x9B1B30) tan = Color(0xBEAA3E) icedcoffee = Color(0xB18F6A) return choice([ Color.teal(), Color.dark_teal(), Color.green(), Color.dark_green(), Color.blue(), Color.dark_blue(), Color.purple(), Color.dark_purple(), Color.magenta(), Color.dark_magenta(), Color.gold(), Color.dark_gold(), Color.orange(), Color.dark_orange(), Color.red(), Color.dark_red(), Color.lighter_grey(), Color.darker_grey(), Color.blurple(), tan, icedcoffee, chilipepper, ])
async def add_error(self, ctx, error): if isinstance(error, commands.BadArgument): await ctx.send(embed=Embed(title="An error occured!", color=Color(value=0xEB4634), description=f'{error}')) elif isinstance(error, commands.MissingPermissions): await ctx.send(embed=Embed(title="An error occured!", color=Color(value=0xEB4634), description="You don't have permission to do this command!")) else: print(f'{error}')
async def karma_error(self, ctx, error): if isinstance(error, commands.MissingRequiredArgument): await ctx.send(embed=Embed( title="An error occured!", color=Color(value=0xEB4634), description= f'{error}\nExample usage: `$karma give @member 3 reason blah blah blah` or `$karma take <ID> 3`' )) elif isinstance(error, commands.BadArgument): await ctx.send(embed=Embed(title="An error occured!", color=Color(value=0xEB4634), description=f'{error}')) elif isinstance(error, commands.MissingPermissions): await ctx.send(embed=Embed( title="An error occured!", color=Color(value=0xEB4634), description="You don't have permission to do this command!")) else: await ctx.send(embed=Embed(title="An error occured!", color=Color(value=0xEB4634), description=f'{error}')) traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
async def device2board(self, ctx, *, search_term: str): """(alias $d2b) Retrieve the board name from a specified brand name as a search term\nExample usage: `$d2b acer chromebook 11`""" if search_term == "": await ctx.send(embed=Embed(title="An error occured!", color=Color(value=0xEB4634), description="You need to supply a boardname! Example: `$d2b acer chromebook`")) return pattern = re.compile("^[a-zA-Z0-9_()&,/ -]*$") if (not pattern.match(search_term)): raise commands.BadArgument("Illegal characters in search term!") search_term = search_term.lower() response = "" async with aiohttp.ClientSession() as session: response = await fetch(session, 'https://raw.githubusercontent.com/skylartaylor/cros-updates/master/src/data/cros-updates.json', ctx) if response is None: return devices = json.loads(response) search_results = [(device["Codename"], device["Brand names"]) for device in devices if 'Brand names' in device and search_term in device['Brand names'].lower()] if len(search_results) == 0: await ctx.send(embed=Embed(title="An error occured!", color=Color(value=0xEB4634), description="A board with that name was not found!")) else: pages = NewMenuPages(source=Source( search_results, key=lambda t: 1, per_page=8), clear_reactions_after=True) await pages.start(ctx)
class Colours: """ Colours used in bot responses. """ error = r = red = Color(15742004) success = g = green = Color(3066993) neutral = n = normal = base = Color(16562199) warn = y = yellow = Color(16707936)
async def channel_error(self, ctx, error): if isinstance(error, commands.BadArgument): await ctx.send(embed=Embed(title="An error occured!", color=Color(value=0xEB4634), description=f'{error}')) return if isinstance(error, commands.MissingRequiredArgument): await ctx.send(embed=Embed( title="An error occured!", color=Color(value=0xEB4634), description=f'{error}. See `.help channel` if you need help.')) return elif isinstance(error, commands.MissingPermissions): await ctx.send(embed=Embed( title="An error occured!", color=Color(value=0xEB4634), description= "You need `MANAGE_SERVER` permission to run this command.")) return else: await ctx.send(embed=Embed( title="An error occured!", color=Color(value=0xEB4634), description= f'{error}. Send a screenshot of this error to SlimShadyIAm#9999' )) print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr) traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr) return
async def help_comm(self, ctx, cog=None): """Gets all cogs and commands of mine.""" if not cog: """Cog listing. What more?""" halp = discord.Embed( title='All commands', color=Color(value=0x3f78eb), description= 'Use `.help commandname` to find out more about a command!\n\nNeed more help? Contact the developer on [Twitter](https://twitter.com/SlimShadyDev) or add him on Discord at SlimShadyIAm#9999' ) for cogs in self.bot.commands: if not cogs.hidden: halp.add_field( name=f'{self.bot.command_prefix}{cogs.name}', value=cogs.help.split("\n")[0], inline=False) await ctx.send(embed=halp) else: for cogs in self.bot.commands: if cogs.name == cog and not cogs.hidden: halp = discord.Embed( title= f'Help results for {self.bot.command_prefix}{cogs.name}', color=Color(value=0x3f78eb), description=cogs.help) await ctx.send(embed=halp) return await ctx.send(embed=Embed(title="An error occured!", color=Color(value=0xEB4634), description='Command not found'))
def get_color(bot, log_level=LogLevel.INFO): """Returns the theme color.""" color = bot.config["colors"][log_level] if color[0] == "#": if len(color) == 4: return Color(int("".join([x * 2 for x in color[1:]]), 16)) else: return Color(int(color[1:], 16)) return Color(color)
async def modhistory_err(self, ctx, error): if isinstance(error, commands.MissingRequiredArgument): await ctx.send(embed=Embed(title="An error occured!", color=Color(value=0xEB4634), description=f'{error}\nExample usage: `$modhistory <@member/id>`')) elif isinstance(error, commands.BadArgument): await ctx.send(embed=Embed(title="An error occured!", color=Color(value=0xEB4634), description=f'{error}')) elif isinstance(error, commands.MissingPermissions): await ctx.send(embed=Embed(title="An error occured!", color=Color(value=0xEB4634), description="You don't have permission to do this command!")) else: await ctx.send(embed=Embed(title="An error occured!", color=Color(value=0xEB4634), description=f'{error}'))
async def err(self, ctx, err: str): """ Parses Nintendo and CTR error codes, with a fancy embed. 0x prefix is not required. Example: .err 0xD960D02B .err 022-2634 """ if re.match('[0-1][0-9][0-9]\-[0-9][0-9][0-9][0-9]', err): embed = discord.Embed(title=err + (": Nintendo 3DS" if err[0] == "0" else ": Wii U")) embed.url = "http://www.nintendo.com/consumer/wfc/en_na/ds/results.jsp?error_code={}&system={}&locale=en_US".format(err, "3DS" if err[0] == "0" else "Wiiu") if err not in self.errcodes: embed.description = "I don't know this one! Click the error code for details on Nintendo Support.\n\nIf you keep getting this issue and Nintendo Support does not help, or know how to fix it, you should report relevant details to <@78465448093417472> so it can be added to the bot." else: embed.description = self.errcodes[err] embed.color = (Color(0xCE181E) if err[0] == "0" else Color(0x009AC7)) # 0xE60012 # Switch Error Codes (w/ website) # Switch Error Codes (w/o website) elif re.match('[0-9][0-9][0-9][0-9]\-[0-9][0-9][0-9][0-9]', err): embed = discord.Embed(title=err + ": Nintendo Switch") embed.url = "http://en-americas-support.nintendo.com/app/answers/landing/p/897" embed.color = Color(0xE60012) if re.match('2110\-1[0-9][0-9][0-9]', err): embed.url = "http://en-americas-support.nintendo.com/app/answers/detail/a_id/22594" embed.description = "General connection error." elif re.match('2110\-29[0-9][0-9]', err): embed.url = "http://en-americas-support.nintendo.com/app/answers/detail/a_id/22277/p/897" embed.description = "General connection error." elif re.match('2110\-2[0-8][0-9][0-9]', err): embed.url = "http://en-americas-support.nintendo.com/app/answers/detail/a_id/22263/p/897" embed.description = "General connection error." else: if err in self.switch_errcodes: embed.url = self.switch_errcodes[err][1] embed.description = self.switch_errcodes[err][0] else: embed.color = embed.Empty embed.description = "I don't know this one! Click the error code for details on Nintendo Support.\n\nIf you keep getting this issue and Nintendo Support does not help, and know how to fix it, you should report relevant details to <@78465448093417472> so it can be added to the bot." else: err = err.strip() if err.startswith("0x"): err = err[2:] rc = int(err, 16) await self.aaaa(rc) desc = rc & 0x3FF mod = (rc >> 10) & 0xFF summ = (rc >> 21) & 0x3F level = (rc >> 27) & 0x1F # garbage embed = discord.Embed(title="0x{:X}".format(rc)) embed.add_field(name="Module", value=self.get_name(self.modules, mod), inline=False) embed.add_field(name="Description", value=self.get_name(self.descriptions, desc), inline=False) embed.add_field(name="Summary", value=self.get_name(self.summaries, summ), inline=False) embed.add_field(name="Level", value=self.get_name(self.levels, level), inline=False) await self.bot.say("", embed=embed)
async def fetch(session, url, ctx): try: async with session.get(url) as response: if response.status == 200: return await response.text() else: await ctx.send(embed=Embed(title="An error occured!", color=Color(value=0xEB4634), description="Error connecting to the feed! Please try again later")) return None except aiohttp.ClientConnectionError: await ctx.send(embed=Embed(title="An error occured!", color=Color(value=0xEB4634), description="Error connecting to the feed! Please try again later")) return None
async def quote(self, args, mobj): """ Quote references. Using !quote will give a random quote. Using !quote add <Key> <Text> will add the text as a quote under the key <Key> Using !quote remove <Key> will remove the quote from the database Using !quote <Key> will print out the quote """ if mobj.server.id not in self.quotes: self.quotes[mobj.server.id] = {} server_quotes = self.quotes[mobj.server.id] if len(args) == 0: if len(server_quotes) == 0: return await self.error(mobj.channel, "No quotes in the database") embd = Embed(title="List of Options", colour=Color(0x7289da)) value = "\n".join(server_quotes.keys()) embd.add_field(name=f"List", value=value) return await self.embed(mobj.channel, embd) elif args[0].lower() == "add" and len(args) > 2: key = args[1].lower() if key in server_quotes: return await self.error(mobj.channel, "Key is already in quotes database.") value = [mobj.author, " ".join(args[2:]).strip()] server_quotes[key] = value await self.quote_lock.acquire() self.save_quotes() self.quote_lock.release() return await self.message(mobj.channel, f"Added quote {key}.") elif args[0].lower() == "remove" and len(args) == 2: key = args[1].lower() if key in server_quotes: del server_quotes[key] await self.quote_lock.acquire() self.save_quotes() self.quote_lock.release() return await self.message( mobj.channel, f"Quote {key} has been removed, you monster.") else: return await self.error( mobj.channel, "That key is not in the quote database.") elif len(args) == 1: key = args[0].lower() if key in server_quotes: value = server_quotes[key] embd = Embed(title=key, colour=Color(0x7289da)) embd.add_field(name=f"{value[0]}", value=f"{value[1]}") return await self.embed(mobj.channel, embd) else: return await self.error(mobj.channel, "Invalid arguments")
async def unsubscribe(self, ctx, device: str): """Unsubscribe from updates from a certain device/feed.\n Available devices: iOS, macOS, watchOS, iPadOS, tvOS, Newsroom\n Example usage: `.unsubscribe ios`""" devices = {"ios": "iOS_role", "macos": "macOS_role", "watchos": "watchOS_role", "ipados": "iPadOS_role", "tvos": "tvOS_role", "newsroom": "newsroom_role" } devices_proper = {"ios": "iOS", "macos": "macOS", "watchos": "watchOS", "ipados": "iPadOS", "tvos": "tvOS", "newsroom": "Newsroom" } device = device.lower() if device not in devices.keys(): raise commands.BadArgument( "Please supply a valid device/feed to subscribe to.\nAvailable devices: iOS, macOS, watchOS, iPadOS, tvOS, Newsroom\n i.e `!unsubscribe macos`.") BASE_DIR = dirname(dirname(abspath(__file__))) db_path = path.join(BASE_DIR, "db.sqlite") try: conn = sqlite3.connect(db_path) c = conn.cursor() c.execute("SELECT * FROM configs WHERE server_id = ?;", (ctx.guild.id,)) res = c.fetchall() finally: conn.close() if len(res) == 1: try: conn = sqlite3.connect(db_path) c = conn.cursor() c.execute(f"UPDATE configs SET {devices[device]} = ? WHERE server_id = ?;", ( -1, ctx.guild.id,)) conn.commit() finally: conn.close() embed = Embed(title="Done!", color=Color( value=0x37b83b), description=f'You have unsubscribed from {devices_proper[device]} notifications.') embed.set_footer( text=f'Requested by {ctx.author.name}#{ctx.author.discriminator}', icon_url=ctx.author.avatar_url) await ctx.send(embed=embed) return await ctx.send(embed=Embed(title="An error occured!", color=Color(value=0xEB4634), description=f'An unforseen error occured, contact SlimShadyIAm#9999 (code: DB_SUBSCRIBE_ERR'))
async def err(self, ctx, err: str): """ Parses Nintendo and CTR error codes, with a fancy embed. 0x prefix is not required. Example: .err 0xD960D02B .err 022-2634 """ if re.match('[0-1][0-9][0-9]\-[0-9][0-9][0-9][0-9]', err): embed = discord.Embed( title=err + (": Nintendo 3DS" if err[0] == "0" else ": Wii U")) embed.url = "http://www.nintendo.com/consumer/wfc/en_na/ds/results.jsp?error_code={}&system={}&locale=en_US".format( err, "3DS" if err[0] == "0" else "Wiiu") if err not in self.errcodes: embed.description = "I don't know this one! Click the error code for details on Nintendo Support.\n\nIf you keep getting this issue and Nintendo Support does not help, or know how to fix it, you should report relevant details to <@78465448093417472> so it can be added to the bot." else: embed.description = self.errcodes[err] embed.color = (Color(0xCE181E) if err[0] == "0" else Color(0x009AC7)) # 0xE60012 elif re.match('[2][0-9][0-9][0-9]\-[0-9][0-9][0-9][0-9]', err): embed = discord.Embed( title= "These aren't the errors you're looking for! ( ͡° ͜ʖ ͡°)⊃━☆゚.*" ) embed.description = "You're searching for a Nintendo Switch error! \n \n **Please use .serr instead**" embed.url = "https://www.youtube.com/watch?v=CnjaUoR15dU" else: err = err.strip() if err.startswith("0x"): err = err[2:] rc = int(err, 16) await self.aaaa(rc) desc = rc & 0x3FF mod = (rc >> 10) & 0xFF summ = (rc >> 21) & 0x3F level = (rc >> 27) & 0x1F # garbage embed = discord.Embed(title="0x{:X}".format(rc)) embed.add_field(name="Module", value=self.get_name(self.modules, mod), inline=False) embed.add_field(name="Description", value=self.get_name(self.descriptions, desc), inline=False) embed.add_field(name="Summary", value=self.get_name(self.summaries, summ), inline=False) embed.add_field(name="Level", value=self.get_name(self.levels, level), inline=False) await self.bot.say("", embed=embed)
async def updates_error(self, ctx, error): if isinstance(error, commands.MissingRequiredArgument): await ctx.send(embed=Embed( title="An error occured!", color=Color(value=0xEB4634), description= "You need to supply a board name! Example: `$updates coral`")) elif isinstance(error, commands.BadArgument): await ctx.send(embed=Embed( title="An error occured!", color=Color(value=0xEB4634), description="The board should only be alphabetical characters!" ))
def reddit_webhook(title, post, name): img = ['.jpeg', '.png', '.gif', '.bmp'] try: color = team_colors[name] except KeyError: color = 0 for x in img: if re.search(x, post): data = Embed(title=title, color=Color(color), url=post).set_image(url=post) return data data = Embed(title=title, color=Color(color), url=post) return data
async def add_error(self, ctx, error): if isinstance(error, commands.MissingRequiredArgument): await ctx.send(embed=Embed( title="An error occured!", color=Color(value=0xEB4634), description= f'{error}\nExample usage:`!add cam-sucks false yeah he does` or `!add fire true You\'re fired!`"' )) elif isinstance(error, commands.BadArgument): await ctx.send(embed=Embed(title="An error occured!", color=Color(value=0xEB4634), description=f'{error}')) else: print(error)
def embed_spell(name): spell_dict = get_spell(name) # handle no results from query if not spell_dict['name']: embed = Embed(title="No results found", description="Check your spelling") return embed # each school of magic gets it's own color colors = { 'abjuration': Color(0).dark_blue(), 'conjuration': Color(0).magenta(), 'divination': Color(0).teal(), 'enchantment': Color(0).blue(), 'evocation': Color(0).red(), 'illusion': Color(0).purple(), 'necromancy': Color(0).dark_purple(), 'transmutation': Color(0).dark_gold(), 'universalist': Color(0).dark_grey() } # if school is improperly formatted or not in dict, use lighter_grey color = colors[spell_dict['school'] ] if spell_dict['school'] in colors else Color(0).lighter_grey() # construct embed - char limits might cause 400 errors # character floors can also cause 400 errors # if an embed val = 0, discord with throw 400 error embed = Embed(title=spell_dict['name'][:256], description=spell_dict['description'][:2048], colour=color) embed.set_author(name=spell_dict['spell_level'][:256] or 'None') embed.add_field(name="Saving Throw", value=spell_dict['saving_throw'][:1024] or 'None') embed.add_field(name="Duration", value=spell_dict['duration'][:1024] or 'None') embed.add_field(name="Area of Effect", value="Targets: {}\nRange: {}\nArea: {}".format(spell_dict['targets'] or 'None', spell_dict['range'] or 'None', spell_dict['area'] or 'None')[:1024]) embed.add_field(name='Misc', value="\n".join( [spell_dict['descriptor'], spell_dict['school'], spell_dict['components'], spell_dict['casting_time']])[:1024]) roman = {'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'} title = '-'.join([word for word in spell_dict['name'].split() if word not in roman]) embed.add_field( name='Link', value="http://www.d20pfsrd.com/magic/all-spells/{}/{}".format(spell_dict['name'][0], title)) return embed
def random(): # type: () -> Color tan = Color(0xBEAA3E) return choice([ Color.teal(), Color.dark_teal(), Color.green(), Color.dark_green(), Color.blue(), Color.dark_blue(), Color.purple(), Color.dark_purple(), Color.magenta(), Color.dark_magenta(), Color.gold(), Color.dark_gold(), Color.orange(), Color.dark_orange(), Color.red(), Color.dark_red(), Color.lighter_grey(), Color.darker_grey(), Color.blurple(), tan, ])
def __init__(self, bot): self.bot = bot self.bot.get_card = self.get_card # there has to be a better way to do this self.bot.card_get_image = self.card_get_image self.bot.card_replace_symbols = self.replace_symbols self.bot.magic_dict = {} self.bot.card_get_color = self.card_get_color self.color_dict = { "Red": Color.red(), "Blue": Color.blue(), "Green": Color.green(), "Black": Color(0x000000), "White": Color(0xffffff), "Gold": Color.gold(), "Grey": Color.light_grey() }
async def rank(self, ctx, ign: str): async with aiohttp.ClientSession() as sesh: async with sesh.get( f'https://euw1.api.riotgames.com/lol/summoner/v4/summoners/by-name/{ign}', params={'api_key': self.api_key}) as response: user = await response.json() summonerID = user['id'] encryptedID = user['puuid'] async with aiohttp.ClientSession() as sesh: async with sesh.get( f'https://euw1.api.riotgames.com/lol/league/v4/entries/by-summoner/{summonerID}', params={'api_key': self.api_key}) as response: data = await response.json() tier = data[0]['tier'] rank = data[0]['rank'] wins = data[0]['wins'] losses = data[0]['losses'] lp = data[0]['leaguePoints'] wr = round((wins / (losses + wins)), 3) * 100 embed = Embed(color=Color(65408)) embed.title = f'Ranked season for {ign}' embed.description = f'Solo Queue: {tier} {rank} {lp}LP' embed.add_field(name='wins', value=wins, inline=True) embed.add_field(name='losses', value=losses, inline=True) embed.add_field(name="Winrate", value=wr, inline=True) await ctx.send(embed=embed)
async def get(self, ctx, member: discord.Member): if not self.db.get_handle(ctx.guild.id, member.id): await discord_.send_message( ctx, f'Handle for {member.mention} is not set currently') return handle = self.db.get_handle(ctx.guild.id, member.id) data = await self.cf.check_handle(handle) if not data[0]: await discord_.send_message(ctx, data[1]) ctx.command.reset_cooldown(ctx) return data = data[1] if "rating" not in data: rating = 0 rank = "unrated" else: rating = data['rating'] rank = data['rank'] embed = discord.Embed( description= f'Handle for {member.mention} currently set to [{handle}](https://codeforces.com/profile/{handle})', color=Color(cf_colors[rank.lower()])) embed.add_field(name='Rank', value=f'{rank}', inline=True) embed.add_field(name='Rating', value=f'{rating}', inline=True) embed.set_thumbnail(url=f"{data['titlePhoto']}") await ctx.send(embed=embed)
async def httpcat(self, ctx, code: Union[int, str] = None): """Get a HTTP Cat for a HTTP error code""" title = None in_valid_range = any( (code in range(*i) for i in HTTP_ERROR_VALID_RANGES)) if code is None: code = 400 title = "Ask with a code" elif isinstance(code, str): code = 422 title = "Invalid number code" elif not in_valid_range: code = 404 title = "Can't find that code..." url = f"https://http.cat/{code}" if not title: title = str(code) embed = Embed(title=title, color=Color(random.randint(0, 0xFFFFFF))) embed.set_image(url=url) await ctx.reply(embed=embed)
async def initialize_roles(self, ctx: commands.Context, *argv): # if not await self.canUseCommand(ctx): # return msg = await ctx.channel.send('初始化身分組: KFP 預設...') for data in ROLE_DATA: for role_dic in data: role_matcher = role_dic['matcher'] role_name = role_dic['name'] roles: Role = self.findRole(ctx.guild.roles, role_matcher) if len(roles) > 0: await msg.edit(content=str(msg.content) + "\n{}已經存在... 合併現有資料".format(roles[0].name)) else: await msg.edit(content=str(msg.content) + "\n創建身分組{}... ".format(role_name)) role = await ctx.guild.create_role( name=role_name, permissions=Permissions(permissions=0), colour=Color(role_dic['color']), mentionable=False, hoist=False) await msg.edit(content=str(msg.content) + "完成".format(role_name)) if len(roles) > 0: role = roles[0] kfpRole: KfpRole = RoleUtil.updateRole(ctx.guild.id, role.id, role.name, role.color, role_dic["category"]) RoleUtil.updateKfpRoleLevel(kfpRole, role_dic['level']) await ctx.channel.send("身分組初始化完成.")
async def xkcd(self, args, mobj): """ Returns the most likely xkcd to be referenced by the keywords """ xkcd_urls = search( f"site:xkcd.com -forums -wiki -blog {' '.join(args)}", 3) match = False for i, cur in enumerate(xkcd_urls): id = re.match(r"https://[\.m]*xkcd.com/(\d*)/", cur.link) if id: match = True break if not match: return await self.error(mobj.channel, "Nothing Found") comic = xkcd.getComic(int(id.group(1))) if comic == -1: return await self.error(mobj.channel, "Nothing Found") embed = Embed( title=comic.getTitle(), url=f"https://xkcd.com/{id.group(1)}", colour=Color(0x7289da) ) embed.set_image(url=comic.getImageLink()) embed.add_field(name="Alt-Text", value=comic.getAltText()) embed.add_field(name="Explanation", value=f"[Link]({comic.getExplanation()})") return await self.embed(mobj.channel, embed)
async def _send_to_queue(self, ctx, video_url): if ctx.author.voice is None: raise NerpyException("Not connected to a voice channel.") if not ctx.author.voice.channel.permissions_for(ctx.guild.me).connect: raise NerpyException("Missing permission to connect to channel.") video_infos = fetch_yt_infos(video_url) if "_type" in video_infos: await self.bot.sendc( ctx, "Please use the playlist command for playlists.") await ctx.send_help(ctx.command) else: video_title = video_infos["title"] video_thumbnail = video_infos["thumbnails"][0]["url"] self.bot.log.info( f"{ctx.guild.name} requesting {video_title} to play") emb = Embed( title="Added Song to Queue!", color=Color(value=int("0099ff", 16)), description=f"[{video_title}]({video_url})", ) emb.set_thumbnail(url=video_thumbnail) # song = QueuedSong(self.bot.get_channel(606539392319750170), volume, self._fetch) song = QueuedSong(ctx.author.voice.channel, self._fetch, video_url, video_title) await self.bot.audio.play(ctx.guild.id, song) await self.bot.sendc(ctx, "", emb)
async def profile(ctx): try: mentioned = ctx.message.mentions[0] except IndexError: mentioned = ctx.author bal = await (getval(str(mentioned.id), 'bal', '0')) temp = open(str(mentioned.id) + '/petlist.txt', 'a+') temp.close() temp = open(str(mentioned.id) + '/activepets.txt', 'a+') temp.close() with open(str(mentioned.id) + '/petlist.txt', 'rb') as fp: try: list = pickle.load(fp) except EOFError: list = ['Nothing'] acpetlist = await converttostr(list, ', ') with open(str(mentioned.id) + '/activepets.txt', 'rb') as fp: try: list = pickle.load(fp) except EOFError: list = ['Nothing'] arpetlist = await converttostr(list, ', ') temp = open(str(mentioned.id) + '/inventory.txt', 'a+') temp.close() with open(str(mentioned.id) + '/inventory.txt', 'rb') as fp: try: list = pickle.load(fp) except EOFError: list = ['Nothing'] inventory = await converttostr(list, ', ') tags = [] with open('developers.txt', 'rb') as fp: devs = pickle.load(fp) with open('supporters.txt', 'rb') as fp: sups = pickle.load(fp) with open('brain.txt', 'rb') as fp: brain = pickle.load(fp) with open('turtle.txt', 'rb') as fp: turtle = pickle.load(fp) if str(mentioned.id) in devs: tags.append('Ъњ╗') if str(mentioned.id) in sups: tags.append('ЪњИ') if str(mentioned.id) in brain: tags.append('ЪДа') if str(mentioned.id) in turtle: tags.append('Ъљб') tags2 = await converttostr(tags, '') embed = Embed(title=str(mentioned) + "'s profile", colour=Color(0x00FF00), description='Balance: ' + bal + '\nActive pets: ' + acpetlist + '\n Archived pets: ' + arpetlist + '\n Inventory: ' + inventory) embed.set_image(url=mentioned.avatar_url) embed.set_footer(text=tags2) return await ctx.send(embed=embed)