如何向频道发送消息
2018-10-24
174
我花了 3 个小时构建和调整 Node.js 网络抓取工具,又花了 4 个小时试图找到一种向 Discord 频道广播消息的怪异方法。此时我已经失去了所有希望...
这是我拥有的代码,有些部分可以工作,例如回复消息。但我找不到任何可能的方法,只发送消息,而不回复该消息。
const discord = require('discord.js');
const bot = new discord.Client();
const cfg = require('./config.json')
bot.on('ready', () => {//this works
console.log(`Logged in as ${bot.user.tag}(${bot.user.id}) on ${bot.guilds.size} servers`)
});
bot.on('message', (msg) => {
switch (msg.content) {
case '/epicinfo':
msg.channel.send('w00t'); //this works
}
});
console.log(bot.users.get("id", "504658757419270144")) //undefined
console.log(bot.channels.get("name", "testbot")) //undefined
console.log(bot.users.find("id", "504658757419270144")) //undefined
console.log(bot.channels.find("name", "testbot")) //undefined
console.log(bot.guilds.get("504658757419270144")); //undefined
console.log(bot.channels.get(504658757419270144)) //undefined
bot.send((discord.Object(id = '504658757419270144'), 'Hello')) //discord.Object is not a function
bot.login(cfg.token);
2个回答
这可能是由于您在机器人登录之前运行代码造成的。
所有操作都必须在机器人发出 ready 事件后进行,您在
ready
事件之外唯一能做的事情就是定义其他事件监听器。
尝试将代码的这一部分放在
ready
事件监听器内,或放在该事件调用的函数内:
client.on('ready', () => {
console.log("Your stuff...");
});
// OR
function partA () {...}
function partB () {...}
client.on('ready', () => {
partA();
console.log("Your stuff...");
partB();
});
// OR
function load() {...}
client.on('ready', load);
在您的情形下:
client.on('ready', () => { // once the client is ready...
let guild = client.guilds.get('guild id here'); // ...get the guild.
if (!guild) throw new Error("The guild does not exist."); // if the guild doesn't exist, exit.
let channel = guild.channels.get('channel id here'); // if it does, get the channel
if (!channel) throw new Error("That channel does not exist in this guild."); // if it doesn't exist, exit.
channel.send("Your message here.") // if it does, send the message.
});
client.login('your token here')
Federico Grandi
2018-10-24
尝试:
bot.channels.find(channel => channel.id === '504658757419270144').send('Your-message');
此外,如果您尝试发送消息的频道在机器人公会中,您可以使用:
bot.on('message' (msg) => {
msg.guild.channels.find(channel => channel.name === 'your-channel-name').send('your-message');
});
Max
2018-10-27