diff --git a/bot/extensions/youtube/tasks.py b/bot/extensions/youtube/tasks.py index 1f5cb766..d2fd87cd 100644 --- a/bot/extensions/youtube/tasks.py +++ b/bot/extensions/youtube/tasks.py @@ -27,6 +27,7 @@ class YoutubeTasks(commands.Cog): def __init__(self, bot: core.DiscordBot): self.bot = bot self.video_links: list[str] = [] + self.update_thumbnail = [] self.check_for_new_videos.start() def cog_unload(self) -> None: @@ -37,6 +38,15 @@ def channel(self) -> discord.TextChannel | None: return self.bot.get_channel(settings.notification.channel_id) async def send_notification(self, video: Video) -> None: + update_thumbnail = False + max_res = video.thumbnail.replace("/hqdefault.jpg", "/maxresdefault.jpg") + async with http.session.get(max_res) as response: + if response.status == 200: + video.thumbnail = max_res + else: + update_thumbnail = True + video.thumbnail = video.thumbnail.replace("/hqdefault.jpg", "/mqdefault.jpg") + embed = discord.Embed( title=video.title, description=video.description.split("\n\n")[0], @@ -44,7 +54,7 @@ async def send_notification(self, video: Video) -> None: color=discord.Color.red(), timestamp=datetime.strptime(video.published, "%Y-%m-%dT%H:%M:%S%z"), ) - embed.set_image(url=video.thumbnail.replace("/hqdefault.jpg", "/mqdefault.jpg")) + embed.set_image(url=video.thumbnail) embed.set_author( name="Tech With Tim", url="https://www.youtube.com/c/TechWithTim", @@ -52,16 +62,30 @@ async def send_notification(self, video: Video) -> None: ) embed.set_footer(text="Uploaded", icon_url=self.bot.user.display_avatar.url) - await self.channel.send( + message = await self.channel.send( content=f"Hey <@&{settings.notification.role_id}>, **Tim** just posted a video! Go check it out!", embed=embed, allowed_mentions=discord.AllowedMentions(roles=True), ) + if update_thumbnail: + self.update_thumbnail.append((message.id, video.thumbnail)) + @tasks.loop(minutes=2) async def check_for_new_videos(self): """Check for new videos""" + for message_id, thumbnail_url in self.update_thumbnail: + async with http.session.get(thumbnail_url.replace("/mqdefault.jpg", "/maxresdefault.jpg")) as response: + if response.status == 404: + continue + + message = await self.channel.fetch_message(message_id) + embed = message.embeds[0] + embed.set_image(url=thumbnail_url) + await message.edit(embed=embed) + self.update_thumbnail.remove((message_id, thumbnail_url)) + url = "https://www.youtube.com/feeds/videos.xml?channel_id=UC4JX40jDee_tINbkjycV4Sg" async with http.session.get(url) as response: data = await response.text()