Skip to content

Commit b1935e3

Browse files
committed
Fix youtube.py error messages
1 parent 97f5807 commit b1935e3

File tree

2 files changed

+136
-135
lines changed

2 files changed

+136
-135
lines changed

plugins/youtube.py

Lines changed: 57 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,14 @@
1010
from cloudbot.util.formatting import pluralize_suffix
1111

1212
youtube_re = re.compile(
13-
r'(?:youtube.*?(?:v=|/v/)|youtu\.be/|yooouuutuuube.*?id=)([-_a-zA-Z0-9]+)', re.I
13+
r"(?:youtube.*?(?:v=|/v/)|youtu\.be/|yooouuutuuube.*?id=)([-_a-zA-Z0-9]+)", re.I
1414
)
1515
ytpl_re = re.compile(
16-
r'(.*:)//(www.youtube.com/playlist|youtube.com/playlist)(:[0-9]+)?(.*)', re.I
16+
r"(.*:)//(www.youtube.com/playlist|youtube.com/playlist)(:[0-9]+)?(.*)", re.I
1717
)
1818

1919

20-
base_url = 'https://www.googleapis.com/youtube/v3/'
20+
base_url = "https://www.googleapis.com/youtube/v3/"
2121

2222

2323
class APIError(Exception):
@@ -46,13 +46,16 @@ def raise_api_errors(response: requests.Response) -> None:
4646
except ValueError:
4747
raise e
4848

49-
errors = data.get('errors')
49+
errors = data.get("errors")
50+
if not errors:
51+
errors = data.get("error", {}).get("errors")
52+
5053
if not errors:
5154
return
5255

5356
first_error = errors[0]
54-
domain = first_error['domain']
55-
reason = first_error['reason']
57+
domain = first_error["domain"]
58+
reason = first_error["reason"]
5659
raise APIError("API Error ({}/{})".format(domain, reason), data) from e
5760

5861

@@ -75,81 +78,81 @@ def do_request(
7578
if params:
7679
kwargs.update(params)
7780

78-
kwargs['part'] = ','.join(parts)
79-
kwargs['key'] = api_key
81+
kwargs["part"] = ",".join(parts)
82+
kwargs["key"] = api_key
8083
return requests.get(base_url + method, kwargs)
8184

8285

8386
def get_video(video_id: str, parts: Parts) -> requests.Response:
84-
return do_request('videos', parts, params={'maxResults': 1, 'id': video_id})
87+
return do_request("videos", parts, params={"maxResults": 1, "id": video_id})
8588

8689

8790
def get_playlist(playlist_id: str, parts: Parts) -> requests.Response:
88-
return do_request('playlists', parts, params={'maxResults': 1, 'id': playlist_id})
91+
return do_request("playlists", parts, params={"maxResults": 1, "id": playlist_id})
8992

9093

91-
def do_search(term: str, result_type: str = 'video') -> requests.Response:
94+
def do_search(term: str, result_type: str = "video") -> requests.Response:
9295
return do_request(
93-
'search', ['snippet'], params={'maxResults': 1, 'q': term, 'type': result_type}
96+
"search", ["snippet"], params={"maxResults": 1, "q": term, "type": result_type}
9497
)
9598

9699

97100
def get_video_description(video_id: str) -> str:
98-
parts = ['statistics', 'contentDetails', 'snippet']
101+
parts = ["statistics", "contentDetails", "snippet"]
99102
request = get_video(video_id, parts)
100103
raise_api_errors(request)
101104

102105
json = request.json()
103106

104-
data = json['items']
107+
data = json["items"]
105108
if not data:
106109
raise NoResultsError()
107110

108111
item = data[0]
109-
snippet = item['snippet']
110-
statistics = item['statistics']
111-
content_details = item['contentDetails']
112+
snippet = item["snippet"]
113+
statistics = item["statistics"]
114+
content_details = item["contentDetails"]
112115

113-
out = '\x02{}\x02'.format(snippet['title'])
116+
out = "\x02{}\x02".format(snippet["title"])
114117

115-
if not content_details.get('duration'):
118+
if not content_details.get("duration"):
116119
return out
117120

118-
length = isodate.parse_duration(content_details['duration'])
119-
out += ' - length \x02{}\x02'.format(
121+
length = isodate.parse_duration(content_details["duration"])
122+
out += " - length \x02{}\x02".format(
120123
timeformat.format_time(int(length.total_seconds()), simple=True)
121124
)
122125
try:
123-
total_votes = float(statistics['likeCount']) + float(statistics['dislikeCount'])
126+
total_votes = float(statistics["likeCount"]) + float(statistics["dislikeCount"])
124127
except (LookupError, ValueError):
125128
total_votes = 0
126129

127130
if total_votes != 0:
128131
# format
129-
likes = pluralize_suffix(int(statistics['likeCount']), "like")
130-
dislikes = pluralize_suffix(int(statistics['dislikeCount']), "dislike")
132+
likes = pluralize_suffix(int(statistics["likeCount"]), "like")
133+
dislikes = pluralize_suffix(int(statistics["dislikeCount"]), "dislike")
131134

132-
percent = 100 * float(statistics['likeCount']) / total_votes
133-
out += ' - {}, {} (\x02{:.1f}\x02%)'.format(likes, dislikes, percent)
135+
percent = 100 * float(statistics["likeCount"]) / total_votes
136+
out += " - {}, {} (\x02{:.1f}\x02%)".format(likes, dislikes, percent)
134137

135-
if 'viewCount' in statistics:
136-
views = int(statistics['viewCount'])
137-
out += ' - \x02{:,}\x02 view{}'.format(views, "s"[views == 1 :])
138+
if "viewCount" in statistics:
139+
views = int(statistics["viewCount"])
140+
out += " - \x02{:,}\x02 view{}".format(views, "s"[views == 1 :])
138141

139-
uploader = snippet['channelTitle']
142+
uploader = snippet["channelTitle"]
140143

141-
upload_time = isodate.parse_datetime(snippet['publishedAt'])
142-
out += ' - \x02{}\x02 on \x02{}\x02'.format(
144+
upload_time = isodate.parse_datetime(snippet["publishedAt"])
145+
out += " - \x02{}\x02 on \x02{}\x02".format(
143146
uploader, upload_time.strftime("%Y.%m.%d")
144147
)
145148

146149
try:
147-
yt_rating = content_details['contentRating']['ytRating']
150+
yt_rating = content_details["contentRating"]["ytRating"]
148151
except KeyError:
149152
pass
150153
else:
151154
if yt_rating == "ytAgeRestricted":
152-
out += colors.parse(' - $(red)NSFW$(reset)')
155+
out += colors.parse(" - $(red)NSFW$(reset)")
153156

154157
return out
155158

@@ -163,10 +166,10 @@ def get_video_id(text: str) -> str:
163166
raise_api_errors(request)
164167
json = request.json()
165168

166-
if not json.get('items'):
169+
if not json.get("items"):
167170
raise NoResultsError()
168171

169-
video_id = json['items'][0]['id']['videoId'] # type: str
172+
video_id = json["items"][0]["id"]["videoId"] # type: str
170173
return video_id
171174

172175

@@ -191,7 +194,7 @@ def youtube(text: str, reply) -> str:
191194
@hook.command("youtime", "ytime")
192195
def youtime(text: str, reply) -> str:
193196
"""<query> - Gets the total run time of the first YouTube search result for <query>."""
194-
parts = ['statistics', 'contentDetails', 'snippet']
197+
parts = ["statistics", "contentDetails", "snippet"]
195198
try:
196199
video_id = get_video_id(text)
197200
request = get_video(video_id, parts)
@@ -204,50 +207,50 @@ def youtime(text: str, reply) -> str:
204207

205208
json = request.json()
206209

207-
data = json['items']
210+
data = json["items"]
208211
item = data[0]
209-
snippet = item['snippet']
210-
content_details = item['contentDetails']
211-
statistics = item['statistics']
212+
snippet = item["snippet"]
213+
content_details = item["contentDetails"]
214+
statistics = item["statistics"]
212215

213-
duration = content_details.get('duration')
216+
duration = content_details.get("duration")
214217
if not duration:
215218
return "Missing duration in API response"
216219

217220
length = isodate.parse_duration(duration)
218221
l_sec = int(length.total_seconds())
219-
views = int(statistics['viewCount'])
222+
views = int(statistics["viewCount"])
220223
total = int(l_sec * views)
221224

222225
length_text = timeformat.format_time(l_sec, simple=True)
223226
total_text = timeformat.format_time(total, accuracy=8)
224227

225228
return (
226-
'The video \x02{}\x02 has a length of {} and has been viewed {:,} times for '
227-
'a total run time of {}!'.format(
228-
snippet['title'], length_text, views, total_text
229+
"The video \x02{}\x02 has a length of {} and has been viewed {:,} times for "
230+
"a total run time of {}!".format(
231+
snippet["title"], length_text, views, total_text
229232
)
230233
)
231234

232235

233236
@hook.regex(ytpl_re)
234237
def ytplaylist_url(match: Match[str]) -> str:
235238
location = match.group(4).split("=")[-1]
236-
request = get_playlist(location, ['contentDetails', 'snippet'])
239+
request = get_playlist(location, ["contentDetails", "snippet"])
237240
raise_api_errors(request)
238241

239242
json = request.json()
240243

241-
data = json['items']
244+
data = json["items"]
242245
if not data:
243246
raise NoResultsError()
244247

245248
item = data[0]
246-
snippet = item['snippet']
247-
content_details = item['contentDetails']
249+
snippet = item["snippet"]
250+
content_details = item["contentDetails"]
248251

249-
title = snippet['title']
250-
author = snippet['channelTitle']
251-
num_videos = int(content_details['itemCount'])
252-
count_videos = ' - \x02{:,}\x02 video{}'.format(num_videos, "s"[num_videos == 1 :])
252+
title = snippet["title"]
253+
author = snippet["channelTitle"]
254+
num_videos = int(content_details["itemCount"])
255+
count_videos = " - \x02{:,}\x02 video{}".format(num_videos, "s"[num_videos == 1 :])
253256
return "\x02{}\x02 {} - \x02{}\x02".format(title, count_videos, author)

0 commit comments

Comments
 (0)