简体   繁体   中英

Send message to specific discord channel in discord.js v12

Every line of code i try to use to send a message to a specific channel doesn't seem to work in discord.js v12 even when i got that code from the official documentation. Here is my code:

const Discord = require('discord.js');
const client = new Discord.Client();
const announcementChannel = client.channels.cache.get(process.env.CHANNELANN);
let announcement = "MESSAGE HERE";

client.on("presenceUpdate", (oldPresence, newPresence) => {
  if (!newPresence.activities) return false;
  newPresence.activities.forEach(activity => {
      if (activity.type == "STREAMING") {
        if(newPresence.user.id == "THE ID IS HERE") {
          announcementChannel.send(announcement);
       }
      } else {
        client.user.setActivity("over the server", {
          type: "WATCHING"
        });
      };
  });
});
client.login(process.env.TOKEN);

Here is the error i receive:

          announcementChannel.send(announcement);
                              ^
TypeError: Cannot read property 'send' of undefined

I was able to fix this by replacing that line with:

client.channels.cache.get(process.env.CHANNELANN).send(announcement);

However, now it just keeps spamming the message and doesn't only send it once then stops. You know any fix for that?

Once initiated, make it wait until the stop streaming

None of the answers I found worked with the latest version (12.5.1) so here's what worked for me.

            const channel = client.channels.cache.get(textChannelId) as TextChannel;
            if (channel) {
                const m = new Message(client, {id: clientId}, channel);
                const content: MessageOptions = {content: message};
                //if (image) {
                //    content.embed = {image: {url: image}};
                //}
                await m.channel.send(content);
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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