Archive

Archive for September, 2011

PacketTerrier Twitter Bot

September 13th, 2011 No comments

Like any good nerd, I felt my dog needed a twitter. This is written in Python using the python-twitter library.

http://www.twitter.com/PacketTerrier


#!/usr/bin/env python
import time
import twitter
import math
import random
import threading
import logging

interface = twitter.Api(consumer_key='', consumer_secret='', access_token_key='', access_token_secret='')

def main():
	logging.basicConfig(filename='packetTwitter.log',level=logging.DEBUG)
	tt = TweeterThread(interface)
	ft = FrienderThread(interface)
	tt.daemon = True
	ft.daemon = True
	tt.start()
	ft.start()
	while True:
		time.sleep(1)
		pass

class TweeterThread(threading.Thread):
	def __init__(self,interface):
		self.interface = interface
		threading.Thread.__init__(self)

	def run(self):
		logging.info("Tweeter Start")
		message = None
		lastMessage = None
		status = None
		while True:
			nextSleep =  math.ceil(random.uniform(1800,7200))
			while message == lastMessage:
				message = chooseTweet(nextSleep)
				time.sleep(15)
			try:
				logging.info("Posting status update")
				status = self.interface.PostUpdate(message)
			except twitter.TwitterError, error:
				logging.error("Twitter API Error: '%s'  Trying again in 60 seconds." % error.message)
				nextSleep = 60
			logging.debug(message)
			lastMessage = message
			time.sleep(nextSleep)

class FrienderThread(threading.Thread):
	def __init__(self,interface):
		self.interface = interface
		threading.Thread.__init__(self)

	def run(self):
		logging.info("Friender Start")
		friends = self.interface.GetFriends()
		while True:
			logging.info("Checking for new friends")
			replies = self.interface.GetReplies()
			for r in replies:
				isFriend = False
				for f in friends:
					if f._screen_name == r._user._screen_name:
						isFriend = True
				if not isFriend:
					logging.info("Making friends with %s" % r._user._screen_name)
					self.interface.CreateFriendship(r._user._screen_name)
					self.interface.PostUpdate("Hai @%s! I like making new friends!  Did you bring me treats?!?!" % r._user._screen_name)
					friends = self.interface.GetFriends()
			time.sleep(600)

def chooseTweet(nextSleep):
    hour = time.strftime("%H")
    minute = time.strftime("%M")
    if hour >= 23 and (hour < = 6 and minute <= 59):
        messageFile = "sleepMessage.txt"
    elif hour >= 16 and hour < = 17 and (time.strftime("%w") >= 1 and time.strftime("%w") <= 5):
        messageFile = "homeSoonMessage.txt"
    else:
        messageFile = "dayMessage.txt"
    messages = list()
    mf = open(messageFile, "r")
    for line in mf:
        messages.append(line)
    mf.close()
    return random.choice(messages).strip()

if __name__ == '__main__':
	main()
Categories: Uncategorized Tags:

dork-e.com is Stephen Fry proof thanks to caching by WP Super Cache