def get_song_now_embed(title: str = "", url: str = "", author: str = "", duration: str = "", thumnail: str = "", time_elapsed: Time = Time(), total_duration: float = 0) -> discord.embeds.Embed: embed = Embed(color=discord.Colour.from_rgb(*START), title=f"Now playing", description=f"{title}", url=url) trail = "" elapsed = time() - time_elapsed.start - \ time_elapsed.compensation + time_elapsed.initial_seek est_time = elapsed / total_duration est_time *= 10 for i in range(10): if floor(est_time) == i: trail += "►" else: trail += "—" embed.set_author(name=author, icon_url=thumnail) \ .set_thumbnail(url=thumnail) \ .add_field(name='Duration', value=f"`{duration}`", inline=True) \ .add_field(name=f"Time Elapsed", value=f"`{number_to_timeformat(ceil(elapsed))} / {duration}`", inline=False) \ .add_field(name='↪', value=f"{trail}", inline=False) return embed
async def log_edit(type_: str, name: str, author: str, url: str): embed = Embed(title=f"Edited {type_}: {name}", color=Colour.blue(), timestamp=datetime.utcnow(), url=url) embed.set_author(name=author) await log_to_webhook(embed=embed)
def em_base(self) -> Embed: """Prepare a basic embed that will be common to all outputs""" em = Embed(title=self.title, description="", color=self.color) em.set_author(**self.author) em.set_footer(text=self.footer) return em
async def _handle_watched_players(self, player_xids: list[int]): """Notify moderators about watched players.""" assert self.interaction.guild mod_role: Optional[discord.Role] = None for role in self.interaction.guild.roles: if role.name.startswith(self.settings.MOD_PREFIX): mod_role = role break if not mod_role: return watch_notes = await self.services.games.watch_notes(player_xids) if not watch_notes: return data = await self.services.games.to_dict() embed = Embed() embed.set_thumbnail(url=self.settings.ICO_URL) embed.set_author(name="Watched user(s) joined a game") embed.color = self.settings.EMBED_COLOR description = ( f"[⇤ Jump to the game post]({data['jump_link']})\n" f"[➤ Spectate the game on SpellTable]({data['spectate_link']})\n\n" f"**Users:**") for user_xid, note in watch_notes.items(): description += f"\n• <@{user_xid}>: {note}" embed.description = description for member in mod_role.members: await safe_send_user(member, embed=embed)
async def pokecenter(ctx, *args): """ Heals your whole party pokemon for ₱150 """ author = ctx.message.author database.add_pokedollars(author, -150) database.heal_party(author) embed = Embed( color=0xB80800, description="**{}** Welcome to the Pokemon Center!".format(author)) embed.set_author( name="Nurse Joy", icon_url= "https://i.pinimg.com/originals/ed/47/7c/ed477c99f4776886de48d5789f25776d.jpg" ) embed.add_field(name="Your Pokemon are healed!", value="Thanks for coming in. Please Come again ;)", inline=False) embed.set_footer( text= "Nurse Joy charged you ₱150 for her services. She ain't messin with no broke broke." ) embed.set_image( url= "https://cdn.bulbagarden.net/upload/thumb/9/9f/Nurse_Joy_anime_SM.png/250px-Nurse_Joy_anime_SM.png" ) return await pokemaster_bot.say(embed=embed)
async def get_user_choice(cls, ctx: Context, search_query: str, entries: List[Tuple[str]]) -> int: em = Embed(colour=cls._embed_colour,) em.set_author(name=f'{cls._track_type} search results - {search_query} - Requested by {ctx.author}') for index, entry in enumerate(entries, 1): em.add_field( name=f'{index} - {entry[0]}', value=entry[1], inline=False) search_message = await ctx.send(embed=em) ensure_future(add_numeric_reactions(search_message, len(entries))) def check(react: Reaction, user: User): return any(( react.message.id == search_message.id, user == ctx.author, react.emoji in (numeric_emoji(n) for n in range(1, 1+len(entries))) )) try: reaction, _ = await ctx.bot.wait_for('reaction_add', check=check, timeout=60) except TimeoutError: raise BadArgument("You did not choose a search result in time.") await search_message.delete() return int(reaction.emoji[0]) - 1
async def add_plopkoek( self, receiver: User, donator: User, message: Message, ): if not can_donate(donator.id, receiver.id): return insert_plopkoek(donator.id, receiver.id, message.channel.id, message.id) embed = Embed(description=message.content) embed.set_author(name=receiver.display_name, icon_url=receiver.avatar_url) try: content = f"Je hebt een plopkoek van {donator.display_name} gekregen! Je hebt er nu {get_income(receiver.id, '%Y-%m')} deze maand verzameld. Goe bezig!" await receiver.send(content, embed=embed) except AttributeError: pass donations_left = get_donations_left(donator.id) if donations_left == 0: content = f"Je hebt een plopkoek aan {receiver.display_name} gegeven. Da was uwe laatste plopkoek van vandaag, geefde gij ook zo gemakkelijk geld uit?" else: content = f"Je hebt een plopkoek aan {receiver.display_name} gegeven. Je kan er vandaag nog {donations_left} uitgeven. Spenden die handel!" await donator.send(content, embed=embed)
async def build_info_embed(ctx, bot): """ build the info embed :param ctx: the discord context object :param bot: the bot object :return: the info embed """ stats = generate_info(guilds=bot.servers, members=bot.get_all_members(), channels=bot.get_all_channels(), voice=bot.voice_clients, logged_in=bot.is_logged_in) user = bot.user lan = bot.localize(ctx) ram = stats['ram'] guild_count = comma(stats['guild_count']) user_count = comma(stats['user_count']) text_count = comma(stats['text_channel_count']) voice_count = comma(stats['voice_count']) if ram < 1024: ram_str = '{0:.2f}MB'.format(ram) else: ram_str = '{0:.2f}GB'.format(ram / 1024) total_ram = virtual_memory().total / 1024 / 1024 / 1024 total_ram_str = '{0:.2f}GB'.format(total_ram) embed = Embed(colour=bot.config['Bot']['colour']) embed.set_author(name=user.name, icon_url='{0.avatar_url}'.format(user)) embed.set_footer( text=lan['info_footer'].format(get_prefix(bot, ctx.message))) embed.add_field(name=lan['ram_used'] + '/' + lan['total_ram'], value=f'{ram_str}/{total_ram_str}') embed.add_field(name=lan['uptime'], value=get_uptime(bot.start_time, lan['days'])) embed.add_field(name=lan['python_ver'], value=platform.python_version()) embed.add_field(name=lan['lib'], value='Discord.py v{}.{}.{}'.format( version_info.major, version_info.minor, version_info.micro)) embed.add_field(name=lan['sys'], value=get_system_name()) devs = bot.config['Bot']['devs'] if devs: embed.add_field(name=lan['devs'], value='\n'.join(devs)) helpers = bot.config['Bot']['helpers'] if helpers: embed.add_field(name=lan['helper'], value='\n'.join(helpers)) embed.add_field(name=lan['guilds'], value=guild_count) embed.add_field(name=lan['users'], value=user_count) embed.add_field(name=lan['text_channels'], value=text_count) embed.add_field(name=lan['voice_channels'], value=voice_count) return embed
async def award_delete(self, guild_award_id: int) -> None: await self.services.guilds.award_delete(guild_award_id) embed = Embed() embed.set_thumbnail(url=self.settings.ICO_URL) embed.set_author(name="Award deleted!") description = "You can view all awards with the `/set awards` command." embed.description = description embed.color = self.settings.EMBED_COLOR await safe_send_channel(self.interaction, embed=embed, ephemeral=True)
async def log_create(type_: str, name: str, author: str, url: str): embed = Embed( title=f"Created {type_}: {name}", color=Colour.green(), timestamp=datetime.utcnow(), url=url, ) embed.set_author(name=author) await log_to_webhook(embed=embed)
def playing_message(self) -> Dict[str, Embed]: em = Embed( colour=self._embed_colour, description=f'[{self._title}]({self._url})' ) em.set_author(name=self._uploader, url=self._uploader_url) em.set_thumbnail(url=self._thumbnail) return {'embed': em}
async def _reply_found_embed(self): embed = Embed() embed.set_thumbnail(url=self.settings.ICO_URL) embed.set_author(name="I found a game for you!") game_data = await self.services.games.to_dict() link = game_data["jump_link"] embed.description = f"You can [jump to the game post]({link}) to see it!" embed.color = self.settings.EMBED_COLOR await safe_followup_channel(self.interaction, embed=embed)
def request_message(self) -> Dict[str, Embed]: """A discord Embed with basic information to be displayed when a track is requested.""" em = Embed( colour=self._embed_colour, description=f'Adding {self.information} to the queue...' ) em.set_author(name=f'{self._track_type} - Requested by {self.requester}') return {'embed': em}
async def get_trainer_info(ctx, author): total_caught = database.get_total_caught(author) total_caught = "{}/718".format(total_caught) pokedollars = "₱{}".format(database.get_pokedollars(author)) embed = Embed(color=0xB80800) embed.set_author(name="{}'s Trainer Profile".format(author), icon_url="https://vignette3.wikia.nocookie.net/pkmnshuffle/images/b/b1/Pikachu_%28Winking%29.png/revision/latest?cb=20170410234514") embed.add_field(name='Pokedex Entries', value=total_caught) embed.add_field(name='Money', value=pokedollars) embed.set_thumbnail(url="http://rs1240.pbsrc.com/albums/gg495/iKyle10/Pokemon%20Trainer/avatar514181_1_zpsfxp46su9.gif~c200") embed.set_image(url="https://archives.bulbagarden.net/media/upload/a/a0/Spr_B2W2_Hilbert.png") return await ctx.send(embed=embed)
def get_embed(self) -> Tuple[Embed, File]: embed = Embed(title=self.title if self.title else "", description=self.description if self.description else "", colour=self.color, timestamp=datetime.utcnow()) for field in self.fields: embed.add_field(name=field['name'], value=field['value']) if self.author: embed.set_author(name=self.author['name'], url=self.author.get('url', EmptyEmbed), icon_url=self.author.get('icon_url', EmptyEmbed)) if self.image_url: embed.set_image(url=self.image_url) return embed, self.file
async def award_add( self, count: int, role: str, message: str, **options: Optional[bool], ) -> None: repeating = bool(options.get("repeating", False)) remove = bool(options.get("remove", False)) max_message_len = GuildAward.message.property.columns[0].type.length # type: ignore if len(message) > max_message_len: await safe_send_channel( self.interaction, f"Your message can't be longer than {max_message_len} characters.", ephemeral=True, ) return if count < 1: await safe_send_channel( self.interaction, "You can't create an award for zero games played.", ephemeral=True, ) return if await self.services.guilds.has_award_with_count(count): await safe_send_channel( self.interaction, "There's already an award for players who reach that many games.", ephemeral=True, ) return await self.services.guilds.award_add( count, role, message, repeating=repeating, remove=remove, ) embed = Embed() embed.set_thumbnail(url=self.settings.ICO_URL) embed.set_author(name="Award added!") every_or_after = "every" if repeating else "after" give_or_take = "take" if remove else "give" description = ( f"• _{every_or_after} {count} games_ — {give_or_take} `@{role}`" f" — {message}\n\nYou can view all awards with the `/set awards` command." ) embed.description = description embed.color = self.settings.EMBED_COLOR await safe_send_channel(self.interaction, embed=embed, ephemeral=True)
def playing_message(self) -> Dict[str, Union[Embed, File]]: self._cover.seek(0) em = Embed( colour=Colour.dark_green(), title=self._title, description=f'{self._album} - ({self._date})' ) em.set_author(name=self._artist) em.set_thumbnail(url='attachment://cover.jpg') return { 'embed': em, 'file': File(self._cover, 'cover.jpg') }
async def _generate_embed(self, mail: MailMessage) -> Embed: embed = Embed( title=f'`Neue E-Mail: {mail.subject}`', type='rich', colour=Colour.dark_magenta(), ) text = self._cut_mail_text(mail.text) embed.set_author(name=mail.from_) embed.add_field(name='Nachricht', value=text) embed.add_field(name='Datum', value=mail.date.strftime('%c')) embed.set_footer(text=self.bot.signature) return embed
async def stats(self, ctx: Context, user: Member=None): """Check Stats for user, If no user mention it will default to command invoker""" if user is None: user = ctx.author userid = user.id guildid = ctx.guild.id response = await db.runCommand("getUserStats", userid, guildid) #page_1 page_1 = Embed(title="User Stats", color=0x00ff59) page_1.set_author(name=user.display_name + user.discriminator, icon_url=user.avatar_url) page_1.add_field(name="Messages Sent", value=response[0], inline=False) page_1.add_field(name="Songs Played", value=response[1], inline=False) page_1.add_field(name="Join Date", value=user.joined_at.strftime("%A, %d/%B/%Y at %H hours %M minutes %S seconds %Z"), inline=False) page_1.set_footer(text="Momento") await ctx.send(embed=page_1)
async def embed(self, ctx: Context, *, content: str): data = content.split('#') if len(data) != 4: await ctx.send(ctx.command.usage) return author, title, message, date = data await ctx.message.delete() embed = Embed( title=title, type='rich', colour=Color.dark_green(), ) embed.set_author(name=author) embed.add_field(name='Aufgabe/Nachricht', value=message) embed.add_field(name='Datum', value=date) embed.set_footer(text=self.bot.signature) await ctx.send(embed=embed)
def create_embed(self, player): embed = Embed(colour=0x4f1608) embed.add_field(name="Name", value=player.get("name")) embed.add_field(name="Rank", value=player.get("rank")) embed.add_field( name="\u200b", value="\u200b" ) # Empty field to make spacing of the object look much nicer embed.add_field(name="Level", value=player.get("level")) embed.add_field(name="Class", value=player.get("class")) embed.add_field(name="Alive", value=str(not player.get("dead"))) if player.get("twitch"): embed.set_author( name=player.get("twitch"), url="https://www.twitch.tv/" + player.get("twitch"), icon_url= "https://cdn1.iconfinder.com/data/icons/micon-social-pack/512/twitch-256.png" ) return embed
async def rule34(ctx, *, tags: str = '*'): url34 = environ.get('URL34') def get_random_posts(url): respond_for_img = requests.get(url=url, headers=HEADERS) bs = BeautifulSoup(respond_for_img.text, 'html.parser') return bs.posts def get_any_random_post_url(url): resp = requests.get(url=url, headers=HEADERS) bs = BeautifulSoup(resp.text, 'html.parser') post_id = bs.title.string.split()[-1] post_url = url34+'page=dapi&s=post&q=index&id='+post_id return post_url if tags == '*': post_url = get_any_random_post_url(url34+'page=post&s=random') post = get_random_posts(post_url).post image_url = post['file_url'] # Image URL post_id = post['id'] # Post ID else: posts_count = get_random_posts(url34+'page=dapi&s=post&q=index&limit=1&tags='+tags)['count'] # Posts count try: post_pid = random.randint(0, int(posts_count) - 1) # Post PID except: await ctx.send(':sob: Не могу найти такой пост...') return post = get_random_posts(url34+'page=dapi&s=post&q=index&limit=1&pid='+str(post_pid)+'&tags='+tags).post # Post object image_url = post['file_url'] # Image URL post_id = post['id'] # Post ID print(f'Sending post ID{post_id}') emb = Embed() if tags != '*': emb.title='Rule34: '+tags emb.description = f'Количество постов с этим тэгом: **{posts_count}**\n' else: emb.title='Rule34: случайный пост' emb.set_author(name=f'ID: {post_id}', url=f'{url34}page=post&s=view&id={post_id}') emb.set_image(url=image_url) emb.set_footer(text='Тэги: '+post['tags']) await ctx.message.delete() await ctx.send(embed=emb)
def ping_embed(package, message, paginate): 'Formats and generates the embed for the ping' embed = Embed() currentmsg = paginate.pages_yielded totalmsgs = currentmsg + paginate.pages_left if currentmsg == 1: embed.title = package['sender'] embed.set_author(name=package['description']) embed.description = message embed.set_thumbnail(url=package['logo_url']) if totalmsgs > 1: embed.set_footer( text='Message {}/{}'.format(currentmsg, totalmsgs)) embed.timestamp = datetime.utcnow() embed.colour = package['embed_colour'] return embed
async def on_feed_update(self, feed: Feed, update: FeedUpdate): channel = self._guild.get_channel(int(self.config.get_channel_id("feed"))) if channel is None: return embed = Embed(colour=config.EMBED_COLOUR, timestamp=datetime.now()) next_line = "\n" last_update = await self._bills_storage.get_last_update(update.get_bill_id()) embed.description = ( f"**Last Stage:**: {last_update['stage']}{next_line}" if last_update is not None else "" f"**Next Stage:** {update.get_stage()}{next_line} **Summary:** {update.get_description()}" f"{next_line}**Categories:**{', '.join(update.get_categories())}" ) embed.title = update.get_title() if self._guild is not None: embed.set_author(name="TLDRBot", icon_url=self._guild.icon_url) self.tracker_status["feed"]["confirmed"] = True await channel.send(embed=embed) # type: ignore
def get_song_start_embed(title: str = "", requestee: str = "", url: str = "", author: str = "", duration: str = "", pos_in_queue: int = 1, thumbnail: str = "") -> discord.embeds.Embed: embed = Embed(color=discord.Colour.from_rgb(*START), title=f"Added to queue", description=f"Playing {title}", url=url) embed.set_author(name=author, icon_url=thumbnail) \ .set_thumbnail(url=thumbnail) \ .set_footer( text=f"This song was requested by {requestee}" if requestee else "") \ .add_field(name='Duration', value=f"`{duration}`", inline=True) \ .add_field(name='Position in Queue', value=pos_in_queue, inline=True) return embed
def to_embed(self, flat: bool = False) -> Embed: embed = Embed(title=self.name or '', url=self.url or Embed.Empty) embed.set_author(name=self.author or '', url=self.author_url or Embed.Empty) embed.set_thumbnail(url=self.thumbnail or Embed.Empty) cards_by_type = self._get_cards_by_type() if logging.vlog_is_on(1): logging.vlog(1, 'Cards by type are: %s', pprint.pformat(cards_by_type)) for type_ in [ 'Land', 'Creature', 'Sorcery', 'Instant', 'Artifact', 'Enchantment', 'Plainswalker', 'Unknown' ]: cards_body = '\n'.join( f'{num} {card.name}' + (f' {card.cost}' if flat else '') for card, num in cards_by_type.get(type_, [])) if not cards_body: continue cards_body = manamojidb.substitute(cards_body) embed.add_field(name=type_, value=cards_body, inline=not flat) return embed
def _make_embed_skeleton(self, header: bool, desc: bool, footer: bool, image: bool): embed = self.template e_new = Embed(colour=embed.colour, type=embed.type) if header: e_new.title = embed.title e_new.url = embed.url author = embed.author if author.name is not EmptyEmbed: e_new.set_author(name=author.name, url=author.url, icon_url=author.icon_url) if desc: e_new.description = embed.description if image: if embed.image.url is not EmptyEmbed: e_new.set_image(url=embed.image.url) if embed.thumbnail.url is not EmptyEmbed: e_new.set_thumbnail(url=embed.thumbnail.url) if footer: e_new.timestamp = embed.timestamp footer = embed.footer e_new.set_footer(text=footer.text, icon_url=footer.icon_url) return e_new
def get_embed(self): embed = D_Embed(title=self.title, colour=self.colour, description=self.description) if self.author: embed.set_author(name=self.author.display_name, icon_url=self.author.avatar_url) if self.image: embed.set_image(url=self.image) for name, value in self.content: if value: embed.add_field(name=name, value=value, inline=False) else: embed.add_field(name=name, value=" - ", inline=False) if self.footer: embed.set_footer(text=self.footer) return embed
def generate_mod_log_entry(action: str, mod: Member, target: Member, reason: str, localize: dict, warn_count: int = None): """ Generate a mod log entry :param action: the action :param mod: the mod that performed the action :param target: the target :param reason: the reason :param localize: the localization strings :param warn_count: the total warning count on the user :return: A discord embed object for the mod log entry """ colour = { localize['mute']: 0x591f60, localize['unmute']: 0x4286f4, localize['ban']: 0xe52424, localize['kick']: 0xdd6f1a, localize['warn']: 0xddc61a, localize['pardon']: 0x4286f4 }[action] embed = Embed(colour=colour) embed.set_author( name=get_name_with_discriminator(target) + ' ({})'.format(target.id), icon_url=get_avatar_url(target) ) embed.set_footer( text=get_name_with_discriminator(mod) + ' | ' + get_date(), icon_url=get_avatar_url(mod) ) embed.add_field(name=localize['type'], value=action.title()) embed.add_field(name=localize['reason'], value=reason) if action == localize['warn'] or action == localize['pardon']: embed.add_field(name=localize['warnings'], value=str(warn_count)) return embed
async def about(self, ctx): embed = Embed( title='Pingu Bot', description='A simple Discord Bot that\'s somewhat useful?', colour=0x0099ff, url=self.client.config.get('bot website', EmptyEmbed), timestamp=datetime.now()) applicationInfo = await self.client.application_info() botOwner = applicationInfo.owner embed.set_author(name=f'{botOwner.name}#{botOwner.discriminator}', icon_url=botOwner.avatar_url_as(static_format='png', size=256), url=self.client.config.get('bot owner website', EmptyEmbed)) botImageUrl = self.client.user.avatar_url_as(static_format='png', size=256) embed.set_image(url=botImageUrl) embed.set_thumbnail(url=botImageUrl) embed.add_field(name='The Best Penguin Around', value='It\'s Pingu your friendly neighborhood Noot!') embed.add_field(name='How does it work?', value='Using discord.py', inline=False) embed.add_field(name='Who\'s it for?', value='People who like Pingu', inline=False) embed.add_field(name='What does it do?', value=f'Check {self.client.prefix}help for that pal.', inline=False) # TODO: Ask Ene7 about what should the footer be embed.set_footer(text=EmptyEmbed, icon_url=EmptyEmbed) await ctx.send(embed=embed)