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:
|
// 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:
| sender | The phone number of the sender of the message. |
| text | The text of the message. |
As you see, associative arrays are also often used by the m library, whenever a set of related values has to be dealt with.
|
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 |