#!/opt/local/bin/python
# -*- coding: utf-8 -*-
"""
@requirements: python-twitter : a wrapper around the Twitter API (http://code.google.com/p/python-twitter/)
@author: Radu Boncea
@contact: http://raduboncea.ro http://twitter.com/raduboncea
"""
import imaplib, sys, re, twitter
GMAIL_USERNAME = 'GMAIL_USERNAME'
GMAIL_PASSWORD = 'GMAIL_PASSWORD'
GMAIL_TWITTER_LABEL = 'TwitterFollow'
TWITTER_USERNAME = 'TWITTER_USERNAME'
TWITTER_PASSWORD = 'TWITTER_PASSWORD'
TWITTER_DM = '10x for the follow. Interested in seo,web,social nets, programming. You can also find me on http://raduboncea.ro Many tweets!'
mail = imaplib.IMAP4_SSL('imap.gmail.com', 993)
try:
mail.login(GMAIL_USERNAME, GMAIL_PASSWORD)
except Exception,e:
print e
sys.exit()
mail.select(GMAIL_TWITTER_LABEL, readonly=False)
retcode, msg_ids = mail.search(None, 'UNSEEN')
if retcode != 'OK':
print 'Error' , retcode
sys.exit()
try:
twitter=twitter.Api(TWITTER_USERNAME,TWITTER_PASSWORD)
except Exception,e:
print e
sys.exit()
for message in msg_ids[0].split(' '):
if message == '':
sys.exit()
(ret, mesginfo) = mail.fetch(message, '(BODY.PEEK[HEADER] FLAGS)') #retrieving only headers and flags
if ret == 'OK':
headers = mesginfo[0][1]
twitter_sender = re.findall(r"X-Twittersenderscreenname: (\w+)", headers,re.M)[0].strip(' ')
twitter_sender_id = re.findall(r"X-Twittersenderid: (\w+)", headers,re.M)[0].strip(' ')
friendship_created = False
try:
twitter.CreateFriendship(twitter_sender)
friendship_created = True
except Exception:
if re.search('Error 403', str(sys.exc_value), re.I):
print "You already follow %s" % twitter_sender.encode( 'utf-8' )
else:
print "Critical error occured while adding %s as friend %s" % ( twitter_sender.encode( 'utf-8' ),sys.exc_value )
sys.exit()
try:
twitter.PostDirectMessage(twitter_sender, TWITTER_DM)
mail.store(message, '+FLAGS', r'(\Seen)')
if friendship_created is True:
print "%s FOLLOW and DM" % twitter_sender.encode( 'utf-8' )
else:
print "%s NOT FOLLOWING only DM" % twitter_sender.encode( 'utf-8' )
except:
print "Critical error could not DM %s %s" % ( twitter_sender.encode( 'utf-8' ),sys.exc_value )
mail.close()
0 Comments