-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnixiebot.py
1566 lines (1444 loc) · 67.5 KB
/
nixiebot.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
NixieBot.py
Author: Robin Bussell
Nixiebot.py will, when run on suitable hardware and provided with valid twitter API keys,
listen for tweets containing a specific hashtag and act on them by displaying words, photographing them
and returning a picture or scrolling movie as a tweet, mentioning the originator ofn the tweet that triggered it.
Inbetween tweet processing it acts as a clock and random tweet display.
Suitable hardware is a raspberry pi with camera module pointed at an array of smartsockets holding B7971
nixie tubes. You'll need to install the picamera and GPIO modues plus grafixmagick for producing the movies.
Tags: #Nixiebotshowme main trigger tag,if no other special tags then display nearest word to tag
words = text.split(" ") so users can:use:non:dispaying:character:to:seperate:a:phrase
probably best to change this tag if you run your own bot from this code!
Other special tags:
Add files of lines of text called filename.ftn into the working directory to activate the tag #filename to chose a random line from that file
This is how the #eightball and #oblique tags work on the original Nixiebot.
#twitswears ... summon list of recent swearwords used on twitter
#twitnice ... summon list of nice words
#twitall ... summon all words used
optional modifiers for lists:
#alphabetic ... sorts the selected wordlist #raw turns off deduplication
#charts ... sorts in order of popularity
Health warning! Currently this is a python monolith that has grown too big and messy for its own good, refactor will happen sometime :)
There are four threads running:
one to gather tweets with the right hashtag(filter streamer)
one to gather random tweets (random streamer)
one to run the clock and tweeting (runClock()
Main thread has a few console commands.
"""
import serial
from twython import Twython , TwythonStreamer
import time
import datetime
import picamera
import queue
import threading
import random
import pickle
import RPi.GPIO as GPIO
import collections
from subprocess import call
from glob import glob
from functools import partial
import os
from shutil import copyfile, move
import re
import html.parser
import botkeys #API keys are stored in botkeys.py ... edit it with your keys
timeThen=time.time()
com = serial.Serial("/dev/ttyAMA0",baudrate=9600,timeout=1.0)
tubes = 8
scrollIt = False
makeMovie=False
frameCount=0
doSwears = False
doNice = False
sortWords = False
popWords = False
dequeHold = False
doRandoms = True
wordAtATime = False
doAllWords=False
running=True
blanked = False
killURLs = True
userFont = False
dummyRun = False
effx = 0
fxspeed = 0
log_level=0
originalTweets = 0
reTweets = 0
profileUpdateCounter = 0
onlyOriginalRandoms=True
displayTwOI=True
timeInterval=15
timeLapseInterval=15 #minutes per frame for daily time lapse
dtctr=0
dtCycles = 3
blankpin = 12 #we use GPIO in BOARD mode so this is a P1 pin number not the broadcom GPIO number
HVToggleTime = 0
scrollInterval = 0.15
userProperChars = ""
cam=None
glitchType = "none"
glitchLevel = 0
dailyMovieCounter = 0
lapseDone = False
basePath="/home/pi/nixiebot/"
botState={'lastDM':0,'lastDMCheckTime':time.time(),'DMdq':collections.deque(),'maxWordQ':0}
badwords=["4r5e", "5h1t", "5hit", "a55", "anal", "anus", "ar5e", "arrse", "arse", "ass", "ass-fucker", "asses", "assfucker", "assfukka", "asshole", "assholes", "asswhole", "a_s_s", "b!tch", "b00bs", "b17ch", "b1tch", "ballbag", "balls", "ballsack", "bastard", "beastial", "beastiality", "bellend", "bestial", "bestiality", "bi+ch", "biatch", "bitch", "bitcher", "bitchers", "bitches", "bitchin", "bitching", "bloody", "blow job", "blowjob", "blowjobs", "boiolas", "bollock", "bollok", "boner", "boob", "boobs", "booobs", "boooobs", "booooobs", "booooooobs", "breasts", "buceta", "bugger", "bum", "bunny fucker", "butt", "butthole", "buttmuch", "buttplug", "c0ck", "c0cksucker", "carpet muncher", "cawk", "chink", "cipa", "cl1t", "clit", "clitoris", "clits", "cnut", "cock", "cock-sucker", "cockface", "cockhead", "cockmunch", "cockmuncher", "cocks", "cocksuck", "cocksucked", "cocksucker", "cocksucking", "cocksucks", "cocksuka", "cocksukka", "cok", "cokmuncher", "coksucka", "coon", "cox", "crap", "cum", "cummer", "cumming", "cums", "cumshot", "cunilingus", "cunillingus", "cunnilingus", "cunt", "cuntlick", "cuntlicker", "cuntlicking", "cunts", "cyalis", "cyberfuc", "cyberfuck", "cyberfucked", "cyberfucker", "cyberfuckers", "cyberfucking", "d1ck", "damn", "dick", "dickhead", "dildo", "dildos", "dink", "dinks", "dirsa", "dlck", "dog-fucker", "doggin", "dogging", "donkeyribber", "doosh", "duche", "dyke", "ejaculate", "ejaculated", "ejaculates", "ejaculating", "ejaculatings", "ejaculation", "ejakulate", "f u c k", "f u c k e r", "f4nny", "fag", "fagging", "faggitt", "faggot", "faggs", "fagot", "fagots", "fags", "fanny", "fannyflaps", "fannyfucker", "fanyy", "fatass", "fcuk", "fcuker", "fcuking", "feck", "fecker", "felching", "fellate", "fellatio", "fingerfuck", "fingerfucked", "fingerfucker", "fingerfuckers", "fingerfucking", "fingerfucks", "fistfuck", "fistfucked", "fistfucker", "fistfuckers", "fistfucking", "fistfuckings", "fistfucks", "flange", "fook", "fooker", "fuck", "fucka", "fucked", "fucker", "fuckers", "fuckhead", "fuckheads", "fuckin", "fucking", "fuckings", "fuckingshitmotherfucker", "fuckme", "fucks", "fuckwhit", "fuckwit", "fudge packer", "fudgepacker", "fuk", "fuker", "fukker", "fukkin", "fuks", "fukwhit", "fukwit", "fux", "fux0r", "f_u_c_k", "gangbang", "gangbanged", "gangbangs", "gaylord", "gaysex", "goatse", "god-dam", "god-damned", "goddamn", "goddamned", "hardcoresex", "hell", "heshe", "hoar", "hoare", "hoer", "homo", "hore", "horniest", "horny", "hotsex", "jack-off", "jackoff", "jap", "jerk-off", "jism", "jiz", "jizm", "jizz", "kawk", "knob", "knobead", "knobed", "knobend", "knobhead", "knobjocky", "knobjokey", "kock", "kondum", "kondums", "kum", "kummer", "kumming", "kums", "kunilingus", "l3i+ch", "l3itch", "labia", "lmfao", "lust", "lusting", "m0f0", "m0fo", "m45terbate", "ma5terb8", "ma5terbate", "masochist", "master-bate", "masterb8", "masterbat*", "masterbat3", "masterbate", "masterbation", "masterbations", "masturbate", "mo-fo", "mof0", "mofo", "mothafuck", "mothafucka", "mothafuckas", "mothafuckaz", "mothafucked", "mothafucker", "mothafuckers", "mothafuckin", "mothafucking", "mothafuckings", "mothafucks", "mother fucker", "motherfuck", "motherfucked", "motherfucker", "motherfuckers", "motherfuckin", "motherfucking", "motherfuckings", "motherfuckka", "motherfucks", "muff", "mutha", "muthafecker", "muthafuckker", "muther", "mutherfucker", "n1gger", "nazi", "nigg3r","nigger", "niggers", "nob", "nob jokey", "nobhead", "nobjocky", "nobjokey", "numbnuts", "nutsack", "orgasim", "orgasims", "orgasm", "orgasms", "p0rn", "pawn", "pecker", "penis", "penisfucker", "phonesex", "phuck", "phuk", "phuked", "phuking", "phukked", "phukking", "phuks", "phuq", "pigfucker", "pimpis", "piss", "pissed", "pisser", "pissers", "pisses", "pissflaps", "pissin", "pissing", "pissoff", "poop", "porn", "porno", "pornography", "pornos", "prick", "pricks", "pron", "pube", "pusse", "pussi", "pussies", "pussy", "pussys", "rectum", "retard", "rimjaw", "rimming", "s hit", "s.o.b.", "sadist", "schlong", "screwing", "scroat", "scrote", "scrotum", "semen", "sex", "sh!+", "sh!t", "sh1t", "shag", "shagger", "shaggin", "shagging", "shemale", "shi+", "shit", "shitdick", "shite", "shited", "shitey", "shitfuck", "shitfull", "shithead", "shiting", "shitings", "shits", "shitted", "shitter", "shitters", "shitting", "shittings", "shitty", "skank", "slut", "sluts", "smegma", "smut", "snatch", "son-of-a-bitch", "spac", "spunk", "s_h_i_t", "t1tt1e5", "t1tties", "teets", "teez", "testical", "testicle", "tit", "titfuck", "tits", "titt", "tittie5", "tittiefucker", "titties", "tittyfuck", "tittywank", "titwank", "tosser", "turd", "tw4t", "twat", "twathead", "twatty", "twunt", "twunter", "v14gra", "v1gra", "vagina", "viagra", "vulva", "w00se", "wang", "wank", "wanker", "wanky", "whoar", "whore", "willies", "willy", "xrated", "xxx"]
nicewords=["love","luv","excellent","happy","joy","joyous","fantastic","superb","great","wonderful","nice","respect","respectful","anticipating","lovely","friendly","friend","best","cheers","thanks","glad","satisfied","satisfying","splendid","kind","welcome","welcoming","charming","delicious","pleasant","polite","tender","affable","sympathy","empathy","empathetic","sympathetic","peaceful","fond","good","cake","pie","kitten","kittens","swell","grand","peace","unity","amity","justice","truce","esteem"]
boringWords=["this","that","with","from","have","what","your","like","when","just"]
validTags=["twitnice","twitswears","twitall","thetime"] #list of tags that can substitute for an actual word
#validTags=[] #temporary measure
client_args = {'timeout': 90 }
twitter = Twython(botkeys.APP_KEY,botkeys.APP_SECRET,botkeys.USER_KEY,botkeys.USER_SECRET, client_args=client_args)
priorityUsers=["Zedsquared", "NixtestTest"] #tweets from these users get high priority (for jumping the queue when testing)
#dummyTweet ={ 'text':"dummy text",
# 'entities' : {
# 'hashtags':["NixieBotShowMe"]
# }
# 'user' : { 'id' : acctID, 'screen_name' : acctName } ,
# }
userCounter = collections.Counter()
minInterval=40 #seconds per tweet minimum (2400 per day allowed)
frameLimit = 100
wordq = queue.PriorityQueue() #Stores incoming command tweets, priority allows quicker live testing
randq=queue.Queue(100) #just a little buffer
consoleQ = queue.Queue() # for direct injection messages
wordQIdx = 0 #usd to keep wordq items sortable
rollq = queue.Queue()
recentTweetDeque = collections.deque('a',1000) #random feed seems to be about five a second
recentTweetDeque.clear()
recentIDDeque = collections.deque('a',100) #deduplication deque to spot incoming duplicates from twitter
recentReqs = []
reqPickleFrequency = 100 #how many requests to hold in RAM before writing out to disc
comLock = threading.RLock()
fortunes = {}
fortuneTags = []
qAtZero = False #flag used to determine whether to update twitter profile
class filterStreamer(TwythonStreamer):
backOffTime = 60
def on_success(self, tweet):
global recentIDDeque
if 'text' in tweet and not ('retweeted_status' in tweet) :
print("<<<<<<<<<<<<<<<<<<< Incoming!<<<<<<<<<<<<<<<<<< " + html.parser.HTMLParser().unescape(tweet['text']) + tweet['id_str'])
if tweet['id_str'] not in recentIDDeque :
processIncomingTweet(tweet)
recentIDDeque.appendleft(tweet['id_str'])
else :
print("!!!! duplicate! Ignored ")
backOffTime = 60
def on_error(self, status_code, data):
global running
print("************************************error from filter stream! ")
print (status_code)
if (status_code == 420) :
print("***************** filter is rate limited!" )
print("*****************sleeping for" + str(self.backOffTime) )
for i in range (1,int(self.backOffTime / 10)) :
if running :
time.sleep(10)
else :
break
if self.backOffTime < 1200 :
self.backOffTime = self.backOffTime * 2
# Want to stop trying to get data because of the error?
# Uncomment the next line!
#self.disconnect()
class randomStreamer(TwythonStreamer):
backOffTime = 60
global randq
global onlyOriginalRandoms
def on_success(self, data):
global originalTweets
global reTweets
global onlyOriginalRandoms
global dequeHold
if 'text' in data:
if killURLs :
data['text'] = killURL(data)
isOriginal = not ('retweeted_status' in data)
if log_level >=4 :
print ("incoming Random, deque at: " + str(len(recentTweetDeque)) + " " + data['text'])
if not dequeHold :
recentTweetDeque.appendleft(data)
if not randq.full():
if (not onlyOriginalRandoms ) or isOriginal :
if log_level >=3 :
print("##queing random: " + data['text'] )
elif log_level >=2 :
print("##queing random: " )
randq.put(data)
backOffTime = 60
def on_error(self, status_code, data):
global running
print("************************************error from random stream! ")
print (status_code)
if (status_code == 420) :
print("!!!!!!!!!!!!!!!!!!!! random is rate limited!" )
print("!!!!!!!!!!!!!!!!!!!! sleeping for" + str(self.backOffTime) )
for i in range (1,int(self.backOffTime / 10)) :
if running :
time.sleep(10)
else :
break
if self.backOffTime <= 7200 :
self.backOffTime = self.backOffTime * 2
# Want to stop trying to get data because of the error?
# Uncomment the next line!
#self.disconnect()
def originality_index(self) :
global recentTweetDeque
retweets = 0
tweets = 0
for i in recentTweetDeque :
if 'retweeted_status' in i :
retweets = retweets +1
tweets = tweets + 1
if tweets > 0 :
return(1-(retweets/tweets))
else :
return(1)
def swears(self) :
global recentTweetDeque
global dequeHold
swearlist=[]
swearcount = 0
wordcount = 0
dequeHold = True
for i in recentTweetDeque :
twords = i['text'].split()
for word in twords :
wordcount = wordcount + 1
if word in badwords :
swearlist.append(word)
swearcount = swearcount + 1
dequeHold = False
return {'wordList':swearlist,'wordTypeCount':swearcount,'totalCount':wordcount}
def nices(self) :
global recentTweetDeque
global dequeHold
nicelist=[]
nicecount = 0
wordcount = 0
dequeHold = True
for i in recentTweetDeque :
twords = i['text'].split()
for word in twords :
wordcount = wordcount + 1
if word in nicewords :
nicelist.append(word)
nicecount = nicecount + 1
dequeHold = False
return {'wordList':nicelist,'wordTypeCount':nicecount,'totalCount':wordcount}
def allWords(self) :
global recentTweetDeque
global dequeHold
twords=[]
dequeHold = True
for i in recentTweetDeque :
twords.extend(i['text'].split())
dequeHold = False
return {'wordList':twords,'wordTypeCount':len(twords),'totalCount':len(twords)}
def wordqPut(item, priority = 50) :
global wordQIdx
global wordq
try:
wordQIdx +=1
wordq.put((priority,wordQIdx,item)) #items are retrieved as worq.get()[2]
except :
print("Exception putting in queue,idx=",wordQIdx)
def runClock(): #TODO ... use queue get with timeout and try catch as I think it's deadlocking this function when neither queue is being filled
global wordq
global randq
global running
global tubes
global twitter
global timeInterval
global dtctr
global cam
global makeMovie
global timeThen
global profileUpdateCounter
global clockPause
global lapseDone
print("**************clock thread starting ")
print("GPIO init")
initGPIO()
print("Tubes on")
lightTubes()
print("Tubes init")
initTubes()
timeThen=time.time()
lastdecade = int(datetime.datetime.now().second ) // timeInterval
print("main loop entry")
with picamera.PiCamera() as cam:
initcam(cam)
while running:
makeMovie = False
if ((time.time() - timeThen) > minInterval) :
if not wordq.empty() :
tweetOutWord()
profileUpdateCounter +=1
if profileUpdateCounter == 4 or ( wordq.empty() and not qAtZero) or (qAtZero and not wordq.empty()) :
updateQlength()
profileUpdateCounter = 0;
if not rollq.empty() :
rollDice()
t=datetime.datetime.now()
if int(t.minute) % timeLapseInterval == 0 :
doTimeLapse() #either choose a frame from recent first frames or, if none available, take one from random stats
#if it's the appointed hour, generate and tweet the time lapse movie.
else :
lapseDone = False
if int(t.second) // timeInterval != lastdecade :
lastdecade = int(t.second) // timeInterval
dtctr += 1
#display time
setEffex(6,5) # funky dissolve effect
displayTime()
time.sleep(1) #give time for dissolve effect to work
setEffex(1,1)
for secs in range(4):
displayTime()
time.sleep(1)
setEffex(6,5)
if displayTwOI and dtctr == dtCycles: #every so many times the time is displayed, also display twitter stats
dtctr=0
if log_level >= 5 : print("TWOi display")
displayString("TWOI " + str(int(randstream.originality_index()*100)).ljust(tubes) )
time.sleep(2)
displayString("Q " + str(wordq.qsize()).ljust(tubes) )
time.sleep(2.5)
if doSwears :
displayWords( randstream.swears(), sortem = sortWords , popularity = popWords, uniq = False, doAutoScroll = True)
if doNice :
displayWords(randstream.nices(), sortem = sortWords, popularity = popWords,uniq = False, doAutoScroll = True)
if doAllWords :
displayWords(randstream.allWords(), sortem = True, popularity = True, minLength=tubes, uniq=True,)
else : #display a random tweet, if there is one ready
if doRandoms and not randq.empty():
tweet = randq.get()
if log_level >= 1 :
print( "Displaying random: " + tweet['text'])
if not scrollIt :
displayList(atMostnLetters(tweet['text'].split(),tubes),0.45,False, True) #TODO ... drop the atmostNletters as it defeats autoscroll
else :
scrollList(tweet['text'].split())
randq.task_done()
doDMs()
# we get here if running is false i.e. quit command received
cam.close()
print("runclcok closing")
return
def tweetOutWord() : #main function for processing a tweet that has a command in it
global makeMovie
global timeThen
global glitchLevel
global glitchType
lightTubes()
nextOne=wordq.get()
tweet = nextOne[2]
timeThen=time.time()
print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Tweeting!>>>>>>>",html.parser.HTMLParser().unescape(tweet['text'])," Queue= " + str(wordq.qsize()))
tt=False #tt used as simple "has a special hashtag been processed" flag
setCamEffex(cam, tweet)
oldGlitchLevel = glitchLevel
oldGlitchType = glitchType
setGlitch(tweet)
for ht in tweet['entities']['hashtags']:
if ht['text'].lower() =="thetime" and not tt:
displayTime()
tt=True
theWord = "TheTimeIs"
if ht['text'].lower() =="twitall" and not tt:
makeMovie = True
displayWords(randstream.allWords(), scanTags(tweet,"alphabetic") , scanTags(tweet,"charts"), not scanTags(tweet,"raw"), not scanTags(tweet,"noAutoScroll"), topCount=20 )
tt = True
tweetMovie("movie.gif",tweet,"all_words")
if ht['text'].lower() =="twitswears" and not tt:
makeMovie = True
displayWords(randstream.swears(), scanTags(tweet,"alphabetic") , scanTags(tweet,"charts"), not scanTags(tweet,"raw"), not scanTags(tweet,"noAutoScroll") )
tt = True
tweetMovie("movie.gif",tweet,"swear_words")
if ht['text'].lower() == "twitnice" and not tt :
makeMovie = True
displayWords(randstream.nices(), scanTags(tweet,"alphabetic") , scanTags(tweet,"charts"), not scanTags(tweet,"raw"), not scanTags(tweet,"noAutoScroll"))
tt = True
tweetMovie("movie.gif",tweet,"nice_words")
if ht['text'].lower() in fortuneTags and not tt :
makeMovie = True
fortuneAsList = random.choice(fortunes[ht['text'].lower()]).split(" ")
print("picked fortune ; ", fortuneAsList)
displayWords({'wordList':fortuneAsList},delay=40)
tt = True
makeMovie = False
tweetMovie("movie.gif",tweet,ht['text'])
if not tt: #tt flag gets set if any action other than "display a word that has been submitted " has happened already
theWord=extractWord(html.parser.HTMLParser().unescape(tweet['text']))
picStatus=makeStatusText(tweet, theWord)
lockCamExposure(cam)
if len(theWord) > tubes or scanTags(tweet,"scroll"):
print("movie")
makeMovie = True
scrollString(proper(theWord," "))
makeGif("tweetWord")
mediaName = 'tweetWord.gif'
makeMovie=False
else :
print("single shot, makeMovie = ", makeMovie)
displayString(proper(theWord," ").ljust(tubes))
time.sleep(1.5)
cam.capture('tweet.jpg',resize=(800,480))
mediaName = 'tweet.jpg'
unlockCamExposure(cam)
pic=open(mediaName,'rb')
addOwners=str(tweet['user']['id'])
for m in tweet['entities']['user_mentions'] : #add all mentions as media owners so they can pass it on
userID=m['id_str']
addOwners = addOwners + "," + userID
if not dummyRun :
try:
print(">>>>>>>>>>>>> Uploading media ", datetime.datetime.now().strftime('%H:%M:%S.%f'))
response = twitter.upload_media(media=pic, additional_owners=addOwners )
print(">>>>>>>>>>>>> Updating status ", datetime.datetime.now().strftime('%H:%M:%S.%f'))
twitter.update_status( status=picStatus,
media_ids=[response['media_id']],
in_reply_to_status_id=tweet['id_str'])
print(">>>>>>>>>>>>> Done ", datetime.datetime.now().strftime('%H:%M:%S.%f'))
except BaseException as e:
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Tweeting exception!" + str(e))
print(" status text =", picStatus)
if not 'retries' in tweet :
tweet['retries'] = 0
wordqPut(tweet,priority = 30)
elif tweet['retries'] < 5 :
tweet['retries'] += 1
wordqPut(tweet,priority = 30)
else :
print("Dummy run, not tweeting")
#flashWord(theWord,10)
cam.image_effect="none"
wordq.task_done()
glitchLevel=oldGlitchLevel
glitchType=oldGlitchType
if blanked : blankTubes()
def setGlitch(tweet) :
#sets glitching according to #glitchlevel:[0-100] and #glitchtype:[swap,shuffle]
global glitchLevel
global glitchType
glitchLevel = 0
glitchType = "none"
print("setting glitch")
level = re.compile(r'glitchlevel(?:100|[0]?[0-9]?[0-9])$')
typ = re.compile(r'glitchtype(swap|shuffle)$')
for tx in tweet['entities']['hashtags'] :
t=tx['text'].lower()
if level.match(t) :
try :
gl = int(t.split("glitchlevel")[1])
print("glitch level req to ", gl)
glitchLevel = gl
except :
print("glitchlevel setting exception text = ", t, "split = ", gl)
pass
if typ.match(t) :
try :
gt = t.split("glitchtype")[1]
print("glitch type req to ", gt)
glitchType = gt
except :
print("glitchtype setting exception text = ", t, "split = ", gt)
pass
if glitchType !="none" and glitchLevel == 0 :
glitchLevel = 50
elif glitchLevel >= 0 and glitchType =="none" :
glitchType = "swap"
def rollDice() :
global makeMovie
lightTubes()
tweet = rollq.get()
if scanTags(tweet,"EightBall") :
tweetOutEightBall() #ToDO ... write this!
else : #scan tags for xxDyy tag to indicate dice
numDice = 0
numFaces = 0
pattern = re.compile("[1-3]D[0-9][0-9]?")
for t in tweet['entities']['hashtags'] :
if pattern.match(t) :
dice = t.split("D")
numDice = int(dice[0])
numfaces = int(dice[1])
break #later, maybe make a list of differnt dice encoded and display them all at once
#TODO dice rolling here
rollq.task_done()
if blanked : blankTubes()
def updateQlength() : #sets the description parameter in twitter profile so that queue length can be read, also adds random usage hint.
global wordq
global twitter
global qAtZero
qLen = wordq.qsize()
desc = "dummy"*50 #start with a big string so loop executes at least once!
while len(desc) > 159 :
baseDesc= "I'm a twitterised, neon display, clock. Tweet with #NixieBotShowMe and a word, full guide on tumblr. "
hints = ["","100 character limit on movies.", "Try #twitNice .", "Phrases:need:separators.", "No need to @ mention me.", "Twitter will munge URLs.", "Ask an #eightBall question.", "Be patient with long queues.", "Remember, tweets are not anonymous!","Try #twitSwears.","Try #oblique.", "Use #scroll on short words for a gif"]
names = ["Neon Clock Tweet Bot", "Nixie McBotFace","Your Words In Neon","Neon Clock Tweet Bot","Neon Clock Tweet Bot"]
desc = baseDesc+random.choice(hints)
nom = random.choice(names)
if qLen > 0 :
desc = desc + " Queue at: "+ str(wordq.qsize()) + " to go."
qAtZero = False
else :
desc = desc + " Queue : Empty"
qAtZero = True
try:
print(">>>>>>>>>>>>> Updating profile ", datetime.datetime.now().strftime('%H:%M:%S.%f'))
twitter.update_profile(description = desc, name=nom)
print(">>>>>>>>>>>>> Done", datetime.datetime.now().strftime('%H:%M:%S.%f'))
except:
print("status update exception!")
def doDMs() :
global botState #we have to keep track of replied to DMs ourselves
DMReply = ''' I'm sorry but this bot does not take display commands from direct messages since there should always be a publicly visible origin of anything that is displayed.
To get a message displayed you need to tweet with the hashtag #NixieBotShowMe and it will display the word immediatley after that hashtag.
For further info see http://nixiebot.tumblr.com/FAQ and http://nixiebot.tumblr.com/ref
This is an automated message sent in reply to all DMs.'''
newOnes = False
if time.time() - botState['lastDMCheckTime'] > 120 : #check dms every couple of minutes
botState['lastDMCheckTime']=time.time()
lastDM = botState['lastDM']
lastDMHere = lastDM
try :
#print("Checking DMs")
dms = twitter.get_direct_messages(since_id=lastDM)
except BaseException as e:
print("DM fetch exception ", str(e))
return
for dm in dms : #gather new messages
if dm['id'] > lastDM :
newOnes = True
print("new DM! ", dm['id'])
botState['DMdq'].appendleft({'ID':dm['sender']['id_str'],'tries':0})
if dm['id'] > lastDMHere :
lastDMHere = dm['id']
botState['lastDM']=lastDMHere
#now send any that are waiting:
quota = 1
while len(botState['DMdq']) > 0 and quota >=1 :
try:
rep = botState['DMdq'].pop()
response = twitter.send_direct_message(user_id = rep['ID'], text=DMReply)
rlr = twitter.get_lastfunction_header('X-Rate-Limit-Remaining')
rlrst = twitter.get_lastfunction_header('X-Rate-Limit-Reset')
# print("DM rate limit remaining = ", rlr )
# print("DM rate limit reset = ", rlrst )
# currently just getting None replies on the above calls... find out why!
if rlr is not None and rlrst is not None :
quota = rlr - int((rlrst - time.time()) / 60) #number of calls available this interval minus the number of minutes left
print("DM quota = ", quota)
else :
quota = quota - 1 #default to one per minute safe rate
except BaseException as e:
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! DM sending exception!" + str(e))
rep['tries'] += 1
quota = quota - 1
if rep['tries'] < 20 :
botState['DMdq'].appendleft(rep)
else :
print("!!!!!****** dropping DM due to too many retries at reply: ", rep)
if newOnes :
pickleMe(botState,'stateStash',dateStamp=False)
def displayTime() :
global tubes
#print("displaytime")
if tubes >= 8 :
displayString(time.strftime("%H %M %S"))
elif tubes >= 6 :
displayString(time.strftime("%H %M %S"))
def scanTags(tweet, tag) : #case insensitive hashtag detection
for t in tweet['entities']['hashtags'] :
if tag.lower() in t['text'].lower() :
return True
return False
def killURL(tweet) :
text = tweet['text']
return(text)
def tweetMovie(fileName, tweet, tag) :
if not dummyRun :
mediaName = fileName
sens_tags=["swear_words"]
pic=open(mediaName,'rb')
picStatus=makeStatusText(tweet, tag)
addOwners=str(tweet['user']['id'])
if tag in sens_tags :
sensitive = True
else : sensitive = False
for m in tweet['entities']['user_mentions'] :
userID=m['id_str']
addOwners = addOwners + "," + userID
#print("tweeting movie, additional owners = ", addOwners)
try:
print(">>>>>>>>>>>>> Uploading Movie ", datetime.datetime.now().strftime('%H:%M:%S.%f'))
response = twitter.upload_media(media=pic, additional_owners=addOwners, possibly_sensitive = sensitive )
print(">>>>>>>>>>>>> Updating status ", datetime.datetime.now().strftime('%H:%M:%S.%f'))
twitter.update_status( status=picStatus,
media_ids=[response['media_id']],
in_reply_to_status_id=tweet['id_str'])
print(">>>>>>>>>>>>> Done ", datetime.datetime.now().strftime('%H:%M:%S.%f'))
except BaseException as e:
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Tweeting movie exception!" + str(e))
print(" status text =", picStatus)
if not 'retries' in tweet :
tweet['retries'] = 0
wordqPut(tweet,priority = prioritise(tweet))
elif tweet['retries'] < 5 :
tweet['retries'] += 1
wordqPut(tweet,priority = prioritise(tweet))
else :
print("Not tweeting...dummy mode")
def displayWords(words, sortem = False, popularity = False, uniq = False, doAutoScroll = True, topCount = None, minLength = 4, maxPop = 1000, delay =20, upperOnly = False ):
global makeMovie
global cam
if makeMovie :
setEffex(0,0)
lockCamExposure(cam)
if len(words['wordList']) > 100 :
words['wordList'] = words['wordList'][:frameLimit]
if sortem :
if uniq :
displayList(sorted(set(words['wordList'])),0.3,True, doAutoScroll)
else :
displayList(sorted(words['wordList']),0.3,True, doAutoScroll)
if log_level >=1 :
print("***** SORTED WORDS:", *sorted(words['wordList']))
elif popularity :
topWords = []
for w in words['wordList'] :
if len(w) >= minLength : topWords.append(w)
c = collections.Counter(topWords)
commons = c.most_common(topCount)
commonlist = []
setEffex(0,0)
for w in commons :#merge in wordcounts
if w[1] < maxPop :
commonlist.append(w[0]+" X "+ str(w[1]))
for w in commonlist :
scrollString(proper(w," "))
if not makeMovie : time.sleep(0.5)
if log_level >=1 :
print("***** COMMON WORDS:", *c.most_common())
else :
displayList(words['wordList'],0.3,False, doAutoScroll)
if log_level >=1 :
print("***** RAW WORDS:", *words['wordList'])
if makeMovie :
unlockCamExposure(cam)
makeGif("movie",delay)
makeMovie=False
def makeGif(name,delay=20) :
global frameCount
print("making Movie!")
# mresult = call(["convert","-delay","20","-loop", "0", "tweetMov*.jpg",name+".gif"]) #imagemagick version
mresult = call(["gm","convert","-delay",str(delay),"-loop", "0", "tweetMov*.jpg",name+".gif"]) #graphicsMagick version
print("Make movie command result code = ",mresult)
for killit in glob("tweetMov*.jpg") :
if not dummyRun :
os.remove(killit) #get rid of the frame files now they're wrapped up
frameCount=0
def takeFrame(resize = True) :
global cam
global frameCount
if frameCount < 10 : #add apropriate leading zeroes to make alpahabetic sort of file names work.
frameStr = "00"+ str(frameCount)
elif frameCount < 100 :
frameStr = "0" + str(frameCount)
else :
frameStr = str(frameCount)
if frameCount % 10 == 0 :
print("capturing frame:", frameCount)
if frameCount <= frameLimit and resize:
cam.capture('tweetMov'+frameStr+'.jpg',resize=(320,200))
if frameCount == 0 :
lapseStash('tweetMov'+frameStr+'.jpg') #save a copy of first frame for use in making daily time lapse movie
frameCount += 1
elif not resize :
cam.capture('tweetMov'+frameStr+'.jpg')
frameCount += 1
else : print("hit frame limit")
def lapseStash(fileName) :
#copy under a different name so it can be used as a candidate for time lapse movie frame
newName = "lapse-" + time.strftime("%Y%m%d-%H%M%S")+".jpg"
try :
copyfile(fileName,newName)
except :
print("Error in lapseStash", e)
def doTimeLapse() :
global cam
global lapseDone
global makeMovie
global effx
global effxspeed
if lapseDone :
return
print("doTimeLapse called")
#delete all lapse*.jpg older than (lapseTime / 2)
#pick youngest lapse*.jpg file and copy to lapseFrames directory youngestName = ""
youngestTime = time.time()
youngestFile= ""
timeLimit = time.time() - ((timeLapseInterval/2) * 60)
files = glob(basePath+"lapse*.jpg")
for f in files :
fileTime = os.path.getatime(f)
if fileTime < timeLimit :
print("deleting ", f, " age =", (time.time() - fileTime)/60)
os.remove(f)
elif fileTime < youngestTime :
youngtestTime = fileTime
youngestFile = f
if youngestFile != "" :
print("moving file", youngestFile , "into frame store")
move(youngestFile, basePath+"lapseFrames/")
else :
#take frame of most popular word in random tweet sample of four or more letters
words=randstream.allWords()['wordList']
bigEnough=[]
for w in words :
if len(w) >= 4 and w not in boringWords and "&" not in w:
bigEnough.append(w)
c = collections.Counter(bigEnough)
topWords=c.most_common(20)
theWord=topWords[0][0]
print(topWords, theWord)
makeMovie = False
stashfx = effx
stashspeed = fxspeed
setEffex(0,0)
lockCamExposure(cam)
displayString(theWord)
cam.capture(basePath+"/lapseFrames/lapse-"+time.strftime("%Y%m%d-%H%M%S")+".jpg",resize=(320,200))
unlockCamExposure(cam)
setEffex(stashfx,stashspeed)
lapseFrames = glob(basePath+"lapseFrames/*.jpg")
#if there are now 96 files in the frames folder, make a movie and tweet it out #NixieLapse
print(len(lapseFrames),"lapse frames found")
if len(lapseFrames) >=96 :
print("making daily time lapse")
delay=20
mresult = call(["gm","convert","-delay",str(delay),"-loop", "0", basePath+"/lapseFrames/*.jpg","Tlapse.gif"])
print("Make movie command result code = ",mresult)
if mresult == 0 :
uploadRetries = 0
while uploadRetries < 3 :
try:
pic =open("Tlapse.gif","rb")
print(">>>>>>>>>>>>> Uploading Timelapse Movie ", datetime.datetime.now().strftime('%H:%M:%S.%f'))
response = twitter.upload_media(media=pic )
print(">>>>>>>>>>>>> Updating status ", datetime.datetime.now().strftime('%H:%M:%S.%f'))
twitter.update_status( status="This is how my day went: #NixieBotTimelapse",
media_ids=[response['media_id']] )
print(">>>>>>>>>>>>> Done ", datetime.datetime.now().strftime('%H:%M:%S.%f'))
uploadRetries = 200
except BaseException as e:
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Tweeting movie exception!" + str(e))
uploadRetries += 1
move(basePath+"Tlapse.gif", basePath+"lapseFrames/Tlapse"+time.strftime("%Y%m%d-%H%M%S")+ ".gif")
for f in lapseFrames :
os.remove(f)
lapseDone = True
return()
def lockCamExposure(camra) :
global makeMovie
camra.exposure_mode='auto'
camra.awb_mode = 'auto'
camra.iso = 0
OLDMM = makeMovie
makeMovie=False
displayString("8"*tubes)
time.sleep(3)
camra.capture('exposure.jpg')
#assumes camera is already open and gains have settled
camra.shutter_speed = camra.exposure_speed
camra.exposure_mode = 'off'
g = camra.awb_gains
camra.awb_mode = 'off'
camra.awb_gains = g
#camra.iso = 800
displayString(" "*tubes)
makeMovie=OLDMM
def unlockCamExposure(camra) :
camra.exposure_mode='auto'
camra.awb_mode = 'auto'
camra.iso = 0
def setCamEffex(camra,tweet) :
#check to see if any camera effect tags are in message and apply them if so (only one effect at a time so last one encountered wins)
for ht in tweet['entities']['hashtags'] :
if ht['text'].lower() in camra.IMAGE_EFFECTS :
camra.image_effect = ht['text'].lower()
def makeStatusText(tweet,aWord):
salutes=("Your wish is my command","Thanks for the suggestion","Hello","Hi",
"Wotcha","Greetings","Thanks","","","","Thanks for the tweet","Eh-up","Wotcher",
"So,","Hello","Hi","Good%DAYTIME%","Salutations","Ahoy there", "Well,", "OK,", "Ummm,", "'Sup", "Ah, there you are" )
scolds = (". How very original,", ". How old are you? I'm guessing 13,", ". 'Edgy' is dank now, didn't you know? Anyway," , ". Would your mother let you say that? Anyway,",
". Really? OK," )
picStatus = random.choice(salutes) + " @" + tweet['user']['screen_name']
if aWord.lower() in badwords :
r = random.random()
if r < 0.25:
picStatus = picStatus + ". How very original,"
elif r < 0.5:
picstatus = picStatus + ". How old are you? I'm guessing 13,"
elif r < 0.6:
picstatus = picStatus + ". 'Edgy' is dank now, didn't you know? Anyway,"
elif r < 0.75:
picStatus = picStatus + ". Would your mother let you say that? Anyway,"
elif r < 0.9:
picstatus = picStatus + ". Really? OK,"
if aWord.upper() in ("BUM","TIT","POO","WEE","FART") :
r = random.random()
if r < 0.25:
picStatus = picStatus + ". Teeheeeheee, rude! "
elif r < 0.5:
picstatus = picStatus + ". Same to you! Anyway, "
elif r < 0.75:
picStatus = picStatus + ". Do your parents know you're playing with twitter?"
elif r < 0.9:
picstatus = picStatus + ". What are you, five?"
if aWord == "TheTimeIs" :
picStatus=picStatus + " The time (hereabouts) is :"
if aWord =="swear_words" :
picStatus=picStatus + " Well, you asked for it, here's a sweary movie:"
elif aWord =="nice_words" :
picStatus=picStatus + " Some nice words from tweeps:"
else :
picStatus = picStatus + " here's your pic. "
if scanTags(tweet, "HMHB") :
picStatus = picStatus + "#HMHB"
tailIt = False
if len(tweet['entities']['user_mentions'])> 0:
#print("############ processing mentions ")
if len(tweet['entities']['user_mentions'])== 1 :
if tweet['entities']['user_mentions'][0]['screen_name'].lower() == "nixiebot" : # educate people @mentioning me
edString = "BTW: No need to @ mention me, just use the tag"
if len(picStatus) + len(edString) < 90 : picStatus = picStatus + edString
picStatus = picStatus + " Hey:"
for m in tweet['entities']['user_mentions'] :
uName=str(m['screen_name'])
if len(picStatus + uName) <= 97 and not (uName.lower() == "nixiebot") :
picStatus = picStatus + " @"+uName + " "
tailIt = True
if tailIt : picStatus=picStatus + " this is for you too!"
return(picStatus)
def hasCommand(tweet) :
global validTags
for t in tweet['entities']['hashtags'] :
if t['text'].lower() in validTags :
return(True)
return(False)
def processIncomingTweet(tweet): #check tweet that has come in via the filter stream, it might have commands in it
# print(tweet)
global botState
global wordq
global randstream
if scanTags(tweet,"NixieBotShowMe") :
theWord=extractWord(html.parser.HTMLParser().unescape(tweet['text']))
if ((theWord is not None ) or ( hasCommand(tweet))) :
wordqPut(tweet,priority = prioritise(tweet))
size = wordq.qsize()
if size > botState['maxWordQ'] : botState['maxWordQ'] = size
print("word request from", tweet['user']['screen_name'], "word = ", theWord, " Word queue at:", size, "maxqueue was ", botState['maxWordQ'])
recentReqs.append(tweet) # store for sending to hard storage every now and then
if len(recentReqs) > reqPickleFrequency :
if pickleMe(recentReqs, "Requests", dateStamp=True) :
recentReqs[:]=[]
#userCounter.update(tweet['user']['screen_name'])
elif scanTags(tweet,"NixieBotRollMe") :
rollq.put(tweet)
print("roll request incoming! Word queue at:", rollq.qsize())
else :
#must be a trump tweet so submit to random for now
randstream.on_success(tweet)
# DMreceipt bad idea as it still counts against rate limit
#for ht in tweet['entities']['hashtags']:
# if ht['text']=="NBreceipt" and not rct:
# sendReceipt(tweet,theWord,tt)
# rct=True
def prioritise(tweet) :
# assign a priority number to a tweet, currently just used to shoehorn test tweets in
# future use: deprioritise abusive users?
if tweet['user']['screen_name'] in priorityUsers :
return(1)
elif scanTags(tweet,"HMHB"):
return(40)
else :
return(50)
def pickleMe(item, baseName, dateStamp = True) : #pickle item out to a file named
fileName = baseName
if dateStamp :
fileName = fileName + "-" + time.strftime("%Y%m%d-%H%M%S")
fileName = fileName + ".pkl"
print("Trying to pickle out " + fileName )
fh = open( fileName, "wb" )
with fh :
try :
pickle.dump(item,fh)
print("OK, done")
return (True)
except :
print("exception pickling! better check disc space ")
return(False)
def sendReceipt(tweet,theWord,tt):
global wordq
global twitter
if theWord is None and not tt:
msg="I'm sorry I couldn't find a word short enough to display in that tweet"
else:
msg="Thanks! your message is at position " + str(wordq.qsize()) + " in the queue. I can only tweet once a minute, "
if wordq.qsize() >5 :
msg = msg + " so you might have to wait a bit, sorry."
msg=msg+" sent: " + time.strftime("%H:%M:%S")
twitter.send_direct_message(user_id=tweet['user']['id'], text=msg)
def extractWord(strng):
#print("***********************extractword... parameter = " + strng + " type " + str(type(strng)))
wordlist=strng.split()
if log_level >=2 :
print("******** wordlist = " + str(wordlist))
preTag=None
result=None
tagged=False
#scan for a suitable word after the hashtag
for w in wordlist:
if w.upper() == "#NIXIEBOTSHOWME" :
tagged = True
continue
else:
preTag = w
if tagged and w[0] != "#":
result=w #get first non hashtag after showme tag
break
if result == None and preTag != None :
result = preTag
return(result)
def initGPIO():
global HVToggleTime
GPIO.setmode(GPIO.BOARD)
GPIO.setup(blankpin,GPIO.OUT)
HVToggleTime = 0 # NB check boot behavior of blanking pin, it's high on boot then set this to time.time() to avoid too quick toggle on program start