-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmy_test.py
173 lines (127 loc) · 3.74 KB
/
my_test.py
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
163
164
165
166
167
168
169
170
171
import sys, traceback
import signal
import traceback
from time import sleep
from threading import Timer
from datetime import datetime
import pytz
try:
import RPi.GPIO as GPIO
except:
GPIO = None
import twitter
from credentials import *
import re
from textblob import TextBlob
# Global constants/variables
channels = [3,5]
fan_balance = 0
gpio_initialised = False
# 1 Jan 1970 constant
epoch = datetime.utcfromtimestamp(0)
# Function for converting timestamps to epochs
def datetime_to_epoch(datestring):
global epoch
time_pattern = '%a %b %d %H:%M:%S +0000 %Y'
dt = datetime.strptime(datestring,time_pattern) #.replace(tzinfo=pytz.UTC)
return (dt - epoch).total_seconds()
def init_gpio():
global gpio_initialised
GPIO.setmode(GPIO.BOARD)
GPIO.setup(channels, GPIO.OUT, initial=GPIO.LOW)
gpio_initialised = True
def signal_handler(signal, frame):
print 'Caught SIGINT - exiting cleanly...'
global gpio_initialised
if gpio_initialised:
print('Cleaning up GPIO')
GPIO.cleanup()
gpio_initialised = False
sys.exit()
def reset_timer(tim, new_time, func, f_args):
tim.cancel()
tim = Timer(new_time, func, args=f_args)
tim.start()
print('Timer set for %.1f seconds' % new_time)
return tim
def inflate(power='FULL'):
print('Inflating ' + power)
if power == 'FULL':
GPIO.output(channels, GPIO.HIGH)
elif power == 'OFF':
GPIO.output(channels, GPIO.LOW)
elif power == 'HALF':
if fan_balance == 0:
GPIO.output(channels, (GPIO.HIGH, GPIO.LOW))
fan_balance = 1
else:
GPIO.output(channels, (GPIO.LOW, GPIO.HIGH))
fan_balance = 0
else:
print('Warning: unknown power level input!')
GPIO.output(channels, GPIO.LOW)
def clean_tweet(tweet):
'''
Utility function to clean tweet text by removing links, special characters
using simple regex statements.
'''
return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split())
def analyse_tweet(tweet):
#analysis = TextBlob(clean_tweet(tweet))
analysis = TextBlob(tweet)
return analysis.sentiment.polarity
def analyse_stream(bear_id, track_list):
if not track_list:
print 'You gave me nothing to track!'
return
try:
stream = api.GetStreamFilter(track=track_list)
tim = Timer(30.0, inflate, args=['OFF'])
last_time = 0
for line in stream:
text = line['text']
sen_val = analyse_tweet(text)
print text
print 'Sentiment: ' + str(sen_val)
if 'power on' in text.lower():
inflate('FULL')
elif 'power off' in text.lower():
inflate('OFF')
elif sen_val > 0.29 and line['user']['id'] != bear_id:
print 'Reposting!'
api.CreateFavorite(status_id=line['id'])
api.PostRetweet(line['id'])
tweet_time = datetime_to_epoch(line['created_at'])
inflate('FULL')
time_dif = tweet_time - last_time
if time_dif > 120.0:
tim = reset_timer(tim, 90.0, inflate, ['OFF'])
elif time_dif > 45.0:
tim = reset_timer(tim, 60.0, inflate, ['OFF'])
else:
tim = reset_timer(tim, 45.0, inflate, ['OFF'])
last_time = tweet_time
print '###########\n'
except:
print 'Error in reading stream!'
traceback.print_exc()
global gpio_initialised
if gpio_initialised:
print('Cleaning up GPIO')
GPIO.cleanup()
gpio_initialised = False
if __name__ == '__main__':
signal.signal(signal.SIGINT, signal_handler)
api = twitter.Api(consumer_key=CONSUMER_KEY,
consumer_secret=CONSUMER_SECRET,
access_token_key=ACCESS_TOKEN,
access_token_secret=ACCESS_SECRET)
init_gpio()
#timeline = api.GetHomeTimeline()
#print timeline
#status = api.PostUpdate('Another post!')
myself = api.VerifyCredentials().AsDict()
print 'id: ', myself['id']
print 'name: ', myself['name']
print 'screen_name: ', myself['screen_name']
analyse_stream(myself['id'], ['#colabssydney','@'+myself['screen_name']])