This repository has been archived by the owner on Jun 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
twitterbot.py
69 lines (51 loc) · 1.74 KB
/
twitterbot.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
"""Twitter bot that tweets a random line from a file.
Uses Twisted to periodically select a random line from an input file,
and Twython to post it to Twitter using your credentials.
Usage: python twitterbot.py file.txt, where each line in file.txt is
a single sentence terminated by a newline ('\n').
"""
import sys
import random
import datetime
from twisted.internet import task
from twisted.internet import reactor
from twython import Twython
TIMEOUT = datetime.timedelta(hours=1).seconds
twitter = Twython("YOUR API KEY",
"YOUR API SECRET",
"YOUR ACCESS TOKEN",
"YOUR ACCESS TOKEN SECRET")
def reservoir(iterator):
"""Select item from iterator.
Reservoir algorithm from http://stackoverflow.com/a/3540315/250241/
"""
select = next(iterator)
for num, item in enumerate(iterator):
if random.randrange(num + 2):
continue
select = item
return select
def get_line(file_name):
"""Open file and select tweetable line."""
with open(file_name) as open_file:
while True:
open_file.seek(0) # reset file iterator to 0
line = reservoir(open_file).strip().replace(" ", " ")
if line[0].isupper() and 4 < len(line) < 140:
return line
def tweet(sentence):
"""Tweet sentence to Twitter."""
try:
sys.stdout.write("{} {}\n".format(len(sentence), sentence))
twitter.update_status(status=sentence)
except:
pass
def do_tweet(file_name):
"""Get line and tweet it"""
line = get_line(file_name)
tweet(line)
if __name__ == '__main__':
file_name = str(sys.argv[1])
l = task.LoopingCall(do_tweet, file_name)
l.start(TIMEOUT)
reactor.run()