def format_weather(self, res: WeatherResponse, /) -> BetterEmbed: """Returns a formatted embed from the data received by the api""" embed = BetterEmbed(title=f"Weather in {res.name} ({res.sys.country})", description=f"Overall description : {res.weather[0].description}") embed.set_thumbnail(url=f"http://openweathermap.org/img/wn/{res.weather[0].icon}@2x.png") main = res.main sys = res.sys wind = res.wind nf = lambda obj, attr: getattr(obj, attr, '[NF]') # -> Any from_timestamp = lambda ts: naturaltime(dt.now(tz.utc) - dt.fromtimestamp(ts, tz=tz.utc)) # -> str from_kelvin = lambda kt: f"{kt - 273.15:.1f}°C | {(kt * 9/5 - 459.67):.1f}°F" # -> str fields = ( ('Min temperature', from_kelvin(main.temp_min)), ('Max temperature', from_kelvin(main.temp_max)), ('Feels like', from_kelvin(main.feels_like)), ('Pressure', f"{main.pressure} hPA"), ('Humidity', f"{main.humidity}%"), ('Visibility', f"{((res.visibility or 0) / 1000):.1f} kilometers"), ('Wind speed', f"{wind.speed} km/h"), ('Wind direction', f"{wind.deg} degrees"), ('Cloudiness', f"{res.clouds.all}%"), ('Data refreshed', from_timestamp(res.dt)), ('Sunrise', from_timestamp(sys.sunrise)), ('Sunset', from_timestamp(sys.sunset)) ) return embed.add_fields(fields)
async def _dice(self, ctx: NewCtx, dice: str = '1d6'): """Generates dice with the supplied format `NdN`""" dice_list = dice.lower().split('d') try: d_count, d_value = int(dice_list[0]), int(dice_list[1]) except ValueError: raise commands.BadArgument( "The entered format was incorrect, `NdN` only currently") counter = [] crit_s, crit_f = 0, 0 if d_count < 0 or d_value < 0: raise commands.BadArgument("You cannot have negative values") for dice_num in range(d_count): randomnum = random.randint(1, d_value) if randomnum == d_value: crit_s += 1 if randomnum == 1: crit_f += 1 counter.append(randomnum) total = sum(counter) embed = BetterEmbed() embed.description = f"{dice} gave {', '.join([str(die) for die in counter])} = {total} with {crit_s} crit successes and {crit_f} fails" await ctx.send(embed=embed)
async def _blackjack(self, ctx: NewCtx, bet: int = 30): """Plays blackjack against the house, default bet is 30 <:peepee:712691831703601223>""" if not(1 <= bet <= 100): return await ctx.send("You must bet between 1 and 100 <:peepee:712691831703601223>.") else: result = await self.db_query(self.bot, 'get_user_data', ctx.author.id) if result: available_currency = result['amount'] if bet > available_currency: return await ctx.send("You don't have enough <:peepee:712691831703601223> for that bet.") else: await ctx.send(f"Very well, your {bet}<:peepee:712691831703601223> will be gladly accepted.") wins = result['wins'] losses = result['losses'] else: query = self.queries['new_user'] await self.bot.pool.execute(query, ctx.author.id, 0, 0, 150) wins = 0 losses = 0 available_currency = 150 await ctx.send("Yoink has not seen you before, have 150 <:peepee:712691831703601223> on the house.") house = await self.db_query(self.bot, 'get_user_data', self.bot.user.id) embed = BetterEmbed() embed.add_field( name=f"{ctx.author.display_name} vs the house", value="[h | hit] [s | stay] [q | quit (only on the first turn)] ", inline=False ) original = await ctx.send(embed=embed) game = blackjack.Blackjack(ctx, original, embed, self.timeout) await original.edit(embed=game.embed) await game.player_turn() await game.dealer_turn() winner = await game.game_end() if winner == 'Draw' and not isinstance(winner, blackjack.Player): await ctx.send("The game was drawn, your <:peepee:712691831703601223> have been returned.") elif winner.id == ctx.author.id: await ctx.send(f"Congratulations, you beat the house, take your {bet}<:peepee:712691831703601223> ") end_amount = available_currency + bet query = self.queries['win'] await self.bot.pool.execute(query, wins + 1, end_amount, ctx.author.id) other_query = self.queries['loss'] await self.bot.pool.execute(other_query, house['losses'] + 1, house['amount'] - bet, self.bot.user.id) else: await ctx.send(f"The house always wins, your {bet}<:peepee:712691831703601223> have been yoinked.") end_amount = available_currency - bet query = self.queries['loss'] await self.bot.pool.execute(query, losses + 1, end_amount, ctx.author.id) other_query = self.queries['win'] await self.bot.pool.execute(other_query, house['wins'] + 1, house['amount'] + bet, self.bot.user.id)
def format_page(self, menu, response: GoogleResponse): safesearch_state = 'OFF' if self.search_is_nsfw else 'ON' embed = BetterEmbed(title=f'{response.title} | Safesearch : {safesearch_state}', description=response.description, url=response.url) return embed.set_image(url=response.image_url)
async def send_cog_help(self, cog): embed = BetterEmbed(title=f'{cog.qualified_name} Category')\ .set_footer(text='⇶ indicates subcommands') description = f'{cog.description or ""}\n\n' entries = await self.filter_commands(cog.get_commands(), sort=True) description += "\n".join([f'{"⇶" if isinstance(c, commands.Group) else "⇾"} **{c.name}** -' f' {c.short_doc or "No description"}' for c in entries]) embed.description = description await self.context.send(embed=embed)
def format_page(self, menu, response: GoogleResponse): safesearch_state = "OFF" if self.search_is_nsfw else "ON" embed = BetterEmbed( title=f"{response.title} | Safesearch : {safesearch_state}", description=response.description, url=response.url, ) return embed.set_image(url=response.image_url)
async def send_group_help(self, group): embed = BetterEmbed(title=self.get_command_signature(group)) description = f'{group.help or "No description provided"}\n\n' entries = await self.filter_commands(group.commands, sort=True) description += "\n".join([f'{"⇶" if isinstance(command, commands.Group) else "⇾"} **{command.name}** -' f' {command.short_doc or "No description"}' for command in entries]) embed.description = description footer_text = '⇶ indicates subcommands' if checks := retrieve_checks(group): footer_text += f' | Checks: {checks}'
def format_snapshot(self, *, response: MagmaChainResponse, is_nsfw: bool) -> BetterEmbed: """Formats the snaphot into an embed""" embed = BetterEmbed( title=f"Screenshot | Safe : {'OFF' if is_nsfw else 'ON'}", url=response.website) embed.add_field(name='Link', value=maybe_url(response.website)) return embed.set_image(url=response.snapshot)
async def about(self, ctx): """ This is the 'about the bot' command. """ description = dedent("""\ A ~~shit~~ fun bot that was thrown together by a team of complete nincompoops. In definitely no particular order:\n 『 Moogs 』#2009, MrSnek#3442, nickofolas#0066 and Umbra#0009 """) # uniq_mem_count = set( # member for member in guild.members if not member.bot for guild in self.bot.guilds) #! TODO fix set comp uniq_mem_count = set() for guild in self.bot.guilds: for member in guild.members: if not member.bot: uniq_mem_count.add(member) # {member for member in ctx.bot.get_all_members() if not member.bot} embed = BetterEmbed(title=f"About {ctx.guild.me.display_name}") embed.description = description embed.set_author(name=ctx.me.display_name, icon_url=ctx.me.avatar_url) embed.add_field(name="Current guilds", value=len(self.bot.guilds), inline=True) embed.add_field(name="Total fleshy people being memed", value=len(uniq_mem_count)) await ctx.send(embed=embed)
async def about(self, ctx): """ This is the 'about the bot' command. """ description = dedent(f"""\ A ~~shit~~ fun bot that was thrown together by a team of complete nincompoops. In definitely no particular order:\n {', '.join([self.bot.get_user(i).__str__() for i in self.bot.owner_ids])} """) # uniq_mem_count = set( # member for member in guild.members if not member.bot for guild in self.bot.guilds) #! TODO fix set comp uniq_mem_count = set() for guild in self.bot.guilds: for member in guild.members: if not member.bot: uniq_mem_count.add(member) # {member for member in ctx.bot.get_all_members() if not member.bot} embed = BetterEmbed(title=f"About {ctx.guild.me.display_name}") embed.description = description embed.set_author(name=ctx.me.display_name, icon_url=ctx.me.avatar_url) embed.add_field(name="Current guilds", value=f'{len(self.bot.guilds):,}') embed.add_field(name="Total fleshy people being memed", value=f'{len(uniq_mem_count):,}') await ctx.send(embed=embed)
async def userinfo(self, ctx, *, user: BetterUserConverter = None): flags = Flags(user.http_dict['public_flags']).flags user = user.obj user_info = UserInfo(user) badges = [badge_mapping.get(f) for f in flags] if user_info.is_nitro: badges.append('<:nitro:711628687455420497>') embed = BetterEmbed( title=user.__str__(), description=' '.join(badges))\ .set_thumbnail(url=user.avatar_url_as(static_format='png')) embed.add_field(name='Info', value=f'Account Created: {humanize.naturaltime(user.created_at)}') await ctx.send(embed=embed)
async def send_bot_help(self, mapping): def key(c): return c.cog_name or '\u200bUncategorized' bot = self.context.bot embed = BetterEmbed(title=f'{bot.user.name} Help') description = f'Use `{self.clean_prefix}help <command/category>` for more help\n\n' entries = await self.filter_commands(bot.commands, sort=True, key=key) for cog, cmds in itertools.groupby(entries, key=key): cmds = sorted(cmds, key=lambda c: c.name) description += f'**➣ {cog}**\n{" • ".join([c.name for c in cmds])}\n' embed.description = description await self.context.send(embed=embed)
def format_page(self, menu, page: Union[_nhentai.Doujinshi, str]): if isinstance(page, str): return page embed = BetterEmbed(title=f"{page.name} | {page.magic}") fields = ( ('Tags', ', '.join(page.tags), False), ('Japanese name', page.jname), ('Page amount', page.pages), ('Galeries id', page.gid) ) return embed.set_image(url=page.cover).add_fields(fields)
def format_page(self, menu, page: Rule34Post): embed = BetterEmbed(title=f'Results for : {self.query}', url=page.file_url) fields = ( ('Size', f'{page.width}x{page.height}'), ('Creator id', page.creator_ID), ('Created at', to_human_datetime(page.created_at, "%a %b %d %H:%M:%S %z %Y")), ) embed.set_image(url=page.file_url) return embed.add_fields(fields)
async def _rand_num(self, ctx: NewCtx, start: Union[int, float], stop: Union[int, float]): """Generates a random number from start to stop inclusive, if either is a float, number will be float""" if isinstance(start, float) or isinstance(stop, float): number = random.uniform(start, stop) else: number = random.randint(start, stop) embed = BetterEmbed() embed.description = f"Number between {start} and {stop}, {number=}" await ctx.send(embed=embed)
def format_page(self, menu, page: Rule34Post): embed = BetterEmbed(title=f"Results for : {self.query}", url=page.file_url) fields = ( ("Size", f"{page.width}x{page.height}"), ("Creator id", page.creator_ID), ( "Created at", to_human_datetime(page.created_at, "%a %b %d %H:%M:%S %z %Y"), ), ) embed.set_image(url=page.file_url) return embed.add_fields(fields)
def format_page(self, menu, page: Rule34Post): embed = BetterEmbed(title=f'Results for : {self.query}', url=page.file_url) created_at = datetime.strptime( page.created_at, "%a %b %d %H:%M:%S %z %Y") # there must be a format for that fields = ( ('Size', f'{page.width}x{page.height}'), ('Creator id', page.creator_ID), ('Created at', naturaldate(created_at)), ) embed.set_image(url=page.file_url) return embed.add_fields(fields)
async def suggest(self, ctx: NewCtx, *, suggestion: str): if len(suggestion) >= 1000: raise commands.BadArgument( message="Cannot forward suggestions longer than 1000 characters" ) embed = BetterEmbed(title='Suggestion', description=suggestion) fields = (('Guild', f"{ctx.guild.name} ({ctx.guild.id})"), ('Channel', f"{ctx.channel.name} ({ctx.channel.id})"), ('User', f"{ctx.author} ({ctx.author.id})")) channel = self.bot.get_channel(config.SUGGESTION) await channel.send(embed=embed.add_fields(fields)) await ctx.send('Thank you for your suggestion')
async def diff(self, ctx: NewCtx): """Returns the difference between two images""" if len(ctx.message.attachments) < 2: raise commands.BadArgument("Expected two attachments") attachment_file_a, _, file_a_size = await self._get_image(ctx, 0) attachment_file_b, _, file_b_size = await self._get_image(ctx, 1) if file_a_size != file_b_size: raise commands.BadArgument( "Attachment images must be the same size") start_time = time.time() new_file = await self.bot.loop.run_in_executor(None, self._diff, attachment_file_a, attachment_file_b) end_time = time.time() fileout = File(new_file, 'diff.png') embed = BetterEmbed(title='diffing done.').set_footer( text=f"That took {end_time-start_time:.2f}s").set_image( url="attachment://diff.png") await ctx.send(embed=embed, file=fileout)
async def morejpeg(self, ctx: NewCtx, severity: int = 15, loopyloops: int = 1): """Adds jpeg compression proportional to severity to an uploaded image or the author's profile picture""" if not (0 <= severity <= 100): raise commands.BadArgument( "severity parameter must be between 0 and 100 inclusive") severity = 101 - severity if not (1 <= loopyloops <= 200): raise commands.BadArgument( "loopyloop parameter must be between 1 and 200 inclusive") attachment_file, _, _ = await self._get_image(ctx) start_time = time.time() new_file = await self.bot.loop.run_in_executor(None, self._loop_jpeg, attachment_file, severity, loopyloops) end_time = time.time() fileout = File(new_file, 'file.jpg') embed = BetterEmbed(title='jpegifying done.').set_footer( text=f"That took {end_time-start_time:.2f}s").set_image( url="attachment://file.jpg") await ctx.send(embed=embed, file=fileout)
async def ping(self, ctx): sabertooth_tiger = perf_counter() m = await ctx.send('_ _') endocrine_title = perf_counter() await m.edit(embed=BetterEmbed( description=f'**API** {endocrine_title-sabertooth_tiger:.2f}s\n**WS** {self.bot.latency:.2f}s' ))
def format_resp(self, *, resp: Translated, text: str) -> BetterEmbed: """Formats the response into an embed""" src = LANGUAGES.get(resp.src) or resp.src dest = LANGUAGES.get(resp.dest) or resp.dest conf = round(resp.confidence * 100, 1) f_confidence = str(conf) + '%' if conf < 50.0: f_confidence += ' (might be innacurate)' embed = BetterEmbed(title="Translated something !") fields = (('original', text, False), ('Translation', resp.text, False), ('Confidence', f_confidence, True), ('Languages', f'{src} -> {dest}', True)) return embed.add_fields(fields)
async def ping(self, ctx: NewCtx): sabertooth_tiger = perf_counter() m = await ctx.send("_ _") endocrine_title = perf_counter() await m.edit( content="", embed=BetterEmbed( description= f"**API** {endocrine_title-sabertooth_tiger:.2f}s\n**WS** {(self.bot.latency*2):.2f}s" ), )
def format_resp(self, *, resp: Translated, text: str) -> BetterEmbed: """Formats the response into an embed""" src = LANGUAGES.get(resp.src) or resp.src dest = LANGUAGES.get(resp.dest) or resp.dest conf = round(resp.confidence * 100, 1) f_confidence = str(conf) + "%" if conf < 50.0: f_confidence += " (might be innacurate)" embed = BetterEmbed(title="Translated something !") fields = ( ("original", text, False), ("Translation", resp.text, False), ("Confidence", f_confidence, True), ("Languages", f"{src} -> {dest}", True), ) return embed.add_fields(fields)
async def on_spinning(self, channel_id): channel = self.bot.get_channel(channel_id) game_state: roulette.Game = self.roulette_games[channel_id] del self.roulette_games[channel_id] text = "The wheel is spinning, all new bets are ignored" await asyncio.sleep(2) original = await channel.send(text) results = game_state.handle_bets() embed = BetterEmbed(title=f"Roulette : {channel.name}") for player_id, bet_info in results.items(): player = self.bot.get_user(player_id) embed.add_field( name=f"{player.display_name} \nBet | Amount", value='`\n`'.join([f"{bet} : {amount}" for bet, amount in bet_info]), inline=True ) text += f"\nThe ball rolls, landing on {game_state.landed}" await original.edit(content=text) await asyncio.sleep(2) await original.edit(content=text, embed=embed)
def format_page(self, menu, response: Result) -> BetterEmbed: """Formats the repsponse into an embed""" header = response.header data = response.data embed = BetterEmbed(title=f"{header.index_name} | {header.similarity}%") embed.set_thumbnail(url=header.thumbnail) embed.add_field(name='External urls', value='\n'.join([maybe_url(url) for url in data.get('ext_urls', [])])) for key, value in data.items(): if not isinstance(value, list): if url := maybe_url(value): embed.add_field(name=key, value=url) # no idea about what it will return
async def embed_file(self, ctx: NewCtx, message: str, fileout: BytesIO, timediff: float, filename: str): fileout = File(fileout, filename) embed = BetterEmbed(title=message) embed.set_footer(text=f"That took {timediff:.2f}s") embed.set_image(url="attachment://" + filename) await ctx.send(embed=embed, file=fileout)
class _ReadingSource(ListPageSource): def __init__(self, data: _nhentai.Doujinshi): super().__init__(data._images, per_page=1) self.data = data self.template = BetterEmbed(title=f"{data.name} | {data.magic}") def format_page(self, menu: MenuPages, page: str): embed = self.template.copy() embed.url = page embed.set_image(url=page) return embed.set_footer(text=f'Page {menu.current_page} out of {self.get_max_pages()}') def get_page(self, page_number: int): self.current_page = page_number return super().get_page(page_number)
async def shift(self, ctx: NewCtx): """Shifts the RGB bands in an attached image or the author's profile picture""" attachment_file, _, file_size = await self._get_image(ctx) start_time = time.time() new_file = await self.bot.loop.run_in_executor(None, self._shifter, attachment_file, file_size) end_time = time.time() fileout = File(new_file, "file.png") embed = BetterEmbed(title='shifting done.').set_footer( text=f"That took {end_time-start_time:.2f}s").set_image( url="attachment://file.png") await ctx.send(embed=embed, file=fileout)
async def webhook_send(self, content: str, *, webhook: discord.Webhook, skip_wh: bool = False, skip_ctx: bool = False) -> None: """ This is a custom ctx addon for sending to the webhook and/or the ctx.channel. """ content = content.strip("```") embed = BetterEmbed(title="Error") embed.description = f"```py\n{content}```" embed.add_field(name="Invoking command", value=f"{self.invoked_with}", inline=True) embed.add_field(name="Author", value=f"{self.author.display_name}") embed.timestamp = datetime.utcnow() if not skip_ctx: await super().send(embed=embed) if not skip_wh: await webhook.send(embed=embed)