Esempio n. 1
0
    def make_embed(self, data):
        avatar = rnd(
            "https://picarto.tv/user_data/usrimg/{}/dsdefault.jpg".format(
                data["name"].lower()))
        url = "https://picarto.tv/" + data["name"]
        thumbnail = data["thumbnails"]["web"]
        embed = discord.Embed(title=data["title"], url=url, color=0x4C90F3)
        embed.set_author(name=data["name"])
        embed.set_image(url=rnd(thumbnail))
        embed.add_field(name=_("Followers"),
                        value=humanize_number(data["followers"]))
        embed.add_field(name=_("Total views"),
                        value=humanize_number(data["viewers_total"]))
        embed.set_thumbnail(url=avatar)
        data["tags"] = ", ".join(data["tags"])

        if not data["tags"]:
            data["tags"] = _("None")

        if data["adult"]:
            data["adult"] = _("NSFW | ")
        else:
            data["adult"] = ""

        embed.set_footer(
            text=_("{adult}Category: {category} | Tags: {tags}").format(
                **data))
        return embed
Esempio n. 2
0
 def make_embed(self, data):
     is_rerun = data["type"] == "rerun"
     url = f"https://www.twitch.tv/{data['login']}" if data[
         "login"] is not None else None
     logo = data["profile_image_url"]
     if logo is None:
         logo = "https://static-cdn.jtvnw.net/jtv_user_pictures/xarth/404_user_70x70.png"
     status = data["title"]
     if not status:
         status = _("Untitled broadcast")
     if is_rerun:
         status += _(" - Rerun")
     embed = discord.Embed(title=status, url=url, color=0x6441A4)
     embed.set_author(name=data["user_name"])
     embed.add_field(name=_("Followers"),
                     value=humanize_number(data["followers"]))
     embed.add_field(name=_("Total views"),
                     value=humanize_number(data["view_count"]))
     embed.set_thumbnail(url=logo)
     if data["thumbnail_url"]:
         embed.set_image(
             url=rnd(data["thumbnail_url"].format(width=320, height=180)))
     if data["game_name"]:
         embed.set_footer(text=_("Playing: ") + data["game_name"])
     return embed
Esempio n. 3
0
    async def format_page(self, menu: GenericMenu, entries):
        bot = menu.ctx.bot
        position = (menu.current_page * self.per_page) + 1
        bal_len = len(humanize_number(entries[0][1]))
        pound_len = len(str(position + 9))
        header = "{pound:{pound_len}}{score:{bal_len}}{name:2}\n".format(
            pound="#",
            name=("Name"),
            score=("Score"),
            bal_len=bal_len + 6,
            pound_len=pound_len + 3,
        )
        msg = ""
        for i, data in enumerate(entries, start=position):
            try:
                server = bot.get_guild(int(data[0])).name
            except AttributeError:
                server = "<unknown server>"
            name = escape(server, formatting=True)

            balance = data[1]
            balance = humanize_number(balance)
            msg += f"{humanize_number(i)}. {balance: <{bal_len + 5}} {name}\n"

        bank_name = "Guild Command Leaderboard."
        page = discord.Embed(
            title=("{}").format(bank_name),
            color=await menu.ctx.embed_color(),
            description="{}\n{} ".format(box(header, lang="prolog"), box(msg, lang="md")),
        )
        page.set_footer(text=f"Page {menu.current_page + 1}/{self.get_max_pages()}")

        return page
Esempio n. 4
0
    async def format_page(self, menu: menus.MenuPages,
                          entries: List[Tuple[int, Dict]]):
        ctx = menu.ctx
        stats_len = len(humanize_number(entries[0][1][self._stat])) + 3
        start_position = (menu.current_page * self.per_page) + 1
        pos_len = len(str(start_position + 9)) + 2
        stats_plural = self._stat if self._stat.endswith(
            "s") else f"{self._stat}s"
        stats_len = (len(stats_plural)
                     if len(stats_plural) > stats_len else stats_len) + 2
        rebirth_len = len("Rebirths") + 2
        header = f"{'#':{pos_len}}{stats_plural.title().ljust(stats_len)}{'Rebirths':{rebirth_len}}{'Adventurer':2}"
        author = ctx.author

        if getattr(ctx, "guild", None):
            guild = ctx.guild
        else:
            guild = None

        players = []
        for (position, (user_id,
                        account_data)) in enumerate(entries,
                                                    start=start_position):
            if guild is not None:
                member = guild.get_member(user_id)
            else:
                member = None

            if member is not None:
                username = member.display_name
            else:
                user = menu.ctx.bot.get_user(user_id)
                if user is None:
                    username = user_id
                else:
                    username = user.name
            username = escape(str(username), formatting=True)
            if user_id == author.id:
                # Highlight the author's position
                username = f"<<{username}>>"

            pos_str = position
            rebirths = humanize_number(account_data["rebirths"])
            stats_value = humanize_number(account_data[self._stat.lower()])

            data = f"{f'{pos_str}.':{pos_len}}" f"{stats_value:{stats_len}}" f"{rebirths:{rebirth_len}}" f"{username}"
            players.append(data)

        embed = discord.Embed(
            title=f"Adventure Weekly Scoreboard",
            color=await menu.ctx.embed_color(),
            description="```md\n{}``` ```md\n{}```".format(
                header,
                "\n".join(players),
            ),
        )
        embed.set_footer(
            text=f"Page {menu.current_page + 1}/{self.get_max_pages()}")
        return embed
Esempio n. 5
0
    async def bankstats(self, ctx: commands.Context):
        """Show stats of the bank."""
        icon = self.bot.user.avatar_url_as(static_format="png")
        user_bal = await bank.get_balance(ctx.author)
        credits_name = await bank.get_currency_name(ctx.guild)
        pos = await bank.get_leaderboard_position(ctx.author)
        bank_name = await bank.get_bank_name(ctx.guild)
        bank_config = bank._config

        if await bank.is_global():
            all_accounts = len(await bank_config.all_users())
            accounts = await bank_config.all_users()
        else:
            all_accounts = len(await bank_config.all_members(ctx.guild))
            accounts = await bank_config.all_members(ctx.guild)
        member_account = await bank.get_account(ctx.author)
        created_at = str(member_account.created_at)
        no = "1970-01-01 00:00:00"
        overall = 0
        for key, value in accounts.items():
            overall += value["balance"]

        em = discord.Embed(color=await ctx.embed_colour())
        em.set_author(name=_("{} stats:").format(bank_name), icon_url=icon)
        em.add_field(
            name=_("{} stats:").format(
                "Global" if await bank.is_global() else "Bank"),
            value=
            _("Total accounts: **{all_accounts}**\nTotal amount: **{overall} {credits_name}**"
              ).format(
                  all_accounts=all_accounts,
                  overall=humanize_number(overall),
                  credits_name=credits_name,
              ),
        )
        if pos is not None:
            percent = round((int(user_bal) / overall * 100), 3)
            em.add_field(
                name=_("Your stats:"),
                value=_(
                    "You have **{bal} {currency}**.\n"
                    "It's **{percent}%** of the {g}amount in the bank.\n"
                    "You are **{pos}/{all_accounts}** in the {g}leaderboard.").
                format(
                    bal=humanize_number(user_bal),
                    currency=credits_name,
                    percent=percent,
                    g="global " if await bank.is_global() else "",
                    pos=humanize_number(pos),
                    all_accounts=humanize_number(all_accounts),
                ),
                inline=False,
            )
        if created_at != no:
            em.set_footer(text=_("Bank account created on: ") +
                          str(created_at))
        await ctx.send(embed=em)
Esempio n. 6
0
 async def usagecount(self, ctx: commands.Context):
     """
         Show the usage count of the bot.
         Commands processed, messages received, and music on servers.
     """
     uptime = str(self.get_bot_uptime())
     commands_count = "`{}`".format(self.get("processed_commands"))
     errors_count = "`{}`".format(self.get("command_error"))
     messages_read = "`{}`".format(self.get("messages_read"))
     messages_sent = "`{}`".format(self.get("msg_sent"))
     try:
         total_num = "`{}/{}`".format(
             humanize_number(len(lavalink.active_players())),
             humanize_number(len(lavalink.all_players())),
         )
     except AttributeError:  # Remove at 3.2
         total_num = "`{}/{}`".format(
             humanize_number(
                 len([p for p in lavalink.players
                      if p.current is not None])),
             humanize_number(len([p for p in lavalink.players])),
         )
     tracks_played = "`{}`".format(self.get("tracks_played"))
     guild_join = "`{}`".format(self.get("guild_join"))
     guild_leave = "`{}`".format(self.get("guild_remove"))
     avatar = self.bot.user.avatar_url_as(static_format="png")
     msg = (bold(_("Commands processed: ")) +
            _("{} commands.\n").format(commands_count) +
            bold(_("Commands errors: ")) +
            _("{} errors.\n").format(errors_count) +
            bold(_("Messages received: ")) +
            _("{} messages.\n").format(messages_read) +
            bold(_("Messages sent: ")) +
            _("{} messages.\n").format(messages_sent) +
            bold(_("Playing music on: ")) +
            _("{} servers.\n").format(total_num) +
            bold(_("Tracks played: ")) +
            _("{} tracks.\n\n").format(tracks_played) +
            bold(_("Servers joined: ")) +
            _("{} servers.\n").format(guild_join) +
            bold(_("Servers left: ")) +
            _("{} servers.").format(guild_leave))
     try:
         em = discord.Embed(color=await ctx.embed_colour())
         em.add_field(
             name=_("Usage count of {} since last restart:").format(
                 ctx.bot.user.name),
             value=msg,
         )
         em.set_thumbnail(url=avatar)
         em.set_footer(text=_("Since {}").format(uptime))
         await ctx.send(embed=em)
     except discord.Forbidden:
         await ctx.send(
             _("Usage count of {} since last restart:\n").format(
                 ctx.bot.user.name) + msg +
             _("\n\nSince {}").format(uptime))
Esempio n. 7
0
    async def covid(self, ctx, *, country: typing.Optional[str]):
        """Stats about Covid-19 or countries if provided.

        Supports multiple countries seperated by a comma.
        Example: [p]covid Ireland, England
        """
        if not country:
            async with ctx.typing():
                data = await self.get(self.api + "/all")
            if isinstance(data, dict):
                if data.get("failed") is not None:
                    return await ctx.send(data.get("failed"))
            if not data:
                return await ctx.send("No data available.")
            embed = discord.Embed(
                color=await self.bot.get_embed_color(ctx.channel),
                title="Covid-19 Global Statistics",
                timestamp=datetime.datetime.utcfromtimestamp(data["updated"] /
                                                             1000),
            )
            embed.add_field(name="Cases", value=humanize_number(data["cases"]))
            embed.add_field(name="Deaths",
                            value=humanize_number(data["deaths"]))
            embed.add_field(name="Recovered",
                            value=humanize_number(data["recovered"]))
            embed.add_field(name="Critical",
                            value=humanize_number(data["critical"]))
            embed.add_field(name="Active",
                            value=humanize_number(data["active"]))
            embed.add_field(name="Affected Countries",
                            value=humanize_number(data["affectedCountries"]))
            embed.add_field(name="Cases Today",
                            value=humanize_number(data["todayCases"]))
            embed.add_field(name="Deaths Today",
                            value=humanize_number(data["todayDeaths"]))
            embed.add_field(name="Recovered Today",
                            value=humanize_number(data["todayRecovered"]))
            embed.add_field(name="Total Tests",
                            value=humanize_number(data["tests"]))
            await ctx.send(embed=embed)
        else:
            async with ctx.typing():
                data = await self.get(self.api +
                                      "/countries/{}".format(country))
            if isinstance(data, dict):
                error = data.get("failed")
                if error is not None:
                    return await ctx.send(error)
                data = [data]
            if not data:
                return await ctx.send("No data available.")
            await GenericMenu(source=CovidMenu(data), ctx=ctx,
                              type="Today").start(
                                  ctx=ctx,
                                  wait=False,
                              )
Esempio n. 8
0
    async def fattest(self, ctx, top: int = 10):
        """See who has the most stacked briefcase."""
        if top < 1:
            top = 10
        guild = ctx.guild
        if await bank.is_global():
            raw_accounts = await self.config.all_users()
            if guild is not None:
                tmp = raw_accounts.copy()
                for acc in tmp:
                    if not guild.get_member(acc):
                        del raw_accounts[acc]
        else:
            raw_accounts = await self.config.all_members(guild)
        briefcaselist = sorted(raw_accounts.items(), key=lambda x: x[1]["briefcase"], reverse=True)[:top]
        try:
            bal_len = len(str(briefcaselist[0][1]["briefcase"]))

        except IndexError:
            return await ctx.send("No one has any money in their briefcase.")
        pound_len = len(str(len(briefcaselist)))
        header = "{pound:{pound_len}}{score:{bal_len}}{name:2}\n".format(
            pound="#", name="Name", score="Rent Money", bal_len=str(humanize_number(int(bal_len + 6))), pound_len=pound_len + 3
        )
        highscores = []
        pos = 1
        temp_msg = header
        for acc in briefcaselist:
            try:
                name = guild.get_member(acc[0]).display_name
            except AttributeError:
                user_id = ""
                if await ctx.bot.is_owner(ctx.author):
                    user_id = f"({str(acc[0])})"
                name = f"{user_id}"
            balance = str(humanize_number(int(acc[1]["briefcase"])))

            if acc[0] != ctx.author.id:
                temp_msg += f"{f'{pos}.': <{pound_len+2}} {balance: <{str(humanize_number(int(bal_len + 5)))}} {name}\n"

            else:
                temp_msg += (
                    f"{f'{pos}.': <{pound_len+2}} "
                    f"{balance: <{str(humanize_number(int(bal_len + 5)))}} "
                    f"<<{ctx.author.display_name}>>\n"
                )
            if pos % 10 == 0:
                highscores.append(box(temp_msg, lang="md"))
                temp_msg = header
            pos += 1

        if temp_msg != header:
            highscores.append(box(temp_msg, lang="md"))

        if highscores:
            await menu(ctx, highscores, DEFAULT_CONTROLS)
Esempio n. 9
0
    async def continent(self, ctx, *, continent: str):
        """Stats about Covid-19 for a particular continent.

        Example: [p]covid continent europe
        """
        async with ctx.typing():
            data = await self.get(self.api + f"/continents/{continent}")
        if isinstance(data, dict) and data.get("failed") is not None:
            return await ctx.send(data.get("failed"))
        if not data:
            return await ctx.send("No data available.")

        embed = discord.Embed(
            color=await self.bot.get_embed_color(ctx.channel),
            title=f"Covid-19 {continent.title()} Statistics",
            timestamp=datetime.datetime.utcfromtimestamp(data["updated"] /
                                                         1000),
        )
        embed.add_field(name="Cases", value=humanize_number(data["cases"]))
        embed.add_field(name="Deaths", value=humanize_number(data["deaths"]))
        embed.add_field(name="Recovered",
                        value=humanize_number(data["recovered"]))
        embed.add_field(name="Critical",
                        value=humanize_number(data["critical"]))
        embed.add_field(name="Active", value=humanize_number(data["active"]))
        embed.add_field(name="Cases Today",
                        value=humanize_number(data["todayCases"]))
        embed.add_field(name="Deaths Today",
                        value=humanize_number(data["todayDeaths"]))
        embed.add_field(name="Recovered Today",
                        value=humanize_number(data["todayRecovered"]))
        embed.add_field(name="Total Tests",
                        value=humanize_number(data["tests"]))
        await ctx.send(embed=embed)
Esempio n. 10
0
 async def settings(self, ctx):
     """Current lifestyle settings."""
     conf = await self.configglobalcheck(ctx)
     data = await conf.all()
     cooldowns = data["cooldowns"]
     workcd = humanize_timedelta(seconds=cooldowns["workcd"])
     robcd = humanize_timedelta(seconds=cooldowns["robcd"])
     crimecd = humanize_timedelta(seconds=cooldowns["crimecd"])
     slutcd = humanize_timedelta(seconds=cooldowns["slutcd"])
     cooldownmsg = "Work Cooldown: `{}`\nCrime Cooldown: `{}`\nSlut Cooldown: `{}`\nRob Cooldown: `{}`".format(
         workcd, crimecd, slutcd, robcd
     )
     embed = discord.Embed(colour=ctx.author.colour, title="Lifestyle Settings")
     embed.add_field(
         name="Using Default Replies?",
         value="Yes" if data["defaultreplies"] else "No",
         inline=True,
     )
     payouts = data["payouts"]
     slutpayout = f"**Max**: {humanize_number(payouts['s**t']['max'])}\n**Min**: {humanize_number(payouts['s**t']['min'])}"
     crimepayout = f"**Max**: {humanize_number(payouts['crime']['max'])}\n**Min**: {humanize_number(payouts['crime']['min'])}"
     workpayout = f"**Max**: {humanize_number(payouts['work']['max'])}\n**Min**: {humanize_number(payouts['work']['min'])}"
     embed.add_field(name="Work Payouts", value=workpayout, inline=True)
     embed.add_field(name="Crime Payouts", value=crimepayout, inline=True)
     embed.add_field(name="S**t Payouts", value=slutpayout, inline=True)
     failrates = data["failrates"]
     embed.add_field(
         name="Fail Rates",
         value=f"**Crime**: {failrates['crime']}%\n**S**t**: {failrates['s**t']}%\n**Rob**: {failrates['rob']}%",
         inline=True,
     )
     bankfine = data["fine"]
     bailamounts = data["bailamounts"]
     embed.add_field(
         name="Bail Amounts",
         value=f"**Max**: {humanize_number(bailamounts['max'])}%\n**Min**: {humanize_number(bailamounts['min'])}%\n**Bank Fee**: {humanize_number(bankfine)}%",
         inline=True,
     )
     embed.add_field(name="Cooldown Settings", value=cooldownmsg, inline=True)
     briefcasesettings = data["disable_briefcase"]
     embed.add_field(
         name="Briefcase Settings",
         value="Disabled."
         if not briefcasesettings
         else f"**Max Balance**: {humanize_number(data['briefcase_max'])}\n**Withdraw Cooldown**: {humanize_timedelta(seconds=cooldowns['withdrawcd'])}\n**Deposit Cooldown**: {humanize_timedelta(seconds=cooldowns['depositcd'])}",
         inline=True,
     )
     minbet = humanize_number(data["betting"]["min"])
     maxbet = humanize_number(data["betting"]["max"])
     betstats = f"**Max**: {maxbet}\n**Min**: {minbet}"
     embed.add_field(name="Betting Info", value=betstats)
     roulette = data["roulette_toggle"]
     game_stats = f"**Roulette**: {'Enabled' if roulette else 'Disabled'}"
     embed.add_field(name="Games", value=game_stats)
     await ctx.send(embed=embed)
Esempio n. 11
0
 async def format_page(self, menu: GenericMenu, country) -> str:
     embed = discord.Embed(
         color=await menu.ctx.embed_colour(),
         title="Covid-19 | {} Statistics".format(country["country"]),
         timestamp=datetime.datetime.utcfromtimestamp(country["updated"] /
                                                      1000),
     )
     embed.set_thumbnail(url=country["countryInfo"]["flag"])
     embed.add_field(name="Cases", value=humanize_number(country["cases"]))
     embed.add_field(name="Deaths",
                     value=humanize_number(country["deaths"]))
     embed.add_field(name="Recovered",
                     value=humanize_number(country["recovered"]))
     embed.add_field(name=f"Cases {menu.type}",
                     value=humanize_number(country["todayCases"]))
     embed.add_field(name=f"Deaths {menu.type}",
                     value=humanize_number(country["todayDeaths"]))
     embed.add_field(name=f"Recovered {menu.type}",
                     value=humanize_number(country["todayRecovered"]))
     embed.add_field(name="Critical",
                     value=humanize_number(country["critical"]))
     embed.add_field(name="Active",
                     value=humanize_number(country["active"]))
     embed.add_field(name="Total Tests",
                     value=humanize_number(country["tests"]))
     embed.set_footer(
         text=f"Page {menu.current_page + 1 }/{menu._source.get_max_pages()}"
     )
     return embed
Esempio n. 12
0
 async def settings(self, ctx):
     """Current unbelievaboat settings."""
     conf = await self.configglobalcheck(ctx)
     data = await conf.all()
     cooldowns = data["cooldowns"]
     workcd = humanize_timedelta(seconds=cooldowns["workcd"])
     robcd = humanize_timedelta(seconds=cooldowns["robcd"])
     crimecd = humanize_timedelta(seconds=cooldowns["crimecd"])
     cooldownmsg = "Work Cooldown: `{}`\nCrime Cooldown: `{}`\nRob Cooldown: `{}`".format(
         workcd, crimecd, robcd)
     embed = discord.Embed(colour=ctx.author.colour,
                           title="Unbelievaboat Settings")
     embed.add_field(
         name="Using Default Replies?",
         value="Yes" if data["defaultreplies"] else "No",
         inline=True,
     )
     payouts = data["payouts"]
     crimepayout = f"**Max**: {humanize_number(payouts['crime']['max'])}\n**Min**: {humanize_number(payouts['crime']['min'])}"
     workpayout = f"**Max**: {humanize_number(payouts['work']['max'])}\n**Min**: {humanize_number(payouts['work']['min'])}"
     embed.add_field(name="Work Payouts", value=workpayout, inline=True)
     embed.add_field(name="Crime Payouts", value=crimepayout, inline=True)
     failrates = data["failrates"]
     embed.add_field(
         name="Fail Rates",
         value=
         f"**Crime**: {failrates['crime']}%\n**Rob**: {failrates['rob']}%\n**Interest Fee**: {data['interest']}%",
         inline=True,
     )
     fines = data["fines"]
     embed.add_field(
         name="Fines",
         value=
         f"**Max**: {humanize_number(fines['max'])}\n**Min**: {humanize_number(fines['min'])}",
         inline=True,
     )
     embed.add_field(name="Cooldown Settings",
                     value=cooldownmsg,
                     inline=True)
     walletsettings = data["disable_wallet"]
     embed.add_field(
         name="Wallet Settings",
         value="Disabled." if not walletsettings else
         f"**Max Balance**: {humanize_number(data['wallet_max'])}\n**Withdraw Cooldown**: {humanize_timedelta(seconds=cooldowns['withdrawcd'])}\n**Deposit Cooldown**: {humanize_timedelta(seconds=cooldowns['depositcd'])}",
         inline=True,
     )
     minbet = humanize_number(data["betting"]["min"])
     maxbet = humanize_number(data["betting"]["max"])
     betstats = f"**Max**: {maxbet}\n**Min**: {minbet}"
     embed.add_field(name="Betting Information", value=betstats)
     roulette = data["roulette_toggle"]
     game_stats = f"**Roulette**: {'Enabled' if roulette else 'Disabled'}"
     embed.add_field(name="Games", value=game_stats)
     await ctx.send(embed=embed)
Esempio n. 13
0
 async def bankset_maxbal(self, ctx: commands.Context, *, amount: int):
     """Set the maximum balance a user can get."""
     try:
         await bank.set_max_balance(amount, ctx.guild)
     except ValueError:
         # noinspection PyProtectedMember
         return await ctx.send(
             _("Amount must be greater than zero and less than {max}.").
             format(max=humanize_number(bank._MAX_BALANCE)))
     await ctx.send(
         _("Maximum balance has been set to: {amount}").format(
             amount=humanize_number(amount)))
Esempio n. 14
0
    async def get_variables(self):
        botinfo = await self.bot._config.custom_info()
        if botinfo is None:
            botinfo = (
                f"Hello, welcome to the Red Discord Bot dashboard for {self.bot.user.name}! "
                f"{self.bot.user.name} is based off the popular bot Red Discord Bot, an open "
                "source, multifunctional bot. It has tons of features including moderation, "
                "audio, economy, fun and more! Here, you can control and interact with "
                f"{self.bot.user.name}'s settings. So what are you waiting for? Invite them now!"
            )

        prefixes = [
            p for p in await self.bot.get_valid_prefixes() if not re.match(r"<@!?([0-9]+)>", p)
        ]

        count = len(self.bot.users)

        if self.invite_url is None:
            core = self.bot.get_cog("Core")
            self.invite_url = await core._invite_url()

        delta = datetime.utcnow() - self.bot.uptime
        uptime_str = humanize_timedelta(timedelta=delta)

        data = await self.cog.config.all()
        client_id = data["clientid"] or self.bot.user.id

        returning = {
            "botname": self.bot.user.name,
            "botavatar": str(self.bot.user.avatar_url_as(static_format="png")),
            "botid": self.bot.user.id,
            "clientid": client_id,
            "botinfo": markdown2.markdown(botinfo),
            "prefix": prefixes,
            "redirect": data["redirect"],
            "support": data["support"],
            "color": data["defaultcolor"],
            "servers": humanize_number(len(self.bot.guilds)),
            "users": humanize_number(count),
            "blacklisted": data["blacklisted"],
            "uptime": uptime_str,
            "invite": self.invite_url,
            "meta": data["meta"],
        }
        if self.owner is None:
            app_info = await self.bot.application_info()
            if app_info.team:
                self.owner = str(app_info.team.name)
            else:
                self.owner = str(app_info.owner)

        returning["owner"] = self.owner
        return returning
Esempio n. 15
0
    async def _set(self, ctx: commands.Context, to: discord.Member,
                   creds: SetParser):
        """Set the balance of a user's bank account.

        Putting + or - signs before the amount will add/remove currency on the user's bank account instead.

        Examples:
            - `[p]bank set @Twentysix 26` - Sets balance to 26
            - `[p]bank set @Twentysix +2` - Increases balance by 2
            - `[p]bank set @Twentysix -6` - Decreases balance by 6

        **Arguments**

        - `<to>` The user to set the currency of.
        - `<creds>` The amount of currency to set their balance to.
        """
        author = ctx.author
        currency = await bank.get_currency_name(ctx.guild)

        try:
            if creds.operation == "deposit":
                await bank.deposit_credits(to, creds.sum)
                msg = _("{author} added {num} {currency} to {user}'s account."
                        ).format(
                            author=author.display_name,
                            num=humanize_number(creds.sum),
                            currency=currency,
                            user=to.display_name,
                        )
            elif creds.operation == "withdraw":
                await bank.withdraw_credits(to, creds.sum)
                msg = _(
                    "{author} removed {num} {currency} from {user}'s account."
                ).format(
                    author=author.display_name,
                    num=humanize_number(creds.sum),
                    currency=currency,
                    user=to.display_name,
                )
            else:
                await bank.set_balance(to, creds.sum)
                msg = _(
                    "{author} set {user}'s account balance to {num} {currency}."
                ).format(
                    author=author.display_name,
                    num=humanize_number(creds.sum),
                    currency=currency,
                    user=to.display_name,
                )
        except (ValueError, errors.BalanceTooHigh) as e:
            await ctx.send(str(e))
        else:
            await ctx.send(msg)
Esempio n. 16
0
    async def getrolesettings(self, ctx, role: discord.Role):
        """Tells the price of one ticket corresponding to the role"""
        role_price = await self.config.role(role).new_price()
        base_credits = await self.config.guild(ctx.guild).base_ticket_price()
        if role_price == 0:
            final_credits = humanize_number(base_credits)
        else:
            final_credits = humanize_number(role_price)

        await ctx.send(
            "People having the {} role have to pay {} credits for one ticket".
            format(role.name, final_credits))
Esempio n. 17
0
    def __str__(self):
        """
            Define str to be our default look for the character sheet :thinkies:
        """
        next_lvl = int((self.lvl + 1)**3)

        if self.heroclass != {} and "name" in self.heroclass:
            class_desc = self.heroclass["name"] + "\n\n" + self.heroclass[
                "desc"]
            if self.heroclass["name"] == "Ranger":
                if not self.heroclass["pet"]:
                    class_desc += "\n\n- Current pet: None"
                elif self.heroclass["pet"]:
                    class_desc += f"\n\n- Current pet: {self.heroclass['pet']['name']}"
        else:
            class_desc = "Hero."
        legend = "( ATT  |  CHA  |  INT  |  DEX  |  LUCK)"
        return ("[{user}'s Character Sheet]\n\n"
                "{{Rebirths: {rebirths}, \n Max Level: {maxlevel}}}\n\n"
                "A level {lvl} {class_desc} \n\n- "
                "ATTACK: {att} [+{att_skill}] - "
                "CHARISMA: {cha} [+{cha_skill}] - "
                "INTELLIGENCE: {int} [+{int_skill}]\n\n - "
                "DEXTERITY: {dex} - "
                "LUCK: {luck} \n\n "
                "Currency: {bal} \n- "
                "Experience: {xp}/{next_lvl} \n- "
                "Unspent skillpoints: {skill_points}\n\n"
                "Items Equipped:\n{legend}{equip}").format(
                    user=self.user.display_name,
                    rebirths=self.rebirths,
                    lvl=self.lvl
                    if self.lvl < self.maxlevel else self.maxlevel,
                    maxlevel=self.maxlevel,
                    class_desc=class_desc,
                    att=self.att,
                    att_skill=self.skill["att"],
                    int=self.int,
                    int_skill=self.skill["int"],
                    cha=self.cha,
                    cha_skill=self.skill["cha"],
                    dex=self.dex,
                    luck=self.luck,
                    bal=humanize_number(self.bal),
                    xp=humanize_number(round(self.exp)),
                    next_lvl=humanize_number(next_lvl)
                    if self.lvl < self.maxlevel else 0,
                    skill_points=0
                    if self.skill["pool"] < 0 else self.skill["pool"],
                    legend=legend,
                    equip=self.__equipment__(),
                )
Esempio n. 18
0
 async def registeramount(self, ctx: commands.Context, creds: int):
     """Set the initial balance for new bank accounts."""
     guild = ctx.guild
     max_balance = await bank.get_max_balance(ctx.guild)
     credits_name = await bank.get_currency_name(guild)
     try:
         await bank.set_default_balance(creds, guild)
     except ValueError:
         return await ctx.send(
             _("Amount must be greater than or equal to zero and less than {maxbal}."
               ).format(maxbal=humanize_number(max_balance)))
     await ctx.send(
         _("Registering an account will now give {num} {currency}.").format(
             num=humanize_number(creds), currency=credits_name))
Esempio n. 19
0
    async def format_page(self, menu: menus.MenuPages, entries: List[Tuple[int, Dict]]):
        ctx = menu.ctx
        loses_len = max(len(humanize_number(entries[0][1]["loses"])) + 3, 8)
        win_len = max(len(humanize_number(entries[0][1]["wins"])) + 3, 6)
        xp__len = max(len(humanize_number(entries[0][1]["xp__earnings"])) + 3, 8)
        gold__len = max(len(humanize_number(entries[0][1]["gold__losses"])) + 3, 12)
        start_position = (menu.current_page * self.per_page) + 1
        pos_len = len(str(start_position + 9)) + 2
        header = (
            f"{'#':{pos_len}}{'Wins':{win_len}}"
            f"{'Losses':{loses_len}}{'XP Won':{xp__len}}{'Gold Spent':{gold__len}}{'Adventurer':2}"
        )

        author = ctx.author

        if getattr(ctx, "guild", None):
            guild = ctx.guild
        else:
            guild = None

        players = []
        for (position, (user_id, account_data)) in enumerate(entries, start=start_position):
            if guild is not None:
                member = guild.get_member(user_id)
            else:
                member = None

            if member is not None:
                username = member.display_name
            else:
                user = await menu.ctx.bot.get_user_global(user_id)
                if user is None:
                    username = user_id
                else:
                    username = user.name

            username = escape(str(username), formatting=True)
            if user_id == author.id:
                # Highlight the author's position
                username = f"<<{username}>>"

            pos_str = position
            loses = humanize_number(account_data["loses"])
            wins = humanize_number(account_data["wins"])
            xp__earnings = humanize_number(account_data["xp__earnings"])
            gold__losses = humanize_number(account_data["gold__losses"])

            data = (
                f"{f'{pos_str}.':{pos_len}} "
                f"{wins:{win_len}} "
                f"{loses:{loses_len}} "
                f"{xp__earnings:{xp__len}} "
                f"{gold__losses:{gold__len}} "
                f"{username}"
            )
            players.append(data)
        msg = "Adventure Negaverse Scoreboard\n```md\n{}``` ```md\n{}``````md\n{}```".format(
            header, "\n".join(players), f"Page {menu.current_page + 1}/{self.get_max_pages()}"
        )
        return msg
Esempio n. 20
0
    async def command_audiostats(self, ctx: commands.Context):
        """Audio stats."""
        server_num = len(lavalink.active_players())
        total_num = len(lavalink.all_connected_players())

        msg = ""
        async for p in AsyncIter(lavalink.all_connected_players()):
            connect_dur = (
                self.get_time_string(
                    int(
                        (
                            datetime.datetime.now(datetime.timezone.utc) - p.connected_at
                        ).total_seconds()
                    )
                )
                or "0s"
            )
            try:
                if not p.current:
                    raise AttributeError
                current_title = await self.get_track_description(
                    p.current, self.local_folder_current_path
                )
                msg += f"{p.guild.name} [`{connect_dur}`]: {current_title}\n"
            except AttributeError:
                msg += "{} [`{}`]: **{}**\n".format(
                    p.guild.name, connect_dur, _("Nothing playing.")
                )

        if total_num == 0:
            return await self.send_embed_msg(ctx, title=_("Not connected anywhere."))
        servers_embed = []
        pages = 1
        for page in pagify(msg, delims=["\n"], page_length=1500):
            em = discord.Embed(
                colour=await ctx.embed_colour(),
                title=_("Playing in {num}/{total} servers:").format(
                    num=humanize_number(server_num), total=humanize_number(total_num)
                ),
                description=page,
            )
            em.set_footer(
                text=_("Page {}/{}").format(
                    humanize_number(pages), humanize_number((math.ceil(len(msg) / 1500)))
                )
            )
            pages += 1
            servers_embed.append(em)

        await menu(ctx, servers_embed, DEFAULT_CONTROLS)
Esempio n. 21
0
    async def commands_atransfer_player(self, ctx: commands.Context,
                                        amount: int, *,
                                        player: discord.Member):
        """Transfer gold to another player."""
        if amount <= 0:
            await smart_embed(
                ctx,
                _("{author.mention} You can't transfer 0 or negative values.").
                format(author=ctx.author),
            )
            ctx.command.reset_cooldown(ctx)
            return
        currency = await bank.get_currency_name(ctx.guild)
        if not await bank.can_spend(member=ctx.author, amount=amount):
            ctx.command.reset_cooldown(ctx)
            return await smart_embed(
                ctx,
                _("{author.mention} you don't have enough {name}.").format(
                    author=ctx.author,
                    name=await bank.get_currency_name(ctx.guild)),
            )
        tax = await self.config.tax_brackets.all()
        highest = 0
        for tax, percent in tax.items():
            tax = int(tax)
            if tax >= amount:
                break
            highest = percent

        try:
            transfered = await bank.transfer_credits(from_=ctx.author,
                                                     to=player,
                                                     amount=amount,
                                                     tax=highest
                                                     )  # Customizable Tax
        except (ValueError, BalanceTooHigh) as e:
            ctx.command.reset_cooldown(ctx)
            return await ctx.send(str(e))

        await ctx.send(
            _("{user} transferred {num} {currency} to {other_user} "
              "(You have been taxed {tax:.2%}, total transfered: {transfered})"
              ).format(
                  user=ctx.author.display_name,
                  num=humanize_number(amount),
                  currency=currency,
                  other_user=player.display_name,
                  tax=highest,
                  transfered=humanize_number(transfered),
              ))
Esempio n. 22
0
 async def usagecount(self, ctx: commands.Context):
     """
     Show the usage count of the bot.
     Commands processed, messages received, and music on servers.
     """
     msg = _(
         "**Commands processed:** `{commands_count}` commands. (`{cpm_commands:.2f}`/min)\n"
         "**Commands errors:** `{errors_count}` errors.\n"
         "**Messages received:** `{messages_read}` messages. (`{cpm_msgs:.2f}`/min)\n"
         "**Messages sent:** `{messages_sent}` messages. (`{cpm_msgs_sent:.2f}`/min)\n"
         "**Playing music on:** `{ll_players}` servers.\n"
         "**Tracks played:** `{tracks_played}` tracks. (`{cpm_tracks:.2f}`/min)\n\n"
         "**Servers joined:** `{guild_join}` servers. (`{cpm_guild_join:.2f}`/hour)\n"
         "**Servers left:** `{guild_leave}` servers. (`{cpm_guild_leave:.2f}`/hour)"
     ).format(
         commands_count=self.get("processed_commands"),
         cpm_commands=self.usage_counts_cpm("processed_commands"),
         errors_count=self.get("command_error"),
         messages_read=self.get("messages_read"),
         cpm_msgs=self.usage_counts_cpm("messages_read"),
         messages_sent=self.get("msg_sent"),
         cpm_msgs_sent=self.usage_counts_cpm("msg_sent"),
         ll_players="`{}/{}`".format(
             humanize_number(len(lavalink.active_players())),
             humanize_number(len(lavalink.all_players())),
         ),
         tracks_played=self.get("tracks_played"),
         cpm_tracks=self.usage_counts_cpm("tracks_played"),
         guild_join=self.get("guild_join"),
         cpm_guild_join=self.usage_counts_cpm("guild_join", 3600),
         guild_leave=self.get("guild_remove"),
         cpm_guild_leave=self.usage_counts_cpm("guild_remove", 3600),
     )
     if await ctx.embed_requested():
         em = discord.Embed(
             color=await ctx.embed_colour(),
             title=_("Usage count of {} since last restart:").format(
                 self.bot.user.name),
             description=msg,
         )
         em.set_thumbnail(url=self.bot.user.avatar_url_as(
             static_format="png"))
         em.set_footer(text=_("Since {}").format(self.get_bot_uptime()))
         await ctx.send(embed=em)
     else:
         await ctx.send(
             _("Usage count of {} since last restart:\n").format(
                 ctx.bot.user.name) + msg +
             _("\n\nSince {}").format(self.get_bot_uptime()))
Esempio n. 23
0
    async def invite(self,
                     ctx: commands.Context,
                     send_in_channel: Optional[bool] = False):
        """Invite [botname] to your server!"""

        check = send_in_channel and await self.bot.is_owner(ctx.author)
        channel = await self._get_channel(ctx) if not check else ctx.channel
        settings = await self.config.all()
        title = settings.get("title", _config_structure["title"]).replace(
            "{bot_name}", ctx.me.name)
        message = settings.get("custom_message",
                               _config_structure["custom_message"]).replace(
                                   "{bot_name}", ctx.me.name)
        url = await self._invite_url()
        time = datetime.datetime.now(tz=datetime.timezone.utc)
        footer = settings.get("footer")
        if footer:
            footer.replace("{bot_name}", ctx.me.name).replace(
                "{guild_count}", humanize_number(len(ctx.bot.guilds))).replace(
                    "{user_count}", humanize_number(len(self.bot.users)))
        timestamp = f"<t:{int(time.timestamp())}>"
        support = settings.get("support_server")

        support_msg = f"\nJoin the support server! <{support}>\n" if support is not None else ""
        kwargs: Dict[str, Any] = {
            "content":
            f"**{title}**\n{message}\n<{url}>{support_msg}\n\n{footer}\n{timestamp}"
        }
        support_server_emoji, invite_emoji = [
            Emoji.from_data(settings.get(x))
            for x in ["support_server_emoji", "invite_emoji"]
        ]
        if await self._embed_requested(ctx, channel):
            message = (f"{message}\n{url}" if await self.config.extra_link()
                       else f"[{message}]({url})")
            embed = discord.Embed(
                title=title,
                description=message,
                colour=await ctx.embed_colour(),
                timestamp=time,
            )
            if support is not None:
                embed.add_field(name="Join the support server", value=support)
            if curl := settings.get("custom_url"):
                embed.set_thumbnail(url=curl)
            if footer:
                embed.set_footer(text=footer)
            kwargs = {"embed": embed}
Esempio n. 24
0
    async def format_page(
            self, menu: SimpleHybridMenu,
            entries: List[Tuple[int, int, int,
                                str]]) -> Union[discord.Embed, str]:
        guild = menu.ctx.guild
        author = menu.ctx.author
        bot = menu.ctx.bot
        position = (menu.current_page * self.per_page) + 1
        bal_len = len(humanize_number(entries[0][0]))

        pound_len = len(str(position + 9))
        header = "{pound:{pound_len}}{score:{bal_len}}{queries:{bal_len}}{name:2}\n".format(
            pound="#",
            name=_("Name"),
            score=_("Entries"),
            queries=_("Queries"),
            bal_len=bal_len + 6,
            pound_len=pound_len + 3,
        )
        for pos, acc in enumerate(entries, start=position):
            try:
                user = guild.get_member(int(acc[1])) or bot.get_user(
                    int(acc[1]))
                name = user.display_name
            except AttributeError:
                user_id = ""
                if await bot.is_owner(menu.ctx.author):
                    user_id = f"({acc[1]})"
                name = f"{acc[3]} {user_id}"
            name = escape(name, formatting=True)

            balance = acc[0]
            balance = humanize_number(balance)
            queries = humanize_number(acc[2])
            if acc[0] != author.id:
                header += (f"{f'{humanize_number(pos)}.': <{pound_len + 2}} "
                           f"{balance: <{bal_len + 5}} "
                           f"{queries: <{bal_len + 5}} "
                           f"{name}\n")
            else:
                header += (f"{f'{humanize_number(pos)}.': <{pound_len + 2}} "
                           f"{balance: <{bal_len + 5}} "
                           f"{queries: <{bal_len + 5}} "
                           f"<<{name}>>\n")

        page = box(header, lang="md")

        return page
Esempio n. 25
0
    async def command_equalizer_list(self, ctx: commands.Context):
        """List saved eq presets."""
        eq_presets = await self.config.custom("EQUALIZER", ctx.guild.id).eq_presets()
        if not eq_presets.keys():
            return await self.send_embed_msg(ctx, title=_("No saved equalizer presets."))

        space = "\N{EN SPACE}"
        header_name = _("Preset Name")
        header_author = _("Author")
        header = box(
            "[{header_name}]{space}[{header_author}]\n".format(
                header_name=header_name, space=space * 9, header_author=header_author
            ),
            lang="ini",
        )
        preset_list = ""
        for preset, bands in eq_presets.items():
            try:
                author = self.bot.get_user(bands["author"])
            except TypeError:
                author = "None"
            msg = f"{preset}{space * (22 - len(preset))}{author}\n"
            preset_list += msg

        page_list = []
        colour = await ctx.embed_colour()
        for page in pagify(preset_list, delims=[", "], page_length=1000):
            formatted_page = box(page, lang="ini")
            embed = discord.Embed(colour=colour, description=f"{header}\n{formatted_page}")
            embed.set_footer(
                text=_("{num} preset(s)").format(num=humanize_number(len(list(eq_presets.keys()))))
            )
            page_list.append(embed)
        await menu(ctx, page_list, DEFAULT_CONTROLS)
Esempio n. 26
0
    async def l_lucky3(self, ctx):
        """Play a game of Lucky 3"""
        if not await self.config.guild(ctx.guild).lucky3.enable():
            return

        cost = await self.config.guild(ctx.guild).lucky3.cost()
        currency = await bank.get_currency_name(ctx.guild)

        if not await bank.can_spend(ctx.author, cost):
            await ctx.send(
                "You do not have enough {} to play, you need at least {}".
                format(currency, cost))
            return

        icons = await self.config.guild(ctx.guild).lucky3.icons() - 1
        prize = await self.config.guild(ctx.guild).lucky3.prize()

        num1 = random.randrange(0, icons)
        num2 = random.randrange(0, icons)
        num3 = random.randrange(0, icons)

        await bank.withdraw_credits(ctx.author, cost)
        await ctx.send(
            f"{self.lucky3[num1]}{self.lucky3[num2]}{self.lucky3[num3]}")

        if num1 == num2 and num1 == num3:
            await ctx.send("🥳 WINNER!!! 🎉 +{} {}".format(
                humanize_number(prize), currency))
            await bank.deposit_credits(ctx.author, prize)
        else:
            await ctx.send("Not a winner 😢")
Esempio n. 27
0
        async def wrapped(*args, **kwargs):
            context: commands.Context = None
            for arg in args:
                if isinstance(arg, commands.Context):
                    context = arg
                    break

            if not context.guild and not await is_global():
                raise commands.UserFeedbackCheckFailure(
                    _("Can't pay for this command in DM without a global bank."
                      ))
            try:
                await withdraw_credits(context.author, amount)
            except Exception:
                credits_name = await get_currency_name(context.guild)
                raise commands.UserFeedbackCheckFailure(
                    _("You need at least {cost} {currency} to use this command."
                      ).format(cost=humanize_number(amount),
                               currency=credits_name))
            else:
                try:
                    return await coro(*args, **kwargs)
                except AbortPurchase:
                    await deposit_credits(context.author, amount)
                except Exception:
                    await deposit_credits(context.author, amount)
                    raise
Esempio n. 28
0
async def deposit_credits(member: discord.Member, amount: int) -> int:
    """Add a given amount of credits to an account.

    Parameters
    ----------
    member : discord.Member
        The member to deposit credits to.
    amount : int
        The amount to deposit.

    Returns
    -------
    int
        The new balance.

    Raises
    ------
    ValueError
        If the deposit amount is invalid.
    TypeError
        If the deposit amount is not an `int`.

    """
    if not isinstance(amount, int):
        raise TypeError("Deposit amount must be of type int, not {}.".format(type(amount)))
    if _invalid_amount(amount):
        raise ValueError(
            "Invalid deposit amount {} <= 0".format(
                humanize_number(amount, override_locale="en_US")
            )
        )

    bal = await get_balance(member)
    return await set_balance(member, amount + bal)
Esempio n. 29
0
    async def after(self,
                    ctx: commands.Context,
                    message_id: RawMessageIds,
                    delete_pinned: bool = False):
        """Delete all messages after a specified message.

        To get a message id, enable developer mode in Discord's
        settings, 'appearance' tab. Then right click a message
        and copy its id.
        """

        channel = ctx.channel
        author = ctx.author

        try:
            after = await channel.fetch_message(message_id)
        except discord.NotFound:
            return await ctx.send(_("Message not found."))

        to_delete = await self.get_messages_for_deletion(
            channel=channel,
            number=None,
            after=after,
            delete_pinned=delete_pinned)

        reason = "{}({}) deleted {} messages in channel {}.".format(
            author.name,
            author.id,
            humanize_number(len(to_delete), override_locale="en_US"),
            channel.name,
        )
        log.info(reason)

        await mass_purge(to_delete, channel)
Esempio n. 30
0
    async def check_100_plus(ctx: commands.Context, number: int) -> bool:
        """
        Called when trying to delete more than 100 messages at once.

        Prompts the user to choose whether they want to continue or not.

        Tries its best to cleanup after itself if the response is positive.
        """

        if ctx.assume_yes:
            return True

        prompt = await ctx.send(
            _("Are you sure you want to delete {number} messages? (y/n)").
            format(number=humanize_number(number)))
        response = await ctx.bot.wait_for(
            "message", check=MessagePredicate.same_context(ctx))

        if response.content.lower().startswith("y"):
            await prompt.delete()
            try:
                await response.delete()
            except discord.HTTPException:
                pass
            return True
        else:
            await ctx.send(_("Cancelled."))
            return False