-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
79 lines (58 loc) · 2.03 KB
/
bot.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
from sys import implementation
import tweepy
import logging
import time
import webscraper
# API code was taken from https://realpython.com/twitter-bot-python-tweepy/
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
def create_apii():
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True,
wait_on_rate_limit_notify=True)
try:
api.verify_credentials()
except Exception as e:
logger.error("Error creating API", exc_info=True)
raise e
logger.info("API created")
return api
def check_mentions(api, keywords, since_id):
logger.info("Retrieving mentions")
new_since_id = since_id
for tweet in tweepy.Cursor(api.mentions_timeline,
since_id=since_id).items():
new_since_id = max(tweet.id, new_since_id)
if tweet.in_reply_to_status_id is not None:
continue
if any(keyword in tweet.text.lower() for keyword in keywords):
emotion = [keyword in tweet.text.lower() for keyword in keywords]
logger.info(f"Answering to {tweet.user.name}")
quote = webscraper.get_quote(emotion[0])
api.update_status(
status=quote,
in_reply_to_status_id=tweet.id,
)
else:
logger.info(f"Answering to {tweet.user.name}")
quote = webscraper.get_quote("Sad")
api.update_status(
status=quote,
in_reply_to_status_id=tweet.id,
)
return new_since_id
def main():
api = create_apii()
since_id = 1
emotions = ["sad", "happy", "angry", "surprise", "fear"]
while True:
since_id = check_mentions(api, emotions, since_id)
logger.info("Waiting...")
time.sleep(5)
if __name__ == "__main__":
main()