paint-brush
A crude iMessage APIby@tk512
11,774 reads
11,774 reads

A crude iMessage API

by Torbjørn KristoffersenSeptember 23rd, 2016
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

If you have a Mac at home (like I do, it runs <a href="http://kodi.tv" target="_blank">Kodi</a> and is connected to my TV), you can <strong>also leverage it to control or query your home in different ways.</strong>

Company Mentioned

Mention Thumbnail
featured image - A crude iMessage API
Torbjørn Kristoffersen HackerNoon profile picture

If you have a Mac at home (like I do, it runs Kodi and is connected to my TV), you can also leverage it to control or query your home in different ways.

Being an iPhone user, I thought it would be neat to be able to send and receive commands to my house using iMessages, whether I’m at home or somewhere else.

Asking my Mac for a joke, it responds

So to limit the scope of this article, I’m just going to implement a very simple joke bot.

First of all, let’s write a shell script powered by AppleScript that allows us to send messages. We need to do this, as Apple does not provide an open API.

Let’s create an actual AppleScript handler for Messages.app:

This script needs to be placed in your ~/Library/Application Scripts/com.apple.iChat folder.

To install the handler, open Messages.app, go to Preferences>General and choose the MessageReceive.script file.

Now — upon receiving a message, Messages.app will send the message to the AppleScript receive handler.

Lastly, as MessageReceive.script simply calls the shell script ~/bin/MessageReceive.sh, we’ll have to create it as well:

#!/bin/bash


# Set shell optionsshopt -s nocasematch


sender=`echo ${1} | cut -d ':' -f 2`read line





sendChuckNorrisJoke() {message=$(curl -s "http://api.icndb.com/jokes/random" | python -mjson.tool | grep '\"joke\"' \| cut -d : -f 2 | sed 's/"/\"/g')${HOME}/bin/SendMessage.sh "${sender}" "${message}"}




if [[ $line =~ "joke" ]]; thensendChuckNorrisJokeexit 0fi


message="I do not understand what you mean."${HOME}/bin/SendMessage.sh "${sender}" "${message}"

The above script is simply a hack that only works with a Chuck Norris joke database.

The concept should be clear though, i.e. you can replace this with any type of script such as your very own personal AI bot, or switching lights on/off.