Hackover 2012/Hashtag Printing

Wechseln zu: Navigation, Suche
Exclamation.png Diese Version des Hashtag-Printing-Scripts ist veraltet. Auf GitHub liegt die aktuelle Version.


Inhaltsverzeichnis

Usage

python hashtag.py <hashtag_ohne_#>

hashtag.py

#!/usr/bin/python
# -*- coding: utf-8 -*-
 
import sys
import serial
from datetime import datetime, timedelta
from time import strftime, asctime, mktime, strptime, sleep
import textwrap
import twitter
 
def printUsage():
	print "Usage: hashtag.py [hashtag]"
 
# Printer stuff
printer = serial.Serial("/dev/ttyUSB0", 19200)
 
try:
	hashtag = sys.argv[1]
except IndexError:
	printUsage()
	quit()
 
 
def headline(text, metadata=None):
	# Bigger font
	printer.write("\x1b\x21\x20" + textwrap.fill(text,24) + "\n" + "\x1b\x21\0")
	printer.write("------------------------------------------------\n")
	printer.write(strftime("%d.%m.%Y %H:%M") + "\n")
 
	if metadata != None:
		for i in range(0,len(metadata)):
			printer.write(metadata[i] + "\n")
 
	printer.write("------------------------------------------------\n\n")
 
 
 
def cut(partial=False):
	# feed paper
	printer.write("\n\n\n\n\n")
 
	if partial:
		printer.write("\x1b\x6D")
	else:
		printer.write("\x1b\x69")
 
 
def main():
	# some fancy metadata stuff
	headline(hashtag)
 
	try:
		while 1:
			last_id_filename = "last_id_hashtag_" + hashtag
 
			try:
				file = open(last_id_filename, "r")
				savepoint = file.read()
				file.close()
			except IOError:
				savepoint = ""
 
			print asctime(), "Doing a search ...",
			twit = twitter.Twitter(True)
			# search query
			timeline = twit.search("%(hashtag)s OR #%(hashtag)s OR from:Hackover2012" \
				% { "hashtag" : hashtag }, since_id=savepoint, max_results=999)
			print len(timeline),"items found."
 
			# filter @replies out and reverse timeline
			timeline = filter(lambda status: status["text"][0] != "@", timeline)
			timeline.reverse()
 
			for status in timeline:
				# Generates messages
				timestamp = datetime.fromtimestamp(mktime(strptime(status["created_at"], "%a, %d %b %Y %H:%M:%S +0000")))
				# GMT+2 (beware of stupid daylight saving)
				timestamp += timedelta(hours=2)
 
				message = "(%(created)s) %(screenname)s: %(statusmessage)s\n\n" \
					% {"created" : timestamp, "screenname" : status["from_user"], "statusmessage" : status["text"]}
 
				# Wraps the text in order to avoid cut text
				message = textwrap.fill(text=message, width=48)
				message = message + "\n\n"
				printer.write(message.encode('cp437', 'replace'))
				print message
 
			# write last printed tweet id to file
			if len(timeline) != 0:
				file = open(last_id_filename, "w")
				file.write(str(timeline[-1]["id"]))
				file.close()
 
			sleep(60)
 
 
	except KeyboardInterrupt:
		cut()
 
main()

twitter.py

#!/usr/bin/python
# -*- coding: utf-8 -*-
 
import datetime
import json
import urllib
import urlparse
 
# "Searching Twitter with Python" by Derrick Petzold 
# http://derrickpetzold.com/p/twitter-python-search/
# (since_id added)
class Twitter(object):
 
	search_url = 'http://search.twitter.com/search.json'
 
	def __init__(self, verbose=False):
		self.verbose = verbose
		super(Twitter, self).__init__()
 
	def search(self, query, until=None, rpp=100, since_id="", max_results=None):
 
		results = []
		params = {
			'q': query,
			'rpp': rpp,
			'since_id' : since_id,
		}
		if until:
			params['until'] = until.strftime('%Y-%m-%d')
 
		if self.verbose:
			print(params)
 
		url = '%s?%s' % (self.search_url, urllib.urlencode(params))
		response = json.loads(urllib.urlopen(url).read())
		results.extend(response['results'])
 
		if len(results) >= max_results:
			return results
 
		while 'next_page' in response:
			url = self.search_url + response['next_page']
			response = json.loads(urllib.urlopen(url).read())
 
			if self.verbose:
				print('%s: %s' % (url, len(response['results'])))
 
			results.extend(response['results'])
			if len(results) >= max_results:
				break
		return results
 
	def search_last_day(self, *args, **kwargs):
		kwargs['until'] = datetime.datetime.now() - datetime.timedelta(days=1)
 
		return self.search(*args, **kwargs)