コード例 #1
0
    async def gw2_worlds(self, ctx):
        """ (List all worlds)

        Example:
        gw2 worlds
        """

        try:
            await ctx.message.channel.trigger_typing()
            endpoint = "worlds?ids=all"
            gw2Api = Gw2Api(self.bot)
            results = await gw2Api.call_api(endpoint)
        except Exception as e:
            await BotUtils.send_error_msg(self, ctx, e)
            return self.bot.log.error(ctx, e)

        color = self.bot.gw2_settings["EmbedColor"]
        desc_na = "~~~~~ NA Servers ~~~~~"
        embed_na = discord.Embed(color=color,
                                 description=Formatting.inline(desc_na))
        desc_eu = "~~~~~ EU Servers ~~~~~"
        embed_eu = discord.Embed(color=color,
                                 description=Formatting.inline(desc_eu))

        for world in results:
            try:
                await ctx.message.channel.trigger_typing()
                wid = world["id"]
                endpoint = f"wvw/matches?world={wid}"
                matches = await gw2Api.call_api(endpoint)
                if wid < 2001:
                    tier_number = matches["id"].replace("1-", "")
                    embed_na.add_field(
                        name=world["name"],
                        value=Formatting.inline(
                            f"T{tier_number} {world['population']}"),
                        inline=True)
                else:
                    tier_number = matches["id"].replace("2-", "")
                    embed_eu.add_field(
                        name=world["name"],
                        value=Formatting.inline(
                            f"T{tier_number} {world['population']}"),
                        inline=True)
            except Exception as e:
                await BotUtils.send_error_msg(self, ctx, e)
                return self.bot.log.error(ctx, e)

        await ctx.send(embed=embed_na)
        await ctx.send(embed=embed_eu)
コード例 #2
0
async def _daily_embed(self, ctx, daily_type: str):
    import datetime as dt
    await ctx.message.channel.trigger_typing()
    achiev_id_lst = []
    todays_date = BotUtils.convert_date_toStr(dt.datetime.now())
    gw2Api = Gw2Api(self.bot)

    try:
        endpoint = "achievements/daily"
        api_all_dailies = await gw2Api.call_api(endpoint)
    except Exception as e:
        await BotUtils.send_error_msg(self, ctx, e)
        return self.bot.log.error(ctx, e)

    for achiev_id in api_all_dailies[daily_type]:
        achiev_id_lst.append(str(achiev_id["id"]))

    try:
        achiev_ids = ','.join(achiev_id_lst)
        endpoint = f"achievements?ids={achiev_ids}"
        api_daily_desc = await gw2Api.call_api(endpoint)
    except Exception as e:
        await BotUtils.send_error_msg(self, ctx, e)
        return self.bot.log.error(ctx, e)

    color = self.bot.gw2_settings["EmbedColor"]
    embed = discord.Embed(color=color)
    embed.set_author(name=f"Today's {daily_type.upper()} Dailies ({todays_date})",
                     icon_url=self.bot.user.avatar_url)

    for x in range(0, len(api_all_dailies[daily_type])):
        await ctx.message.channel.trigger_typing()
        name = str(api_daily_desc[x]["name"])
        requirement = str(api_daily_desc[x]["requirement"])

        reward_id = str(api_daily_desc[x]["rewards"][0]["id"])
        try:
            endpoint = f"items/{reward_id}"
            api_items_desc = await gw2Api.call_api(endpoint)
            reward_name = api_items_desc["name"]
            reward_amount = str(api_daily_desc[x]["rewards"][0]["count"])
        except Exception as e:
            await BotUtils.send_error_msg(self, ctx, e)
            return self.bot.log.error(ctx, e)

        dt = x + 1
        name = f"{dt}) {name} ({reward_amount} {reward_name})"
        value = Formatting.inline(requirement)

        embed.add_field(name=name, value=value, inline=False)

    await ctx.message.channel.trigger_typing()
    await BotUtils.send_embed(self, ctx, embed, False)
コード例 #3
0
ファイル: account.py プロジェクト: ddc/DiscordBot
    async def gw2_account(self, ctx):
        """(General information about your GW2 account)

        Required API permissions: account

        Example:
        gw2 account

        """

        await ctx.message.channel.trigger_typing()
        discord_user_id = ctx.message.author.id
        gw2Api = Gw2Api(self.bot)
        gw2KeySql = Gw2KeySql(self.bot)

        rs = await gw2KeySql.get_server_user_api_key(ctx.guild.id, discord_user_id)
        if len(rs) == 0:
            await ctx.message.channel.trigger_typing()
            await BotUtils.send_error_msg(self, ctx,
                                       "You dont have an API key registered in this server.\n" \
                                       f"To add or replace an API key use: `{ctx.prefix}gw2 key add <api_key>`\n"
                                       f"To check your API key use: `{ctx.prefix}gw2 key info`")
        else:
            permissions = str(rs[0]["permissions"])
            api_key = str(rs[0]["key"])
            is_valid_key = await gw2Api.check_api_key(api_key)
            if not isinstance(is_valid_key, dict):
                return await BotUtils.send_error_msg(self, ctx,
                                                  is_valid_key.args[1] + "\n" \
                                                  "This API Key is INVALID or no longer exists in gw2 api database.\n\n" \
                                                  f"To add or replace an API key use: {ctx.prefix}gw2 key add <api_key>\n"
                                                  f"To check your API key use: `{ctx.prefix}gw2 key info`")

            await ctx.message.channel.trigger_typing()
            if "account" not in permissions:
                return await BotUtils.send_private_error_msg(self, ctx,
                                                          "Your API key doesnt have permission to access your gw2 account.\n" \
                                                          "Please add one key with account permission.")
            else:
                try:
                    # getting infos gw2 api
                    await ctx.message.channel.trigger_typing()
                    endpoint = "account"
                    api_req_acc = await gw2Api.call_api(endpoint, key=api_key)

                    server_id = api_req_acc["world"]
                    endpoint = f"worlds/{server_id}"
                    api_req_server = await gw2Api.call_api(endpoint, key=api_key)

                    if "pvp" in permissions:
                        await ctx.message.channel.trigger_typing()
                        endpoint = "pvp/stats"
                        api_req_pvp = await gw2Api.call_api(endpoint, key=api_key)
                        pvprank = api_req_pvp["pvp_rank"] + api_req_pvp["pvp_rank_rollovers"]

                    # if "characters" in permissions:
                    #     api_req_characters= await gw2Api.call_api("characters", key=api_key)
                    #     char_names = dict()
                    #     for i, char_name in enumerate(api_req_characters):
                    #         await ctx.message.channel.trigger_typing()
                    #         endpoint = f"characters/{char_name}/core"
                    #         current_char = await gw2Api.call_api(endpoint, key=api_key)
                    #         char_names[char_name] = dict()
                    #         char_names[char_name]["race"]       = current_char["race"]
                    #         char_names[char_name]["gender"]     = current_char["gender"]
                    #         char_names[char_name]["profession"] = current_char["profession"]
                    #         char_names[char_name]["level"]      = current_char["level"]
                    #         char_names[char_name]["age"]        = current_char["age"]
                    #         char_names[char_name]["created"]    = current_char["created"]
                    #         char_names[char_name]["deaths"]     = current_char["deaths"]
                    #
                    # if "progression" in permissions:
                    #     await ctx.message.channel.trigger_typing()
                    #     endpoint = "account/achievements"
                    #     api_req_acc_achiev = await gw2Api.call_api(endpoint, key=api_key)
                    #     achiev_points = await Gw2Utils.calculate_user_achiev_points(self, api_req_acc_achiev, api_req_acc)
                except Exception as e:
                    await BotUtils.send_error_msg(self, ctx, e)
                    return self.bot.log.error(ctx, e)

                await ctx.message.channel.trigger_typing()
                # acc_id          = api_req_acc["id"]
                age = api_req_acc["age"]
                guilds = api_req_acc["guilds"]
                acc_name = api_req_acc["name"]
                access = ' | '.join(api_req_acc["access"])
                access = access.replace("GuildWars2", "Guild Wars 2")
                access = access.replace("HeartOfThorns", "Heart Of Thorns")
                access = access.replace("PathOfFire", "Path Of Fire")
                is_commander = "Yes" if api_req_acc["commander"] else "No"
                created = api_req_acc["created"].split("T", 1)[0]
                server_name = api_req_server["name"]
                population = api_req_server["population"]

                color = self.bot.gw2_settings["EmbedColor"]
                embed = discord.Embed(title="Account Name", description=Formatting.inline(acc_name), color=color)
                embed.set_author(name=ctx.message.author.display_name, icon_url=ctx.message.author.avatar_url)
                await ctx.message.channel.trigger_typing()

                try:
                    guilds_names = []
                    guild_leader_names = []
                    if "guilds" in api_req_acc:
                        for i in range(0, len(guilds)):
                            guild_id = guilds[i]
                            try:
                                endpoint = "guild/" + guild_id
                                api_req_guild = await gw2Api.call_api(endpoint, key=api_key)
                            except Exception as e:
                                await BotUtils.send_error_msg(self, ctx, e)
                                return self.bot.log.error(ctx, e)
                            name = api_req_guild["name"]
                            tag = api_req_guild["tag"]
                            full_name = f"[{tag}] {name}"
                            guilds_names.insert(i, full_name)

                            if "guild_leader" in api_req_acc:
                                guild_leader = ','.join(api_req_acc["guild_leader"])
                                if len(guild_leader) > 0:
                                    if guild_id in guild_leader:
                                        guild_leader_names.insert(i, full_name)
                except APIError as e:
                    return self.bot.log.error(ctx, e)

                if "progression" in permissions:
                    await ctx.message.channel.trigger_typing()
                    fractallevel = api_req_acc["fractal_level"]
                    # daily_ap        = api_req_acc["daily_ap"]
                    # monthly_ap      = api_req_acc["monthly_ap"]
                    wvwrank = api_req_acc["wvw_rank"]
                    wvw_title = Gw2Utils.get_wvw_rank_title(int(wvwrank))
                    embed.add_field(name="Fractal Level", value=Formatting.inline(fractallevel))
                    embed.add_field(name="WvW Rank", value=Formatting.inline(f"{wvw_title}\n({wvwrank})"))
                    # embed.add_field(name="Achievements Points", value=Formatting.inline(achiev_points))

                if "pvp" in permissions:
                    pvp_title = str(Gw2Utils.get_pvp_rank_title(pvprank))
                    embed.add_field(name="PVP Rank", value=Formatting.inline(f"{pvp_title}\n({pvprank})"))

                embed.add_field(name="Commander Tag", value=Formatting.inline(is_commander))
                embed.add_field(name="Server", value=Formatting.inline(f"{server_name}\n({population})"))
                embed.add_field(name="Access", value=Formatting.inline(access), inline=False)

                if len(guilds_names) > 0:
                    embed.add_field(name="Guilds", value=Formatting.inline('\n'.join(guilds_names)), inline=False)

                if len(guild_leader_names) > 0:
                    embed.add_field(name="Guild Leader", value=Formatting.inline('\n'.join(guild_leader_names)),
                                    inline=False)

                hours = age / 60
                days = hours / 24
                # years = days / 365.25
                embed.add_field(name="Created", value=Formatting.inline(f"{created} ({round(days)} days ago)"),
                                inline=False)

                await BotUtils.send_embed(self, ctx, embed, False)
コード例 #4
0
    async def gw2_wvwinfo(self, ctx, world: str = None):
        discord_user_id = ctx.message.author.id
        await ctx.message.channel.trigger_typing()
        gw2Api = Gw2Api(self.bot)

        if not world:
            try:
                gw2KeySql = Gw2KeySql(self.bot)
                rs = await gw2KeySql.get_server_user_api_key(ctx.guild.id, discord_user_id)
                if len(rs) == 1:
                    api_key = rs[0]["key"]
                    results = await gw2Api.call_api("account", key=api_key)
                    wid = results["world"]
                else:
                    return await BotUtils.send_error_msg(self,
                                                      ctx,
                                                      "You dont have an API key registered in this server.\n"
                                                      f"To add or replace an API key use: `{ctx.prefix}gw2 key add <api_key>`\n"
                                                      f"To check your API key use: `{ctx.prefix}gw2 key info`")
            except APIKeyError as e:
                return await BotUtils.send_error_msg(self, ctx, "No world name or key associated with your account")
            except Exception as e:
                await BotUtils.send_error_msg(self, ctx, e)
                return self.bot.log.error(ctx, e)
        else:
            wid = await Gw2Utils.get_world_id(self, world)

        if not wid:
            return await BotUtils.send_error_msg(self, ctx, f"Invalid world name\n{world}")

        try:
            await ctx.message.channel.trigger_typing()
            endpoint = f"wvw/matches?world={wid}"
            matches = await gw2Api.call_api(endpoint)

            endpoint = f"worlds?id={wid}"
            worldinfo = await gw2Api.call_api(endpoint)
        except Exception as e:
            await BotUtils.send_error_msg(self, ctx, e)
            return self.bot.log.error(ctx, e)

        if wid < 2001:
            tier_number = matches["id"].replace("1-", "")
            tier = f"North America Tier {tier_number}"
        else:
            tier_number = matches["id"].replace("2-", "")
            tier = f"Europe Tier {tier_number}"

        for key, value in matches["all_worlds"].items():
            if wid in value:
                worldcolor = key
        if not worldcolor:
            await BotUtils.send_error_msg(self, ctx, "Could not resolve world's color")
            return
        if worldcolor == "red":
            color = discord.Color.red()
        elif worldcolor == "green":
            color = discord.Color.green()
        else:
            color = self.bot.gw2_settings["EmbedColor"]

        ppt = 0
        score = format(matches["scores"][worldcolor], ',d')
        victoryp = matches["victory_points"][worldcolor]

        await ctx.message.channel.trigger_typing()
        for m in matches["maps"]:
            for objective in m["objectives"]:
                if objective["owner"].lower() == worldcolor:
                    ppt += objective["points_tick"]

        population = worldinfo["population"]

        if population == "VeryHigh":
            population = "Very high"

        kills = matches["kills"][worldcolor]
        deaths = matches["deaths"][worldcolor]

        if kills == 0 or deaths == 0:
            kd = "0.0"
        else:
            kd = round((kills / deaths), 3)

        skirmish_now = len(matches["skirmishes"]) - 1
        skirmish = format(matches["skirmishes"][skirmish_now]["scores"][worldcolor], ',d')

        kills = format(matches["kills"][worldcolor], ',d')
        deaths = format(matches["deaths"][worldcolor], ',d')
        _title = f"{worldinfo['name']}"

        embed = discord.Embed(title=_title, description=tier, color=color)
        embed.add_field(name="Score", value=Formatting.inline(score), inline=True)
        embed.add_field(name="Points per tick", value=Formatting.inline(ppt), inline=True)
        embed.add_field(name="Victory Points", value=Formatting.inline(victoryp), inline=True)
        embed.add_field(name="Skirmish", value=Formatting.inline(skirmish), inline=True)
        embed.add_field(name="Kills", value=Formatting.inline(kills), inline=True)
        embed.add_field(name="Deaths", value=Formatting.inline(deaths), inline=True)
        embed.add_field(name="K/D ratio", value=Formatting.inline(str(kd)), inline=True)
        embed.add_field(name="Population", value=Formatting.inline(population), inline=False)
        await BotUtils.send_embed(self, ctx, embed, False)
コード例 #5
0
async def _info_key(self, ctx, sub_command=None):
    discord_user_id = ctx.message.author.id
    discord_server_id = ctx.message.guild.id
    author_icon_url = ctx.message.author.avatar_url
    color = self.bot.gw2_settings["EmbedColor"]
    gw2KeySql = Gw2KeySql(self.bot)
    gw2Api = Gw2Api(self.bot)
    serversSql = ServersSql(self.bot)

    if sub_command is not None and sub_command.lower() == "all":
        rs_all = await gw2KeySql.get_all_user_api_key(discord_user_id)
        if len(rs_all) == 0:
            await BotUtils.send_private_error_msg(
                self, ctx,
                "You dont have an API key registered in this server.\n"
                f"To add or replace an API key use: `{ctx.prefix}gw2 key add <api_key>`\n"
                f"To check your API key use: `{ctx.prefix}gw2 key info`")
        else:
            for x in range(0, len(rs_all)):
                rs_guild_info = await serversSql.get_server_by_id(
                    rs_all[x]["discord_server_id"])
                footer_guild_name = rs_guild_info[0]["server_name"]
                footer_icon_url = rs_guild_info[0]["icon_url"]

                try:
                    api_key = rs_all[x]["key"]
                    is_valid_key = await gw2Api.check_api_key(api_key)
                    if not isinstance(is_valid_key, dict):
                        is_valid_key = "NO"
                        name = "***This API Key is INVALID or no longer exists in gw2 api database***"
                    else:
                        is_valid_key = "YES"
                        name = f"{ctx.message.author}"
                except Exception as e:
                    await BotUtils.send_private_error_msg(self, ctx, e)
                    self.bot.log.error(ctx, e)
                    return

                _embed = discord.Embed(title="Account Name",
                                       description=Formatting.inline(
                                           rs_all[x]["gw2_acc_name"]),
                                       color=color)
                _embed.set_author(name=name, icon_url=author_icon_url)
                _embed.add_field(name="Server",
                                 value=Formatting.inline(
                                     rs_all[x]["server_name"]),
                                 inline=True)
                _embed.add_field(name="Key Name",
                                 value=Formatting.inline(
                                     rs_all[x]["key_name"]),
                                 inline=True)
                _embed.add_field(name="Valid",
                                 value=Formatting.inline(is_valid_key),
                                 inline=True)
                _embed.add_field(name="Permissions",
                                 value=Formatting.inline(
                                     rs_all[x]["permissions"].replace(
                                         ",", "|")),
                                 inline=False)
                _embed.add_field(name="Key",
                                 value=Formatting.inline(rs_all[x]["key"]),
                                 inline=False)
                _embed.set_footer(text=footer_guild_name,
                                  icon_url=footer_icon_url)
                await BotUtils.send_embed(self, ctx, _embed, True)
    elif sub_command is None:
        footer_guild_name = str(ctx.message.guild)
        footer_icon_url = ctx.message.guild.icon_url

        rs = await gw2KeySql.get_server_user_api_key(discord_server_id,
                                                     discord_user_id)
        if len(rs) == 0:
            await BotUtils.send_private_error_msg(
                self, ctx,
                "You dont have an API key registered in this server.\n"
                f"To add or replace an API key use: `{ctx.prefix}gw2 key add <api_key>`\n"
                f"To check your API key use: `{ctx.prefix}gw2 key info`")
        else:
            try:
                api_key = rs[0]["key"]
                is_valid_key = await gw2Api.check_api_key(api_key)
                if not isinstance(is_valid_key, dict):
                    is_valid_key = "NO"
                    name = "***This API Key is INVALID (or no longer exists in gw2 api database)***"
                else:
                    is_valid_key = "YES"
                    name = f"{ctx.message.author}"
            except Exception as e:
                await BotUtils.send_private_error_msg(self, ctx, e)
                self.bot.log.error(ctx, e)
                return

            _embed = discord.Embed(title="Account Name",
                                   description=Formatting.inline(
                                       rs[0]["gw2_acc_name"]),
                                   color=color)
            _embed.set_author(name=name, icon_url=author_icon_url)
            _embed.add_field(name="Server",
                             value=Formatting.inline(rs[0]["server_name"]),
                             inline=True)
            _embed.add_field(name="Key Name",
                             value=Formatting.inline(rs[0]["key_name"]),
                             inline=True)
            _embed.add_field(name="Valid",
                             value=Formatting.inline(is_valid_key),
                             inline=True)
            _embed.add_field(name="Permissions",
                             value=Formatting.inline(
                                 rs[0]["permissions"].replace(",", "|")),
                             inline=False)
            _embed.add_field(name="Key",
                             value=Formatting.inline(rs[0]["key"]),
                             inline=False)
            _embed.set_footer(text=footer_guild_name, icon_url=footer_icon_url)
            await BotUtils.send_embed(self, ctx, _embed, True)
    else:
        raise commands.BadArgument(message="BadArgument")
コード例 #6
0
async def execute_private_msg(self, ctx):
    is_command = True if ctx.prefix is not None else False
    if is_command is False:
        # checking for custom messages
        customMessages = await _check_custom_messages(self, ctx.message)
        if customMessages:
            return

        if BotUtils.is_bot_owner(ctx, ctx.message.author):
            msg = f"Hello master.\nWhat can i do for you?"
            embed = discord.Embed(color=discord.Color.green(), description=f"{Formatting.inline(msg)}")
            await ctx.message.author.send(embed=embed)

            cmd = self.bot.get_command("owner")
            await ctx.author.send(Formatting.box(cmd.help))
        else:
            msg = "Hello, I don't accept direct messages."
            embed = discord.Embed(color=discord.Color.red(), description=f"{Formatting.error_inline(msg)}")
            await ctx.message.author.send(embed=embed)
    else:
        if not (await _check_exclusive_users(self, ctx)):
            return

        blacklistsSql = BlacklistsSql(self.bot)
        bl = await blacklistsSql.get_blacklisted_user(ctx.message.author.id)
        if len(bl) > 0:
            if ctx.message.content.startswith(ctx.prefix):
                servers_lst = []
                reason_lst = []
                for key, value in bl.items():
                    servers_lst.append(value["server_name"])
                    if value["reason"] is None:
                        reason_lst.append("---")
                    else:
                        reason_lst.append(value["reason"])

            servers = '\n'.join(servers_lst)
            if len(reason_lst) > 0:
                reason = '\n'.join(reason_lst)
            msg = "You are blacklisted.\n" \
                  "You cannot execute any Bot commands until your are removed from all servers."
            embed = discord.Embed(title="", color=discord.Color.red(), description=Formatting.error_inline(msg))
            embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url)
            embed.add_field(name="You are blacklisted on following servers:",
                            value=Formatting.inline(servers),
                            inline=True)
            embed.add_field(name="Reason", value=Formatting.inline(reason), inline=True)
            await ctx.message.channel.send(embed=embed)
            return

        msg = "That command is not allowed in direct messages."
        embed = discord.Embed(color=discord.Color.red(), description=f"{Formatting.error_inline(msg)}")
        user_cmd = ctx.message.content.split(' ', 1)[0]
        allowed_DM_commands = self.bot.settings["DMCommands"]

        if allowed_DM_commands is not None:
            if (isinstance(allowed_DM_commands, tuple)):  # more than 1 command, between quotes
                sorted_cmds = sorted(sorted(allowed_DM_commands))
            elif (isinstance(allowed_DM_commands, str)):
                if "," in allowed_DM_commands:
                    sorted_cmds = allowed_DM_commands.split(",")
                else:
                    sorted_cmds = allowed_DM_commands.split()

            for allowed_cmd in sorted_cmds:
                if user_cmd == ctx.prefix + allowed_cmd:
                    await self.bot.process_commands(ctx.message)
                    return

            allowed_cmds = '\n'.join(sorted_cmds)
            embed.add_field(name="Commands allowed in direct messages:",
                            value=f"{Formatting.inline(allowed_cmds)}",
                            inline=False)

        await ctx.message.author.send(embed=embed)