You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord Bot如何根据?+id指令查询SQL库对应行并返回Embed消息

问题原因

你的现有代码存在3个核心问题:

  • 仅硬编码匹配了?1指令,没有动态提取用户发送的ID参数
  • SQL查询语句错误:将ID字段名id错写为#,还查询了表结构中不存在的end字段
  • 未加WHERE条件过滤指定ID的行,查询返回的是全表所有数据

修正后完整代码

# 先判断消息是否为?开头的查询指令
if message.content.startswith('?'):
    try:
        # 提取?后的内容转为整数ID
        target_id = int(message.content.strip()[1:])
        # 【关键】使用参数化查询过滤指定ID,避免SQL注入风险
        cursor.execute("SELECT id, CATEGORIE, RANK, SCORE FROM test WHERE id = ?", (target_id,))
        row = cursor.fetchone()
        if not row:
            await message.channel.send("未查询到对应ID的数据")
            return
        # 构造Embed消息
        embed = discord.Embed(title='test', color=0x0000FF)
        embed.set_thumbnail(url='https://www.pngkit.com/png/detail/231-2316751_database-database-icon-png.png')
        embed.add_field(name='id', value=row[0], inline=False)
        embed.add_field(name='CATEGORIE', value=row[1], inline=False)
        embed.add_field(name='RANK', value=row[2], inline=False)
        embed.add_field(name='SCORE', value=row[3], 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')
    except ValueError:
        # 处理?后不是数字的异常情况
        await message.channel.send("指令格式错误,正确格式为:?[数字ID]")

注意事项

  • 必须使用参数化查询传递ID参数,禁止直接拼接SQL字符串,防止恶意用户构造SQL注入语句篡改/删除你的数据库数据
  • 若你的数据库不是SQLite,参数占位符可能需要替换为%s(MySQL)或%s/%(name)s(PostgreSQL),根据你使用的数据库驱动调整即可

内容的提问来源于stack exchange,提问作者Phil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 16:45:00