Пример #1
0
    async def visibility_subcommand(self, ctx, visibility=None):
        # If they don't give a visibility, tell them what their current
        # setting is
        if not visibility:
            db = mysql()
            query = """
                SELECT fc_visibility
                FROM user_preferences
                WHERE user_id = %s;
            """
            results = db.query(query, [ctx.author.id])
            db.close()

            if not results:
                visibility = "private"
            else:
                visibility = results[0]['fc_visibility']

            await ctx.send(embed=lib.embedder.make_embed(
                type="info",
                title=f"Your F.C. Visibility",
                content=
                f"Your friend code visibility is currently set to `{visibility.title()}`"
            ))
            return

        # Normalize it to all lowercase
        visibility = visibility.lower()

        # List of available visibility settings
        visibility_settings = ["public", "private", "hidden"]

        # Check if the given one is within the list. If not, spit out an
        # error embed and return
        if visibility not in visibility_settings:
            await ctx.send(embed=lib.embedder.make_embed(
                type="error",
                title=f"Error Changing F.C. Visibility",
                content=f"{visibility.title()} is not a valid option."))
            return

        db = mysql()
        query = """
            INSERT INTO user_preferences (user_id, fc_visibility)
            VALUES (%s, %s)
            ON DUPLICATE KEY UPDATE fc_visibility = VALUES(fc_visibility);
        """
        db.execute(query, [ctx.author.id, visibility])
        db.close()

        await ctx.send(embed=lib.embedder.make_embed(
            type="success",
            title=f"Changed F.C. Visibility",
            content=
            f"Changed your friend code visibility to `{visibility.title()}`."))
Пример #2
0
    def store_pokemon_images(self, files):
        # Open a connection to the database and set the query up
        db = mysql()
        query = """
            INSERT INTO pokemon (dex, type, isotope, filename, shiny)
            VALUES (%s, %s, %s, %s, %s)
            ON DUPLICATE KEY UPDATE shiny = VALUES(shiny);
        """

        # Iterate through each of the Pokemon picture files and store them in
        # the table
        for file in files:
            data = self.translate_filename(file.path)
            db.execute(
                query,
                [
                    data['dex'],
                    data['type'],
                    data['isotope'],
                    data['filename'],
                    data['shiny'],
                ],
            )

        # Finally close the connection
        db.close()
Пример #3
0
def get_prefix(client, message):
    # If it is a DM from a user, use these. "" needs to be on the very end of
    # the previous prefixes won't work.
    if isinstance(message.channel, discord.DMChannel):
        return ("!", ".", "?", "$", "%", ":", ";", ">", "")

    # Link the prefixes variable in this function to the global one, so it
    # all updates
    global prefixes

    # If their prefix isn't in the list for some reason, re-run
    if message.guild.id not in prefixes:
        db = mysql()
        query = """
            SELECT
                guild,
                command_prefix

            FROM guild_preferences;
        """
        prefix_list = db.query(query)
        db.close()
        for prefix in prefix_list:
            prefixes[prefix['guild']] = prefix['command_prefix']

    # Return their prefix from the prefixes dictionary
    return commands.when_mentioned_or(*prefixes[message.guild.id])(client,
                                                                   message)
Пример #4
0
    async def listall_subcommand(self, ctx):
        # This MySQL statement is janky, but it works. Plus it is just an
        # admin command, so it doesn't really matter
        db = mysql()
        query = """
            SELECT
                fc.user_id AS user_id,
                GROUP_CONCAT(CONCAT(fc.identifier, ': ', LPAD(fc.code, 12, '0')) SEPARATOR '\n') AS information
            FROM friend_codes fc
            LEFT JOIN user_preferences up ON up.user_id = fc.user_id
            WHERE up.home_guild = %s
            GROUP BY fc.user_id
            ORDER BY fc.identifier ASC;
        """
        results = db.query(query, [ctx.guild.id])
        db.close()

        # For every result returned, send an embed with the friend code and
        fields = []
        for result in results:
            # This is here in case someone leaves the guild, but it is still
            # set to their home guild
            if ctx.guild.get_member(result['user_id']):
                user_name = ctx.guild.get_member(
                    result['user_id']).display_name
            else:
                user_name = self.client.get_user(result['user_id'])

            fields.append((user_name, result['information'], True))

        await ctx.send(embed=lib.embedder.make_embed(
            type="info",
            title=f"F.C. List for {ctx.guild.name}",
            fields=fields))
Пример #5
0
 def __init__(self, userid, itemid):
     if self.itemcf.get(int(itemid)):
         self.msql = mysql.mysql()
         self.userid = str(userid)
         self.itemid = int(itemid)
     else:
         raise ValueError("道具未定义")
Пример #6
0
    async def sethome(self, ctx):
        db = mysql()
        query = """
            INSERT INTO user_preferences (user_id, home_guild)
            VALUES (%s, %s)
            ON DUPLICATE KEY UPDATE home_guild = VALUES(home_guild);
        """
        db.execute(query, [ctx.author.id, ctx.guild.id])
        db.close()

        delete_delay = 120
        message = await ctx.send(embed=lib.embedder.make_embed(
            type="info",
            title="Home Server Set!",
            content=f"Your home server has been set to `{ctx.guild.name}`.\
                \n\nThe \"home server\" is used for leaderboards and other server specific commands.\
                \n\nTo change this later, just run `{ctx.prefix}sethome` in your main server.",
            footer=f"This message will self-destruct in {delete_delay} seconds"
        ), delete_after=delete_delay)

        expire_time = datetime.now() + timedelta(seconds=delete_delay)
        self.temp_redis.set(
            str(uuid.uuid4()),
            f"{ctx.channel.id},{message.id},{expire_time}",
            0
        )
Пример #7
0
    async def list_subcommand(self, ctx):
        db = mysql()
        query = """
            SELECT
                fc.identifier AS identifier,
                fc.code AS code
            FROM friend_codes fc
            WHERE fc.user_id = %s
            ORDER BY fc.identifier ASC;
        """
        results = db.query(query, [ctx.author.id])
        db.close()

        # For every result returned, send an embed with the friend code and
        fields = []
        for result in results:
            fields.append((result['identifier'], result['code'], True))

        delete_delay = 60
        message = await ctx.send(embed=lib.embedder.make_embed(
            type="info",
            title=f"F.C. List for {ctx.author.display_name}",
            fields=fields,
            footer=f"This message will self-destruct in {delete_delay} seconds"
        ),
                                 delete_after=delete_delay)

        expire_time = datetime.now() + timedelta(seconds=delete_delay)
        self.temp_redis.set(str(uuid.uuid4()),
                            f"{ctx.channel.id},{message.id},{expire_time}", 0)
Пример #8
0
    def get_pokemon_data(self, input):
        db = mysql()
        query = """
            SELECT
                pkmn.dex AS 'dex',
                name.english AS 'name',
                pkmn.type AS 'type',
                pkmn.isotope AS 'isotope',
                pkmn.filename AS 'filename',
                pkmn.shiny AS 'shiny'
            FROM pokemon pkmn
            LEFT JOIN pokemon_names name on name.dex = pkmn.dex
            WHERE (
                pkmn.dex = %s OR
                name.chinese = %s OR
                name.english = %s OR
                name.french = %s OR
                name.german = %s OR
                name.italian = %s OR
                name.japanese = %s OR
                name.korean = %s OR
                name.portuguese = %s OR
                name.spanish = %s OR
                name.thai = %s
            );
        """
        db.execute(query, [input, input, input, input, input, input, input, input, input, input, input])
        results = db.fetchall()
        db.close()

        return results
Пример #9
0
    async def shiny_subcommand_group(self, ctx):
        # If a subcommand is given, just skip anything else from this command
        if ctx.invoked_subcommand is not None:
            return

        # WIP need to add in an option for global and guild specific. Right now
        # it is just global
        db = mysql()
        query = """
            SELECT
                us.user_id,
                home_guild,
                SUM(us.count) AS total
            FROM user_shinies us
            JOIN user_preferences up ON up.user_id = us.user_id
            WHERE home_guild = %s
            GROUP BY user_id
            ORDER BY total DESC;
        """
        results = db.query(query, [ctx.guild.id])
        db.close()

        if not results:
            await ctx.send(embed=lib.embedder.make_embed(
                type="warning",
                title=f"{ctx.guild.name} Shiny Leaderboard",
                content=
                f"Sadly `{ctx.guild.name}` doesn't have any users set as their main server.",
            ))
            return

        columns = {"left": "", "right": ""}
        for result in results[:10]:
            # This is here in case someone on the leaderboard leaves the context
            # guild, but it is still set to their main guild
            if ctx.guild.get_member(result['user_id']):
                user_name = ctx.guild.get_member(
                    result['user_id']).display_name
            else:
                user_name = self.client.get_user(result['user_id'])

            columns['left'] += f"{user_name}\n"
            columns['right'] += f"{result['total']}\n"

        rank = self.find_user_place(ctx.author.id, results)

        fields = [
            ("Name", columns['left'], True),
            ("Count", columns['right'], True),
            lib.embedder.separator,
            ("Your Rank:", rank, True),
            ("Your Count", results[rank - 1]['total'], True),
        ]

        await ctx.send(embed=lib.embedder.make_embed(
            type="info",
            title=f"{ctx.guild.name} Shiny Leaderboard",
            fields=fields,
        ))
Пример #10
0
 def init(self):
     self.currentDir = sys.path[0]
     self.logPath = configApi.LOG_PATH
     self.log = mylog.mylog(
         os.path.join(self.currentDir, self.logPath,
                      self.scriptName + '.log'))
     self.apiPre = "report_api_"
     self.confTable = configDb.API_CONFIG_TABLE
     self.dbData = db.mysql(configDb.MYSQL_MOBGI_DATA)
Пример #11
0
 def store_commit_hash(self, hash):
     db = mysql()
     query = """
         INSERT INTO checks (name, value)
         VALUES (%s, %s)
         ON DUPLICATE KEY UPDATE value = VALUES(value);
     """
     db.execute(query, ['pogo_assets_commit_hash', hash])
     db.close()
Пример #12
0
 def initDb(self, conf):
     try:
         conn_key = self.md5(str(conf))
         if self.db_conn.has_key(
                 conn_key) is False or self.db_conn[conn_key] == None:
             self.db_conn[conn_key] = db.mysql(conf)
         return self.db_conn[conn_key]
     except Exception, e:
         raise Exception("db connect failed:" + str(e))
Пример #13
0
async def on_guild_remove(guild):
    print(f"Left guild: {guild.id} / {guild.name}")

    # Removes the preferences line for a guild
    db = mysql()
    query = """
        DELETE FROM guild_preferences
        WHERE guild = %s;
    """
    db.execute(query, [guild.id])
    db.close()
Пример #14
0
async def on_connect():
    db = mysql()

    # Whenever the bot connects up to Discord double check that at least the
    # default preferences are set for each guild it is in
    for guild in client.guilds:
        set_default_preferences(db, guild.id)

    db.close()

    print("Bot Connected")
Пример #15
0
 def __init__(self, username=None, userid=None):
     '''初始化'''
     # 通过username字段初始化user对象
     if username:
         self.username = username
         self.msql = mysql.mysql()
         self.__getUserCreateUserid()
         if not self.userid:
             print("用户最初创建")
             self.createtime = self.logintim = ctime()
             return
         else:
             print(self.userid, "这里应该得到用户id")
             self.__getUserPasswd()
             self.uploadUserinfo()
     elif userid:
         self.userid = int(userid)
         self.msql = mysql.mysql()
         self.__getUsername()
         self.__getUserPasswd()
         self.__getUserPasswd()
         self.uploadUserinfo()
Пример #16
0
    async def list_subcommand(self, ctx, target: Optional[discord.Member]):
        # If no target is given, use the user who wrote the command
        target = target or ctx.author

        db = mysql()
        query = """
            SELECT
                name.english AS name,
                user_shiny.dex AS dex,
                user_shiny.type AS type,
                user_shiny.isotope AS isotope,
                user_shiny.count AS count
            FROM user_shinies user_shiny
            LEFT JOIN pokemon_names name on name.dex = user_shiny.dex
            WHERE
                user_shiny.user_id = %s
                AND user_shiny.count > 0
            ORDER BY name.english;
        """
        results = db.query(query, [target.id])
        db.close()

        # If the user doesn't have any shiny Pokemon in their list, tell them
        # that
        if not results:
            await ctx.send(embed=lib.embedder.make_embed(
                type="error",
                title="Shiny Checklist",
                content=f"Unfortunately {target.display_name} doesn't have \
any Pokémon in your shiny list...",
            ))

        else:
            total_count = 0
            output = ""
            for result in results:
                output += f"{result['name']}: {result['count']}\n"
                total_count += result['count']

            fields = [
                ("Total:", total_count, False),
            ]

            await ctx.send(embed=lib.embedder.make_embed(
                type="info",
                title=f"{target.display_name}'s Shiny List:",
                content=output,
                fields=fields,
            ))
Пример #17
0
    async def shiny_subcommand_global(self, ctx):
        # WIP need to add in an option for global and guild specific. Right now
        # it is just global
        db = mysql()
        query = """
            SELECT
                user_id,
                SUM(count) AS total
            FROM user_shinies
            GROUP BY user_id
            ORDER BY total DESC;
        """
        results = db.query(query)
        db.close()

        if not results:
            await ctx.send(embed=lib.embedder.make_embed(
                type="error",
                title="Global Shiny Leaderboard",
                content=
                "Apparently no one has any shiny Pokémon in their checklist?",
            ))
            return

        columns = {"left": "", "right": ""}
        for result in results[:25]:
            columns['left'] += f"{self.client.get_user(result['user_id'])}\n"
            columns['right'] += f"{result['total']}\n"

        rank = self.find_user_place(ctx.author.id, results)

        fields = [
            ("Name:", columns['left'], True),
            ("Count:", columns['right'], True),
            lib.embedder.separator,
            ("Your Rank:", rank, True),
            ("Your Count", results[rank - 1]['total'], True),
        ]

        await ctx.send(embed=lib.embedder.make_embed(
            type="info",
            title="Global Shiny Leaderboard",
            fields=fields,
        ))
Пример #18
0
    async def missing_pokemon_form_names(self):
        """Sends a DM when there are forms that need names

        Creates a neat little ASCII table with the list of all of the Pokemon
        that are needing names for their forms.
        """
        db = mysql()
        query = """
            SELECT pkmn.dex AS 'dex',
                name.english AS 'english',
                pkmn.type AS 'type',
                pkmn.isotope AS 'isotope',
                pkmn.filename AS 'filename'

            FROM pokemon pkmn
            LEFT JOIN pokemon_names name ON name.dex = pkmn.dex
            LEFT JOIN pokemon_form_names form_name
                ON form_name.dex = pkmn.dex
                AND form_name.type = pkmn.type

            WHERE pkmn.type != "00"
            AND form_name.name IS NULL
            AND pkmn.dex != 327;
        """  # Ignore Spinda types, since they are dumb
        results = db.query(query)
        db.close()

        # If no results were returned, just skip everything below
        if not results:
            return

        # Set up and generate the ASCII table
        table = PrettyTable()
        table.field_names = results[0].keys()
        for result in results:
            table.add_row(result.values())

        # Finally print out the table in a codeblock and DM it to me
        owner_user = self.client.get_user(self.client.owner_id)
        await owner_user.send(embed=lib.embedder.make_embed(
            type="info",
            title="Missing Pokemon Form Information",
            content=f"```{table}```"))
Пример #19
0
async def changeprefix(ctx, prefix):
    # If someone tries to set more than a single character
    if len(prefix) > 1:
        ctx.send("Command prefix can only be a single character")
        return

    # Store the character in the preferences table
    db = mysql()
    query = """
        UPDATE guild_preferences
        SET command_prefix = %s
        WHERE guild = %s;
    """
    db.execute(query, [prefix, ctx.guild.id])
    db.close()

    # Set the local prefix dictionary to blank
    global prefixes
    prefixes = {}

    # Then finally send the user a message saying that it is changed
    await ctx.send(f"Prefix has been changed to: {prefix}")
Пример #20
0
    async def remove_subcommand(self, ctx, identifier):
        db = mysql()
        query = """
            DELETE FROM friend_codes
            WHERE user_id = %s
            AND identifier = %s;
        """
        db.execute(query, [ctx.author.id, identifier])
        count = db.cursor.rowcount
        db.close()

        if count == 0:
            pass
            await ctx.send(embed=lib.embedder.make_embed(
                type="error",
                title=f"Error Removing Friend Code",
                content=f"{identifier} not found on your list."))

        else:
            await ctx.send(embed=lib.embedder.make_embed(
                type="success",
                title=f"Removed Friend Code",
                content=f"Removed {identifier} from your list."))
Пример #21
0
    def check_commit_hash(self, hash):
        # Grab the current commit hash that we have stored
        db = mysql()
        query = """
            SELECT value
            FROM checks
            WHERE name = %s;
        """
        results = db.query(query, ['pogo_assets_commit_hash'])
        db.close()

        # If the value doesn't doesn't exist in the checks table, add it and say
        # that its a new commit
        if len(results) == 0:
            self.store_commit_hash(hash)
            return True

        # If the grabbed commit hash equals the one that we have stored, it's
        # not a new commit
        if results[0]['value'] == hash:
            return False

        # Otherwise just assume it's a new commit, it shouldn't hurt anything
        return True
Пример #22
0
    async def setmain_subcommand(self, ctx, identifier):
        db = mysql()
        # Remove any friend codes that the user has set as their main
        query = """
            UPDATE friend_codes
            SET main = 0
            WHERE user_id = %s;
        """
        db.execute(query, [ctx.author.id])

        # Then set the new one
        query = """
            UPDATE friend_codes
            SET main = 1
            WHERE user_id = %s
            AND identifier = %s;
        """
        db.execute(query, [ctx.author.id, identifier])
        db.close()

        await ctx.send(embed=lib.embedder.make_embed(
            type="success",
            title="Changed Main Friend Code",
            content=f"Changed your main friend code to {identifier}."))
Пример #23
0
 def initDb(self, conf):
     try:
         return db.mysql(conf)
     except Exception, e:
         self.error("db connect failed:" + str(conf))
         return None
Пример #24
0
    async def remove_subcommand(self, ctx, pokemon, count = 1):
        # Just a couple of sanity checks, since I know someone will test this at some point
        if count == 0:
            await ctx.send(embed = lib.embedder.make_embed(
                type = "error",
                title = "Shiny Checklist",
                content = "You can't remove 0 of something.",
            ))
            return
        elif count < 0:
            count = count * -1

        pokemon_data = self.get_pokemon_data(pokemon)
        if not pokemon_data:
            await ctx.send(embed = lib.embedder.make_embed(
                type = "warning",
                title = "Shiny Checklist",
                content = f"Pokémon `{pokemon}` doesn't exist",
            ))
            return
        elif len(pokemon_data) > 1: # WIP Not implemented right now
            await ctx.send(embed = lib.embedder.make_embed(
                type = "warning",
                title = "Shiny Checklist",
                content = "Pokémon with multiple forms, costumes, or variants aren't supported right now.",
            ))
            return
        else:
            db = mysql()
            query = """
                SELECT count
                FROM user_shinies
                WHERE
                    user_id = %s
                    AND dex = %s
                    AND type = %s
                    AND isotope = %s;
            """
            db.execute(query, [
                ctx.message.author.id,
                pokemon_data[0]['dex'],
                pokemon_data[0]['type'],
                pokemon_data[0]['isotope'],
            ])

            # Check if the user has any of the Pokemon in their list. If they
            # don't, tell them, close the DB and then return.
            #
            # Also check if they have the amount they want to remove, if not,
            # set it to what they have
            result = db.fetchone()
            if (not result) or (result['count'] == 0):
                db.close()
                await ctx.send(embed = lib.embedder.make_embed(
                    type = "warning",
                    title = "Shiny Checklist",
                    content = f"You don't have any shiny {pokemon_data[0]['name']} in your list to remove",
                    thumbnail = self.generate_image_link(pokemon_data[0], shiny = True)
                ))
                return
            elif result['count'] < count:
                count = result['count']

            # If they do however, update the count
            query = """
                UPDATE user_shinies
                SET count = count - %s
                WHERE
                    user_id = %s
                    AND dex = %s
                    AND type = %s
                    AND isotope = %s;
            """
            db.execute(query, [
                count,
                ctx.message.author.id,
                pokemon_data[0]['dex'],
                pokemon_data[0]['type'],
                pokemon_data[0]['isotope'],
            ])
            db.close()

            await ctx.send(embed = lib.embedder.make_embed(
                type = "success",
                title = "Shiny Checklist",
                content = f"Removed {count} shiny {pokemon_data[0]['name']} from your list",
                thumbnail = self.generate_image_link(pokemon_data[0], shiny = True)
            ))
Пример #25
0
    async def add_subcommand(self, ctx, pokemon, count = 1):
        # Check that the user has their home guild set. If not, then set it.
        # Check if this was invoked from a guild
        if not isinstance(ctx.channel, discord.DMChannel):
            db = mysql()
            query = """
                SELECT
                    user_id,
                    home_guild
                FROM user_preferences
                WHERE user_id = %s;
            """
            results = db.query(query, [ctx.author.id])
            db.close()

            # If nothing was returned, then invoke the sethome command
            if not results or not results[0]['home_guild']:
                await ctx.invoke(self.client.get_command("sethome"))

        # Just a couple of sanity checks, since I know someone will test this at some point
        if count == 0:
            await ctx.send(embed = lib.embedder.make_embed(
                type = "error",
                title = "Shiny Checklist",
                content = "You can't add 0 of something.",
            ))
            return
        elif count < 0:
            await ctx.send(embed = lib.embedder.make_embed(
                type = "error",
                title = "Shiny Checklist",
                content = "There is no such thing as negative Pokémon. At least... not yet.",
            ))
            return

        # Grab the list of Pokemon for the given name or dex number
        pokemon_data = self.get_pokemon_data(pokemon)

        # If no results are returned, tell the user that that Pokemon doesn't
        # exist.
        # If there is more than one returned value... right now it's a WIP and needs to be dealt with
        # If there is only one response returned than work for it
        if not pokemon_data:
            await ctx.send(embed = lib.embedder.make_embed(
                type = "warning",
                title = "Shiny Checklist",
                content = f"Pokémon `{pokemon}` doesn't exist",
            ))
            return
        elif len(pokemon_data) > 1: # WIP Not implemented right now
            await ctx.send(embed = lib.embedder.make_embed(
                type = "warning",
                title = "Shiny Checklist",
                content = "Pokémon with multiple forms, costumes, or variants aren't supported right now.",
            ))
            return
        else:
            db = mysql()
            query = """
                INSERT INTO user_shinies (user_id, dex, type, isotope, count)
                VALUES (%s, %s, %s, %s, %s)
                ON DUPLICATE KEY UPDATE count = count + VALUES(count);
            """
            db.execute(query, [
                ctx.message.author.id,
                pokemon_data[0]['dex'],
                pokemon_data[0]['type'],
                pokemon_data[0]['isotope'],
                count,
            ])
            db.close()

            # Tell the user that they added the Pokemon successfully to their list
            await ctx.send(embed = lib.embedder.make_embed(
                type = "success",
                title = "Shiny Checklist",
                content = f"Added {'a' if count == 1 else count} shiny {pokemon_data[0]['name']} to your list",
                thumbnail = self.generate_image_link(pokemon_data[0], shiny = True)
            ))
Пример #26
0
 def __init__(self):
     self.dbhousead = mysql(configDb.MYSQL_MOBGI_HOUSEAD)
     poolr = redis.ConnectionPool(host=configRedis.REDIS_ADX["host"],
                                  port=configRedis.REDIS_ADX["port"])
     self.r = redis.Redis(connection_pool=poolr)
Пример #27
0
async def on_guild_join(guild):
    print(f"Joined guild: {guild.id} / {guild.name}")
    # Set the default preferences for a guild upon joining
    db = mysql()
    set_default_preferences(db, guild.id)
    db.close()
Пример #28
0
 def init(self):
     self.adsId = self.scriptName
     self.adsTable = configApi.ADS_TABLE
     self.dbConf = db.mysql(configDb.MYSQL_MOBGI_DATA)
     self.dbOldConf = db.mysql(configDb.MYSQL_MOBGI_DATA_OLD)
Пример #29
0
    async def friendcode_group(self,
                               ctx,
                               target: Optional[discord.Member],
                               filter=None):
        # If no target is given, use the user who wrote the command
        target = target or ctx.author

        db = mysql()
        query = """
            SELECT
                up.home_guild AS home_guild,
                up.fc_visibility AS visibility,
                fc.identifier AS identifier,
                fc.code AS code,
                fc.main AS main
            FROM friend_codes fc
            LEFT JOIN user_preferences up ON up.user_id = fc.user_id
            WHERE fc.user_id = %s
            AND fc.identifier LIKE %s
            ORDER BY fc.main DESC, fc.identifier ASC;
        """
        results = db.query(query, [target.id, f"%{filter if filter else ''}%"])
        db.close()

        # Check if the target has any friend codes on file. If not, send a
        # warning embed and return.
        if not results:
            if filter:
                await ctx.send(embed=lib.embedder.make_embed(
                    type="warning",
                    title=f"{target.display_name}'s Friend Codes",
                    content=
                    f"No friend codes were found for `{target.display_name}` with `{filter}` in it"
                ))
                return
            else:
                await ctx.send(embed=lib.embedder.make_embed(
                    type="warning",
                    title=f"{target.display_name}'s Friend Codes",
                    content=
                    f"Sadly `{target.display_name}` doesn't have any friend codes stored."
                ))
                return

        # Check if the user's visibility is hidden. If so, give an error and
        # return.
        if target.id != ctx.author.id and results[0]['visibility'] == "hidden":
            await ctx.send(embed=lib.embedder.make_embed(
                type="error",
                title=f"{target.display_name}'s Friend Codes",
                content=
                f"`{target.display_name}` has their friend code visibility set to hidden. Only they can send them."
            ))
            return

        # Check if they have a home server set. If not, give an error and
        # return.
        if target.id != ctx.author.id and not results[0]['home_guild']:
            await ctx.send(embed=lib.embedder.make_embed(
                type="error",
                title=f"{target.display_name}'s Friend Codes",
                content=
                f"`{target.display_name}` doesn't have a home server set.",
                footer=f"They need to run !sethome"))
            return

        # Check if the target is the original author,
        # if not then check if their visibility is private,
        # if it is then check if this is their home guild.
        # If it isn't, send an error embed and return.
        if (target.id != ctx.author.id
                and (not results[0]['visibility']
                     or results[0]['visibility'] == "private")
                and results[0]['home_guild'] != ctx.guild.id):
            await ctx.send(embed=lib.embedder.make_embed(
                type="error",
                title=f"{target.display_name}'s Friend Codes",
                content=
                f"This is not `{target.display_name}`'s home server and their visibility is set to private."
            ))
            return

        # Send the instructions message and store the info in Redis for cleanup
        # later if needed
        delete_delay = 60
        message = await ctx.send(embed=lib.embedder.make_embed(
            type="info",
            title=f"F.C.'s for {target.display_name}",
            content=f"The friend codes below are for `{target.display_name}`.\
                \n\nThe codes below will auto-delete in 15 minutes. \
                \n\nYou can copy-paste the message below right into Pokemon \
                GO's Add Friend page, since Pokemon GO only uses the first \
                12 characters in a paste to the Add Friend page.",
            footer=f"This message will self-destruct in {delete_delay} seconds"
        ),
                                 delete_after=delete_delay)

        expire_time = datetime.now() + timedelta(seconds=delete_delay)
        self.temp_redis.set(str(uuid.uuid4()),
                            f"{ctx.channel.id},{message.id},{expire_time}", 0)

        # For every result returned, send a message with the friend code. Also
        # store the info in Redis for cleanup later if needed
        delete_delay = 60 * 15
        for result in results:
            code = str(result['code']).zfill(12)
            message = await ctx.send(
                f"{code} <- {result['identifier']}{' (main)' if result['main'] else ''}",
                delete_after=delete_delay)

            expire_time = datetime.now() + timedelta(seconds=delete_delay)
            self.temp_redis.set(
                str(uuid.uuid4()),
                f"{ctx.channel.id},{message.id},{expire_time}", 0)
Пример #30
0
    async def add_subcommand(self,
                             ctx,
                             input_identifier,
                             code,
                             code_part2="",
                             code_part3=""):
        # Check that the user has their home guild set. If not, then set it.
        # Check if this was invoked from a guild
        if not isinstance(ctx.channel, discord.DMChannel):
            db = mysql()
            query = """
                SELECT
                    user_id,
                    home_guild
                FROM user_preferences
                WHERE user_id = %s;
            """
            results = db.query(query, [ctx.author.id])
            db.close()

            # If nothing was returned, then invoke the sethome command
            if not results or not results[0]['home_guild']:
                await ctx.invoke(self.client.get_command("sethome"))

        # This and the additional two code "parts" are for if the user
        # uses a separated version of the friend code.
        if code_part2 != "" or code_part3 != "":
            code = code + code_part2 + code_part3

        # Checks if the identifier if over 16 characters long. If so then send
        # an error embed and return.
        if len(input_identifier) > 16:
            await ctx.send(embed=lib.embedder.make_embed(
                type="error",
                title=f"Error Adding Friend Code",
                content=
                "The trainer name / identifier that you gave is longer than the maximum character limit."
            ))
            return

        # Check that the friend code was numbers and that it was 12 digits
        # long, if it isn't then send an error embed and return
        if not code.isdigit():
            await ctx.send(embed=lib.embedder.make_embed(
                type="error",
                title=f"Error Adding Friend Code",
                content="The given friend code isn't all numbers."))
            await ctx.send_help(str(ctx.command))
            return

        if len(code) != 12:
            await ctx.send(embed=lib.embedder.make_embed(
                type="error",
                title=f"Error Adding Friend Code",
                content="The given friend code isn't 12 digits long."))
            await ctx.send_help(str(ctx.command))
            return

        db = mysql()
        query = """
            INSERT INTO friend_codes (user_id, identifier, code, updated)
            VALUES (%s, %s, %s, NOW())
            ON DUPLICATE KEY UPDATE
                code = VALUES(code),
                updated = VALUES(updated);
        """
        db.execute(query, [ctx.message.author.id, input_identifier, code])
        db.close()

        # Set up the output text ahead of time so that we can add in info if
        # needed.
        output = f"Added friend code `{code}` for `{input_identifier}`."

        # Delete the user's command message, for privacy reasons
        if not isinstance(ctx.message.channel, discord.DMChannel):
            await ctx.message.delete()
            output += "\n\nYour message was deleted for privacy reasons."

        delete_delay = 120
        message = await ctx.send(embed=lib.embedder.make_embed(
            type="success",
            title=f"Added Friend Code",
            content=output,
            footer=f"This message will self-destruct in {delete_delay} seconds"
        ),
                                 delete_after=delete_delay)

        expire_time = datetime.now() + timedelta(seconds=delete_delay)
        self.temp_redis.set(str(uuid.uuid4()),
                            f"{ctx.channel.id},{message.id},{expire_time}", 0)