-
Notifications
You must be signed in to change notification settings - Fork 1
/
Trending_Bot.py
174 lines (144 loc) · 6.05 KB
/
Trending_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
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
# Framework credits: twitterbot by thricedotted
import tweepy
from Reverse_Geocoding import FormatOSMTrendingNames as Ft
import datetime as dt
import logging
import time
import os
TWITTER_STATUS_LIMIT = 116 # with image
DATE = (dt.datetime.now() - dt.timedelta(days=2)).replace(hour=0, minute=0, second=0, microsecond=0)
REGION = 'world' # Hard coded for now
ERROR_MSG = 'Trending places bot has been unable to find data for the last few days... It will return tomorrow'
class TrendingTweepy:
def __init__(self, conf_file='config'):
self.config = {}
# Configure with environemnt variables on unix based systems
try:
self.config['CONSUMER_KEY'] = os.environ['CONSUMER_KEY']
self.config['CONSUMER_SECRET'] = os.environ['CONSUMER_SECRET']
self.config['ACCESS_TOKEN_SECRET'] = os.environ['ACCESS_TOKEN_SECRET']
self.config['ACCESS_TOKEN'] = os.environ['ACCESS_TOKEN']
except KeyError:
raise Exception('The environment variable for twitter bot authentication are missing')
# Authentication
self.auth = tweepy.OAuthHandler(self.config['CONSUMER_KEY'], self.config['CONSUMER_SECRET'])
self.auth.set_access_token(self.config['ACCESS_TOKEN'], self.config['ACCESS_TOKEN_SECRET'])
self.auth.secure = True
self.api = tweepy.API(self.auth)
# Self details
self.followers = {}
self.id = self.api.me().id
self.screen_name = self.api.me().screen_name
self.followers['existing'] = self.api.followers_ids(self.id)
self.followers['new'] = []
self.friends = self.api.friends_ids(self.id)
# Tweepy bot state
self.state = {}
self.state['last_follow_check'] = 0
self.state['last_tweet'] = 0
self.state['Trending items'] = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Tile_log')
self._follow_all()
logging.basicConfig(format='%(asctime)s | %(levelname)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p',
filename=self.screen_name + '.log',
level=logging.DEBUG)
logging.info('Initializing bot...')
def on_follow(self, f_id):
"""
Follow back on being followed
"""
try:
self.api.create_friendship(f_id, follow=True)
self.friends.append(f_id)
logging.info('Followed user id {}'.format(f_id))
except tweepy.TweepError as e:
self._log_tweepy_error('Unable to follow user', e)
def tweet_status_trends(self):
"""
Tweets the top trending places
"""
logging.info("Updating status with Trending places....")
try:
base_text = "Top trending places in #OSM " + DATE.strftime('%d/%m') + ': '
end_text = ''
count_available = TWITTER_STATUS_LIMIT - len(base_text) - len(end_text)
text = Ft().get_cities_from_file(str(DATE.date()), REGION, count_available)
img = Ft.get_trending_graph(str(DATE.date()), REGION)
if text:
self.api.update_with_media(img, base_text + text + end_text)
self.state['last_tweet'] = time.time()
else:
self.api.update_status(ERROR_MSG)
logging.info("Could not update status. Rechecking in a while....")
except tweepy.TweepError as e:
self._log_tweepy_error('Can\'t update status because', e)
def on_message(self):
"""
On receiving a direct message from a follower add to subscribed country list
Returns
-------
"""
pass
def update_subscribers(self):
"""
Find the top 10 trending OSM places for the subscribed countries and notify subscribers
Returns
-------
"""
pass
def _config_bot(self, file):
with open(file, 'r') as conf_file:
for line in conf_file:
try:
configuration, value = line.split('=')
self.config[configuration.strip()] = value.strip()
except ValueError as e:
self._log_tweepy_error('Wrong configuration parameters', e)
check_values = ['CONSUMER_KEY', 'CONSUMER_SECRET', 'ACCESS_TOKEN_SECRET', 'ACCESS_TOKEN']
if len((check_values - self.config.keys())) != 0:
raise Exception('The configuration file is missing parameters')
def log(self, message, level=logging.INFO):
if level == logging.ERROR:
logging.error(message)
else:
logging.info(message)
def _log_tweepy_error(self, message, e):
try:
e_message = e.message[0]['message']
code = e.message[0]['code']
self.log("{}: {} ({})".format(message, e_message, code), level=logging.ERROR)
except:
self.log(message, e)
def _follow_all(self):
"""
follows all followers on initialization
"""
logging.info("Following back all followers....")
try:
self.followers['new'] = list(set(self.followers['existing']) - set(self.friends))
self._handle_followers()
except tweepy.TweepError as e:
self._log_tweepy_error('Can\'t follow back existing followers', e)
def _check_followers(self):
"""
Checks followers.
"""
logging.info("Checking for new followers...")
try:
self.followers['new'] = [f_id for f_id in self.api.followers_ids(self.id) if f_id not in self.followers['existing']]
self.state['last_follow_check'] = time.time()
except tweepy.TweepError as e:
self._log_tweepy_error('Can\'t update followers', e)
def _handle_followers(self):
"""
Handles new followers.
"""
for f_id in self.followers['new']:
self.on_follow(f_id)
def run(self):
"""
Runs the main tweepy smallbot
"""
self.tweet_status_trends()
if __name__ == '__main__':
smallbot = TrendingTweepy()
smallbot.run()