简体   繁体   English

如何向特定频道发送消息 Discord.js

[英]how to send a message to specific channel Discord.js

I need the code to send a message to a channel I have looked on stack overflow but there all too old and through up a error我需要代码将消息发送到我查看过堆栈溢出的通道,但那里太旧并且出现错误

There is a guide for this on the discord.js guide. 在 discord.js 指南上有一个指南。

const channel = <client>.channels.cache.get('<id>');
channel.send('<content>');

An improved version would be:改进的版本是:

<client>.channels.fetch('<id>').then(channel => channel.send('<content>'))

At first you need to get the channel ID or Channel Name to do that首先,您需要获取频道 ID 或频道名称才能执行此操作

/* You handle in command and have message */
// With Channel Name
const ChannelWantSend = message.guild.channels.cache.find(channel => channel.name === 'Channel Name');
// With Channel ID
const ChannelWantSend = message.guild.channels.cache.get(channelId);
ChannelWantSend.send('Your Message');

/* If you start from root of your bot , having client */

// With Channel Name
const ChannelWantSend = client.channels.cache.find(channel => channel.name === 'Channel Name');
// With Channel ID
const ChannelWantSend = client.channels.cache.get(channelId);
ChannelWantSend.send('Your Message');

// In both case If ChannelWantSend is undefined where is a small chance that discord.js not caching channel so you need to fetch it

const ChannelWantSend = client.channels.fetch(channelId);

Discord.js sending a message to a specific channel Discord.js 向特定通道发送消息

Not sure if you have tested out this code yet, but it looks like this may answer your question?不确定您是否已经测试过此代码,但看起来这可能会回答您的问题?

I haven't tested this, but the thread I linked seems to have tested it as of June 2020!我尚未对此进行测试,但我链接的线程似乎已在 2020 年 6 月对其进行了测试!

Shortly, I send message to specific channel like under.很快,我将消息发送到特定的频道,例如下面。

<client>.channels.cache.get("<channel_id>").send("SEND TEXT");

Under code piece is my own usage.在代码片下是我自己的用法。
In my case, I save all of Direct Messages to my own channel.就我而言,我将所有直接消息保存到我自己的频道。

const Discord = require('discord.js');
const client = new Discord.Client();

function saveDMToAdminChannel(message) {
  var textDM = `${message.author.username}#${message.author.discriminator} : ${message.content}`;
  client.channels.cache.get("0011223344556677").send(textDM);
  // "0011223344556677" is just sample.
}

client.on("message", async message => {
  if(message.author.bot) return;
  if(message.channel.type == 'dm') {
    saveDMToAdminChannel(message);
  }
});

In my own channel, DM's are saved like,在我自己的频道中,DM 的保存方式如下:

00:00 User1#1234 : Please fix bug
07:30 User2#2345 : Please fix bug!!
10:23 User3#3456 : Please fix bug!!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM