[英]Sending message to specific channel in discord.js
I want to send a message to a specific channel but it doesn't work, I've tried client.guilds.cache.get("<id>").send("<msg>")
but I get the error ".send is not a function".我想向特定频道发送消息但它不起作用,我试过
client.guilds.cache.get("<id>").send("<msg>")
但我收到错误消息“ .send 不是函数”。 What am I missing here?我在这里错过了什么?
There are three ways of sending message to a specific channel.可以通过三种方式将消息发送到特定频道。
1. Using a fetch method 1.使用fetch方法
const channel = await <client>.channels.fetch('channelID')
channel.send({content: "Example Message"})
2. Using a get method 2.使用get方法
const channel = await <client>.channels.cache.get('channelID')
channel.send({content: "Example Message"})
3. Using a find method 3.使用查找方法
a.一种。
const channel = await <client>.channels.cache.find(channel => channel.id === "channelID")
channel.send({content: "Example Message"})
b. b.
const channel = await <client>.channels.cache.find(channel => channel.name === "channelName")
channel.send({content: "Example Message})
Your current code line is getting the GUILD_ID not the CHANNEL_ID.您当前的代码行获取的是 GUILD_ID 而不是 CHANNEL_ID。
You are trying to get from the cache a Guild
not a Channel
, or more specifically a TextChannel
, that's why what you try is not working, you should try to change the code to something like this and it should work.您正在尝试从缓存中获取
Guild
而不是Channel
,或者更具体地说是TextChannel
,这就是您尝试的方法不起作用的原因,您应该尝试将代码更改为这样的代码,它应该可以工作。
const channel = client.channels.cache.get('Channel Id');
channel.send({ content: 'This is a message' });
Also, as something extra, I would recommend using the fetch
method for these things, since it checks the bot's cache and in the case of not finding the requested object it sends a request to the api, but it depends on the final use if you need it or not.另外,作为额外的东西,我建议对这些东西使用
fetch
方法,因为它会检查机器人的缓存,并且在找不到请求的 object 的情况下,它会向 api 发送请求,但这取决于最终用途,如果你需要与否。
const channel = await client.channels.fetch('Channel Id');
channel.send({ content: 'This is a message' });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.