'Fetches the inbound SMS from Twilio API
http://www.twilio.com/docs/api/rest'

@staticmethod
def poll_twilio(channel_id):

    db = current.db
    s3db = current.s3db
    table = s3db.msg_twilio_channel
    query = (table.channel_id == channel_id)
    channel = db(query).select(table.account_sid, table.auth_token, table.url, limitby=(0, 1)).first()
    if (not channel):
        return ('No    Such    Twilio    Channel:    %s' % channel_id)
    account_sid = channel.account_sid
    url = ('%s/%s/SMS/Messages.json' % (channel.url, account_sid))
    passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
    passman.add_password(None, url, account_sid, channel.auth_token)
    authhandler = urllib2.HTTPBasicAuthHandler(passman)
    opener = urllib2.build_opener(authhandler)
    urllib2.install_opener(opener)
    try:
        smspage = urllib2.urlopen(url)
    except urllib2.HTTPError as e:
        error = ('Error:    %s' % e.code)
        current.log.error(error)
        S3Msg.update_channel_status(channel_id, status=error, period=(300, 3600))
        return error
    else:
        sms_list = json.loads(smspage.read())
        messages = sms_list['sms_messages']
        stable = db.msg_twilio_sid
        sids = db((stable.id > 0)).select(stable.sid)
        downloaded_sms = [s.sid for s in sids]
        mtable = s3db.msg_sms
        minsert = mtable.insert
        sinsert = stable.insert
        update_super = s3db.update_super
        parser = s3db.msg_parser_enabled(channel_id)
        if parser:
            ptable = db.msg_parsing_status
            pinsert = ptable.insert
        for sms in messages:
            if ((sms['direction'] == 'inbound') and (sms['sid'] not in downloaded_sms)):
                sender = (('<' + sms['from']) + '>')
                _id = minsert(channel_id=channel_id, body=sms['body'], status=sms['status'], from_address=sender, received_on=sms['date_sent'])
                record = dict(id=_id)
                update_super(mtable, record)
                message_id = record['message_id']
                sinsert(message_id=message_id, sid=sms['sid'])
                if parser:
                    pinsert(message_id=message_id, channel_id=channel_id)
    return 'OK'
