Anton Lieskovsky
Anton Lieskovsky

Reputation: 189

JDA - send message

I have my own Discord BOT based on JDA. I need to send a text message to the specific channel. I know how to send the message as onEvent response, but in my situation I do not have such event.

I have: Author (BOT), Token and Channel number.

My question is: how to send the message to this channel without an event?

Upvotes: 1

Views: 13005

Answers (2)

Ivanka
Ivanka

Reputation: 248

Ok I think I know what you mean. You don't need to have an event to get an ID of a channel and send a message. The only thing you need to do is to instantiate the JDA, call awaitReady(), from the instance you can get all channels (MessageChannels, TextChannels, VoiceChannels, either by calling

  • get[Text]Channels()
  • get[Text]ChannelById(id=..)
  • get[Text]ChannelsByName(name, ignore case))

So 1. Instantiate JDA

    JDABuilder builder; 
    JDA jda = builder.build();
    jda.awaitReady();
  1. Get Channel

    List<TextChannel> channels = jda.getTextChannelsByName("general", true);
    for(TextChannel ch : channels)
    {
        sendMessage(ch, "message");
    }
    
  2. Send message

    static void sendMessage(TextChannel ch, String msg) 
    {
        ch.sendMessage(msg).queue();
    }
    

Hope it helps.

Upvotes: 8

Minn
Minn

Reputation: 6134

You need only one thing to make this happen, that is an instance of JDA. This can be retrieved from most entities like User/Guild/Channel and every Event instance. With that you can use JDA.getTextChannelById to retrieve the TextChannel instance for sending your message.

class MyClass {
    private final JDA api;
    private final long channelId;
    private final String content;

    public MyClass(JDA api) {
        this.api = api;
    }

    public void doThing() {
         TextChannel channel = api.getTextChannelById(this.channelId);
         if (channel != null) {
             channel.sendMessage(this.content).queue();
         }
    }
}

If you don't have a JDA instance you would have to manually do an HTTP request to send the message, for this lookup the discord documentation or jda source code. The JDA source code might be a little too complicated to take as an example as its more abstract to allow using any endpoint.

Upvotes: 1

Related Questions