-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlistening_bot2.py
66 lines (48 loc) · 1.95 KB
/
listening_bot2.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Twitter Bot Starter Kit: Responding Bot
# This bot listens to the account @ocertat, and when that account
# tweets, it responds with a line of Twain
# Download a Project Gutenberg "Plain Text UTF-8" file,
# open it in Notepad, remove junk at beginning,
# and replace all double-linebreaks with single linebreaks.
# Housekeeping: do not edit
import tweepy
import time
from credentials import *
from random import randint
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
api = tweepy.API(auth)
# initially, the script will assume that the last tweet was a null value
last_tweet = None
# What the bot will tweet
filename = open('data/twain.txt', 'r')
tweet_text = filename.readlines()
filename.close()
# a function that picks a random line
def line_number():
return randint(0, len(tweet_text) - 1)
# this is the function that does most of the work of the bot
def compare_tweets():
# uses the global lasttweet variable, rather than the local one.
# (it's probably best practice not to use a global variable for
# this purpose, but we've shown this approach for its readability.)
global last_tweet
# gets the most recent tweet by @realdonaldtrump and prints its id
most_recent_tweet = api.user_timeline('realdonaldtrump')[0]
print(most_recent_tweet.id)
# compares the two tweets, and tweets a line of Twain
# if there is a new tweet from @realdonaldtrump
if most_recent_tweet != last_tweet:
line = tweet_text[line_number()]
api.update_status(status=line)
print(line)
# updates last_tweet to the most_recent_tweet
last_tweet = most_recent_tweet
# runs the compare_tweets function every 5 seconds
while True:
compare_tweets()
print("sleeping")
time.sleep(5) # Sleep for 5 seconds
# To quit: CTRL+C and wait a few seconds