当我将一个项目附加到一个包含现有项目的列表中时,它只是覆盖它并替换现有项目

2024-05-15 23:11:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题是,当我使用一次命令时,它会给我一条鱼,但如果我再次使用,它会用最新的鱼替换以前的鱼。它应该将自己添加到列表中,而不是覆盖它。下面是清单。每次我使用该命令时,都会在该列表中添加一条鱼

async def fish(ctx, *, msg: str):
    level = 1
    storage = []
    cash = 0
    kind = []
    fishes = 0

    name = ctx.author.name
    guild_id = ctx.guild.id
    user_id = ctx.author.id
    large_chance = ['Carp', 'Salmon', 'Frog']
    medium_chance = ['Catfish', 'Eel', 'Large Bass']
    small_chance = ['Angelfish', 'Blobfish', 'Shark']

    cursor.execute("SELECT fish FROM fishing WHERE user_id = %s AND guild_id = %s",
                   (user_id, guild_id))
    result1 = cursor.fetchone()
    if result1 is None:
        cursor.execute(
            "INSERT INTO fishing (name, user_id, guild_id, fish, kind) VALUES (%s, %s, %s, %s, %s)",
            (name, user_id, guild_id, fishes, kind))
        conn.commit()
    elif result1 is not None:
        if msg == 'fish':
            y = random.randint(0, 100)
            if y >= 30:
                small = random.choice(large_chance)
                embed = discord.Embed(title='Fishing Game',
                                      color=ctx.author.color)
                embed.set_thumbnail(url=ctx.author.avatar_url)
                embed.add_field(name='You caught a common fish', value=f'You caught a {small}')
                embed.add_field(name="Worth:", value="$5")
                await ctx.send(embed=embed)
                kind.append(small)
                fishes = result1[0] + 1
                await ctx.send(kind)
                cursor.execute("UPDATE fishing SET kind = %s, fish = %s WHERE user_id = %s AND guild_id = %s",
                               (kind, fishes, user_id, guild_id))
                conn.commit()

Tags: nameidexecuteembedcursorauthorsmallctx
2条回答

每次运行该命令时都会重新定义kind。相反,尝试从正在使用的数据库中读取当前用户kind,并将其设置为要使用的变量

cursor.execute("SELECT kind FROM fishing WHERE user_id = %s AND guild_id = %s",
                   (user_id, guild_id))
kind = cursor.fetchone()

用这个代替kind=[]应该很有希望

这里有几个问题。第一个是@Silas Hayes Williams提到的,即每次运行函数时都将kind重置为空列表。所以你一次只能吃一种鱼。第二个问题是在文本字段中存储列表。关于这一切意味着什么,请参见psycopg2文档中的List。简短的版本是:

['Carp'] 
# Becomes
'{Carp}'

在检索时,除非执行以下操作:

cur.execute("select kind::varchar[] from fishing")

这将导致返回一个列表,供您使用。最后一件事是您必须在上面的代码中放入一些代码,为用户(per@Silas Hayes Williams)检索现有的kind,并使用这些代码附加到

相关问题 更多 >