Auto-Creating Slack Channels from WordPress


Image from page 279 of “The Ladies’ home journal” (1889) flickr photo by Internet Archive Book Images shared with no copyright restriction (Flickr Commons)

In working through the project page a bit more, it seemed like it’d be more pleasant to start in WordPress and have our events echo outward in other services. One of those events is the creation of project specific Slack channels. In the past, I’d mainly listened for events . . . programmatically checking back every so often to see if something had occurred so I could do something else. In this case it made more sense to have one action directly precipitate another.

These are the three functions that fire when we publish the custom-post-type Project.1 In any case, it’s a pretty instantaneous creation and invitation to the channels.

function slackChannelMaker($id, $post){
	$token = 'yoursecrettoken';
	$id = $post->ID; //gets the post slug
	$channelName = $post->post_name;
	$slackAPI = 'https://slack.com/api/channels.create?token='.$token.'&name=%23'.$channelName.'&pretty=1'; //creates the channel
	file_get_contents($slackAPI); 
	$channelId = getSlackChannelId($channelName);	//goes to created channel to get the ID because you need that to invite people
	$invite = slackInviteUsers($channelId); //invites people via their unique ID 
}

function getSlackChannelId ($channelName){
                $token = 'yoursecrettoken';
		$channel_url = 'https://slack.com/api/channels.list?token='.$token.'&exclude_archived=true&pretty=1';
		$channels = file_get_contents($channel_url);
		$data = json_decode($channels);		
		$num_chan = sizeof($data->channels);
		for($i=1; $i < $num_chan; $i++){
			if ($data->channels[$i]->name == $channelName){
				$id = $data->channels[$i]->id;
				return $id;
			} 
	} return 'foo';
}

function slackInviteUsers($channelId){
	$token = 'yoursecrettoken';
	$jeff = 'jeffsuniqueID'; //I changed these just in case they mattered 
	$matt = 'mattsuniqueID';
	$tom = 'tomsuniqueID';
	$users = [$jeff,$matt,$tom];
	for ($x = 0; $x < sizeof($users); $x++) {		
		$fullURL = 'https://slack.com/api/channels.invite?token='.$token.'&channel='.$channelId.'&user='.$users[$x].'&pretty=1'; // It appears you have to invite one by one, thus the loop 
	    file_get_contents($fullURL);	    
	}
}


add_action( 'publish_project', 'slackChannelMaker', 10, 2); //the trigger for the function that fires on the publishing of the project custom post type

1 I don’t know how to punctuate that but it’s probably not hyphens.

Comments on this post

No comments.

Leave a Reply

Trackbacks and Pingbacks on this post

No trackbacks.

TrackBack URL