def handle(self, *args, **options): settings_obj = Site.objects.get_current().settings self.stdout.write("Updating the Strava cache...") if settings.STRAVA_ACCESS_TOKEN == None: self.stdout.write("You must set STRAVA_ACCESS_TOKEN") return client = Client() client.access_token = settings.STRAVA_ACCESS_TOKEN if settings.STRAVA_CYCLING_CLUB != 0: cycling_club = client.get_club(settings.STRAVA_CYCLING_CLUB) self.stdout.write("Got this many cyclists = " + str(cycling_club.member_count)) settings_obj.cyclists = cycling_club.member_count # self.stdout.write("Getting cycling activities") # cycling_activities = client.get_club_activities(settings.STRAVA_CYCLING_CLUB) # Just get all of them, database can dedupe # self.insert_into_db(cycling_activities, ActivityCache.RIDE) if settings.STRAVA_RUNNING_CLUB != 0: running_club = client.get_club(settings.STRAVA_RUNNING_CLUB) self.stdout.write("Got this many runners = " + str(running_club.member_count)) settings_obj.runners = running_club.member_count # self.stdout.write("Getting running activities") # running_activities = client.get_club_activities(settings.STRAVA_RUNNING_CLUB) # self.insert_into_db(running_activities, ActivityCache.RUN) settings_obj.save()
class StravaBot: def __init__(self): Config = ConfigParser.ConfigParser() Config.read("configuration/config") Config.sections() self.clientId = Config.get('Strava', 'ClientId') self.clientSecret = Config.get('Strava', 'ClientSecret') self.clientAccessToken = Config.get('Strava', 'ClientAccessToken') self.clubId = Config.get('Strava', 'ClubId') self.mattermostUrl = Config.get('Mattermost', 'URL') self.delay = Config.get('Bot', 'Delay') self.client = Client() self.client.access_token = self.clientAccessToken self.club = self.client.get_club(self.clubId) self.http = urllib3.PoolManager( cert_reqs='CERT_REQUIRED', ca_certs=certifi.where()) print('Bot for club {name} with id {id} is here :^)\n'.format(name=self.club.name, id=self.clubId)) def post_activity(self, activity): payload = {} if (activity.athlete.firstname is None): activity.athlete = self.client.get_athlete(activity.athlete.id) first_name = activity.athlete.firstname last_name = activity.athlete.lastname distance = kilometers(activity.distance) activity_duration = activity.moving_time speed = kilometers_per_hour(activity.average_speed) climbing = meters(activity.total_elevation_gain) activity_id = activity.id description = activity.name if (len(description) > 100): description = description[:97] + "..." payload = {'username': '******', 'icon_url': 'https://raw.githubusercontent.com/patoupatou/pymatterstrava/master/icon-strava.png', 'text': u':bicyclist: *{} {} : distance: {}, moving time duration: {}, speed: {}, climbing: {}* [{}](http://strava.com/activities/{}) :bicyclist:'.format(first_name, last_name, distance, activity_duration, speed, climbing, description, activity_id)} r = self.http.request('POST', self.mattermostUrl, headers={'Content-Type': 'application/json'}, body=json.dumps(payload)) print(time.ctime() + ': New activity posted') print('payload: ' + str(payload) + '\n') def get_activity_details(self, activity): return self.client.get_activity(activity.id) def get_new_activities(self, old_activities, new_activities): new_list = [] new_activity_ids = [] old_activity_ids = [] for new_activity in new_activities: new_activity_ids.append(new_activity.id) for old_activity in old_activities: old_activity_ids.append(old_activity.id) diff_ids = list(set(new_activity_ids) - set(old_activity_ids)) new_list = [act for act in new_activities if act.id in diff_ids] return new_list def run(self): activities = set(self.client.get_club_activities(self.clubId, limit=5)) new_activities = activities # for activity in activities: # details = self.get_activity_details(activity) # self.post_activity(details) while(1): new_activities = set(self.client.get_club_activities(self.clubId, limit=5)) diff_activities = self.get_new_activities(activities, new_activities) if len(diff_activities) > 0: print(time.ctime() + ': New activities!\n') print(diff_activities) for new_activity in diff_activities: details = self.get_activity_details(new_activity) self.post_activity(details) else: print(time.ctime() + ': No new activities\n') activities = new_activities time.sleep(float(self.delay))
class Strava(object): def __init__(self, client_id, client_secret, refresh_token, club_id): # First store the client id, secret and refresh token self.client_id = client_id self.client_secret = client_secret self.refresh_token = refresh_token # And store some other fields self.club_id = club_id self.club = None self.club_expires_at = 0 # Then we get a new access token using the client id, secret and refresh token self.token = self.get_access_token() # Now we have the access token we can create an instance of the stravalib Client self.client = Client(access_token=self.token['access_token']) def get_access_token(self): # Get a new access token to fetch data from the Strava API auth_url = "https://www.strava.com/oauth/token" payload = { 'client_id': self.client_id, 'client_secret': self.client_secret, 'refresh_token': self.refresh_token, 'grant_type': "refresh_token", 'f': 'json' } res = requests.post(auth_url, data=payload, verify=False) return res.json() def update_access_token(self): # Update the existing access token refresh_response = self.client.refresh_access_token( client_id=self.client_id, client_secret=self.client_secret, refresh_token=self.refresh_token) # refresh_response contains the following fields: # - refresh_token # - expires_at # We save the new token self.token = refresh_response # And save the new refresh token which should be used next time self.refresh_token = refresh_response['refresh_token'] def update_club(self): # Get new data of the strava club if self.token_expired: # If the access token has been expired, we need to update it beofre we can fetch data from strava print('access_token has expired, updating access_token') self.update_access_token() # Get the strava club data self.club = self.client.get_club(self.club_id) # And set the data to expire in 5 minutes self.club_expires_at = time.time() + 300 def get_member_count(self): # Get the member count of the strava club if self.club_expired: # Only fetch data from strava if the club data has been expired print('club has expired, updating club') self.update_club() return self.club.member_count @property def token_expired(self): # Check if the straca access token has been expired return time.time() > self.token['expires_at'] @property def club_expired(self): # Check if the cached club data has been expired return time.time() > self.club_expires_at