twitter.py 2.89 KB
#!/usr/bin/env python

import tweepy
import random
import MySQLdb
import os
import base64

consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""

sql_host = "localhost"
sql_port = 3306
sql_user = ""
sql_password = ""
sql_database = ""

repost_text = False
random_mode = True

class Post:
	text = ""
	picture = ""
	def __init__(self,picture,text):
		self.text = text
		self.picture = picture

	def post(self,api):
		api.update_with_media(self.picture,self.text)
		os.remove(self.picture)

def login():
	auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
	auth.set_access_token(access_token, access_token_secret)
	return tweepy.API(auth)

def getRandomNum(limit):
	return random.randint(0,limit-1)
	
def openDB(host,port,user,password,database):
	db = MySQLdb.connect(host,user,password,database)
	return db	

def saveImage(filename,data):
	image = open(filename,'wb')
	image.write(base64.b64decode(data))
	image.close()

def getNewPostNumber():
	db = openDB(sql_host,sql_port,sql_user,sql_password,sql_database)
	num = -1
	cur = db.cursor()
	cur.execute("SELECT COUNT(*) FROM twitter_newposts");
	num = cur.fetchone()[0]
	cur.close()
	db.close()
	return num

def getOldPostNumber():
        db = openDB(sql_host,sql_port,sql_user,sql_password,sql_database)
        num = -1
        cur = db.cursor()
        cur.execute("SELECT COUNT(*) FROM twitter_oldposts");
        num = cur.fetchone()[0]
	cur.close()
        db.close()
        return num

def getPost(num,newPosts):
	db = openDB(sql_host,sql_port,sql_user,sql_password,sql_database)
	table = ""
	if(not newPosts):
		table = "twitter_oldposts"
	else:
		table = "twitter_newposts"

	cur = db.cursor()
	cur.execute("SELECT * FROM " + table + " ORDER BY id LIMIT " + str(num) + ",1")
	#text,filename,data
	print "post is " + str(num) + " from " + table
	entry = cur.fetchone()
	text = ""
	if((table == "twitter_newposts") or ((table == "twitter_oldposts") and repost_text)):
		text = entry[1]
	
	saveImage("/tmp/"+entry[2],entry[3])
	post = Post("/tmp/"+entry[2],text)
	cur.close()
	db.close()
	return post

def movePost(num):
	db = openDB(sql_host,sql_port,sql_user,sql_password,sql_database)
	cur = db.cursor()
	cur.execute("SELECT * FROM twitter_newposts ORDER BY id LIMIT " + str(num) + ",1")
	#text,filename,data
       	entry = cur.fetchone()
	cur.execute("DELETE FROM twitter_newposts WHERE id="+str(entry[0]))
	db.commit();
	cur.execute("INSERT INTO twitter_oldposts (text,filename,picture) VALUES(\'"+entry[1]+"\',\'"+entry[2]+"\',\'"+entry[3]+"\')")
	db.commit()
	cur.close()
	db.close()


api = login()
num = 0
newPosts = True
if(getNewPostNumber() == 0):
	newPosts = False
if(newPosts or getOldPostNumber() != 0):
	if(random_mode):
		if(not newPosts):
			num = getRandomNum(getOldPostNumber())
		else:
			num = getRandomNum(getNewPostNumber())	

	post = getPost(num,newPosts)
	post.post(api)
	if(newPosts):
		movePost(num)
else:
	print "No content. Exiting!"