Skip to content

Commit

Permalink
Merge branch 'master' of git@github.com:matburt/stormtweet
Browse files Browse the repository at this point in the history
  • Loading branch information
tiberius committed Jun 15, 2009
2 parents 13b7901 + f500994 commit 7e53042
Show file tree
Hide file tree
Showing 5 changed files with 120 additions and 60 deletions.
8 changes: 4 additions & 4 deletions model.py
@@ -1,7 +1,7 @@
from elixir import *
import mx.DateTime

## Set the data base backend (maybe pgsql later?)
# Set the data base backend
metadata.bind = "postgres://stormtweet:270rm@localhost/stormtweet"
## Debug SQL for now
metadata.bind.echo = True
Expand Down Expand Up @@ -72,7 +72,7 @@ def createDataBase():
TweetStates(value='New')
TweetStates(value='Successful')
TweetStates(value='Error')

FollowerStates(value='Active')
FollowerStates(value='Silenced')
FollowerStates(value='Inactive')
Expand Down Expand Up @@ -126,6 +126,6 @@ def createDataBase():
UnitedStates(value='WA', name='Washington')
UnitedStates(value='WV', name='West Virginia')
UnitedStates(value='WI', name='Wisconsin')
UnitedStates(value='WY', name='Wyoming')
UnitedStates(value='WY', name='Wyoming')

session.commit()
File renamed without changes.
43 changes: 20 additions & 23 deletions noaaRSS.py
Expand Up @@ -52,8 +52,6 @@ def parse(self, nfeed):
self.displayEntry(e)
storm=self.recordEntry(e)
self.alertOnStorm(storm)
## n = NOAA2Message()
## n.convert(self.shelf["thunderstorm"][newid])
self.shelf["thunderstorm"][newid]

# Clean up the existing entries
Expand All @@ -67,35 +65,34 @@ def summarize(self):
pass

def recordEntry(self, e):
stormType=StormType.get_by(value='Thunderstorm')
stormState=StormStates.get_by(value='New')
uState=UnitedStates.get_by(abbreviation=e['id'][0:2])
newStorm=Storm(stormID=e['id'],stormType=stormType,effective=e['cap_effective'],
expires=e['cap_expires'],sevLevel=e['cap_severity'],
urgency=e['cap_urgency'],summary=e['summary'],
uState=uState,sState=sState)
stormType=StormType.get_by(value ='Thunderstorm')
stormState=StormStates.get_by(value = 'New')
uState=UnitedStates.get_by(abbreviation = e['id'][0:2])
newStorm=Storm(stormID = e['id'],
stormType = stormType,
effective = e['cap_effective'],
expires = e['cap_expires'],
sevLevel = e['cap_severity'],
urgency = e['cap_urgency'],
summary = e['summary'],
uState = uState,
sState = sState)
newStorm.update_or_save()
return newStorm

def alertOnStorm(self,storm):
# this whole function may need to run as a separate thread
# instead of inline with the rss parsing

## change the state to proccessing until we finish sending the alerts
stormState=StormStates.get_by(value='Processing')
# change the state to proccessing until we finish sending the alerts
stormState=StormStates.get_by(value = 'Processing')
storm.sState=stormState
storm.update_or_save()
##find all active users following the uState affected by the storm
#find all active users following the uState affected by the storm

## for each active user
#######send a direct message to each user
# for each active user
# send a direct message to each user
#record the tweet sent to each user

#######record the tweet sent to each user

##after alerting all users, change the stormstate to dispatched so we know we told everyone






#after alerting all users, change the stormstate to dispatched so we
#know we told everyone
4 changes: 4 additions & 0 deletions stormtweet.conf
Expand Up @@ -2,3 +2,7 @@
checkinterval = 240
noaafeed = http://www.weather.gov/alerts-beta/us.php?x=1
shelfFile = stormtweet

[tweetbox]
user = stormwarn
password = xxx
125 changes: 92 additions & 33 deletions tweetBot.py
Expand Up @@ -2,58 +2,90 @@
import time
from model import *
from sqlalchemy import func
from ConfigParser import RawConfigParser
import optparse

## setup the model
SORRY_MSG = """
I am sorry %s , I can not do that. Please try follow|silence|stop XX
"""
FOLLOW_SUCCESS_MSG = """
Congrats! You are now following storms in %s. Silence updates with: silence %s
"""
SILENCE_SUCCESS_MSG = """
SHHHHHH. You have silenced updates for storms in %s. Enable
updates with: follow %s
"""
STOP_SUCCESS_MSG = """
FOR SHAME! You are no longer following storms in %s. Enable updates with:
follow %s
"""
UNKNOWN_MSG = """
I am sorry %s , I can not do that. Please try follow|silence|stop XX
"""
FOLLOWING_MSG = """
Thanks for following StormWarn! To get storm warnings for a state with postal
abbreviation XX send me:\nfollow XX to get updates
"""
# setup the model
setup_all()

class TweetBot:
def __init__(self):
self.tbox=Twitter('stormwarn','st0rmp22wd')
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 abbreveation
# 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)

follower=Follower.get_by(userid = sender)
if not follower:
follower=Follower(userid=sender)
follower=Follower(userid = sender)
session.commit()

ustate = UnitedStates.get_by(value=state)
if not ustate:
self.tbox.direct_messages.new(user=sender, text='I am sorry %s , I can not do that. Please try follow|silence|stop XX' % sender)
self.tbox.direct_messages.new(user = sender,
text=SORRY_MSG % sender)

if action == 'follow':
fstate=FollowerStates.get_by(value='Active')
follower.fState=fstate
follower.uState=ustate
fstate = FollowerStates.get_by(value='Active')
follower.fState = fstate
follower.uState = ustate
follower.update()
self.tbox.direct_messages.new(user=sender, text='Congrats! You are now following storms in %s. Silence updates with silence %s' % (state,state))
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
fstate = FollowerStates.get_by(value='Slienced')
follower.fState = fstate
follower.uState = ustate
follower.update()
self.tbox.direct_messages.new(user=sender, text='SHHHHHH. You have silenced updates for storms in %s. Enable updates with follow %s' % (state,state))
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
fstate = FollowerStates.get_by(value='Inactive')
follower.fState = fstate
follower.uState = ustate
follower.update()
self.tbox.direct_messages.new(user=sender, text='FOR SHAME! You are no longer following storms in %s. Enable updates with follow %s' % (state,state))
self.tbox.direct_messages.new(user = sender,
text = STOP_SUCCESS_MSG %
(state,state))
else:
self.tbox.direct_messages.new(user=sender, text='I am sorry %s , I can not do that. Please try follow|silence|stop XX' % sender)

self.tbox.direct_messages.new(user = sender,
text = UNKNOWN_MSG % sender)

session.commit()


def getMessages(self):
lastMessageID=DirectMessages.query().max(DirectMessages.messageID)
messages=self.tbox.direct_messages(since_id=lastMessageID)
lastMessageID = DirectMessages.query().max(DirectMessages.messageID)
messages = self.tbox.direct_messages(since_id = lastMessageID)
for aMessage in messages:
self.recordMessage(aMessage)

Expand All @@ -64,21 +96,48 @@ def makeFriends(self):
newFriends=followers - currentFriends
for aFriend in newFriends:
self.tbox.friendships.create(id=aFriend)
screen_name=self.tbox.users.show(id=aFriend)['screen_name']
self.tbox.direct_messages.new(user=screen_name, text='''Thanks for following StormWarn! To get storm warnings for a state with postal abbreviation XX send me:\nfollow XX to get updates''')
screen_name=self.tbox.users.show(id = aFriend)['screen_name']
self.tbox.direct_messages.new(user = screen_name,
text = FOLLOWING_MSG)
session.commit()

def doit(self):
self.makeFriends()
self.getMessages()

def getConfig(path): # move into common module with stormtweet.getConfig
rc = RawConfigParser()
if path not in rc.read(path):
print("Invalid Configuration File")
sys.exit(1)
return rc

def getOptions():
op = optparse.OptionParser()
op.add_option("-c", "--config", dest="config",
help="configuration file")
op.add_option("-i", "--initialize", dest="initialize",
help="Initialize database, don't actually post entries")
op.add_option("-v", "--verbose", dest="verbose",
help="Display extra information")
(options, args) = op.parse_args()

if __name__=='__main__':
spam=TweetBot()
if options.config is None:
print("Configuration file required")
sys.exit(1)

return (options, args)

def main():
options, args = getOptions()
config = getConfig(options.config)
spam=TweetBot(config.get("tweetbox", "user"),
config.get("tweetbox", "password"))

while 1:
spam.doit()
print 'sleeping ....'
time.sleep(1800)


if __name__=='__main__':
main()

0 comments on commit 7e53042

Please sign in to comment.