discord.py:从 SQLite3 数据库中读取多个用户时出现问题

discord.py: Problems when reading out several users from a SQLite3 DB

我的 SQLite3 数据库有问题。我的以下代码适用于一个用户。 当用户生日时,我的机器人会检查我的数据库并将其打印出来。

但有时会有两三个用户在同一天过生日。 我如何修改我的代码以便机器人输出所有可能的生日用户?

我尝试用fetchmany (2) 来解决。不幸的是,如果遇到只有一个用户生日的日子,这将失败。

async def bday_check():
    await bot.wait_until_ready()
    while not bot.is_closed():
        channel = bot.get_channel(1234567890)
        bdaydate = datetime.strftime(datetime.now(), '%d.%m.')
        bdaytime = datetime.strftime(datetime.now(), '%H:%M')
        async with aiosqlite.connect("path/to/my.db") as db:
            c = await db.execute('SELECT * FROM user WHERE birthday = ?',(bdaydate,))
            data = await c.fetchone()
            await db.commit()

        if (bdaydate == data[6]) and (bdaytime == '09:00'):
           messages = f'Happy Birthday {data[0]}.'
           embed = discord.Embed(title=f"**Birthday of {data[0]}**", colour=discord.Colour(0xffffff))
           embed.add_field(name="\u200B", value=messages, inline=False)
           embed.set_thumbnail(url=data[2])
           await channel.send(embed=embed)
           await asyncio.sleep(60)
        else:
           await asyncio.sleep(60)
        

bot.loop.create_task(bday_check())

生日数据存储在“用户”数据库的“生日”列中。日期和月份的格式为 dd.mm.

我希望有人能在这里帮助我。

async def bday_check():
await bot.wait_until_ready()
while not bot.is_closed():
    channel = bot.get_channel(1234567890)
    bdaydate = datetime.strftime(datetime.now(), '%d.%m.')
    bdaytime = datetime.strftime(datetime.now(), '%H:%M')
    rows = []
    async with aiosqlite.connect("path/to/my.db") as db:
        offset = 0
        while True:
            c = await db.execute('SELECT * FROM user WHERE birthday = ? limit 1 offset ' + str(offset),(bdaydate,))
            data = await c.fetchone()
            if data is not None:
                rows.append(data)
                offset += 1
            else:
                break
        await db.commit()

    for data in rows:
        if (bdaydate == data[6]) and (bdaytime == '09:00'):
            messages = f'Happy Birthday {data[0]}.'
            embed = discord.Embed(title=f"**Birthday of {data[0]}**", colour=discord.Colour(0xffffff))
            embed.add_field(name="\u200B", value=messages, inline=False)
            embed.set_thumbnail(url=data[2])
            await channel.send(embed=embed)

    await asyncio.sleep(60)

bot.loop.create_task(bday_check())

您是否尝试过使用 .fetchall() 方法?

async for user in db.exec(xxx).fetchall():
    #do something about the user

另外我刚刚注意到,如果您不写入数据库(INSERT、DELETE 或 UPDATE),则不必每次都调用 commit