JDA - send message

此生再无相见时 提交于 2020-06-21 05:44:07

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/53484588/jda-send-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!