[英]How to send a message to a channel
我花了 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);
這可能是由於您在機器人登錄之前運行代碼這一事實造成的。
每個動作都必須在機器人發出就緒事件后進行,在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')
嘗試:
bot.channels.find(channel => channel.id === '504658757419270144').send('Your-message');
此外,如果您嘗試向其發送消息的頻道在 bots 公會中,您可以使用:
bot.on('message' (msg) => {
msg.guild.channels.find(channel => channel.name === 'your-channel-name').send('your-message');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.