async def icon(self, ctx: Context, *, guild: Guild = None) -> None: """ Displays a servers icon. `guild`: The server of which to get the icon for. Can be it's ID or Name. Defaults to the current server. """ if not guild: guild = ctx.guild if not guild.icon: await ctx.send( description=f'The server `{guild}` does not have an icon.', color=Color.red()) return embed = Embed(title=f"{guild.name}'s icon", description=f''' [PNG]({guild.icon_url_as(format="png")}) [JPEG]({guild.icon_url_as(format="jpeg")}) [WEBP]({guild.icon_url_as(format="webp")}) ''', color=Color.blue()) embed.set_image(url=str(guild.icon_url_as(format='png'))) if guild.is_icon_animated(): embed.description += f'\n[GIF]({guild.icon_url_as(format="gif")})' embed.set_image( url=str(guild.icon_url_as(size=1024, format='gif'))) await ctx.send(embed=embed)
async def permissions_add_level( self, ctx, level: str, *, user_or_role: Union[User, Role, str] ): """ Add a user, role, or everyone permission to use commands of a permission level. Do not ping `@everyone` for granting permission to everyone, use "everyone" or "all" instead, `user_or_role` may be a role ID, name, mention, user ID, name, mention, "all", or "everyone". """ if level.upper() not in PermissionLevel.__members__: embed = Embed( title="Error", color=Color.red(), description="The permission level you are attempting to point " f"to does not exist: `{level}`.", ) return await ctx.send(embed=embed) if hasattr(user_or_role, "id"): value = user_or_role.id elif user_or_role in {"everyone", "all"}: value = -1 else: raise commands.BadArgument(f'User or Role "{user_or_role}" not found') await self.bot.update_perms(PermissionLevel[level.upper()], value) embed = Embed( title="Success", color=self.bot.main_color, description=f"Permission for {level} was successfully updated.", ) return await ctx.send(embed=embed)
def _account(msg, account): """ Returns account message embed """ desc = "" color = None if account.isDestroyed: desc = "This account token is no longer valid" color = Color.dark_grey() elif account.isValidated: desc = f'Id: `{account.strId}`\n' + f'Username: `{account.ident}`\n' + f'Password: `{account.pwd}`\n' + 'Note: This account is given to you only for the time of **ONE** match' color = Color.green() else: desc = "Accept the rules by reacting with a checkmark to get your account details." color = Color.red() embed = Embed( colour=color, title='Jaeger Account', description= f'**MUST READ: [Account usage](https://planetsideguide.com/other/jaeger/)**' ) embed.add_field(name="Logging details", value=desc, inline=False) embed.set_thumbnail( url= "https://media.discordapp.net/attachments/739231714554937455/739522071423614996/logo_png.png" ) embed.set_footer( text= 'Failure to follow account usage rules can result in your suspension from ALL Jaeger events.' ) return embed
async def permissions_remove_command( self, ctx, command: str, *, user_or_role: Union[User, Role, str] ): """ Remove a user, role, or everyone permission to use a command. Do not ping `@everyone` for granting permission to everyone, use "everyone" or "all" instead, `user_or_role` may be a role ID, name, mention, user ID, name, mention, "all", or "everyone". """ if command not in self.bot.all_commands: embed = Embed( title="Error", color=Color.red(), description="The command you are attempting to point " f"to does not exist: `{command}`.", ) return await ctx.send(embed=embed) if hasattr(user_or_role, "id"): value = user_or_role.id elif user_or_role in {"everyone", "all"}: value = -1 else: raise commands.BadArgument(f'User or Role "{user_or_role}" not found') await self.bot.update_perms( self.bot.all_commands[command].name, value, add=False ) embed = Embed( title="Success", color=self.bot.main_color, description=f"Permission for {command} was successfully updated.", ) return await ctx.send(embed=embed)
async def config_set(self, ctx, key: str.lower, *, value: str): """Set a configuration variable and its value.""" keys = self.bot.config.allowed_to_change_in_command if key in keys: try: value, value_text = await self.bot.config.clean_data(key, value) except InvalidConfigError as exc: embed = exc.embed else: await self.bot.config.update({key: value}) embed = Embed( title="Success", color=self.bot.main_color, description=f"Set `{key}` to `{value_text}`", ) else: embed = Embed( title="Error", color=Color.red(), description=f"{key} is an invalid key.", ) valid_keys = [f"`{k}`" for k in keys] embed.add_field(name="Valid keys", value=", ".join(valid_keys)) return await ctx.send(embed=embed)
async def format_not_found(self, ctx, command): prefix = ctx.prefix embed = Embed( title='Impossible de trouver une commande ou une catégorie', color=Color.red()) embed.set_footer(text=f'Tapez "{prefix}help" pour obtenir ' 'une liste complète de commandes.') choices = set() # filter out hidden commands & blank cogs for i in self.bot.cogs: for cmd in self.bot.commands: if cmd.cog_name == i and not cmd.hidden and \ await self.verify_checks(ctx, cmd): # as long as there's one valid cmd, add cog choices.add(i) break for i in self.bot.commands: if not i.hidden and await self.verify_checks(ctx, i): choices.add(i.name) closest = get_close_matches(command, choices, n=1, cutoff=0.45) if closest: # Perhaps you meant: # - `item` embed.description = (f'**Peut-être que vous vouliez dire:**\n' f'\u2000- `{closest[0]}`') return embed
async def get(self, ctx, key=None): """Affiche les variables de configuration actuellement définies.""" keys = self.bot.config.allowed_to_change_in_command if key: if key in keys: desc = f'`{key}` est réglé sur `{self.bot.config.get(key)}`' embed = Embed(color=self.bot.main_color, description=desc) embed.set_author(name='Config variable', icon_url=self.bot.user.avatar_url) else: embed = Embed(title='Erreur', color=Color.red(), description=f'`{key}` est une clé invalide.') valid_keys = [f'`{k}`' for k in keys] embed.add_field(name='Clés valides', value=', '.join(valid_keys)) else: embed = Embed(color=self.bot.main_color, description='Voici une liste des variables de ' 'configuration actuellement définies.') embed.set_author(name='Configuration actuelle', icon_url=self.bot.user.avatar_url) config = { k: v for k, v in self.bot.config.cache.items() if v and k in keys } for k, v in reversed(list(config.items())): embed.add_field(name=k, value=f'`{v}`', inline=False) return await ctx.send(embed=embed)
async def github_search(self, ctx: commands.Context, *, term: str): # TODO: Docs req = await self.github_request(ctx, "GET", "/search/repositories", dict(q=term, per_page=5)) data = await req.json() if not data["items"]: return await ctx.send(embed=Embed( title=f"Searched for {term}", color=Color.red(), description="No results found", )) em = Embed( title=f"Searched for {term}", color=Color.green(), description="\n\n".join([ "[{0[owner][login]}/{0[name]}]({0[html_url]})\n{0[stargazers_count]:,} :star:\u2800{0[forks_count]} \u2387\u2800\n{1}" .format(result, self.repo_desc_format(result)) for result in data["items"] ]), ) await ctx.send(embed=em)
async def clear(self, ctx, amount): """Clears a given amount of messages. (Mods only)""" channel = ctx.message.channel try: n = int(amount) + 1 except ValueError: return await ctx.send("Please mention a valid amount of messages!") try: await channel.purge(limit=n) await ctx.send( "🗑️ Cleared {} messages in this channel!".format(amount)) try: emb = Embed(title="Messages Cleared", colour=Color.red()) emb.add_field(name="Mod:", value=ctx.message.author, inline=True) emb.add_field(name="Channel:", value=ctx.message.channel, inline=True) emb.add_field(name="Amount:", value=amount, inline=True) logchannel = self.bot.logs_channel await logchannel.send("", embed=emb) except errors.Forbidden: await ctx.send("💢 I dont have permission to do this.") except errors.Forbidden: await ctx.say("💢 I don't have permission to do this.")
def flip_accounts(ctx, account_names): embed = Embed(colour=Color.red()) embed.add_field(name="Characters affected:", value="\n".join(i_name for i_name in account_names), inline=False) return embed
async def thank_leaderboard(self, ctx: commands.Context): await ctx.trigger_typing() lb = ( await UserModel.annotate( thank_count=Count("thanks", _filter=Q(thanks__guild_id=ctx.guild.id)) ) .filter(thank_count__gt=0) .order_by("-thank_count") .limit(5) ) if not lb: return await ctx.send( embed=Embed( title="Oopsy", description="There are no thanks here yet!", color=Color.red(), ) ) invis = "\u2800" embed = Embed( title="LeaderBoard", color=Color.blue(), description="\n\n".join( [ f"**{m.thank_count} Thanks**{invis * (4 - len(str(m.thank_count)))}<@!{m.id}>" for m in lb ] ), ) await ctx.send(embed=embed)
async def unregister(self, ctx): if not len( list( self.bot.userCollection.find( {'discordID': str(ctx.author.id)}))): await ctx.send(embed=Embed(title='가입이 안되있습니다', color=Color.red())) return msg = await ctx.send(embed=Embed( title='정말 탈퇴하시겠습니까?', description= '정말 가입을 하실거면 `네넹` 이라고 보내주세요(30초 동안 `네넹`을 안보내시면 자동으로 취소됩니다)', color=Color.orange())) try: await self.bot.wait_for('message', check=(lambda m: (m.content == '네넹') and (m.channel == ctx.channel) and (m.author == ctx.author)), timeout=30) except TimeoutError: await msg.edit(embed=Embed(title='탈퇴를 취소했습니다', color=Color.green()) ) return self.bot.userCollection.remove({'discordID': str(ctx.author.id)}) await msg.edit(embed=Embed(title='탈퇴를 했습니다', color=Color.green()))
async def register(self, ctx): if len( list( self.bot.userCollection.find( {'discordID': str(ctx.author.id)}))): await ctx.send(embed=Embed(title='이미 가입되셨습니다', color=Color.red())) return msg = await ctx.send(embed=Embed( title='정말 가입하시겠습니까?', description= 'DB에는 사용자의 정보중 `ID`만 저장합니다\n정말 가입을 하실거면 `네넹` 이라고 보내주세요(30초 동안 `네넹`을 안보내시면 자동으로 취소됩니다)', color=Color.orange())) try: await self.bot.wait_for('message', check=(lambda m: (m.content == '네넹') and (m.channel == ctx.channel) and (m.author == ctx.author)), timeout=30) except TimeoutError: await msg.edit(embed=Embed(title='가입을 취소했습니다', color=Color.green()) ) return self.bot.userCollection.insert({ 'discordID': str(ctx.author.id), 'point': 0, 'permissions': [], 'following': [] }) await msg.edit(embed=Embed(title='가입을 했습니다', color=Color.green()))
def profile_id(ctx, args): syntax_err = discord.Embed(title="Failed", colour=Color.red(), description="ERROR: !profileid <user id>") if len(args) < 2: return syntax_err user_id = args[1] user_presence = RobloxAPI.get_user_presence(user_id).json() user = RobloxAPI.get_user_by_id(user_id).json() pfp = RobloxAPI.get_pfp_by_id(user_id) status = RobloxAPI.get_user_status(user_id) display_name = user['displayName'] presence_type = RobloxAPI.get_presence_type( user_presence['userPresences'][0]['userPresenceType']) presence_type_num = user_presence['userPresences'][0]['userPresenceType'] game_name = "Not in game" if presence_type_num is 0 or presence_type_num is 1 else \ user_presence['userPresences'][0][ 'lastLocation'] game_id = user_presence['userPresences'][0]['placeId'] game_url = None if presence_type_num is 1 or presence_type_num is 0 else RobloxAPI.get_game_link( game_id) e = discord.Embed(title=display_name, colour=Color.teal(), description="Information on Roblox Profile", url=game_url) e.set_thumbnail(url=pfp) e.add_field(name="Status", value=status, inline=False) e.add_field(name="In-Game", value=presence_type, inline=True) e.add_field(name="Game", value=game_name, inline=False) return e
async def get(self, ctx, key=None): """Shows the config variables that are currently set.""" keys = self.bot.config.allowed_to_change_in_command if key: if key in keys: desc = f'`{key}` is set to `{self.bot.config.get(key)}`' embed = Embed(color=self.bot.main_color, description=desc) embed.set_author(name='Config variable', icon_url=self.bot.user.avatar_url) else: embed = Embed(title='Error', color=Color.red(), description=f'`{key}` is an invalid key.') valid_keys = [f'`{k}`' for k in keys] embed.add_field(name='Valid keys', value=', '.join(valid_keys)) else: embed = Embed(color=self.bot.main_color, description='Here is a list of currently ' 'set configuration variables.') embed.set_author(name='Current config', icon_url=self.bot.user.avatar_url) config = { k: v for k, v in self.bot.config.cache.items() if v and k in keys } for k, v in reversed(list(config.items())): embed.add_field(name=k, value=f'`{v}`', inline=False) return await ctx.send(embed=embed)
async def crime(self, ctx, user: User): """Try to steal from a user""" if str(user.id) not in economy: economy[str(user.id)] = economy['default_economy'] if str(ctx.author.id) not in economy: economy[str(ctx.author.id)] = economy['default_economy'] stats = economy[str(user.id)] percentage = random.randint(0, 20) amount = int(stats['coins'] * percentage / 100) if random.choice([False] * 5 + [True] * 7): economy[str(ctx.author.id)]['coins'] += amount auth_stats = economy[str(ctx.author.id)] embed = Embed( title=f"You stole {amount} coins from {user}!", description=f"You now have {auth_stats['coins']} coins.", color=Color.green()) await ctx.send('Success!', embed=embed) else: economy[str(ctx.author.id)]['coins'] -= int(amount * 1.2) auth_stats = economy[str(ctx.author.id)] embed = Embed( title= f"You were caught stealing! You lost {int(amount * 1.2)} coins!", description=f"You now have {auth_stats['coins']} coins.", color=Color.red()) await ctx.send('Failure.', embed=embed)
async def parse_json(ctx: Context, json_code: str) -> t.Union[dict, bool]: # Sanitize code (remove codeblocks if any) if "```" in json_code: json_code = json_code.replace("```json\n", "") json_code = json_code.replace("```\n", "") json_code = json_code.replace("```json", "") json_code = json_code.replace("```", "") # Parse the code into JSON try: return json.loads(json_code) except json.JSONDecodeError as e: lines = json_code.split("\n") embed = Embed( description=textwrap.dedent( f""" Sorry, I couldn't parse this JSON: ``` {e} ``` The error seems to be here *(`line: {e.lineno} col: {e.colno}`)*: ``` {lines[e.lineno - 1]} {" " * (int(e.colno) - 1)}^ ``` """ ), color=Color.red(), ) await ctx.send(f"Sorry {ctx.author.mention}", embed=embed) return False
async def coin_flip(self, ctx, wager: int): """Take a 50-50 chance to win or lose a wager""" wager = abs(wager) if str(ctx.author.id) not in economy: economy[str(ctx.author.id)] = economy['default_economy'] stats = economy[str(ctx.author.id)] if wager > stats['coins']: raise errors.UserInputError( 'Your wager is larger than your coin amount') if random.choice([True, False]): economy[str(ctx.author.id)]['coins'] += wager embed = Embed( title="You won!", description= f"{ctx.author} now has {economy[str(ctx.author.id)]['coins']} coins", color=Color.green()) await ctx.send(embed=embed) else: economy[str(ctx.author.id)]['coins'] -= wager embed = Embed( title="You lost!", description= f"{ctx.author} now has {economy[str(ctx.author.id)]['coins']} coins", color=Color.red()) await ctx.send(embed=embed)
async def set(self, ctx, key: str.lower, *, value): """ Définit une variable de configuration et sa valeur """ keys = self.bot.config.allowed_to_change_in_command if key in keys: try: value, value_text = await self.bot.config.clean_data( key, value) except InvalidConfigError as exc: embed = exc.embed else: await self.bot.config.update({key: value}) embed = Embed(title='Succès', color=self.bot.main_color, description=f'Set `{key}` à `{value_text}`') else: embed = Embed(title='Erreur', color=Color.red(), description=f'{key} est une clé invalide.') valid_keys = [f'`{k}`' for k in keys] embed.add_field(name='Clés valides', value=', '.join(valid_keys)) return await ctx.send(embed=embed)
async def set(self, ctx, key: str.lower, *, value): """ Sets a configuration variable and its value """ keys = self.bot.config.allowed_to_change_in_command if key in keys: try: value, value_text = self.bot.config.clean_data(key, value) except InvalidConfigError as exc: embed = exc.embed else: embed = Embed(title='Success', color=self.bot.main_color, description=f'Set `{key}` to `{value_text}`') await self.bot.config.update({key: value}) else: embed = Embed(title='Error', color=Color.red(), description=f'{key} is an invalid key.') valid_keys = [f'`{k}`' for k in keys] embed.add_field(name='Valid keys', value=', '.join(valid_keys)) return await ctx.send(embed=embed)
async def sysinfo(self, ctx: Context) -> None: """Get system information (show info about the server this bot runs on).""" uname = platform.uname() system = textwrap.dedent(f""" • System: **{uname.system}** • Node Name: **{uname.node}** """) version = textwrap.dedent(f""" • Release: **{uname.release}** • Version: **{uname.version}** """) hardware = textwrap.dedent(f""" • Machine: **{uname.machine}** • Processor: **{uname.processor}** """) embed = Embed(title="BOT SYSTEM INFO", color=Color.red()) embed.add_field(name="**❯❯ System**", value=system, inline=True) embed.add_field(name="**❯❯ Hardware**", value=hardware, inline=True) embed.add_field(name="**❯❯ Version**", value=version, inline=False) embed.set_author( name=f"{self.bot.user.name}'s System Data", icon_url=self.bot.user.avatar_url, ) await ctx.send(embed=embed)
async def eval(self, ctx: CommandContext, *, to_eval: str = None): if to_eval is None: return await ctx.send( embed=Embed( description="<Insert generic insult about your stupidity here>", color=Color.red())) await handle_eval(ctx.message, self.bot, to_eval)
async def send_error_message(self, msg): # pylint: disable=W0221 logger.warning(error(f"CommandNotFound: {msg}")) embed = Embed(color=Color.red()) embed.set_footer( text=f'Command/Category "{self.context.kwargs.get("command")}" not found.' ) choices = set() for name, cmd in self.context.bot.all_commands.items(): if not cmd.hidden: choices.add(name) command = self.context.kwargs.get("command") closest = get_close_matches(command, choices) if closest: embed.add_field( name=f"Perhaps you meant:", value="\n".join(f"`{x}`" for x in closest) ) else: embed.title = "Cannot find command or category" embed.set_footer( text=f'Type "{self.clean_prefix}{self.command_attrs["name"]}" ' "for a list of all available commands." ) await self.get_destination().send(embed=embed)
async def relay_message(self, message: Message) -> None: """Relays the message's content and attachments to the duck pond channel.""" if message.clean_content: await send_webhook( webhook=self.webhook, content=message.clean_content, username=message.author.display_name, avatar_url=message.author.avatar_url ) if message.attachments: try: await send_attachments(message, self.webhook) except (errors.Forbidden, errors.NotFound): e = Embed( description=":x: **This message contained an attachment, but it could not be retrieved**", color=Color.red() ) await send_webhook( webhook=self.webhook, embed=e, username=message.author.display_name, avatar_url=message.author.avatar_url ) except discord.HTTPException: log.exception("Failed to send an attachment to the webhook") await message.add_reaction("✅")
async def config_remove(self, ctx, key: str.lower): """Delete a set configuration variable.""" keys = self.bot.config.allowed_to_change_in_command if key in keys: try: del self.bot.config.cache[key] await self.bot.config.update() except KeyError: # when no values were set pass embed = Embed( title="Success", color=self.bot.main_color, description=f"`{key}` had been deleted from the config.", ) else: embed = Embed( title="Error", color=Color.red(), description=f"{key} is an invalid key.", ) valid_keys = [f"`{k}`" for k in keys] embed.add_field(name="Valid keys", value=", ".join(valid_keys)) return await ctx.send(embed=embed)
def random(): c = [ 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 ] return c[randint(0, len(c) - 1)]
async def on_member_ban(self, guild, user): # TODO: what if we arent allowed to see audit logs # NOTE: we assume the event always gets called before the audit logs get updated trigger_time = datetime.datetime.utcnow() - datetime.timedelta( seconds=10) # Give Discord some time to put the ban in the audit logs await asyncio.sleep(1) # Only check bans and after the time this event got triggered async for entry in guild.audit_logs(action=AuditLogAction.ban): # NOTE: the `after`-tag in audit_logs seems to get ignored :|, so we have to check manually if trigger_time > entry.created_at: await self.log( guild=guild, embed=Embed( color=Color.purple(), description= "Ban happened, but audit logs dont seem to have information" ).set_author(name=str(user))) break elif entry.target == user: # Check if the target is the user that got banned await self.log(guild=guild, embed=Embed(color=Color.red()).set_author( name=str(entry.user)).add_field( name="banned", value=str(user)).add_field( name="reason", value=entry.reason)) break
async def on_error(self, event, *args, **kwargs): """ format python traceback into a more descriptive format, put it into an embed and send it to error_channels """ exc_type, exc_value, exc_traceback = sys.exc_info() exc = traceback.format_exception(exc_type, exc_value, exc_traceback, chain=False) description = '```py\n%s\n```' % ''.join(exc) time = datetime.datetime.utcnow() message = 'Event {0} at {1}: More info: {2}'.format( event, time, description) embed = Embed(title='Event {0} at {1}:'.format(event, time), description=description[-1500:], color=Color.red()) with open("assets/local_db.json", "r", encoding="utf-8") as file: local_db = json.load(file) for channel_id in local_db["error_channels"]: channel = self.get_channel(channel_id) if channel: await channel.send(embed=embed) print(message)
async def format_not_found(self, ctx, command): prefix = ctx.prefix embed = Embed(title='Unable to Find Command or Category', color=Color.red()) embed.set_footer(text=f'Type "{prefix}help" to get ' 'a full list of commands.') choices = set() # filter out hidden commands & blank cogs for i in self.bot.cogs: for cmd in self.bot.commands: if cmd.cog_name == i and not cmd.hidden and \ await self.verify_checks(ctx, cmd): # as long as there's one valid cmd, add cog choices.add(i) break for i in self.bot.commands: if not i.hidden and await self.verify_checks(ctx, i): choices.add(i.name) closest = get_close_matches(command, choices, n=1, cutoff=0.45) if closest: # Perhaps you meant: # - `item` embed.description = (f'**Perhaps you meant:**\n' f'\u2000- `{closest[0]}`') return embed
async def splash(self, ctx: Context, *, guild: Guild = None): """ Displays a servers splash. `guild`: The server of which to get the splash for. Can be it's ID or Name. Defaults to the current server. """ if not guild: guild = ctx.guild if not guild.splash: await ctx.send( description= f'The server `{guild}` does not have an splash icon.', color=Color.red()) return embed = Embed(color=discord.Color.blurple(), title=f"{guild.name}'s splash") embed.description = f''' [PNG]({guild.splash_url_as(format="png")}) [JPEG]({guild.splash_url_as(format="jpeg")}) [WEBP]({guild.splash_url_as(format="webp")}) ''' embed.set_image(url=str(guild.splash_url_as(format='png'))) return await ctx.send(embed=embed)