forked from isaac-chung/strava-kudos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
give_kudos.py
211 lines (183 loc) · 7.68 KB
/
give_kudos.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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import os
import time
import requests
import telegram
from playwright.sync_api import sync_playwright
BASE_URL = "https://www.strava.com/"
TG_TOKEN = os.environ.get('TELEGRAM_LHF_TOKEN')
TG_CHAT_ID = os.environ.get('TELEGRAM_LHF_CHAT_ID')
class KudosGiver:
"""
Logins into Strava and gives kudos to all activities under
Following.
"""
def __init__(self, max_run_duration=540) -> None:
self.EMAIL = os.environ.get('STRAVA_EMAIL')
self.PASSWORD = os.environ.get('STRAVA_PASSWORD')
if self.EMAIL is None or self.PASSWORD is None or TG_TOKEN is None or TG_CHAT_ID is None :
raise Exception("Must set environ variables EMAIL, PASSWORD, TELEGRAM API. \
e.g. run export STRAVA_EMAIL=YOUR_EMAIL")
self.max_run_duration = max_run_duration
self.start_time = time.time()
self.num_entries = 100
self.web_feed_entry_pattern = '[data-testid=web-feed-entry]'
p = sync_playwright().start()
self.browser = p.firefox.launch() # does not work in chrome
self.page = self.browser.new_page()
def send_telegram(self,message):
bot = telegram.Bot(token=TG_TOKEN)
bot.send_message(chat_id=TG_CHAT_ID, text=message)
def _send_telegram_message(self,message):
url = f"https://api.telegram.org/bot{TG_TOKEN}/sendMessage"
payload = {
"chat_id": TG_CHAT_ID,
"text": message
}
headers = {
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200:
print("Telegram message sent successfully.")
else:
print(f"Failed to send Telegram message. Status code: {response.status_code}, Response: {response.text}")
def email_login(self):
"""
Login using email and password
"""
self.page.goto(os.path.join(BASE_URL, 'login'))
try:
self.page.get_by_role("button", name="Reject").click(timeout=5000)
except Exception as _:
pass
self.page.get_by_role("textbox", name='email').fill(self.EMAIL)
self.page.get_by_role("textbox", name="password").fill(self.PASSWORD)
self.page.get_by_role("button", name="Log In").click()
print("---Logged in!!---")
self._run_with_retries(func=self._get_page_and_own_profile)
def _run_with_retries(self, func, retries=3):
"""
Retry logic with sleep in between tries.
"""
for i in range(retries):
if i == retries - 1:
raise Exception(f"Retries {retries} times failed.")
try:
func()
return
except Exception as _:
time.sleep(1)
def _get_page_and_own_profile(self):
"""
Limit activities count by GET parameter and get own profile ID.
"""
self.page.goto(os.path.join(BASE_URL, f"dashboard?num_entries={self.num_entries}"))
## Scrolling for lazy loading elements.
for _ in range(5):
self.page.keyboard.press('PageDown')
time.sleep(0.5)
self.page.keyboard.press('PageUp')
try:
self.own_profile_id = self.page.locator(".user-menu > a").get_attribute('href').split("/athletes/")[1]
print("id", self.own_profile_id)
except Exception as _:
print("can't find own profile ID")
def locate_kudos_buttons_and_maybe_give_kudos(self, web_feed_entry_locator) -> int:
"""
input: playwright.locator class
Returns count of kudos given.
"""
w_count = web_feed_entry_locator.count()
given_count = 0
print(f"web feeds found: {w_count}")
for i in range(w_count):
# run condition check
curr_duration = time.time() - self.start_time
if curr_duration > self.max_run_duration:
print("Max run duration reached.")
break
web_feed = web_feed_entry_locator.nth(i)
p_count = web_feed.get_by_test_id("entry-header").count()
# check if feed item is a club post
if self.is_club_post(web_feed):
print('c', end='')
continue
# check if activity has multiple participants
if p_count > 1:
for j in range(p_count):
participant = web_feed.get_by_test_id("entry-header").nth(j)
# ignore own activities
if not self.is_participant_me(participant):
kudos_container = web_feed.get_by_test_id("kudos_comments_container").nth(j)
button = self.find_unfilled_kudos_button(kudos_container)
given_count += self.click_kudos_button(unfilled_kudos_container=button)
else:
# ignore own activities
if not self.is_participant_me(web_feed):
button = self.find_unfilled_kudos_button(web_feed)
given_count += self.click_kudos_button(unfilled_kudos_container=button)
print(f"\nKudos given: {given_count}")
self.send_telegram(f"Kudos given: {given_count}")
#self._send_telegram_message(f"Kudos given: {given_count}")
return given_count
def is_club_post(self, container) -> bool:
"""
Returns true if the container is a club post
"""
if(container.get_by_test_id("group-header").count() > 0):
return True
if(container.locator(".clubMemberPostHeaderLinks").count() > 0):
return True
return False
def is_participant_me(self, container) -> bool:
"""
Returns true is the container's owner is logged-in user.
"""
owner = self.own_profile_id
try:
h = container.get_by_test_id("owners-name").get_attribute('href')
hl = h.split("/athletes/")
owner = hl[1]
except Exception as _:
print("Some issue with getting owners-name container.")
return owner == self.own_profile_id
def find_unfilled_kudos_button(self, container):
"""
Returns button as a playwright.locator class
"""
button = None
try:
button = container.get_by_test_id("unfilled_kudos")
except Exception as _:
print("Some issue with finding the unfilled_kudos container.")
return button
def click_kudos_button(self, unfilled_kudos_container) -> int:
"""
input: playwright.locator class
Returns 1 if kudos button was clicked else 0
"""
if unfilled_kudos_container.count() == 1:
unfilled_kudos_container.click(timeout=0, no_wait_after=True)
print('=', end='')
time.sleep(1)
return 1
return 0
def give_kudos(self):
"""
Interate over web feed entries
"""
## Give Kudos on loaded page ##
try:
self.page.get_by_role("button", name="Accept").click(timeout=5000)
print("Accepting updated terms.")
except Exception as _:
pass
web_feed_entry_locator = self.page.locator(self.web_feed_entry_pattern)
self.locate_kudos_buttons_and_maybe_give_kudos(web_feed_entry_locator=web_feed_entry_locator)
self.browser.close()
def main():
kg = KudosGiver()
kg.email_login()
kg.give_kudos()
if __name__ == "__main__":
main()