-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwitterb.py
More file actions
executable file
·162 lines (126 loc) · 5.25 KB
/
Copy pathtwitterb.py
File metadata and controls
executable file
·162 lines (126 loc) · 5.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# -*- coding: utf-8 -*-º
#!/usr/bin/python
# This is a Python port of Adafruit's "Gutenbird" sketch for Arduino.
# Polls one or more Twitter accounts for changes, displaying updates
# on attached thermal printer.
# Written by Adafruit Industries. MIT license.
#
# Required hardware includes an Internet-connected system with Python
# (such as Raspberry Pi) and an Adafruit Mini Thermal Receipt printer
# and all related power supplies and cabling.
# Required software includes Adafruit_Thermal and PySerial libraries.
#
# Resources:
# http://www.adafruit.com/products/597 Mini Thermal Receipt Printer
# http://www.adafruit.com/products/600 Printer starter pack
#
# Uses Twitter 1.1 API application-only authentication. This
# REQUIRES a Twitter account and some account configuration. Start
# at dev.twitter.com, sign in with your Twitter credentials, select
# "My Applications" from the avatar drop-down menu at the top right,
# then "Create a new application." Provide a name, description,
# placeholder URL and complete the captcha, after which you'll be
# provided a "consumer key" and "consumer secret" for your app.
# Copy these strings to the globals below, and configure the search
# string to your liking. DO NOT SHARE your consumer key or secret!
# If you put code on Github or other public repository, replace them
# with dummy strings.
from __future__ import print_function
import base64, HTMLParser, httplib, json, sys, urllib, zlib
from unidecode import unidecode
from Adafruit_Thermal import *
import RPi.GPIO as IO
import time
import os
# Configurable globals. Edit to your needs. -------------------------------
# Twitter application credentials -- see notes above -- DO NOT SHARE.
consumer_key = os.environ['CONSUMER_KEY']
consumer_secret = os.environ['CONSUMER_SECRET']
# queryString can be any valid Twitter API search string, including
# boolean operators. See http://dev.twitter.com/docs/using-search
# for options and syntax. Funny characters do NOT need to be URL
# encoded here -- urllib takes care of that.
queryString = 'amor'
# Other globals. You probably won't need to change these. -----------------
printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)
host = 'api.twitter.com'
authUrl = '/oauth2/token'
searchUrl = '/1.1/search/tweets.json?'
agent = 'Gutenbird v1.0'
# lastID is command line value (if passed), else 1
if len(sys.argv) > 1: lastId = sys.argv[1]
else: lastId = '1'
# Initiate an HTTPS connection/request, uncompress and JSON-decode results
def issueRequestAndDecodeResponse(method, url, body, headers):
connection = httplib.HTTPSConnection(host)
connection.request(method, url, body, headers)
response = connection.getresponse()
if response.status != 200:
# This is OK for command-line testing, otherwise
# keep it commented out when using main.py
# print('HTTP error: %d' % response.status)
exit(-1)
compressed = response.read()
connection.close()
return json.loads(zlib.decompress(compressed, 16+zlib.MAX_WBITS))
# Mainline code. -----------------------------------------------------------
def start_printing():
# LED configuration
IO.setmode(IO.BOARD)
IO.setup(33, IO.OUT)
IO.setup(31, IO.OUT)
IO.setup(29, IO.OUT)
# Get access token. --------------------------------------------------------
token = issueRequestAndDecodeResponse(
'POST', authUrl, 'grant_type=client_credentials',
{'Host' : host,
'User-Agent' : agent,
'Accept-Encoding' : 'gzip',
'Content-Type' : 'application/x-www-form-urlencoded;charset=UTF-8',
'Authorization' : 'Basic ' + base64.b64encode(
urllib.quote(consumer_key) + ':' + urllib.quote(consumer_secret))}
)['access_token']
# Perform search. ----------------------------------------------------------
IO.output(33, True)
time.sleep(1)
data = issueRequestAndDecodeResponse(
'GET',
(searchUrl + 'count=3&since_id=%s&q=%s' %
(lastId, urllib.quote(queryString))),
None,
{'Host' : host,
'User-Agent' : agent,
'Accept-Encoding' : 'gzip',
'Authorization' : 'Bearer ' + token})
IO.output(33, False)
# Display results. ---------------------------------------------------------
maxId = data['search_metadata']['max_id_str']
# Printer LED on
IO.output(31, True)
time.sleep(1)
for tweet in data['statuses']:
printer.inverseOn()
printer.print(' ' + '{:<31}'.format(tweet['user']['screen_name']))
printer.inverseOff()
printer.underlineOn()
printer.print('{:<32}'.format(tweet['created_at']))
printer.underlineOff()
# max_id_str is not always present, so check tweet IDs as fallback
id = tweet['id_str']
if(id > maxId): maxId = id # String compare is OK for this
# Remove HTML escape sequences
# and remap Unicode values to nearest ASCII equivalents
printer.print(unidecode(
HTMLParser.HTMLParser().unescape(tweet['text'])))
printer.feed(3)
# Printer LED off
IO.output(31, False)
time.sleep(5)
IO.output(29, True)
time.sleep(3)
IO.output(29, False)
IO.cleanup()
print(maxId) # Piped back to calling process
time.sleep(10)
while True:
start_printing()