JDA - send message

前端 未结 2 1799
时光取名叫无心
时光取名叫无心 2020-12-12 07:57

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 n

相关标签:
2条回答
  • 2020-12-12 08:21

    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.

    0 讨论(0)
  • 2020-12-12 08:36

    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.

    0 讨论(0)
提交回复
热议问题