Discord.js实现:搜索后发送用户选定的YouTube视频链接
Discord机器人YouTube搜索反应选择实现方案
核心思路
发送包含搜索结果的Embed消息后,给消息添加对应数量的数字表情反应,通过监听用户的反应操作,匹配对应的视频链接并发送。
具体实现步骤
步骤1:给搜索结果消息添加反应
假设你已获取到YouTube搜索结果数组(如searchResults,每个元素含视频标题、链接等),发送Embed后,给消息添加对应数量的数字表情(建议最多5个,避免杂乱)。
以discord.js为例的代码片段:// 发送做好的搜索结果Embed const sentMsg = await interaction.channel.send({ embeds: [yourEmbed] }); // 定义要使用的数字表情 const reactionEmojis = ['1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣']; // 给消息添加对应数量的反应 for (let i = 0; i < Math.min(searchResults.length, 5); i++) { await sentMsg.react(reactionEmojis[i]); }步骤2:监听反应并处理用户选择
使用反应收集器监听该消息的反应,仅允许发起命令的用户触发,设置超时时间(如60秒)。当用户点击反应时,匹配对应索引的视频链接并发送。
代码片段:// 过滤条件:仅命令发起者的有效反应 const filter = (reaction, user) => { return user.id === interaction.user.id && reactionEmojis.includes(reaction.emoji.name); }; // 创建反应收集器,设置60秒超时 const collector = sentMsg.createReactionCollector({ filter, time: 60000 }); // 监听收集到反应的事件 collector.on('collect', (reaction) => { const selectedIndex = reactionEmojis.indexOf(reaction.emoji.name); const targetVideo = searchResults[selectedIndex]; // 发送选中的视频链接 interaction.channel.send(`选中视频:${targetVideo.title}\n链接:${targetVideo.url}`); // 停止收集并移除所有反应 collector.stop(); sentMsg.reactions.removeAll(); }); // 监听收集器结束事件(超时未选择) collector.on('end', (collected) => { if (collected.size === 0) { interaction.channel.send('选择超时,请重新发起搜索命令。'); sentMsg.reactions.removeAll(); } });关键注意事项
- 严格限定触发反应的用户为命令发起者,避免无关操作干扰
- 合理设置超时时间,防止消息长期挂着反应
- 控制搜索结果数量在5个以内,提升交互体验
- 若使用其他Discord开发库(如discord.py),逻辑一致:发送消息→添加反应→监听反应→匹配结果发送
内容的提问来源于stack exchange,提问作者BlackDelta
相关产品推荐
相关产品推荐

