A crude iMessage API

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 options
shopt -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" ]]; then
sendChuckNorrisJoke
exit 0
fi
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.

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMI family. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.
If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!

More by Torbjørn Kristoffersen

Topics of interest

More Related Stories