async def latest(self, ctx: commands.Context, version=None): if version is None: version = VersionInfo.getLatest(self.BC_VERSION_LIST.keys()) if version not in self.BC_VERSION_LIST.keys(): await ctx.send( f"Sorry but `{version}` does not seem to be a valid MC version that has BuildCraft releases." ) else: async with ctx.typing(): latestBC = VersionInfo.getLatest(self.BC_VERSION_LIST[version]) latestBCinfo = await self.getVersionDetails( "BuildCraft", latestBC) info = f"Buildcraft {latestBC}:\n[Changelog](https://www.mod-buildcraft.com/pages/buildinfo/BuildCraft/changelog/{latestBC}.html) | [Blog]({latestBCinfo['blog_entry'] if 'blog_entry' in latestBCinfo else 'https://www.mod-buildcraft.com'}) | [Direct download]({latestBCinfo['downloads']['main']})" if version in self.BCC_VERSION_LIST.keys(): latestBCC = VersionInfo.getLatest( self.BCC_VERSION_LIST[version]) latestBCCinfo = await self.getVersionDetails( "BuildCraftCompat", latestBCC) info = f"{info}\n\nBuildcraft Compat {latestBCC}:\n[Changelog](https://www.mod-buildcraft.com/pages/buildinfo/BuildCraftCompat/changelog/{latestBCC}.html) | [Blog]({latestBCCinfo['blog_entry'] if 'blog_entry' in latestBCCinfo else 'https://www.mod-buildcraft.com'}) | [Direct download]({latestBCCinfo['downloads']['main']})" embed = disnake.Embed( colour=disnake.Colour(0x54d5ff), timestamp=datetime.datetime.utcfromtimestamp(time.time()), description=info) embed.set_author( name=f"BuildCraft releases for {version}", url="https://www.mod-buildcraft.com/pages/download.html", icon_url="https://i.imgur.com/YKGkDDZ.png") await ctx.send(embed=embed)
async def get(self, ctx: Context, cog_only=False) -> Config: await self._bot.wait_until_ready() if not isinstance(ctx, Context): message = disnake.Object(id=0) message.guild = self._bot.get_guild(ctx) message._state = message.guild._state ctx = Context(bot=self._bot, message=message, prefix=None, view=None) document = await self._bot.config.guild(ctx.guild.id) cog_doc = document.get(self._template.__key__, {}) if not cog_only: items = self._bot.config.general_context._template.items + self._template.items doc = { **cog_doc, **document.get( self._bot.config.general_context._template.__key__, {}) } else: items = self._template.items doc = cog_doc log.debug( f'Creating config {self._template} for guild {ctx.guild.name} ({ctx.guild.id})' ) return await Config.from_doc(self._template, ctx, doc, items)
async def get_player(self, ctx: commands.Context, *, player: Optional[Union[discord.Member, discord.User, int]] = None): await general_util.delete_message(self.bot, ctx) if player is None: player = ctx.author elif isinstance(player, int): player = await general_util.get_user(self.bot, player) if player is None: return ctx.send(embed=general_util.generate_error_message( Strings.rpg_player_get_player_doesnt_exist), delete_after=Config.base_error_duration) db_player = self.player_repo.get_player(player) embed = discord.Embed(title=f"{player.display_name} profile", color=discord.Color.blue()) embed.set_thumbnail( url=player.display_avatar.url if player. display_avatar is not None else player.default_avatar.url) embed.add_field(name="Level", value=str(db_player.level)) embed.add_field(name="XP", value=str(db_player.xp)) embed.add_field( name="XP to level", value=str( rpg_util.get_next_level_xp_requirement(db_player.level) - db_player.xp)) embed.add_field(name="Coins", value=str(db_player.money)) embed.add_field(name="Energy", value=str(db_player.energy)) embed.add_field( name="Inventory", value= f"{self.player_repo.get_current_size_of_inventory(player.id)}/{rpg_util.get_inventory_size(db_player.level)}" ) embed.add_field(name="Action", value=ActionsEnum.get_name(db_player.action.action_id) if db_player.action is not None else "None") if db_player.action is not None: embed.add_field( name="Remaining time", value=humanize.naturaldelta( db_player.action.end_date.replace(tzinfo=timezone.utc) - datetime.now(tz=timezone.utc))) embed.add_field( name="Return time (UTC)", value=db_player.action.end_date.strftime("%d.%b.%Y %H:%M")) if db_player.action.rewards: rewards_str = rpg_util.get_expected_rewards_string( db_player.action.rewards, length_limit=1000, header=False) if rewards_str != "": embed.add_field(name="Action reward", value=rewards_str) general_util.add_author_footer(embed, ctx.author) await ctx.send(embed=embed, delete_after=Config.base_long_success_duration)
async def huggers(self, ctx: commands.Context): """ Get the biggest huggers. """ async with ctx.typing(): menu = get_top_huggers_menu(base_embed=disnake.Embed( title="{0} TOP HUGGERS {0} ".format( self.get_default_emoji("peepoHugger") or ""))) await self.check.botroom_check(ctx.message) await menu.start(ctx)
async def hugboard(self, ctx: commands.Context): """ Overall hugging stats. """ async with ctx.typing(): menu = get_hugboard_menu(base_embed=disnake.Embed( title="{0} HUGBOARD {0}".format( self.get_default_emoji("peepoHugger") or ""))) await self.check.botroom_check(ctx.message) await menu.start(ctx)
async def bonk(self, ctx: commands.Context, member: disnake.User) -> None: """Sends gif of mentioned member being "bonked" by Yoda.""" pfp = await member.display_avatar.read() created_at = ctx.message.created_at.strftime("%Y-%m-%d_%H-%M") out_filename = f"bonk_{member.id}_{created_at}.gif" func = functools.partial(self._generate_gif, pfp) async with ctx.typing(): with futures.ThreadPoolExecutor() as pool: out_gif = await asyncio.get_running_loop().run_in_executor( pool, func) out_gif.seek(0) await ctx.send(file=disnake.File(out_gif, out_filename))
async def huggers(self, ctx: commands.Context): """ Get the biggest huggers. """ async with ctx.typing(): page_source = LeaderboardPageSource( bot=self.bot, author=ctx.author, query=self.hugs_repo.get_top_givers_query(), row_formatter=self._tophuggers_formatter, title='TOP HUGGERS', emote_name='peepoHugger') page = page_source.get_page(0) embed = page_source.format_page(page) await self.check.botroom_check(ctx.message) view = EmbedView(embeds=[embed], page_source=page_source) view.message = await ctx.send(embed=embed, view=view)
async def hugboard(self, ctx: commands.Context): """ Overall hugging stats. """ async with ctx.typing(): page_source = LeaderboardPageSource( bot=self.bot, author=ctx.author, query=self.hugs_repo.get_top_all_query(), row_formatter=_tophugs_formatter, title='HUGBOARD', emote_name='peepoHugger', ) page = page_source.get_page(0) embed = page_source.format_page(page) await self.check.botroom_check(ctx.message) view = EmbedView(embeds=[embed], page_source=page_source) view.message = await ctx.send(embed=embed, view=view)
async def room(self, ctx: commands.Context, *, room: str): url = f"https://www.fit.vut.cz/fit/map/.cs?show={room.upper()}&big=1" r = requests.get(url) if r.status_code != 200: return await ctx.send(Messages.fit_room_unreach) async with ctx.typing(): try: soup = BeautifulSoup(r.content, 'html.parser') main_body = soup.find("main", {"id": "main"}) floor_list = main_body.find("ul", {"class": "pagination__list"}) active_floor = floor_list.find("a", {"aria-current": "page"}) image = main_body.find("svg") cursor = image.find("polygon", {"class": "arrow"}) except: return await ctx.send(Messages.fit_room_parsing_failed) if image is None or cursor is None: return await ctx.send( utils.fill_message("fit_room_room_not_on_plan", room=room)) image_bytes = BytesIO() image_bytestring = str(image).replace( kachnicka_path, kachnicka_url).encode("utf-8") svg2png(bytestring=image_bytestring, write_to=image_bytes, parent_width=720, parent_height=1000, background_color="white", dpi=300) image_bytes.seek(0) embed = disnake.Embed(title=f"Místnost: {room}", color=disnake.Color.dark_blue()) embed.set_image(url="attachment://plan.png") embed.description = f"[Odkaz na plánek]({url})" utils.add_author_footer(embed, ctx.author, additional_text=[str(active_floor.text)]) file = disnake.File(fp=image_bytes, filename="plan.png") await ctx.send(embed=embed, file=file)
async def hugs(self, ctx: commands.Context, user: disnake.Member = None): """ Get your lovely hug stats. """ if user is None or user == ctx.author: user = ctx.author user_str = utils.get_username(user) title = "{0} Your Lovely Hug Stats {0}" else: user_str = utils.get_username(user) title = f"{{0}} {user_str}'s Lovely Hug Stats {{0}}" async with ctx.typing(): stats = self.hugs_repo.get_members_stats(user.id) positions = self.hugs_repo.get_member_position(stats) avg_position = int((positions[0] + positions[1]) // 2) embed = disnake.Embed( title=title.format( self.get_default_emoji("peepoHugger") or ""), description=" | ".join(( "**Ranks**", f"Given: **{positions[0]}.**", f"Received: **{positions[1]}.**", f"Avg: **{avg_position}.**", )), ) embed.set_author(name=user_str, icon_url=user.avatar.url) utils.add_author_footer(embed, ctx.author) given_emoji = self.get_default_emoji("peepohugs") or "" recv_emoji = self.get_default_emoji("huggers") or "" embed.add_field(name=f"{given_emoji} Given", value=str(stats.given)) embed.add_field(name=f"{recv_emoji} Received", value=str(stats.received)) await ctx.send(embed=embed) await self.check.botroom_check(ctx.message)
async def hug(self, ctx: commands.Context, user: disnake.Member = None, intensity: int = 0): """Because everyone likes hugs""" if user is None: user = ctx.author elif user.bot: await ctx.send( self.get_default_emoji("huggers") or ":people_hugging:") return async with ctx.typing(): emojis = config.hug_emojis if user != ctx.author: self.hugs_repo.do_hug(giver_id=ctx.author.id, receiver_id=user.id) user_str = utils.get_username(user) if 0 <= intensity < len(emojis): await ctx.send(f"{emojis[intensity]} **{user_str}**") else: await ctx.send(f"{choice(emojis)} **{user_str}**")
async def reloadconfigs(self, ctx:commands.Context): """Reloads all server configs from disk""" async with ctx.typing(): Configuration.load_master() await Configuration.initialize(self.bot) await ctx.send("Configs reloaded")
async def eval_command(self, ctx: Context, language: str, *, code: str = "") -> Optional[Message]: """ Evaluate code, format it, and send the output to the corresponding channel. Return the bot response. """ async with ctx.typing(): eval_helper = EvalHelper(language) parsed_data = await eval_helper.parse(code) ( inputs, code, lang, options, compiler_flags, command_line_options, args, ) = parsed_data text = None if ctx.message.attachments: text = await eval_helper.code_from_attachments(ctx) if not text: return elif code.split(" ")[-1].startswith("link="): # Code in a paste service (gist or a hastebin link) text = await eval_helper.code_from_url(ctx, code) if not text: return elif code.strip("`"): # Code in message text = code.strip("`") first_line = text.splitlines()[0] if not language.startswith("```"): text = text[len(first_line) + 1:] if text is None: # Ensures code isn't empty after removing options raise commands.MissingRequiredArgument( ctx.command.clean_params["code"]) if lang in self.quick_map: lang = self.quick_map[lang] if lang in self.default_languages: lang = self.default_languages[lang] if lang not in self.languages: if not escape_mentions(lang): embed = Embed( title="MissingRequiredArgument", description=f"Missing Argument Language.\n\nUsage:\n" f"```{ctx.prefix}{ctx.command} {ctx.command.signature}```", color=SOFT_RED, ) else: embed = Embed( title="Language Not Supported", description=f"Your language was invalid: {lang}\n" f"All Supported languages: [here](https://tio.run)\n\nUsage:\n" f"```{ctx.prefix}{ctx.command} {ctx.command.signature}```", color=SOFT_RED, ) await ctx.send(embed=embed) logger.info("Exiting | Language not found.") return if options["--wrapped"]: if not (any( map(lambda x: lang.split("-")[0] == x, self.wrapping))) or lang in ("cs-mono-shell", "cs-csi"): await ctx.send(f"`{lang}` cannot be wrapped") return for beginning in self.wrapping: if lang.split("-")[0] == beginning: text = self.wrapping[beginning].replace("code", text) break tio = Tio(lang, text, inputs, compiler_flags, command_line_options, args) result = await tio.get_result() result = result.rstrip("\n") if not options["--stats"]: try: start, end = result.rindex("Real time: "), result.rindex( "%\nExit code: ") result = result[:start] + result[end + 2:] except ValueError: pass format_output = FormatOutput(language=lang) if (len(result) > format_output.max_output_length or result.count("\n") > format_output.max_lines): output = await eval_helper.paste(result) embed = format_output.format_hastebin_output(output, result) await ctx.send(content=f"{ctx.author.mention}", embed=embed) logger.info("Result Sent.") return embed = format_output.format_code_output(result) await ctx.send(content=f"{ctx.author.mention}", embed=embed) logger.info("Result Sent.")