首页 > 解决方案 > 无法读取未定义的属性“nsfw”-discord.js

问题描述

我目前正在开发一个使用“discord.js”、“discord.js-commando”和“snekfetch”的不和谐机器人。我正在尝试创建一个函数,如果公会成员键入“!meme”,discord 机器人将从 r/dankmemes 抓取随机帖子并使用richEmbed 将其发送到相应的频道。但是,在测试该功能时,会出现以下错误消息:

TypeError: Cannot read property 'nsfw' of undefined

TypeError: Cannot read property 'send' of undefined

我已经尝试解决这个问题 4 天了,我完全不知道是什么导致了这个问题。根据 discord.js 文档,这应该可以正常工作。我在下面附加了命令模块:

const Commando = require('discord.js-commando');
const Discord = require('discord.js');
const snekfetch = require('snekfetch');

class MemesRssCommand extends Commando.Command
{
    constructor(client)
    {
        super(client,{
            name: 'meme',
            group: 'simple',
            memberName: 'meme',
            description: 'Takes a random meme from r/dankmemes'
        });
    }

    async run(client, message, args) {
        try {
            const { body } = await snekfetch
                .get('https://www.reddit.com/r/dankmemes.json?sort=top&t=week')
                .query({ limit: 800 });
            const allowed = message.channel.nsfw ? body.data.children : body.data.children.filter(post => !post.data.over_18);
            if (!allowed.length) return message.channel.send('Our farmers were unable to locate any ripe memes! Try again later (You shouldnt see this message. If you are reading this, then reddit is probably offline. If reddit is online and you still get this message, contact @#1612');
            const randomnumber = Math.floor(Math.random() * allowed.length)
            const embed = new Discord.RichEmbed()
            .setColor(0x00A2E8)
            .setTitle(allowed[randomnumber].data.title)
            .setDescription("Posted by: " + allowed[randomnumber].data.author)
            .setImage(allowed[randomnumber].data.url)
            .addField("Other info:", "Up votes: " + allowed[randomnumber].data.ups + " / Comments: " + allowed[randomnumber].data.num_comments)
            .setFooter("Posted by: " + allowed[randomnumber].data.author + " | Memes provided by https://www.reddit.com/r/dankmemes")
            message.channel.send(embed)
        } catch (err) {
            return console.log(err);
        }
    }

}

module.exports = MemesRssCommand

标签: javascriptdiscord.jscommando

解决方案


根据文档中的示例,回调runrun(message, args)但您将其定义为run(client, message, args),因此message.channel未定义,因为您试图在错误的对象上访问它。

    async run(message, args) {
        const member = args.member;
        const channel = message.channel
        // ....
    }

推荐阅读