async def dog_image(self, ctx): URL = "https://some-random-api.ml/img/dog" random = randint(1, 103) if random != 100 and random != 101 and random != 102: async with request("GET", URL, headers={}) as response: if response.status == 200: data = await response.json() embed = Embed(title="Dog Picture!", colour=ctx.author.colour) embed.set_footer( text=f"{ctx.author} requested this picture!", icon_url=ctx.author.avatar_url) embed.set_image(url=data["link"]) await ctx.send(embed=embed) elif random == 100: embed = Embed( title="Lucky Dog Picture!", description= "This is [Liquid Mendo](https://twitter.com/mendo)'s dog Koda!", colour=Colour.gold()) embed.set_footer( text= f"{ctx.author} got this lucky dog picture! | There is a 1 in 100 chance of getting this picture!", icon_url=ctx.author.avatar_url) embed.set_image( url= "https://pbs.twimg.com/media/EgXfe_XUcAABT41?format=jpg&name=360x360" ) await ctx.send(embed=embed) elif random == 101: embed = Embed( title="Lucky Dog Picture!", description= "There is a 1 in 100 chance of getting this picture!", colour=Colour.gold()) embed.set_footer(text=f"{ctx.author} got this lucky dog picture!", icon_url=ctx.author.avatar_url) embed.set_image(url="https://i.imgur.com/pzqRLdi.jpg") await ctx.send(embed=embed) elif random == 102: embed = Embed( title="Lucky Dog Picture!", description= "This is [Weest](https://twitter.com/weesterner)'s dog Kevin!", colour=Colour.gold()) embed.set_footer( text= f"{ctx.author} got this lucky dog picture! | There is a 1 in 100 chance of getting this picture!", icon_url=ctx.author.avatar_url) embed.set_image(url="https://i.imgur.com/guF2Y3z.png") await ctx.send(embed=embed)
class WebhookHandler(logging.Handler): _colours = { logging.DEBUG: Colour.light_grey(), logging.INFO: Colour.gold(), logging.WARNING: Colour.orange(), logging.ERROR: Colour.red(), logging.CRITICAL: Colour.dark_red() } def __init__(self, webhook_url, level=logging.NOTSET): super().__init__(level) self._webhook_logger = EmbedWebhookLogger(webhook_url) def emit(self, record: logging.LogRecord): self.format(record) message = f'{record.message}\n{record.exc_text or ""}' message = message[:1987] + '...' if len(message) > 1987 else message self._webhook_logger.log( Embed(colour=self._colours.get(record.levelno), title=record.name, description=f'```py\n{message}\n```', timestamp=datetime.datetime.fromtimestamp( record.created)).add_field( name=ZWSP, value=f'{record.filename}:{record.lineno}'))
async def create_rule(ctx) -> None: embed = discord.Embed(colour=Colour.gold()) embed.set_author(name='Commands:') embed.add_field( name=">createname: ", value="create the character by provinding his/hers name", inline=True) embed.add_field( name=">creatrace: ", value= "choose the race by provinding his/hers name and the race number", inline=True) embed.add_field( name=">creatclasss: ", value= "choose the class by provinding his/hers name and the class number", inline=True) embed.add_field(name=">createrule: ", value="print the commands", inline=True) embed.add_field(name=">createrandom: ", value="create the character randomly", inline=True) embed.add_field( name=">creatprint: ", value="print the characther stauts by provinding his/hers name", inline=True) embed.add_field( name=">roll: ", value="roll the dice by providint its faces and the roll times", inline=True)
async def on_call(self, ctx, args, **flags): if len(args) == 1: discrim = ctx.author.discriminator else: if args[1].isdigit() and len(args[1]) == 4: discrim = args[1] else: return '{warning} Invalid discriminator given' matched = [] for user in self.bot.users: if user.discriminator == discrim and not user.bot and user != ctx.author: matched.append(user) if not matched: return '{warning} Users with discriminator **%s** not found' % discrim lines = sorted([str(u) for u in matched], key=lambda s: (len(s), s)) users_per_chunk = 30 chunks = [ lines[i:i + users_per_chunk] for i in range(0, len(lines), users_per_chunk) ] p = Paginator(self.bot) for i, chunk in enumerate(chunks): e = Embed(description=f'```\n' + '\n'.join(chunk) + '```', colour=Colour.gold()) e.set_footer( text=f'Page {i + 1}/{len(chunks)} ({len(lines)}) results') p.add_page(embed=e) await p.run(ctx)
async def match(self, ctx, team1: Union[Role, Member], team2: Union[Role, Member], *schedule_args): "Schedule a match between two teams." schedule_args = " ".join(schedule_args) # Parse schedule string datetime_obj, datetime_str = parsing.parse_date(schedule_args) embed = Embed(title="**Match scheduled**", colour=Colour.gold()) embed.set_footer(text=datetime_str) for team, emoji in zip([team1, team2], [one_emoji, two_emoji]): if isinstance(team, Member): embed.add_field(name=emoji, value=team.mention) elif isinstance(team, Role): embed.add_field(name=emoji + " " + team.name, value='\n'.join(m.mention for m in team.members)) else: await ctx.send( f"Error: teams must be mentioned by role or user " f"({team} is {type(team)}") return send_channel = ctx.guild.get_channel( await ctx.bot.db.channels.get_redirect_channel(ctx.channel.id)) match_message = await send_channel.send(embed=embed) await match_message.add_reaction(one_emoji) await match_message.add_reaction(two_emoji)
def __init__(self, alerts): """Generate an embed containing the list of alerts Parameters: ----------- l_alerts: iterable of :class:`warframe.parser.alerts.Alerts` The list of alerts. platform: str [Optional] The platform those alerts are on. Attributes: ----------- _desc_gotl: str The description present if the alert is a gift of the lotus """ self._desc_gotl = "Gift of The Lotus" title = "Alerts" Embed.__init__(self, title=title, type="rich") if alerts is not None: for alert in alerts: self.add_alert(alert) self.colour = Colour.gold()
def make_embed(chunk): e = Embed(colour=Colour.gold(), title='Command usage:', description='```\n' + "\n".join(chunk) + '```') e.set_footer(text=f'Commands used in total: {total_usage}', icon_url=self.bot.user.avatar_url) return e
async def embed_builder(ctx, title, description, data: list, destination=None, thumbnail=None, c: Colour = None): """ Build embed from data provided :param ctx: Discord Context :param title: Title for embed :param description: Description of embed :param data: data as list of dict :param destination: where embed is sent :param thumbnail: where embed is sent :return: """ if not c: c = Colour.gold() embed = Embed(title=title, description=description, colour=c) for d in data: embed.add_field(name=d['name'], value=d['value'], inline=False) if thumbnail: embed.set_thumbnail(url=thumbnail) try: if destination: await ctx.author.send(embed=embed) else: await ctx.channel.send(embed=embed, delete_after=40) except Exception: await ctx.channel.send(embed=embed)
async def stellar_wallet_overall(ctx, coin_stats: dict, utc_now): try: bridges = coin_stats['bridges'] except KeyError: bridges = 0 building_bridges = Embed( title=f':construction_site: Building Bridges :construction_site:', description= "Your Input on bridging the Stellar Network with Discord " "Users through Crypto Link.", colour=Colour.gold(), timestamp=utc_now) building_bridges.add_field( name=f':bridge_at_night: Created Bridges :bridge_at_night: ', value=f'```{int(bridges)}```') await ctx.author.send(embed=building_bridges) for k, v in coin_stats.items(): if k in ["xlm"]: coin_stats = Embed( title=f'{k.upper()} wallet statistics', description= f':bar_chart: ***__Statistical Data on Stellar Lumen Discord Wallet__*** ' f':bar_chart:', colour=Colour.light_grey(), timestamp=utc_now) coin_stats.add_field( name=f':inbox_tray: Total Deposits :inbox_tray:', value=f'Deposited ***{v["depositsCount"]}*** with total ' f'***{v["totalDeposited"]}*** ') coin_stats.add_field(name=f'\u200b', value='\u200b') coin_stats.add_field( name=f':outbox_tray: Total Withdrawals :outbox_tray: ', value= f'Withdrawn ***{v["withdrawalsCount"]}*** withdrawals with ' f'total ***{v["totalWithdrawn"]}*** ') coin_stats.add_field( name= f':family_man_woman_boy: Public Tx :family_man_woman_boy:', value=f':incoming_envelope: `{v["publicTxSendCount"]}`\n' f':money_with_wings: `{(int(v["publicSent"] * (10 ** 7))) / (10 ** 7):.7f}`\n' f':envelope_with_arrow: `{v["publicTxReceivedCount"]}`\n' f':money_mouth: `{(int(v["publicReceived"] * (10 ** 7))) / (10 ** 7):.7f}`' ) coin_stats.add_field( name=f':detective: Private Tx :detective:', value=f':incoming_envelope: `{v["privateTxSendCount"]}`\n' f':money_with_wings: `{(int(v["privateSent"] * (10 ** 7))) / (10 ** 7):.7f}`\n' f':envelope_with_arrow: `{v["privateTxReceivedCount"]}`\n' f':money_mouth: `{(int(v["privateReceived"] * (10 ** 7))) / (10 ** 7):.7f}` ' ) coin_stats.add_field( name= f':convenience_store: Merchant purchases :convenience_store: ', value=f':man_juggling:` `{v["roleTxCount"]}`\n' f':money_with_wings: `{(int(v["spentOnRoles"] * (10 ** 7))) / (10 ** 7): .7f}`\n', inline=False) await ctx.author.send(embed=coin_stats)
def __init__(self, message): super().__init__() self.simple = False self.message = message self.id = message.id url = message.jump_url content = message.content # Gold colour self.colour = Colour.gold() self.description = f'[Ver a mensagem]({url})\n{content}' self = self.set_author(name=message.author.display_name, url=Embed.Empty, icon_url=message.author.avatar_url) attachments = message.attachments if is_simple(attachments): if len(attachments) == 1 and isimage(attachments[0].filename): image_url = attachments[0].url self = self.set_image(url=image_url) self.simple = True creation_date = message.created_at.astimezone(timezone('Etc/GMT+6')) timestamp = creation_date.strftime("%d/%m/%Y, %H:%M:%S") self = self.set_footer(text=timestamp)
async def weather(ctx, *, location): """ !weather <location> - look up weather information in a city or a region """ weather = get_weather(location) embed = Embed() embed.type = "rich" embed.color = Colour.gold() embed.add_field(name=":rainbow: Weather in ", value=weather[0]) embed.add_field(name=":sun_with_face: Temperature: ", value=str(weather[1]) + " C") embed.add_field(name=":warning: Conditions: ", value=', '.join(weather[4])) embed.add_field(name=":cloud_tornado: Wind speed: ", value=str(weather[2]) + " m/s") embed.add_field(name=":white_sun_small_cloud: Cloudiness: ", value=str(weather[3]) + " %") await bot.say(None, embed=embed)
async def voice(self, ctx, *, alias: str = ''): """ Modifies/displays voice profile information of the command invoker. parameter: ctx [Context]: context object representing command invocation alias [str] (default=''): name of command invoker's new voice """ member = ctx.author.display_name # Check if an alias was provided if not alias: # Retrieve command invoker's current alias alias = self.voice_profiles[(ctx.author, ctx.channel)] prefix = self.prefixes[ctx.guild] embed = Embed(title=":gear: **Voice Settings**", colour=Colour.gold()) embed.add_field(name=f"**{member}'s Current Voice:**", value=f"`{alias}`", inline=False) embed.add_field(name="**Update Voice:**", value=f"`{prefix}voice [New Voice]`", inline=False) elif await voice_is_valid(alias): # Set the command invoker's new alias self.voice_profiles[(ctx.author, ctx.channel)] = alias embed = Embed( title=(f":white_check_mark: **{member}'s new voice is **" f"`{alias}`"), colour=Colour.green()) await ctx.send(embed=embed)
async def system(self, ctx): embed = Embed( title='System Info', timestamp=datetime.utcnow(), color=Colour.gold() ) svmem = psutil.virtual_memory() cpufreq = psutil.cpu_freq() partitions = psutil.disk_partitions() embed.add_field( name='CPU', inline=False, value=f'Total Cores: `{psutil.cpu_count(logical=False)}/{psutil.cpu_count(logical=True)}`' f'\nFrequency: ```{cpufreq.current:,.2f}Mhz ({psutil.cpu_percent()})%```' ) embed.add_field( name='Memory', inline=False, value=f'Usage: ```{get_size(svmem.used)}/{get_size(svmem.total)} ({svmem.percent}%)```' ) for partition in partitions: try: partition_usage = psutil.disk_usage(partition.mountpoint) except PermissionError: continue embed.add_field( name=f'Disk', inline=False, value=f'\nUsed: ```{get_size(partition_usage.used)}/{get_size(partition_usage.total)} ' f'({partition_usage.percent}%)```' ) break await ctx.send(embed=embed)
async def on_call(self, ctx, args, **flags): user = None if len(args) > 1: user = await find_user(args[1:], ctx.message, global_search=False) if user is None: return '{warning} User not found' roles = user.roles else: roles = ctx.guild.roles lines = [f'{r.id:<19}| {r.name}' for r in roles[::-1]] lines_per_chunk = 30 chunks = [ f'```{"id":<19}| name\n{"-" * 53}\n' + '\n'.join(lines[i:i + lines_per_chunk]) + '```' for i in range(0, len(lines), lines_per_chunk) ] p = Paginator(self.bot) for i, chunk in enumerate(chunks): e = Embed( title= f'''{'Guild' if user is None else str(user) + "'s"} roles ({len(lines)})''', colour=Colour.gold(), description=chunk) e.set_footer(text=f'Page {i + 1} / {len(chunks)}') p.add_page(embed=e) await p.run(ctx)
async def paginator_update_func(self, p): async with self.bot.sess.get(API_URL) as r: if r.status == 200: e = Embed(colour=Colour.gold()) e.set_image(url=await r.text()) e.set_footer(text='Powered by https://inspirobot.me') return {'embed': e}
async def game_stats( self, ctx: Context, ) -> None: if ctx.invoked_subcommand is None: state = GameState.get_or_create(ctx) await self.show_game(ctx, state, Colour.gold()) return
def __init__(self, synthesis, name): name = name.title() title = f"Synthesis Target - {name}" Embed.__init__(self, title=title, type="rich") if synthesis is not None: for target in synthesis: if target['name'] == name: self.add_target(target) self.colour = Colour.gold()
async def element_color(element): switch = { 'Light': Colour.gold(), 'Dark': Colour.dark_purple(), 'Fire': Colour.dark_red(), 'Water': Colour.dark_blue(), 'Forest': Colour.dark_green() } return switch.get(element)
def make_embed(chunk, page=None): e = Embed(title=f'{len(guilds)} common guilds', colour=Colour.gold(), description=chunk) e.set_author(name=user, icon_url=user.avatar_url) if page is not None: e.set_footer(text=f'Page {i + 1} / {len(chunks)}') return e
async def on_member_join(self, member: Member): """ This event will trigger when someone (re)joins the server. At this point we will look up the user in our database and check whether they are in superstar-prison. If so, we will change their name back to the forced nickname. """ response = await self.bot.http_session.get( URLs.site_superstarify_api, headers=self.headers, params={"user_id": str(member.id)}) response = await response.json() if response and response.get( "end_timestamp") and not response.get("error_code"): forced_nick = response.get("forced_nick") end_timestamp = response.get("end_timestamp") log.debug( f"{member.name} rejoined but is currently in superstar-prison. " f"Changing the nick back to {forced_nick}.") await member.edit(nick=forced_nick) try: await member.send( "You have left and rejoined the **Python Discord** server, effectively resetting " f"your nickname from **{forced_nick}** to **{member.name}**, " "but as you are currently in superstar-prison, you do not have permission to do so. " "Therefore your nickname was automatically changed back. You will be allowed to " "change your nickname again at the following time:\n\n" f"**{end_timestamp}**.") except Forbidden: log.warning( "The user left and rejoined the server while in superstar-prison. " "This led to the bot trying to DM the user to let them know their name was restored, " "but the user had either blocked the bot or disabled DMs, so it was not possible " "to DM them, and a discord.errors.Forbidden error was incurred." ) # Log to the mod_log channel log.trace( "Logging to the #mod-log channel. This could fail because of channel permissions." ) mod_log_message = ( f"**{member.name}#{member.discriminator}** (`{member.id}`)\n\n" f"Superstarified member potentially tried to escape the prison.\n" f"Restored enforced nickname: `{forced_nick}`\n" f"Superstardom ends: **{end_timestamp}**") await self.modlog.send_log_message( icon_url=Icons.user_update, colour=Colour.gold(), title="Superstar member rejoined server", text=mod_log_message, thumbnail=member.avatar_url_as(static_format="png"))
async def on_member_join(self, member: Member): """ This event will trigger when someone (re)joins the server. At this point we will look up the user in our database and check whether they are in superstar-prison. If so, we will change their name back to the forced nickname. """ active_superstarifies = await self.bot.api_client.get( 'bot/infractions', params={ 'active': 'true', 'type': 'superstar', 'user__id': member.id }) if active_superstarifies: [infraction] = active_superstarifies forced_nick = get_nick(infraction['id'], member.id) await member.edit(nick=forced_nick) end_timestamp_human = (datetime.fromisoformat( infraction['expires_at'][:-1]).strftime('%c')) try: await member.send( "You have left and rejoined the **Python Discord** server, effectively resetting " f"your nickname from **{forced_nick}** to **{member.name}**, " "but as you are currently in superstar-prison, you do not have permission to do so. " "Therefore your nickname was automatically changed back. You will be allowed to " "change your nickname again at the following time:\n\n" f"**{end_timestamp_human}**.") except Forbidden: log.warning( "The user left and rejoined the server while in superstar-prison. " "This led to the bot trying to DM the user to let them know their name was restored, " "but the user had either blocked the bot or disabled DMs, so it was not possible " "to DM them, and a discord.errors.Forbidden error was incurred." ) # Log to the mod_log channel log.trace( "Logging to the #mod-log channel. This could fail because of channel permissions." ) mod_log_message = ( f"**{member.name}#{member.discriminator}** (`{member.id}`)\n\n" f"Superstarified member potentially tried to escape the prison.\n" f"Restored enforced nickname: `{forced_nick}`\n" f"Superstardom ends: **{end_timestamp_human}**") await self.modlog.send_log_message( icon_url=Icons.user_update, colour=Colour.gold(), title="Superstar member rejoined server", text=mod_log_message, thumbnail=member.avatar_url_as(static_format="png"))
def game_config_to_embed(config: GameConfig, context: 'Context') -> Embed: """Utility function to convert a GameConfig object into an Embed. :return: An Embed displaying a GameConfig.""" ret = Embed(title=str(config), type='rich', timestamp=datetime.now(), colour=Colour.gold()) role = get(context.guild.roles, id=int(config.completion_role_id)) ret.add_field(name='Role', value=f'{role.name} ({role.id})') return ret
async def update(self, ctx, type: CoinType, user: discord.Member, amount: Amount): embed = Embed(colour=Colour.gold()) embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar_url) embed.add_field( name="Update Request", value= f"Successfully updated {amountToString(amount)} {type.format_string()} to {user.mention} wallet", inline=False) await ctx.send(embed=embed) self.bot.update_amount(user.id, amount, type)
async def client_info(self, ctx): embed = Embed( title='Client Info', color=Colour.gold(), timestamp=datetime.utcnow() ) embed.add_field(name='Total Guilds', value=f'{str(len(self.client.guilds))}') embed.add_field( name='Ping', value=f'{round(self.client.latency*1000)} ms') await ctx.send(embed=embed)
def make_page(title, chunk, page): e = Embed(colour=Colour.gold(), title=title, description='```\n' + '\n'.join(chunk) + '```') e.set_footer(text=f'Current prefix: {local_prefix}') return { 'embed': e, 'content': f'Page **{page}/{total_pages}** ({len(module_list)}) commands' }
async def on_call(self, ctx, args, **flags): if args[1:].lower() == 'list': return '\n'.join(f'`{k}`: {v}' for k, v in self.langs.items()) out_lang = flags.get('out', 'en').lower() if out_lang not in self.langs: return '{warning} Invalid out language. Try using list subcommand' chain_len = flags.get('len', DEFAULT_CHAIN_LEN) if isinstance(chain_len, str) and not chain_len.isdigit(): return '{error} Wrong value given for chain len' chain_len = int(chain_len) if chain_len > MAX_CHAIN_LEN: return '{warning} Max chain len is %d, you asked for %d' % (MAX_CHAIN_LEN, chain_len) if chain_len < 2: return '{error} Chain len should not be shorter than 2. Use goodtranslator2 instead' async with ctx.channel.typing(): langs = random.sample(self.langs.keys(), chain_len + 1) if 'en' in langs: langs.remove('en') langs = langs[:chain_len] langs.append(out_lang) text = args[1:] try: for i, l in enumerate(langs): params = { 'key': self.api_key, 'text': text, 'lang': f'{langs[i - 1] + "-" if i else ""}{l}' } async with self.bot.sess.post(API_URL + 'translate', params=params) as r: if r.status != 200: return '{error} Failed to translate. Please, try again later' text = (await r.json())['text'][0] except Exception: return '{error} Failed to translate. Please, try again later' e = Embed(colour=Colour.gold(), title='BadTranslator 2') e.description = text[:2048] e.add_field( name='Chain', value=' -> '.join(self.langs.get(l, l) for l in langs[:-1]) ) e.set_footer(text=ctx.author, icon_url=ctx.author.avatar_url) await ctx.send(embed=e)
def get_guild_info(self, guild): e = Embed(colour=Colour.gold()) e.add_field(name='guild id', value=guild.id) bot_count = sum(1 for m in guild.members if m.bot) bot_ratio = round(bot_count / guild.member_count * 100) e.add_field(name='members', value=f'{guild.member_count - bot_count} + {bot_count} bots') e.add_field(name='owner id', value=guild.owner.id) e.add_field(name='bot ratio', value=f'{bot_ratio}%') e.add_field(name='total guilds', value=len(self.bot.guilds)) e.set_thumbnail(url=guild.icon_url or guild.owner.avatar_url) e.set_footer(text=f'owner: {guild.owner}', icon_url=guild.owner.avatar_url) return e
def meta_roles_to_embed(meta_roles: 'List[MetaRoleConfig]') -> Embed: """Utility function to convert a list of MetaRoleConfig into an Embed. :return: An Embed displaying a List of MetaRoleConfig.""" ret = Embed(title='Meta Roles', type='rich', timestamp=datetime.now(), colour=Colour.gold()) config_str = '' for i, meta_role in enumerate(meta_roles): config_str += f'{i + 1}) {meta_role}\n' ret.add_field(name='Meta Roles', value=config_str) return ret
def config_list_to_embed(config_list: 'List[GameConfig]') -> Embed: """Utility function to convert a list of GameConfig into an Embed. :return: An Embed displaying a List of Game Config.""" ret = Embed(title='Active Games', type='rich', timestamp=datetime.now(), colour=Colour.gold()) config_str = '' for i, config in enumerate(config_list): config_str += f'{i + 1}) {config.game.name}\n' ret.add_field(name='Games', value=config_str) return ret
async def create_class(ctx, name: str, r_class: int) -> None: name = self.list_names[-1] classes = [i for i in self.classes.keys()] class_choice = classes[r_class - 1] self.manager.set_class(name, class_choice) embed = discord.Embed(colour=Colour.gold()) embed.set_author(name=f"Characther {name} is ready") embed.add_field( name="Next: ", value= f"Now use the command 'createprint {name}' to see the characther", inline=True) await ctx.channel.send(embed=embed)