A crude iMessage API

Written by tk512 | Published 2016/09/23
Tech Story Tags: tech | docker

TLDRvia the TL;DR App

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.


Published by HackerNoon on 2016/09/23