Discord.js v13 使用better-sqlite3插入数据库时出现交互失败错误
错误原因与修复方案
核心错误:按钮交互未响应
Discord要求所有交互事件必须在3秒内完成响应,你在按钮点击的回调中仅执行了数据库写入操作,没有对按钮触发的i交互对象做任何响应,触发了Discord的超时机制,直接返回"This interaction failed"。
其他潜在错误点
- 数据库插入语句未指定字段:如果
discorddata表的字段顺序、字段数量和你插入的两个值不匹配,会直接抛出数据库错误,阻塞流程导致交互无响应 - 无错误捕获逻辑:数据库操作出现异常时没有兜底处理,同样会导致交互无法正常响应
- 冗余的收集器停止逻辑:你在创建收集器时已经配置了
max:1,收集到1次交互后会自动终止,不需要手动调用collector.stop()
修复后代码
const { MessageActionRow, MessageButton, MessageEmbed } = require('discord.js'); const db = require("better-sqlite3")("../../main.db") module.exports = { name: 'test', description: "test buy", options: [ { name: 'buy', description: 'ซื้อสคริป', type: "SUB_COMMAND", options: [ { name: "link", description: 'ลิ้งซองเงิน 99 บาท', type: "STRING", required: true, } ] }, ], run: async(client, interaction, args) => { if (interaction.options.getSubcommand() === 'buy') { const button = new MessageActionRow() .addComponents( new MessageButton() .setCustomId('confirm') .setLabel('c') .setStyle('SUCCESS'), new MessageButton() .setCustomId('cancel') .setLabel('b') .setStyle('DANGER'), new MessageButton() .setURL('https://www.youtube.com/') .setLabel('a') .setStyle('LINK'), ); const embed = new MessageEmbed() .setColor('#FF0000') .setTitle('ShuShi') .setDescription('info') await interaction.reply({ephemeral: true, embeds: [embed], components: [button] }); const filter = i => i.user.id === interaction.member.id; const collector = interaction.channel.createMessageComponentCollector({ filter, time: 600000, max: 1 }); collector.on('collect', async i => { if (i.customId === 'confirm') { try { // 插入语句指定字段,避免表结构不匹配报错 db.prepare(`INSERT INTO discorddata (id, own) VALUES(:id,:own)`).run({ id: interaction.user.id, own: 'true' }) // 给交互响应,这里用ephemeral回复仅触发用户可见 await i.reply({content: '购买成功', ephemeral: true}) } catch (err) { console.error('数据库写入失败:', err) await i.reply({content: '操作失败,请稍后重试', ephemeral: true}) } } else if (i.customId === 'cancel') { await i.reply({content: '已取消操作', ephemeral: true}) } }) } } }
内容的提问来源于stack exchange,提问作者Farn
相关产品推荐
相关产品推荐

