python - 数据库行删除与 Discord.py 集成不删除
问题描述
所以到目前为止,我有一个非常可靠的程序,我正处于这个过程的最后一步。程序的这一部分是当用户键入时!view
,Discord 机器人会在单独的嵌入中显示数据库中的所有租金。然后每个嵌入在其下方都有一个垃圾桶表情符号,当用户单击它时,它会删除 Discord 消息。唯一缺少的部分是,当他们单击垃圾桶表情符号时,我希望它删除 Discord 消息(它确实如此)以及从数据库中删除该行。我在第 1 列中有 id,所以我知道如何做到这一点,但它在最后一个函数中不起作用。这是我所拥有的:
if message.content.startswith('!view'):
rows = cursor.execute("SELECT id, name, renter, duration, price, start, end FROM rental").fetchall()
for x in rows:
embed = discord.Embed(title='Rental #{}'.format(x[0]), color=0x0000FF)
embed.set_thumbnail(url='https://www.pngkit.com/png/detail/231-2316751_database-database-icon-png.png')
embed.add_field(name='Bot Name:', value=x[1], inline=False)
embed.add_field(name='Renter Name:', value=x[2], inline=False)
embed.add_field(name='Rental Duration:', value='{} day(s)'.format(x[3]), inline=False)
embed.add_field(name='Rental Price:', value='${}'.format(x[4]), inline=False)
embed.add_field(name='Start Date:', value=x[5], inline=False)
embed.add_field(name='End Date:', value=x[6], inline=False)
embed.set_footer(icon_url='https://pbs.twimg.com/profile_images/1325672283881484289/oaGtVIOD_400x400.png', text='Created by @Expected')
msg = await message.channel.send(embed=embed)
await msg.add_reaction('\U0001F5D1')
@client.event
async def on_raw_reaction_add(payload):
if payload.user_id == client.user.id:
return
if str(payload.emoji) == '\U0001F5D1':
channel = await client.fetch_channel(payload.channel_id)
message = await channel.fetch_message(payload.message_id)
await message.delete()
cursor.execute("DELETE FROM rental WHERE id={}".format(x[0]))
connection.commit()
该on_raw_reaction_add
函数的倒数第二行是出现问题的地方。在我得到这个半工作代码之前,我刚刚在 for 循环之外进行数据库删除工作cursor.execute("DELETE FROM rental WHERE id={}".format(x[0]))
,因为 x 在 for 循环中它可以工作,但是当我将 x 带出循环并进入另一个函数时显然被读取为未定义的变量。然后我尝试创建rows
一个全局变量并使用rows[0][0]
来删除要删除的 id,但这没有用。没有从数据库中删除任何内容。它也是错误的行,因为x[0]
从该行获取最近添加的行和 id。所以我然后尝试ORDER BY id ASC
在行游标中执行,但无济于事,我得到了 sqlite3.cursor 不可下标的错误。我有点没有想法,也许我的一个想法会奏效,但我只是以错误的方式执行它。我会很感激任何帮助。
解决方案
您可以从嵌入的消息中获取 ID,而不是尝试将查询结果从一个函数范围带到另一个函数范围:
@client.event
async def on_raw_reaction_add(payload):
if payload.user_id == client.user.id:
return
if str(payload.emoji) == '\U0001F5D1':
channel = await client.fetch_channel(payload.channel_id)
message = await channel.fetch_message(payload.message_id)
try:
embed = message.embeds[0]
# Extract number from title after #
rental_id = embed.title.rsplit('#', 1)[1]
except: # Very broad catch for shortness
# Message has no embed or title is not in correct format
return
await message.delete()
cursor.execute("DELETE FROM rental WHERE id={}".format(rental_id))
connection.commit()
推荐阅读
- z3 - 当断言 0 除以 0 为 1 时,z3 返回未知
- python-3.x - 人脸识别库
- c# - OnTriggerEnter 触发太晚了
- python - 用于提取占位符匹配的 RegEx
- excel - 通过 cmd 运行 excel 宏
- android - 如何设置 EditText 菜单项的文本?
- python - Python argparse - 具有“store_true”行为的用户定义操作
- django - Django:获取带注释的值
- java - Spring Boot jdbc 问题。配置数据源失败:未指定“url”属性,无法配置嵌入式数据源
- bash - 如何防止while循环输出与以前的输出冲突?