Zsa Zsa Mendoza
Zsa Zsa Mendoza

Reputation: 11

Specifying which channel to send chat from a discord bot (say-channel command)

It's a feature that's found in GLaDOS bot, the Connor RK800 bot, and the TypicalBot.

Often the command appears like this:

!say #general heck

And the text, through the bot, will appear in that channel.

I'd like to add this to my own bot, if possible!

I have a bare-bones code for the say-delete command. What will I have to add, and what will I have to take away?

      if (command === "say") {
  const sayMessage = args.join(" ");

  message.delete().catch(O_o => {
    // Catch error
  });
  message.channel.send(sayMessage);
}

Thank you! I really appreciate it.

Upvotes: 1

Views: 1292

Answers (2)

JED
JED

Reputation: 11

// making the say command
const sayCommand = `${prefix}say`
// say command
if (message.content.toLowerCase().startsWith(`${sayCommand}`)) {
        // declaring args variable
        const args = message.content.slice(sayCommand.length).split(/ +/);
        // delcaring sayMessage that clears the say command from the say message
        let sayMessage = args.join(` `);
        // deletes the command message
        message.delete();
        // bot sends the contents of the command without the say command
        message.channel.send(sayMessage)
    }

this works for me verry well

Upvotes: 1

yogsoy
yogsoy

Reputation: 61

First, you would want to change the code for defining the arguments in this case to const channel = args.shift();, which will return the first item in the args[] array.

Then you can identify the channel the user wants to send the message to with message.guild.channels[channel].send(sayMessage); (I think).

All together, your code would be:

if(command === "say") {

   const channel = args.shift();
   const sayMessage = args.join(" ");

   message.delete().catch(O_o=>{});  

   message.guild.channels[channel].send(sayMessage);

}

As I can't check this right now, I don't know for sure if this would work, but it's worth a shot! If you'd like I can test it for you once I am able to.

EDIT: I tested and fixed the code, hopefully the comments I have written are explanatory enough.

const channel = args.shift().slice(2,-1); // this is due to how channel mentions work in discord (they are sent to clients as <#462650628376625169>, this cuts off the first <# and the finishing >)
const sayMessage = args.join(` `);

message.delete(); // you may want to add a catch() here, i didn't because my bot requires permissions to be added to a server
client.channels.get(channel).send(sayMessage); // client here may need to be replaced with bot, or app, or whatever you're using - client.channels returns a collection, which we use get() to find an item in

Just to be clear, this code will have to go within your if (command === "say") block.

Upvotes: 1

Related Questions