【问题标题】:Discord.js Bot giveaway command : embedSent.reactions.get is not a functionDiscord.js Bot 赠品命令:embedSent.reactions.get 不是函数
【发布时间】:2020-09-17 01:33:24
【问题描述】:

我正在尝试制作一个发送嵌入的 Discord.js 赠品命令,将其保存到变量 embedSent 然后使用 reactions.get() 方法收集 TimeOut 后的反应,但我不断收到错误 TypeError: embedSent.reactions.get is not a function 这是我的代码部分:

var embed = new Discord.MessageEmbed();
embed.setColor(0x3333ff);
embed.setTitle("Nouveau Giveaway !");
embed.setDescription("**" + item + "**");
embed.addField(`Durée : `, ms(ms(time), {
  long: true
}), true);
embed.setFooter("Réagissez à ce message avec ???? pour participer !");
var embedSent = await message.channel.send(embed);
embedSent.react("????");

setTimeout(function () {
  var peopleReacted = embedSent.reactions.get("????").users.filter(user => user.id !== client.user.id).array()
}, time);

【问题讨论】:

    标签: javascript bots discord


    【解决方案1】:

    好的,经过将近 2 个月,我终于弄明白了。完整的工作命令(DiscordJS v12):

    if (command == "giveaway") {
        // !giveaway {time s/m/d} {item}
        const messageArray = message.content.split(" ");
        if (!message.member.hasPermission(["ADMINISTRATOR"])) return message.channel.send("You don't have enough permissions to start a giveaway !")
        var item = "";
        var time;
        var winnerCount;
        for (var i = 1; i < args.length; i++) {
          item += (args[i] + " ");
        }
        time = args[0];
        if (!time) {
          return message.channel.send(`Invalid duration provided`);
        }
        if (!item) {
          item = "No title"
        }
        var embed = new Discord.MessageEmbed();
        embed.setColor(0x3333ff);
        embed.setTitle("New Giveaway !");
        embed.setDescription("**" + item + "**");
        embed.addField(`Duration : `, ms(ms(time), {
          long: true
        }), true);
        embed.setFooter("React to this message with ? to participate !");
        var embedSent = await message.channel.send(embed);
        embedSent.react("?");
    
        setTimeout(async () => {
          try{
            const peopleReactedBot = await embedSent.reactions.cache.get("?").users.fetch();
            var peopleReacted = peopleReactedBot.array().filter(u => u.id !== client.user.id);
          }catch(e){
            return message.channel.send(`An unknown error happened during the draw of the giveaway **${item}** : `+"`"+e+"`")
          }
          var winner;
    
          if (peopleReacted.length <= 0) {
            return message.channel.send(`Not enough participants to execute the draw of the giveaway **${item}** :(`);
          } else {
            var index = Math.floor(Math.random() * peopleReacted.length);
            winner = peopleReacted[index];
          }
          if (!winner) {
            message.channel.send(`An unknown error happened during the draw of the giveaway **${item}**`);
          } else {
            console.log(`Giveaway ${item} won by ${winner.toString()}`)
            message.channel.send(`? **${winner.toString()}** has won the giveaway **${item}** ! Congratulations ! ?`);
          }
        }, ms(time));
    }
    

    希望对大家有所帮助!

    【讨论】:

    • 嗨!我需要帮助,
    • 所以当我调用机器人时我应该输入什么!赠品以及在哪个日期/时间?
    • @LZ 命令语法为:赠品 {time with ms module syntax 无空格} {赠品名称}。示例:!giveaway 3d Discord Nitro (1 month) 将开始为期 3 天的赠品活动,名为“Discord Nitro(1 个月)”。
    • 感谢您的回答!
    【解决方案2】:

    我猜这个赠品命令对我有用 - Discord.js V13

    • 如果您还没有安装 npm i ms,请不要忘记安装
    const { Client, Intents, CommandInteraction, ReactionUserManager } = require('discord.js'); 
    const INTENTS = new Intents(32767); // 32767 == full intents, calculated from intent calculator 
    
    const client = new Client({
      intents: INTENTS
    });
    
    const Discord = require('discord.js');
    const ms = require('ms') // make sure package ms is downloaded in console, to do this, simply type:   npm i ms     in your terminal
    // https://www.npmjs.com/package/ms
    
    client.once("ready" , () => {
        console.log("I am online!")
    });
    
    client.on('messageCreate', async message => {
    
        const prefix = "!" // this can be any prefix you want
        let args = message.content.substring(prefix.length).split(" ")
    
        // COMMAND FORMAT: !startgiveaway {duration} {winners} {#channel} {prize}
        // E.g. !startgiveaway 24h 3w #giveaways Free Discord Nitro
    
        if ((message.content.startsWith(`${prefix}startgiveaway`))) { // this condition can be changed to any command you'd like, e.g. `${prefix}gstart`
            if (message.member.roles.cache.some(role => (role.name === 'Giveaway') )) { // user must have a role named Giveaway to start giveaway
            let duration = args[1];
            let winnerCount = args[2];
    
            if (!duration) 
                return message.channel.send('Please provide a duration for the giveaway!\nThe abbreviations for units of time are: `d (days), h (hours), m (minutes), s (seconds)`');
            if (
                !args[1].endsWith("d") &&
                !args[1].endsWith("h") &&
                !args[1].endsWith("m") &&
                !args[1].endsWith("s") 
            )
                return message.channel.send('Please provide a duration for the giveaway!\nThe abbreviations for units of time are: `d (days), h (hours), m (minutes), s (seconds)`');
    
            if (!winnerCount) return message.channel.send('Please provide the number of winners for the giveaway! E.g. `1w`')
    
            if (isNaN(args[2].toString().slice(0, -1)) || !args[2].endsWith("w")) // if args[2]/winnerCount is not a number (even after removing end 'w') or args[2] does not end with 'w', condition returns:
                return message.channel.send('Please provide the number of winners for the giveaway! E.g. `3w`');
                    if ((args[2].toString().slice(0, -1)) <= 0)   
                        return message.channel.send('The number of winners cannot be less than 1!');
    
                let giveawayChannel = message.mentions.channels.first();
                if (!giveawayChannel || !args[3]) return message.channel.send("Please provide a valid channel to start the giveaway!")
    
                let prize = args.slice(4).join(" ");
                if (!prize) return message.channel.send('Please provide a prize to start the giveaway!');
    
                let startGiveawayEmbed = new Discord.MessageEmbed()
                    .setTitle("? GIVEAWAY ?")
                    .setDescription(`${prize}\n\nReact with ? to participate in the giveaway!\nWinners: **${winnerCount.toString().slice(0, -1)}**\nTime Remaining: **${duration}**\nHosted By: **${message.author}**`)
                    .setColor('#FFFFFF')
                    .setTimestamp(Date.now() + ms(args[1])) // Displays time at which the giveaway will end
                    .setFooter("Giveaway ends"); 
    
                let embedGiveawayHandle = await giveawayChannel.send({embeds: [startGiveawayEmbed]})
                embedGiveawayHandle.react("?").catch(console.error); 
    
                setTimeout(() => {
                    if (embedGiveawayHandle.reactions.cache.get("?").count <= 1) {
                        return giveawayChannel.send("Nobody joined the giveaway :(")
                    }
                    if (embedGiveawayHandle.reactions.cache.get("?").count <= winnerCount.toString().slice(0, -1)) { // this if-statement can be removed
                        return giveawayChannel.send("There's not enough people in the giveaway to satisfy the number of winners!")
                    }
    
                    let winner = embedGiveawayHandle.reactions.cache.get("?").users.cache.filter((users) => !users.bot).random(winnerCount.toString().slice(0, -1)); 
    
                    const endedEmbedGiveaway = new Discord.MessageEmbed()
                    .setTitle("? GIVEAWAY ?")
                    .setDescription(`${prize}\n\nWinner(s): ${winner}\nHosted By: **${message.author}**\nWinners: **${winnerCount.toString().slice(0, -1)}**\nParticipants: **${embedGiveawayHandle.reactions.cache.get("?").count - 1}**\nDuration: **${duration}**`)
                    .setColor('#FFFFFF')
                    .setTimestamp(Date.now() + ms(args[1])) // Displays time at which the giveaway ended
                    .setFooter("Giveaway ended"); 
    
                    embedGiveawayHandle.edit({embeds:[endedEmbedGiveaway]}); // edits original giveaway message to show that the giveaway ended successfully
    
                    const congratsEmbedGiveaway = new Discord.MessageEmbed()
                    .setDescription(`? Congratulations ${winner}! You just won **${prize}**!`)
                    .setColor('#FFFFFF')
    
                    giveawayChannel.send({embeds: [congratsEmbedGiveaway]}).catch(console.error); 
                }, ms(args[1]));
    
            } // end "Giveaway" role condition
        }
    })
    
    client.login('INSERT YOUR BOT TOKEN HERE'); 
    
    

    【讨论】:

      猜你喜欢
      • 2020-11-06
      • 2020-03-17
      • 2021-04-18
      • 2021-03-10
      • 2020-04-17
      • 2021-03-20
      • 2021-04-02
      • 1970-01-01
      • 2020-10-30
      相关资源
      最近更新 更多