Instantly share code, notes, and snippets.

Embed
What would you like to do?
Checks a twitter account's most recent tweet. Sends an email if new.
#!/usr/bin/python
import os
import subprocess as sub
import urllib2
from BeautifulSoup import BeautifulSoup
TWITTERUSER = cupcakory # if you want to check twitter.com/cupcakory for updates
EMAILADDR = gabe@example.com
# get the most recent tweet from Twitter
page = urllib2.urlopen("http://twitter.com/" + TWITTERUSER)
soup = BeautifulSoup(page)
contentTags = soup.findAll('span', attrs={"class" : "entry-content"})
twitterTweet = contentTags[0].string
# Have we seen that Tweet before, and saved it?
newTweet = False
filename = os.path.join(os.path.dirname(__file__), 'recentest.txt')
try:
f = open(filename, 'r')
fileTweet = f.read();
if fileTweet != twitterTweet:
newTweet = True
f.close()
except IOError:
newTweet = True # file not present, make new file with current tweet
# if new, overwrite old file with new tweet and send email alert
if newTweet:
with open(filename, 'w') as f:
f.write(twitterTweet)
# prepare mail messages:
mailMsg = "to:" + EMAILADDR + "\n"
mailMsg += "subject:Update from " + TWITTERUSER + "\n\n"
mailMsg += twitterTweet
mailMsg += "\n"
# send via sendmail subprocess
p = sub.Popen(['/usr/sbin/sendmail -t'], shell=True, stdin=sub.PIPE)
p.communicate(input=mailMsg)
@losvedir

This comment has been minimized.

Owner

losvedir commented Sep 13, 2010

Full disclosure: Only as I was pasting it into this gist box did I pull the TWITTERUSER and EMAILADDR out and up to the top -- haven't tested it. It works if you just hardcode that info into the script, though, as I did.

@losvedir

This comment has been minimized.

Owner

losvedir commented Sep 15, 2010

Brief walkthrough here: http://www.gabedurazo.com/blog/?p=39

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment