DiscordJS - 发送消息

问题描述 投票:0回答:2

我正在尝试通过 DiscordJS 发送消息

有人可以帮助我吗

我试过这个代码

const channel = client.channels.cache.get('example discord guild');
channel.send('content');

但这不起作用

index.js

// Credetials
const { token } = require('./json/token.json');
const { guild } = require('./json/guild.json');
const { client } = require('./json/client.json')

// Init
const { Client, Intents } = require('discord.js');
const bot = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_>

bot.login(guild);
console.log("Logged In As DeltaBOT");
const channel = client.channels.cache.get(guild);
channel.send('content');

错误

const channel = client.channels.cache.get(guild);
                                ^

TypeError: Cannot read properties of undefined (reading 'cache')
    at Object.<anonymous> (/storage/emulated/0/Download/node/index.js:15:33)
    at Module._compile (node:internal/modules/cjs/loader:1097:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47
node.js discord.js
2个回答
2
投票

您应该等待客户端登录,然后再尝试发送消息/获取频道。您可以通过使用就绪事件来完成此操作。例如:

bot.on('ready', async () => {
    console.log('Logged in as: ' + bot.user.tag);
    const channel = await bot.channels.fetch(guild);
    await channel.send('content');
})

我注意到的另一件事是你使用客户端而不是机器人。 client 是一个 json 对象,但您将不和谐的 bot 对象定义为 bot 变量。因此,请使用机器人变量而不是客户端变量。

确保公会是有效的公会ID。我不知道您的客户端 json 文件中有什么,但您似乎没有使用它。


0
投票

您发送的第一个代码主要遇到的唯一问题是您似乎将异步代码与罪恶代码混淆了

确保您理解问题,因为您稍后可能会遇到它。

查看您发送的代码示例

const channel = client.channels.cache.get('example discord guild');
channel.send('content');

首先,它从缓存中获取,通常仅在获取它或对其进行任何交互后才存在(忘记它到底是如何工作的),因此您需要等待获取或进行类似的操作

const channel = client.channels.cache.get('example discord guild') || await client.channels.fetch(guild);
channel.send('content');

此外,您不能使用 JSON 作为客户端(您已导入),因为您想要的客户端是库的类实例,您可以使用 bot 变量来代替。

const { token } = require('./json/token.json');
const { guild } = require('./json/guild.json');

const { Client, Intents } = require('discord.js');
const bot = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_>

const bot = await bot.login(guild);

console.log(`Logged in as ${client?.user?.username}`);

const channel = client.channels.cache.get(guild) || await client.channels.fetch(guild)

await channel.send({
  content: 'content'
});
© www.soinside.com 2019 - 2024. All rights reserved.