使用jslack的RTM库与slack进行通信

我正在尝试使用jslack:https://github.com/seratch/jslack RTM库来发送和接收消息 . 但我不确定为什么 rtmClient.sendMessage("Hello WOrld"); 没有将消息发送到slack bot,尽管它能够成功连接到机器人 . 请告诉我,哪里出错了 .

JsonParser jsonParser = new JsonParser();
        try (RTMClient rtmClient = new Slack().rtm("xoxwerq-12632550058135")) {

            rtmClient.addMessageHandler((message) -> {
                JsonObject json = jsonParser.parse(message).getAsJsonObject();
                if (json.get("type") != null) {
                  log.info("Handled type: {}", json.get("type").getAsString());
                  //System.out.println("working");
                }
              });

              RTMMessageHandler handler2 = (message) -> {
                  log.info("Hello!");
                  //Logger.debug("client connected to the server: {}", wssUri);

                 // System.out.println("got it");
                  };

                 //rtmClient.addMessageHandler(RTMMessageHandler messageHandler);

                  rtmClient.addMessageHandler(handler2);

                  // must connect within 30 seconds after issuing wss endpoint
                  try {
                    rtmClient.connect();
                    rtmClient.sendMessage("Hello WOrld");
                    Thread.sleep(5000);

                    System.out.println("Bot started!!!!!!");
                    //rtmClient.addMessageHandler(handler2);
                    //Thread.sleep(5000);

                } catch (DeploymentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                 rtmClient.removeMessageHandler(handler2);
        }`

回答(1)

2 years ago

我不确定sendMessage方法是否可以使用 . 我试过,它也没有向机器人 Channels 发布消息 .

这是我用来将消息发布到特定 Channels 的方法 . 在回答机器人的情况下,我只是从机器人消息中检索通道ID:

private void postMessage(String channel, String message) {
        try {
            // https://slack.com/api/chat.postMessage
            ChatPostMessageResponse postResponse =
                    slack.methods().chatPostMessage(ChatPostMessageRequest.builder().token(token)
                            .channel(channel).text(message).build());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }