Reputation: 9289
I am playing with slack apis to create an integration. I am able to sucessfully create a slack channel using
this.http.post(slackApiHost + '/channels.create', payload, {headers: headers})
.subscribe(
res => {
console.log(res);
resolve(res)
},
err => {
console.log('error:' + err)
}
)
})
the payload looks like
var payload = {
"name" : channelName
};
So, it will fail with name_taken if the channel already exists. which is great. However, I need to find the channel id of the existing channel so that i can then use it for my purpose. how do i go about it?
Upvotes: 11
Views: 21291
Reputation: 111
You can use built-in admin.conversations.search and then iterate found results.
One more kind of fast tricky solution: try to send chat.scheduleMessage and then if it was sent chat.deleteScheduledMessage or catch error. Ruby example:
def channel_exists?(channel)
begin
response = @slack_client.chat_scheduleMessage(channel: channel, text: '', post_at: Time.now.to_i + 100)
@slack_client.chat_deleteScheduledMessage(channel: channel, scheduled_message_id: response.scheduled_message_id)
return true
rescue Slack::Web::Api::Errors::ChannelNotFound
return false
end
end
Upvotes: 5
Reputation: 2883
There's currently no direct Slack API to find a slack channel by its name. But you can use conversations.list to handle this and here's the right code to use:
const slack = new SlackWebClient(token);
const channelNameToFind = "test";
for await (const page of slack.paginate("conversations.list", {
limit: 50,
})) {
for (const channel of page.channels) {
if (channel.name === channelNameToFind) {
console.log(`Found ${channelNameToFind} with slack id ${channel.id}`);
break;
}
}
}
This is the right way™️ to do it since it will ensure you stop listing channels as soon as you found the right one.
Good luck!
Upvotes: 6
Reputation: 32698
To get a list of all existing channel you can use conversations.list
. This is the most flexible approach and allows you to retrieve any type of channel if you so choose.
If you are looking for a channel by a specific name you will need to first retrieve the list of all channels and then run your own name matching against the full list. An API method which allows you to directly search for a channel by name does not exist.
Note that if you are looking for private channels this method will only retrieve channels that you (the installer of your Slack app / your bot user) has been invited to.
Upvotes: 12