class TweetBot: def __init__(self, tUser, tPassword): self.tbox = Twitter(tUser, tPassword) def recordMessage(self, message): # Need to parse the really lame timestamp twitter uses in 'created_at' dm = DirectMessages(messageID = message['id']) # Expect the message to be 'follow XX' where XX is a state # abbreveiation action = message['text'].split()[0].lower() state = message['text'].split()[1].upper() sender = message['sender_screen_name'] follower=Follower.get_by(userid = sender) if not follower: follower=Follower(userid = sender) session.commit() ustate = UnitedStates.get_by(value=state) if not ustate: self.tbox.direct_messages.new(user = sender, text=SORRY_MSG % sender) return if action == 'follow': fstate = FollowerStates.get_by(value='Active') follower.fState = fstate follower.uState = ustate follower.update() self.tbox.direct_messages.new(user = sender, text = FOLLOW_SUCCESS_MSG % (state,state)) elif action == 'silence': fstate = FollowerStates.get_by(value='Slienced') follower.fState = fstate follower.uState = ustate follower.update() self.tbox.direct_messages.new(user = sender, text = SILENCE_SUCCESS_MSG % (state,state)) elif action == 'stop': fstate = FollowerStates.get_by(value='Inactive') follower.fState = fstate follower.uState = ustate follower.update() self.tbox.direct_messages.new(user = sender, text = STOP_SUCCESS_MSG % (state,state)) else: self.tbox.direct_messages.new(user = sender, text = UNKNOWN_MSG % sender) session.commit() def getMessages(self): prevMsgs = DirectMessages.query().order_by( desc(DirectMessages.messageTime)).limit(1).all() if len(prevMsgs) < 1: lastMessageID = None else: lastMessageID = prevMsgs[0].messageID print "Getting Direct Messages since %s " %(lastMessageID) messages = self.tbox.direct_messages(since_id = lastMessageID) for aMessage in messages: self.recordMessage(aMessage) def makeFriends(self): currentFriends=set(self.tbox.friends.ids.stormwarn()) followers=set(self.tbox.followers.ids.stormwarn()) newFriends=followers - currentFriends for aFriend in newFriends: try: self.tbox.friendships.create(id=aFriend) except Exception: print "Failed to follow %s" % aFriend continue screen_name=self.tbox.users.show(id = aFriend)['screen_name'] self.tbox.direct_messages.new(user = screen_name, text = FOLLOWING_MSG) session.commit() def run(self): while True: print("Making friends and processing messages.") self.makeFriends() self.getMessages() time.sleep(900)