async def display_video(self, name): for item in self.data["items"]: if item["snippet"]["title"] == name: url = f"https://www.googleapis.com/youtube/v3/videos?part=contentDetails%2Csnippet%2Cstatistics&id={item['id']['videoId']}&key={Config.YOUTUBE_API_KEY}" await self.message.clear_reactions() async with self.ctx.bot.session.get(url) as response: if not 200 <= response.status <= 299: return await self.message.edit( content= f"The YouTube API returned {response.status} {response.reason}.", embed=None) data = (await response.json())["items"][0] duration = self.ctx.bot.get_cog("YouTube").get_duration( data["contentDetails"]["duration"]) published_at = chron.from_iso( data["snippet"]["publishedAt"][:-1]) await self.message.edit(embed=discord.Embed.from_dict({ "title": item["snippet"]["title"], "description": f"Click [here](https://youtube.com/watch?v={item['id']['videoId']}) to watch. Use `{Config.PREFIX}yt video {item['id']['videoId']}` for detailed video information.", "color": DEFAULT_EMBED_COLOUR, "author": { "name": "Query" }, "footer": { "text": f"Requested by {self.ctx.author.display_name}", "icon_url": f"{self.ctx.author.avatar_url}", }, "fields": [ { "name": "Published on", "value": f"{chron.long_date(published_at)}", "inline": True }, { "name": "Duration", "value": duration, "inline": True }, { "name": "Views", "value": f"{int(data['statistics']['viewCount']):,}", "inline": True, }, ], }))
async def yt_video_command(self, ctx: commands.Context, id_: str) -> None: url = f"https://www.googleapis.com/youtube/v3/videos?part=contentDetails%2CliveStreamingDetails%2Csnippet%2Cstatistics&id={id_}&key={Config.YOUTUBE_API_KEY}" async with ctx.typing(): async with self.bot.session.get(url) as response: if not 200 <= response.status <= 299: return await ctx.send( f"The YouTube API returned {response.status} {response.reason}." ) if not (data := (await response.json())["items"]): return await ctx.send("Invalid video ID.") data = data[0] if data["snippet"]["channelId"] != Config.YOUTUBE_CHANNEL_ID: return await ctx.send("That is not a Carberra video.") if (stream := "liveStreamingDetails" in data.keys()): published_at = chron.from_iso( data["liveStreamingDetails"]["actualStartTime"][:-1])
async def get_new_streams(self) -> tuple: data = await self.call_twitch_api() if data: live_now = await self.bot.db.field( "SELECT StreamLive FROM streams WHERE ID = 1") if data["is_live"] and not live_now: # The stream is live and we havent announced it yet start = chron.from_iso(data["started_at"].strip("Z")) message = await self.videos_channel.send( f"Hey {self.streams_role.mention}, I'm live on Twitch now! Come watch!", embed=discord.Embed.from_dict({ "title": data["title"], "description": f"**Category: {data['game_name']}**", "color": LIVE_EMBED_COLOUR, "url": "https://www.twitch.tv/carberratutorials", "author": { "name": "Carberra Tutorials" }, "thumbnail": { "url": data["thumbnail_url"] }, "footer": { "text": f"Started: {chron.long_date_and_time(start)} UTC" }, }), ) await self.bot.db.execute( "UPDATE streams SET StreamLive = ?, StreamStart = ?, StreamMessage= ? WHERE ID = 1", 1, start, message.id, ) return data["title"], False elif not data["is_live"] and live_now: # The stream is not live and last we checked it was (stream is over) await self.bot.db.execute( "UPDATE streams SET StreamLive = ?, StreamEnd = ? WHERE ID = 1", 0, dt.datetime.utcnow()) start, stream_message, end = await self.bot.db.record( "SELECT StreamStart, StreamMessage, StreamEnd FROM streams WHERE ID = 1" ) duration = chron.from_iso(end) - chron.from_iso(start) try: message = await self.videos_channel.fetch_message( stream_message) except (discord.NotFound, discord.Forbidden, discord.HTTPException): return else: await message.edit( content= f"Hey {self.streams_role.mention}, I'm live on Twitch now! Come watch!", embed=discord.Embed.from_dict({ "title": "The stream has ended.", "description": "**Catch you in the next one!**", "color": LIVE_EMBED_COLOUR, "url": "https://www.twitch.tv/carberratutorials", "author": { "name": "Carberra Tutorials" }, "thumbnail": { "url": data["thumbnail_url"] }, "footer": { "text": f"Runtime: {chron.long_delta(duration)}" }, }), ) return data["title"], True
async def get_new_premieres(self) -> tuple: known_premieres = { _id: [_upcoming, _announced] for _id, _upcoming, _announced in await self.bot.db.records( "SELECT * FROM premieres") } for item in await self.call_feed(): data = await self.call_yt_api(item.yt_videoid) thumbnails = data["snippet"]["thumbnails"] duration = data["contentDetails"]["duration"] live_content = data["snippet"]["liveBroadcastContent"] upcoming = known_premieres[ item.yt_videoid][0] if item.yt_videoid in known_premieres.keys( ) else None announced = known_premieres[ item.yt_videoid][1] if item.yt_videoid in known_premieres.keys( ) else None if "liveStreamingDetails" in data.keys(): start_time = data["liveStreamingDetails"][ "scheduledStartTime"].strip("Z") scheduled_time = chron.from_iso(start_time) if not upcoming and duration != "P0D": # We have not seen this premiere before if live_content == "upcoming" and not announced: # This premiere is upcoming and not live await self.videos_channel.send( f"Hey {self.videos_role.mention}, a new premiere is scheduled for {chron.long_date_and_time(scheduled_time)} UTC! Hope to see you there!", embed=discord.Embed.from_dict({ "title": item.title, "description": desc if len(desc := item.summary) <= 500 else f"{desc[:500]}...", "color": DEFAULT_EMBED_COLOUR, "url": item.link, "author": { "name": "Carberra Tutorials" }, "image": { "url": thumbnails["maxres"]["url"] }, "footer": { "text": f"Runtime: {self.youtube.get_duration(duration, long=True)}" }, }), ) await self.bot.db.execute( "REPLACE INTO premieres (VideoID, Upcoming, Announced) VALUES (?, ?, ?)", item.yt_videoid, 1, 0, ) return item.yt_videoid, False elif live_content == "live" and not upcoming and not announced: # The premiere was never upcoming is now live await self.videos_channel.send( f"Hey {self.videos_role.mention}, a new premiere started on {chron.long_date_and_time(scheduled_time)} UTC! Come and join us!", embed=discord.Embed.from_dict({ "title": item.title, "description": desc if len(desc := item.summary) <= 500 else f"{desc[:500]}...", "color": DEFAULT_EMBED_COLOUR, "url": item.link, "author": { "name": "Carberra Tutorials" }, "image": { "url": thumbnails["maxres"]["url"] }, "footer": { "text": f"Runtime: {self.youtube.get_duration(duration, long=True)}" }, }), )
async def yt_info_command(self, ctx: commands.Context) -> None: url = f"https://www.googleapis.com/youtube/v3/channels?part=brandingSettings%2Csnippet%2Cstatistics&id={Config.YOUTUBE_CHANNEL_ID}&key={Config.YOUTUBE_API_KEY}" async with ctx.typing(): async with self.bot.session.get(url) as response: if not 200 <= response.status <= 299: return await ctx.send( f"The YouTube API returned {response.status} {response.reason}." ) data = (await response.json())["items"][0] published_at = chron.from_iso(data["snippet"]["publishedAt"][:-1]) await ctx.send(embed=discord.Embed.from_dict({ "title": f"Channel information for {data['brandingSettings']['channel']['title']}", "description": data["brandingSettings"]["channel"]["description"], "color": DEFAULT_EMBED_COLOUR, "thumbnail": { "url": data["snippet"]["thumbnails"]["high"]["url"] }, "image": { "url": data["brandingSettings"]["image"] ["bannerTvImageUrl"] }, "author": { "name": "Information" }, "footer": { "text": f"Requested by {ctx.author.display_name}", "icon_url": f"{ctx.author.avatar_url}", }, "fields": [ { "name": "Trailer", "value": f"Click [here](https://www.youtube.com/watch?v={data['brandingSettings']['channel']['unsubscribedTrailer']}) to watch.", "inline": False, }, { "name": "Country", "value": data["brandingSettings"]["channel"] ["country"], "inline": False, }, { "name": "Published on", "value": f"{chron.long_date_and_time(published_at)} UTC", "inline": False, }, { "name": "Existed for", "value": chron.long_delta(dt.datetime.utcnow() - published_at), "inline": False, }, ], }))
f"The YouTube API returned {response.status} {response.reason}." ) if not (data := (await response.json())["items"]): return await ctx.send("Invalid video ID.") data = data[0] if data["snippet"]["channelId"] != Config.YOUTUBE_CHANNEL_ID: return await ctx.send("That is not a Carberra video.") if (stream := "liveStreamingDetails" in data.keys()): published_at = chron.from_iso( data["liveStreamingDetails"]["actualStartTime"][:-1]) else: published_at = chron.from_iso( data["snippet"]["publishedAt"][:-1]) duration = self.get_duration(data["contentDetails"]["duration"]) await ctx.send(embed=discord.Embed.from_dict({ "title": "Video information", "description": f"{data['snippet']['title']}. Click [here](https://youtube.com/watch?v={data['id']}) to watch.", "color": DEFAULT_EMBED_COLOUR, "author": { "name": "Information" }, "footer": { "text": f"Requested by {ctx.author.display_name}", "icon_url": f"{ctx.author.avatar_url}",