簡體   English   中英

如何向特定頻道發送消息 Discord.js

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

我需要代碼將消息發送到我查看過堆棧溢出的通道,但那里太舊並且出現錯誤

在 discord.js 指南上有一個指南。

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

改進的版本是:

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

首先,您需要獲取頻道 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 向特定通道發送消息

不確定您是否已經測試過此代碼,但看起來這可能會回答您的問題?

我尚未對此進行測試,但我鏈接的線程似乎已在 2020 年 6 月對其進行了測試!

很快,我將消息發送到特定的頻道,例如下面。

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

在代碼片下是我自己的用法。
就我而言,我將所有直接消息保存到我自己的頻道。

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);
  }
});

在我自己的頻道中,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