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

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");

补充说明

  1. 你可以根据需求任意增减hugGifs数组内的资源,代码会自动适配数组长度生成随机下标,不需要额外修改逻辑
  2. 如果使用本地GIF,要确保路径相对于机器人启动文件的位置正确;如果使用网络链接,要确认是GIF直链(直接访问即可加载GIF,不是包含GIF的网页链接)
  3. 若GIF资源数量较多,也可以单独存储到JSON文件中读取,避免主文件代码冗余

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 12:06:00