Discord.js开发hug命令 如何实现随机GIF嵌入embed消息发送
Discord机器人hug指令随机GIF实现方案
核心实现逻辑
- 先把所有要使用的抱抱GIF资源(本地路径/公网直链都可)存入一个数组
- 利用
Math.random()生成随机下标从数组中取出单个GIF资源 - 替换原有固定GIF路径即可
完整修改后代码
const Discord = require("discord.js"); const { UserAgent } = require("discord.js/src/util/Constants"); const ytdl = require("ytdl-core"); const Client = new Discord.Client({ intents : [ Discord.Intents.FLAGS.GUILDS, Discord.Intents.FLAGS.GUILD_MESSAGES ] }); const prefix ="<"; // 在此处填入你所有的抱抱GIF资源,可替换为本地路径或公网GIF直链 const hugGifs = [ "gif1.gif", "gif2.gif", "gif3.gif", "gif4.gif" ]; Client.on("ready", () => { console.log("bot opérationnel") }); Client.on("message", message => { if (message.author.bot) return; if (message.content.startsWith (prefix + "hug")){ let mention = message.mentions.members.first(); if(mention === undefined){ message.channel.send("u have to hug someone who actually exists"); } else { // 随机从hugGifs数组中取出一个GIF资源 const randomGif = hugGifs[Math.floor(Math.random() * hugGifs.length)]; const embed = new Discord.MessageEmbed() .setColor("DARK_RED") .setTitle(":hugging: " + mention.displayName + " recieved a hug from " + message.author.username + " !") .setImage(randomGif); message.channel.send({embeds: [embed]}); } } }); Client.login("token");
补充说明
- 你可以根据需求任意增减
hugGifs数组内的资源,代码会自动适配数组长度生成随机下标,不需要额外修改逻辑- 如果使用本地GIF,要确保路径相对于机器人启动文件的位置正确;如果使用网络链接,要确认是GIF直链(直接访问即可加载GIF,不是包含GIF的网页链接)
- 若GIF资源数量较多,也可以单独存储到JSON文件中读取,避免主文件代码冗余
内容的提问来源于stack exchange,提问作者jaajsousse
相关产品推荐
相关产品推荐

