【问题标题】:Discord.js Giveaway CommandDiscord.js 赠品命令
【发布时间】:2020-03-17 18:41:26
【问题描述】:

我尝试为我的 discord.js 机器人调整赠品命令,但我收到代码错误。

这是代码

const {RichEmbed, Collection} = require("discord.js");
class Giveaway {
    constructor(client, message, match, data) {
        const [full, channel, winnerCount, timeInSeconds, days, hours, minutes, seconds, title] = match;
        this.giveawayCache = new Collection();
        this.lastGiveawayCache = new Collection();
        this.client = client;

        this.message = message;

        this.channel = data ? this.client.guilds.get(data.guild).channels.get(data.channel) : message.guild.channels.get(channel) || message.channel;

        this.winnerCount = winnerCount || 1;

        this.length = timeInSeconds ? timeInSeconds : (60 * 60 * 24 * (days ? Number(days) : 0)) + (60 * 60 * (hours ? Number(hours) : 0)) + (60 * (minutes ? Number(minutes) : 0)) + (seconds ? Number(seconds) : 0);

        this.remaining = data ? data.remaining : this.length;

        this.endTime = Date.now() + this.length * 1000;

        this.title = title;

        this.winners = [];

        this.msg;

        this.interval;

        this.suffix = this.giveawayCache.filter(giveaway => giveaway.channel.id === this.channel.id).size+1;

        this.match = match;

        this.valid = true;

        if (data) { this.continue(data); } else { this.init(); }
    }

    async init() {
        this.msg = new RichEmbed()
            .setColor(0xcc8822)
            .setTitle(this.title)
            .setDescription(`Nombre de gagnants : ${this.winnerCount}\nRéagis avec :tada: pour participer !`)
            .setFooter(`${this.suffix} | Termine à`)
            .setTimestamp(new Date(this.endTime));
            this.channel.send(this.msg)
                .then(async function (message) {
                    await message.react('????')
                });
        this.interval = setInterval(() => this.intervalFunction(), 1000);

        this.giveawayCache.set(`${this.channel.id}-${this.suffix}`, this);
    }

    async continue(data) {
        this.msg = await this.client.channels.get(data.channel).messages.fetch(data.msg).catch(() => {
            clearInterval(this.interval);
            this.lastGiveawayCache.set(`${this.channel.id}-${this.suffix}`, this);
            this.giveawayCache.delete(`${this.channel.id}-${this.suffix}`);
        });
        this.winnerCount = await data.winnerCount;
        this.title = await data.title;
        this.interval = setInterval(() => this.intervalFunction(), 1000);

        this.giveawayCache.set(`${this.channel.id}-${this.suffix}`, this);
    }

    async intervalFunction() {
        this.remaining--;

        this.channel.fetchMessages(this.msg.id).catch(() => {
            clearInterval(this.interval);
            this.lastGiveawayCache.set(`${this.channel.id}-${this.suffix}`, this);
            this.giveawayCache.delete(`${this.channel.id}-${this.suffix}`);
        });

        if(Date.now() >= this.endTime){
            clearInterval(this.interval);
            this.lastGiveawayCache.set(`${this.channel.id}-${this.suffix}`, this);
            this.giveawayCache.delete(`${this.channel.id}-${this.suffix}`);

            const embed = this.msg.embeds[0];
            embed.color = 0x171c23;

            const users = await this.msg.reactions.get("????").users.fetch();
            const list = users.array().filter(u => u.id !== this.msg.author.id);

            if (!list.length) {
                embed.description = `Gagnant : Personne.`;
                embed.footer.text = `Giveaway terminé !`;

                return this.msg.edit({ embed });
            }

            for (let i = 0; i < this.winnerCount; i++) {
                const x = this.draw(list);

                if (!this.winners.includes(x)) this.winners.push(x);
            }

            embed.description = `Gagnant : ${this.winners.filter(u => u !== undefined && u !== null).map(u => u.toString()).join(", ")}`;
            embed.footer.text = `${this.suffix} | Giveaway terminé !`;

            this.msg.edit({ embed });

            if (this.winners.length) this.channel.send(`Bravo, ${this.winners.map(u => u.toString()).join(", ")}! Tu as gagné le giveaway pour **${this.title}**!`);
        }

    }

    shuffle(arr) {
        for (let i = arr.length; i; i--) {
            const j = Math.floor(Math.random() * i);
            [arr[i - 1], arr[j]] = [arr[j], arr[i - 1]];
        }
        return arr;
    }

    draw(list) {
        const shuffled = this.shuffle(list);
        return shuffled[Math.floor(Math.random() * shuffled.length)];
    }
}

module.exports = Giveaway;

这是错误:

unhandledRejection Error:  TypeError: Cannot read property '0' of undefined

at Giveaway.intervalFunction (/home/mef/structure/giveaway.js:82:40)

at Timeout.<anonymous> (/home/mef/structure/giveaway.js:50:48)

at listOnTimeout (internal/timers.js:531:17)

at processTimers (internal/timers.js:475:7)

问题所在: const embed = this.msg.embeds[0]; 但我不知道如何解决它。

【问题讨论】:

    标签: javascript command bots discord discord.js


    【解决方案1】:

    问题在于intervalFunction 运行的范围。最简单的解决方案是将this 传递给您的区间

    this.interval = setInterval((thisArg) => thisArg.intervalFunction(), 1000, this);
    

    【讨论】:

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