Home > Software design >  How to create a function to send messages
How to create a function to send messages

Time:02-01

I have a node.js app that I have created a discord bot to interact with. I would like it so that if a particular event happens with my node.js app that it will send a message to a particular channel in my discord server.

This is my first time using discord.js. However, my thought was to create a function that I can call to send my messages. However, it would seem that I need to wait for my client to be ready first.

Alternatively, would I just have to instantiate a new client every time I want to send a message and wait for it to come available before I send the message I want?

I feel like there has to be a better way... Is there a clean way that I can set up this basic discord bot that I can just call a function to send a message from anywhere within my app?

Here is the code that I have now:

import { Client, Events, GatewayIntentBits } from "discord.js";
import { botToken, CHANNEL_ID } from "../../config.js";

const client = new Client({ intents: [GatewayIntentBits.Guilds] }); // Create a new client instance

// When the client is ready, run this code (only once)
// We use 'c' for the event parameter to keep it separate from the already defined 'client'
client.once(Events.ClientReady, c => {
    console.log(`Ready! Logged in as ${c.user.tag}`);
    client.channels.cache.get(CHANNEL_ID).send("Hello!");
});

// Log in to Discord with your client's token
client.login(botToken);

CodePudding user response:

"I would like it so that if a particular event happens with my node.js app that it will send a message to a particular channel in my discord server."

It sounds like you're looking for webhooks. Webhooks are a way for an external source, such as your Node.js app, to send messages to a Discord channel without having to log in as a bot. Instead of using a Discord bot, you can use a webhook to send messages to a channel as if they were posted by a bot.

Using a webhook is simple; you just need to make an HTTP POST request to a URL provided by Discord, with the message you want to send in the body of the request. Discord will then post that message to the specified channel.

This is useful in cases where you want to receive notifications from your app in a Discord channel, or simply want to send messages to a channel without having to log in as a bot. It's a clean and efficient way to integrate your app with Discord.

Here is an example of a sendMessage function. It takes two arguments, payload and webhookUrl. If the payload is not a string, it is assumed to be an object that conforms to the Discord webhook format and will be used as is.

function sendMessage(payload, webhookUrl) {
  const data = typeof payload === 'string' ? { content: payload } : payload;

  return new Promise((resolve, reject) => {
    fetch(webhookUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
      .then((response) => {
        if (!response.ok) {
          reject(new Error(`Could not send message: ${response.status}`));
        }
        resolve();
      })
      .catch((error) => {
        console.error(error);
        reject(error);
      });
  });
}

If you're using node.js v18 , you can use the built-in fetch, if not, you'll need to install a library like node-fetch, axios, or something else.

Here is an example how you could use it:

// send a simple message
sendMessage('Hello from my app!', WEBHOOK_URL).catch((error) =>
  console.error(error),
);

// send a message, but change the username and the avatar
sendMessage(
  {
    content: 'Hello from my app!',
    avatar_url: 'https://i.imgur.com/KEungv8.png',
    username: 'Test Hook',
  },
  WEBHOOK_URL,
).catch((error) => console.error(error));

// send an embed and change the user again
sendMessage(
  {
    avatar_url: 'https://i.imgur.com/ofPowdD.png',
    username: 'Cattian Hook',
    embeds: [
      {
        title: 'Cats, cats, cats',
        color: 0xe7d747,
        thumbnail: {
          url: 'https://i.imgur.com/2bvab7y.jpeg',
        },
      },
    ],
  },
  WEBHOOK_URL,
).catch((error) => console.error(error));

And here is the result:

enter image description here

If you're already using discord.js, you can use the enter image description here enter image description here

  • Related