如何从Slack API获取频道列表?

时间:2017-12-28 18:30:33

标签: java webhooks slack

我在Java上使用Slack的API。我已经发现如何创建一个简单的代码来使用传入的Webhooks发送消息,但现在我有兴趣在getChannels函数中接收可用频道的列表。

问题在于我没有在Java中找到关于此的例子。

现在,我的代码是:

package slack;

import com.github.seratch.jslack.Slack;
import java.io.IOException;

import com.github.seratch.jslack.api.methods.SlackApiException;
import com.github.seratch.jslack.api.webhook.*;

public class SlackManager {

    private String token_="{myToken}";
    private Slack slack_ = Slack.getInstance();
    private String url_="{url}";

    public void sendMessage(String text, String channel, String name) throws IOException, SlackApiException {
        Payload payload = Payload.builder()
            .channel("#"+channel)
            .username(name)
            .iconEmoji(":smile_cat:")
            .text(text)
            .build();

        WebhookResponse response = slack_.send(url_, payload);
        System.out.println(response.getMessage().toString());
    }

    public void getChannels(){
        //I don't know how to get the channel list!!!
    }
}

我试试这个:

public void getChannels() throws IOException, SlackApiException{

    List<String> channels = slack_.methods().channelsList(ChannelsListRequest.builder().token(token_).build())
            .getChannels().stream()
            .map(c -> c.getId()).collect(Collectors.toList());

    for (String string : channels) {
        System.out.println(string);
    }
}

但结果是&#39; javaNullPointException&#39;。令牌必须是String吗?

1 个答案:

答案 0 :(得分:1)

Slack的传入webhooks将无法提供此功能 - 您需要使用Slack的Web API来获取所需内容。

使用来自您正在使用的jslack库的try following this example的Web API:

List<String> channels = slack.methods().channelsList(ChannelsListRequest.builder().token(token).build())
        .getChannels().stream()     
        .map(c -> c.getId()).collect(toList());