Skip to content

Commit 82a4321

Browse files
authored
Merge pull request #464 from TotallyNotRobots/fix-yt-likes
chore: Handle missing dislike data due to YouTube API changes
2 parents 461df27 + f13c3d8 commit 82a4321

File tree

2 files changed

+40
-17
lines changed

2 files changed

+40
-17
lines changed

plugins/youtube.py

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
import isodate
55
import requests
6+
from requests import Response
67

78
from cloudbot import hook
89
from cloudbot.bot import bot
@@ -23,7 +24,9 @@
2324

2425

2526
class APIError(Exception):
26-
def __init__(self, message: str, response: Optional[str] = None) -> None:
27+
def __init__(
28+
self, message: str, response: Optional[Union[str, Response]] = None
29+
) -> None:
2730
super().__init__(message)
2831
self.message = message
2932
self.response = response
@@ -35,8 +38,8 @@ def __init__(self) -> None:
3538

3639

3740
class NoResultsError(APIError):
38-
def __init__(self) -> None:
39-
super().__init__("No results")
41+
def __init__(self, response: Response) -> None:
42+
super().__init__("No results", response)
4043

4144

4245
def raise_api_errors(response: requests.Response) -> None:
@@ -115,7 +118,7 @@ def get_video_description(video_id: str) -> str:
115118

116119
data = json["items"]
117120
if not data:
118-
raise NoResultsError()
121+
raise NoResultsError(request)
119122

120123
item = data[0]
121124
snippet = item["snippet"]
@@ -131,20 +134,21 @@ def get_video_description(video_id: str) -> str:
131134
out += " - length \x02{}\x02".format(
132135
timeformat.format_time(int(length.total_seconds()), simple=True)
133136
)
134-
try:
135-
total_votes = float(statistics["likeCount"]) + float(
136-
statistics["dislikeCount"]
137-
)
138-
except (LookupError, ValueError):
139-
total_votes = 0
140137

141-
if total_votes != 0:
142-
# format
143-
likes = pluralize_suffix(int(statistics["likeCount"]), "like")
144-
dislikes = pluralize_suffix(int(statistics["dislikeCount"]), "dislike")
138+
like_data = statistics.get("likeCount")
139+
dislike_data = statistics.get("dislikeCount")
145140

146-
percent = 100 * float(statistics["likeCount"]) / total_votes
147-
out += " - {}, {} (\x02{:.1f}\x02%)".format(likes, dislikes, percent)
141+
if like_data:
142+
# format
143+
likes = int(like_data)
144+
out += " - {}".format(pluralize_suffix(likes, "like"))
145+
if dislike_data:
146+
dislikes = int(dislike_data)
147+
total_votes = likes + dislikes
148+
percent = 100 * likes / total_votes
149+
out += ", {} (\x02{:.1f}\x02%)".format(
150+
pluralize_suffix(dislikes, "dislike"), percent
151+
)
148152

149153
if "viewCount" in statistics:
150154
views = int(statistics["viewCount"])
@@ -178,7 +182,7 @@ def get_video_id(text: str) -> str:
178182
json = request.json()
179183

180184
if not json.get("items"):
181-
raise NoResultsError()
185+
raise NoResultsError(request)
182186

183187
video_id = json["items"][0]["id"]["videoId"] # type: str
184188
return video_id

tests/plugin_tests/test_youtube.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,25 @@ def test_success_no_likes(self, mock_requests, mock_api_keys):
131131

132132
assert youtube.get_video_description("phL7P6gtZRM") == result
133133

134+
def test_success_no_dislikes(self, mock_requests, mock_api_keys):
135+
data = deepcopy(video_data)
136+
del data["items"][0]["statistics"]["dislikeCount"]
137+
138+
mock_requests.add(
139+
"GET",
140+
self.api_url.format(id="phL7P6gtZRM", key="APIKEY"),
141+
match_querystring=True,
142+
json=data,
143+
)
144+
145+
result = (
146+
"\x02some title\x02 - length \x0217m 2s\x02 - 4,633 likes - "
147+
"\x0268,905\x02 views - \x02a channel\x02 on "
148+
"\x022019.10.10\x02"
149+
)
150+
151+
assert youtube.get_video_description("phL7P6gtZRM") == result
152+
134153
def test_success_nsfw(self, mock_requests, mock_api_keys):
135154
data = deepcopy(video_data)
136155
data["items"][0]["contentDetails"]["contentRating"] = {

0 commit comments

Comments
 (0)