【问题标题】:Cannot read properties of undefined (reading 'channel')无法读取未定义的属性(读取“通道”)
【发布时间】:2022-01-06 13:05:13
【问题描述】:

我正在尝试为我的不和谐创建一个 /ping 命令。该机器人正在使用类型脚本和一个名为 WOKCommands 的插件。

我在下面收到此错误(仅当我使用斜杠命令而不是前缀命令 {>ping} 时才会发生这种情况)。

Cannot read properties of undefined (reading 'channel')

这是因为下面代码中的const msg = await message.channel.send ({content: `> ???? Pinging..`}) 行

import { Client, Message, MessageEmbed, MessageActionRow, MessageButton, MessageSelectMenu } from'discord.js';
const db = require('quick.db')
const moment = require('moment')
import { ICommand } from "wokcommands";


export default {
    name: 'ping',
    description: "Fetches the client latency",
    category: "Utilities",

    slash: 'both',
    testonly: true,


    /** 
     * @param {Client} client 
     * @param {Message} message 
     * @param {String[]} args 
     */

    callback: async({client, message, args}) => {
        const msg = await message.channel.send ({content: `> ???? Pinging..`})
        msg.edit({content: `> ???? Pong! Latency: **${client.ws.ping}ms**`})
    }
} as ICommand

【问题讨论】:

    标签: typescript discord.js


    【解决方案1】:

    只有当我使用斜杠命令而不是前缀命令>ping时才会发生这种情况

    这是您的错误的原因。当您使用斜杠命令时,不涉及任何消息。斜杠命令不是作为消息发送的,而是作为交互发送的。当您将 ping 命令用作斜杠命令时,message 未定义。

    此外,当使用斜线命令时,您必须发送回复而不是简单地在频道中发送消息。否则,您将收到额外的错误。我建议在这里切换为对前缀命令和斜杠命令使用.reply() 方法(尽管我没有在下面的代码中为您的前缀命令进行切换)。这是修复回调的一种方法:

    ({ client, message, interaction, args }) => {
        if (message) {
            const msg = await message.channel.send ({content: `> ? Pinging..`})
            msg.edit({content: `> ? Pong! Latency: **${client.ws.ping}ms**`})
        }
        else if (interaction) {
            await interaction.reply({content: `> ? Pinging..`});
            interaction.editReply({content: `> ? Pong! Latency: **${client.ws.ping}ms**`});
        }
    }
    

    您可能会发现 WOKCommands 文档对诸如此类的问题很有用。他们的文档甚至有an example of a ping command,尽管版本更简单。

    【讨论】:

    • 你知道为什么我得到这个 throw new DiscordAPIError(data, res.status, request); ^ DiscordAPIError:未知交互
    • @RipTide12 您是在我的答案和您的问题中仅使用代码时遇到该错误,还是您在callback 函数中添加了更多代码?仅此答案中的代码不应该发生该错误,afaik。如果您在回调中添加了更多代码并且导致错误,则需要为此打开一个新问题,因为这将是一个单独的问题。通常该错误是由于没有足够快地使用.reply()。如果需要延迟回复,可以随时使用.deferReply()。
    • 不,我只是使用您提供的代码
    猜你喜欢
    • 2020-11-28
    • 2021-03-31
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 2018-12-07
    • 2021-10-20
    相关资源
    最近更新 更多