Accessing SMS

Given our small database db, we can now look into receiving and sending SMS.

To access the SMS functionality of your phone from m, we load the corresponding module. There are many modules for different functions of your phone, or of m; chapter * () gives you an overview. A few good reasons for having modules:

The module giving SMS access is called, not surprisingly, module sms. Using it, our service could look as follows:

// load the SMS module
use sms
// define the reply database
db=["party": "The party starts at 8pm!",
    "place": "I am at home.",
    "mood": "Just don't ask."];
while true do
  // wait for a message
  id=sms.receive();
  // get the message
  msg=sms.get(id);
  // get the trimmed text in lowercase
  t=lower(trim(msg["text"]));
  // if we find it in our database, reply
  if db[t]#null then
    print "Got",t,"from",msg["sender"];
    sms.send(msg["sender"], db[t]);
    sms.delete(id)
  end
end

A few explanations:

When creating automated replying systems, it is a good idea to check whether we are not accidentally replying to a message coming from ourselves, and entering into a never ending loop. Let's assume we have added a keyword "echo" with reply "echo":

db["echo"]="echo";

If we now send ourselves a message "echo", the service will start to reply to itself until it is stopped.

This is unlikely to happen, but if it does, the consequences may be quite expensive.

In m, there is a simple way to check whether we sent a message to ourselves: if m is properly configured, gsm.number contains our own phone number which we can check against. The above check for a valid message can be completed by:

  // if it's not from us, and we find it
  // in our database, reply
  if msg["sender"]#gsm.number and db[t]#null then

Don't forget to add module gsm to the use clause:

use sms, gsm


© 2004-2010 airbit AG, CH-8008 Zürich
Document AB-M-TUT-869