async def prefix(self, ctx, new_prefix=None): """View or set a prefix within a server.""" if new_prefix == None or ctx.guild == None: embed = discord.Embed( description= f"Hey there, my name is { self.bot.user.name if ctx.guild == None else ctx.guild.me.display_name } and my prefix is `{ get_prefix(ctx.message) }`", color=embed_color(ctx.author) if ctx.guild != None else Config.MAINCOLOR) else: if ctx.author.guild_permissions.manage_guild == False: embed = discord.Embed( title="Missing Permissions", description= "You're missing the **Manage Server** permission which is required to change a server's prefix!", color=Config.ERRORCOLOR) else: if len(new_prefix) > 5 and new_prefix.lower() != "remove": embed = discord.Embed( title="Prefix Too Long", description= "Please keep the prefix under five characters long!", color=Config.ERRORCOLOR) else: embed = discord.Embed( title=f"Prefix Updated", description= f"My prefix is now `{ new_prefix if new_prefix.lower() != 'remove' else Config.PREFIX }`", color=embed_color(ctx.author)) Config.CLUSTER["servers"]["prefixes"].delete_one({ "_id": ctx.guild.id }) if new_prefix.lower() == "remove" or new_prefix.lower( ) == Config.PREFIX else Config.CLUSTER["servers"][ "prefixes"].update_one( {"_id": ctx.guild.id}, {"$set": { "prefix": new_prefix }}, upsert=True) if (new_prefix.lower() == "remove" or new_prefix.lower() == Config.PREFIX) and ctx.guild.id in prefixes: if ctx.guild.me.guild_permissions.change_nickname: await ctx.guild.me.edit( nick=ctx.guild.me.display_name.replace( f"[{ get_prefix(ctx.message) }]", "")) prefixes.pop(ctx.guild.id) else: if ctx.guild.me.guild_permissions.change_nickname: await ctx.guild.me.edit( nick=ctx.guild.me.display_name.replace( f"[{ get_prefix(ctx.message) }]", f"[{ new_prefix }]" ) if f"[{ get_prefix(ctx.message) }]" in ctx.guild.me.display_name else f"[{ new_prefix }] { ctx.guild.me.display_name }" ) prefixes[ctx.guild.id] = new_prefix await ctx.send(embed=embed)
async def top(self, ctx, user: Union[discord.User, str] = None): """View the top profiles on [discord.bio](https://discord.bio/profiles).""" user = user if user else ctx.author async with aiohttp.ClientSession() as session: async with session.get( f"https://api.discord.bio/user/top") as resp: if resp.status == 200: data = await resp.json() data = data["payload"] i = 1 list = [] for user in data["users"]: if i <= 10: list.append( f"**{ i }. [dsc.bio/{ user['user']['slug']}](https://discord.bio/p/{ user['user']['slug'] }):** { user['user']['likes'] } likes" ) else: break i += 1 embed = discord.Embed(title="Top Liked Users", description="\n".join(list), color=embed_color(ctx.author) if ctx.guild else Config.MAINCOLOR) embed.set_thumbnail( url= "https://cdn.discordapp.com/emojis/788292835782426626.png?v=1" ) else: embed = discord.Embed( title="Error", description= f"**```\nuser/top returned error code: { resp.status }\n```**", color=Config.ERRORCOLOR) embed.set_footer(text="Please report this to Polar#6880") await ctx.send(embed=embed)
async def stats(self, ctx): """View some detailed statistics about the bot.""" commands = 0 for COG in Config.COGS: commands += len(set(self.bot.cogs[COG].walk_commands())) channels = 0 roles = 0 for guild in self.bot.guilds: channels += len(guild.channels) roles += len(guild.roles) process = psutil.Process(os.getpid()) total_mem = psutil.virtual_memory().total current_mem = process.memory_info().rss name = f"{self.bot.user.name}'" if self.bot.user.name[ -1] == "s" else f"{self.bot.user.name}'s" embed = discord.Embed( title=f"{name} Statistics", timetamp=datetime.utcnow(), color=embed_color(ctx.author) if ctx.guild else Config.MAINCOLOR) embed.add_field( name="📊 Bot Statistics", value= f"**Servers:** {len(self.bot.guilds)}\n**Users:** {len(self.bot.users)}\n**Channels:** {channels}\n**Roles:** {roles}\n**Shards:** {self.bot.shard_count} `[ID: {(ctx.guild.shard_id if ctx.guild else 0) + 1}]`", inline=False) embed.add_field( name="📋 Bot Information", value= f"**Creator:** [**Polar#6880**](https://discord.com/users/619284841187246090)\n**Bot Version:** {__version__}\n**Lines of Code:** 870\n**Commands:** {commands}" ) embed.add_field( name="🖥 Hardware", value= f"**discord.py Version:** v{discord.__version__}\n**Python Version:** {platform.python_version()}\n**Operating System:** {platform.system()} {platform.release()} {platform.version()}\n**Memory Usage:** {(current_mem / total_mem) * 100:.2f}% ({process.memory_info().rss / 1000000:.2f}mb)", inline=False) await ctx.send(embed=embed)
async def links(self, ctx): """Obtain all of the important links.""" embed = discord.Embed( title="Important Links", description= "**[Invite Link](https://discord.com/api/oauth2/authorize?client_id=675515934475288576&permissions=67488768&scope=bot)\n[discord.bio Official Server](https://discord.gg/QCA8RjA5RJ)\n[My GitHub](https://github.com/xPolar/discord.bio)**", color=embed_color(ctx.author) if ctx.guild else Config.MAINCOLOR) await ctx.send(embed=embed)
async def restart(ctx): """Restart the bot's cogs.""" embed = discord.Embed( title = "Bot Restarted", color = Config.MAINCOLOR if ctx.guild == None else embed_color(ctx.author) ) # Print a new line and then reload each cog, as well as print that each cog has been reloaded, then print out that the bot has been fully reloaded. print() for COG in Config.COGS: bot.reload_extension(f"Cogs.{COG}") print(f"{Style.BRIGHT}{Fore.GREEN}[SUCCESS]{Fore.WHITE} Reloaded Cog: {COG}") await ctx.send(embed = embed) print(f"{Style.BRIGHT}{Fore.CYAN}[BOT-RESTARTED]{Fore.WHITE} Restart by {ctx.author} - {ctx.author.id}, I'm currently in {len(bot.guilds)} servers with {len(bot.users)} users!")
async def help(self, ctx): """View the help menu or information on a certain command.""" if ctx.invoked_subcommand == None: prefix = get_prefix(ctx.message) embed = discord.Embed( color = embed_color(ctx.author) if ctx.guild else Config.MAINCOLOR ) embed.set_author(name = "Command Help", icon_url = "https://cdn.discordapp.com/emojis/512367613339369475.png?width=834&height=834") embed.add_field(name = "Help", value = f"`{prefix}help [Command]`\n*View the help menu or information on a certain command.*", inline = False) embed.add_field(name = "Links", value = f"`{prefix}links`\n*Obtain all of the important links.*", inline = False) embed.add_field(name = "Ping", value = f"`{prefix}ping`\n*Get the latency between our bot and Discord as well as the latency of the host.*", inline = False) embed.add_field(name = "Prefix", value = f"`{prefix}prefix [New Prefix]`\n*View or set a prefix within a server.*", inline = False) if ctx.author.id in Config.OWNERIDS: embed.add_field(name = "Restart", value = f"`{prefix}restart`\n*Restart the bot's cogs.*", inline = False) embed.add_field(name = "Stats", value = f"`{prefix}stats`\n*View some detailed statistics about the bot.*", inline = False) embed.add_field(name = "Top", value = f"`{prefix}top`\n*View the top profiles on [discord.bio](https://discord.bio/profiles).*", inline = False) embed.add_field(name = "User", value = f"`{prefix}user [User or Slug]`\n*View a [discord.bio](https://discord.bio) account.*", inline = False) await ctx.send(embed = embed)
async def ping(self, ctx): """Get the latency between our bot and Discord as well as the latency of the host.""" # Get the time at one point, trigger typing, get the time again then subtract the two values to get the host latency. To get API latency use self.bot.latency, get round trip by adding up the two latencies. t1 = time.perf_counter() await ctx.trigger_typing() t2 = time.perf_counter() embed = discord.Embed( title="🏓 Pong!", description= f"Host latency is { round((t2 - t1) * 1000) }ms.\nAPI latency is { int(round(self.bot.latency * 1000, 2)) }ms.\nRound Trip took { int(round((t2 - t1) * 1000) + round(self.bot.latency * 1000, 2)) }ms.", color=embed_color(ctx.author) if ctx.guild != None else Config.MAINCOLOR) # Print out into the console when the round trip takes over 500 milliseconds. if round((t2 - t1) * 1000) + round(self.bot.latency * 1000, 2) > 500: print() print( f"{Style.BRIGHT}{Fore.RED}[WARNING]{Fore.WHITE} API latency is { round((t2 - t1) * 1000) }ms, host latency is { int(round(self.bot.latency * 1000, 2)) }ms, and round trip took { int(round((t2 - t1) * 1000) + round(self.bot.latency * 1000, 2)) }ms." ) await ctx.send(embed=embed)
def command_help(self, ctx, name : str, description : str, usage : str, aliases : list = None): """Generate a help embed for commands. Args: ctx (discord.Context): discord.py's context object. name (str): The name of the command. description (str): The of the command. usage (str): How to use the command. aliases (str, optional): If there are any aliases to the command. Defaults to None. Returns: discord.Embed: The generated embed. """ embed = discord.Embed( title = name, description = description, color = embed_color(ctx.author) if ctx.guild else Config.MAINCOLOR ) embed.set_author(name = "Command Help", icon_url = "https://cdn.discordapp.com/emojis/512367613339369475.png?width=834&height=834") embed.description = embed.description + f"\n\nPlease do: `{usage}`" if aliases: embed.description = embed.description + "\n\nAliases: " + ", ".join([ f'`{alias}`' for alias in aliases ]) return embed
async def user(self, ctx, user : Union[discord.User, str] = None): """View the discord.bio profile of a user.""" user = user if user else ctx.author async with aiohttp.ClientSession() as session: async with session.get(f"https://api.discord.bio/user/details/{ user if isinstance(user, str) else user.id }") as resp: if resp.status == 200: data = await resp.json() data = data["payload"] try: user = await self.bot.fetch_user(int(data["discord"]["id"])) if isinstance(user, str) else user except discord.NotFound: user = user embed = discord.Embed( url = f"https://discord.bio/p/{ data['user']['details']['slug'] }", description = f"{ Config.EMOTES['pencil'] } **Description:** {data['user']['details']['description']}\n{ Config.EMOTES['heart'] } **Likes:** { data['user']['details']['likes'] }", color = embed_color(ctx.author) if ctx.guild else Config.MAINCOLOR ) try: embed.title = f"{ user } `({data['user']['details']['slug']})`{ ' ' + Config.EMOTES['diamond'] if data['user']['details']['premium'] else '' }{ ' ' + Config.EMOTES['gavel'] if data['user']['details']['staff'] else '' }{ ' ' + Config.EMOTES['settings'] if user.id in Config.OWNERIDS else '' }" except KeyError: embed.title = f"{ user } `({data['user']['details']['slug']})`{ ' ' + Config.EMOTES['diamond'] if data['user']['details']['premium'] else '' }{ ' ' + Config.EMOTES['settings'] if user.id in Config.OWNERIDS else '' }" embed.set_thumbnail(url = user.avatar_url) if data["user"]["details"]["banner"]: embed.set_image(url = data["user"]["details"]["banner"]) if data["user"]["details"]["birthday"]: birthdate = datetime.datetime.strptime(data["user"]["details"]["birthday"], "%Y-%m-%d") embed.description += f"\n{ Config.EMOTES['cake'] } **Birthdate:** { birthdate.strftime('%A, %B %d, %Y')}" connections = "" if data["user"]["discordConnections"]: i = 0 for connection in data["user"]["discordConnections"]: connection = list(connection.keys())[0] if connection == "github": connections += f"[{ Config.EMOTES[connection] }](https://github.com/{ data['user']['discordConnections'][i][connection]['name'] })" elif connection == "reddit": connections += f"[{ Config.EMOTES[connection] }](https://reddit.com/u/{ data['user']['discordConnections'][i][connection]['name'] })" elif connection == "steam": connections += f"[{ Config.EMOTES[connection] }](https://steamcommunity.com/profiles/{ data['user']['discordConnections'][i][connection]['id'] })" elif connection == "twitch": connections += f"[{ Config.EMOTES[connection] }](https://twitch.tv/{ data['user']['discordConnections'][i][connection]['name'] })" elif connection == "twitter": connections += f"[{ Config.EMOTES[connection] }](https://twitter.com/{ data['user']['discordConnections'][i][connection]['name'] })" elif connection == "spotify": connections += f"[{ Config.EMOTES[connection] }](https://open.spotify.com/user/{ data['user']['discordConnections'][i][connection]['id']})" i += 1 if data["user"]["userConnections"]: for connection in data["user"]["userConnections"]: if connection == "website": connections += f"[{ Config.EMOTES[connection] }]({ 'https://' if data['user']['userConnections'][connection].startswith('https://') == False and data['user']['userConnections'][connection].startswith('https://') == False else '' }{ data['user']['userConnections'][connection] })" elif connection == "instagram": connections += f"[{ Config.EMOTES[connection] }](https://instagram.com/{ data['user']['userConnections'][connection] })" elif connection == "snapchat": connections += f"[{ Config.EMOTES[connection] }](https://www.snapchat.com/add/{ data['user']['userConnections'][connection] })" elif connection == "linkedin": connections += f"[{ Config.EMOTES[connection] }](https://www.linkedin.com/in/{ data['user']['userConnections'][connection] })" if connections != "": embed.description += f"\n{ Config.EMOTES['website'] } **Connections:** { connections }" if data["user"]["details"]["email"]: embed.description += f"\n{ Config.EMOTES['envelope'] } **Email:** { data['user']['details']['email'] }" if data["user"]["details"]["gender"]: if data["user"]["details"]["gender"] == 0: embed.description += f"\n{ Config.EMOTES['gender'] } **Gender:** Male" else: embed.description += f"\n{ Config.EMOTES['gender'] } **Gender:** { 'Female' if data['user']['details']['gender'] == 1 else 'Nonbinary' }" if data["user"]["details"]["location"]: embed.description += f"\n{ Config.EMOTES['map'] } **Location:** { data['user']['details']['location'] }" if data["user"]["details"]["occupation"]: embed.description += f"\n{ Config.EMOTES['briefcase'] } **Occupation:** { data['user']['details']['occupation'] }" elif resp.status == 401: embed = discord.Embed( title = "Empty Argument", description = "Please provide a user or a slug to view!", color = Config.ERRORCOLOR ) elif resp.status == 404: embed = discord.Embed( title = "Invalid Argument", description = "Please provide a valid user or a slug to view!", color = Config.ERRORCOLOR ) await ctx.send(embed = embed)