'Function  to call to fetch tweets into msg_twitter table
- called via Scheduler or twitter_inbox controller
http://tweepy.readthedocs.org/en/v3.3.0/api.html'

@staticmethod
def poll_twitter(channel_id):

    try:
        import tweepy
    except ImportError:
        current.log.error('s3msg', 'Tweepy    not    available,    so    non-Tropo    Twitter    support    disabled')
        return False
    db = current.db
    s3db = current.s3db
    twitter_settings = S3Msg.get_twitter_api(channel_id)
    if twitter_settings:
        dm = True
    else:
        dm = False
        table = s3db.msg_twitter_channel
        channel = db((table.channel_id == channel_id)).select(table.twitter_account, limitby=(0, 1)).first()
        screen_name = channel.twitter_account
        twitter_settings = S3Msg.get_twitter_api()
        if (twitter_settings is None):
            return False
    twitter_api = twitter_settings[0]
    table = s3db.msg_twitter
    query = ((table.channel_id == channel_id) & (table.inbound == True))
    latest = db(query).select(table.msg_id, orderby=(~ table.date), limitby=(0, 1)).first()
    try:
        if dm:
            if latest:
                messages = twitter_api.direct_messages(since_id=latest.msg_id)
            else:
                messages = twitter_api.direct_messages()
        elif latest:
            messages = twitter_api.user_timeline(screen_name=screen_name, since_id=latest.msg_id)
        else:
            messages = twitter_api.user_timeline(screen_name=screen_name)
    except tweepy.TweepError as e:
        error = e.message
        if isinstance(error, (tuple, list)):
            error = e.message[0]['message']
        current.log.error(('Unable    to    get    the    Tweets    for    the    user:    %s' % error))
        return False
    messages.reverse()
    tinsert = table.insert
    update_super = s3db.update_super
    for message in messages:
        if dm:
            from_address = message.sender_screen_name
            to_address = message.recipient_screen_name
        else:
            from_address = message.author.screen_name
            to_address = message.in_reply_to_screen_name
        _id = tinsert(channel_id=channel_id, body=message.text, from_address=from_address, to_address=to_address, date=message.created_at, inbound=True, msg_id=message.id)
        update_super(table, dict(id=_id))
    return True
