Skip to content

Commit

Permalink
docs: add docstring
Browse files Browse the repository at this point in the history
  • Loading branch information
Mantouisyummy committed Mar 2, 2024
1 parent 97bf0f7 commit 80e5da5
Show file tree
Hide file tree
Showing 5 changed files with 227 additions and 16 deletions.
24 changes: 19 additions & 5 deletions tystream/async_api/twitch.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,26 +15,40 @@ def __init__(self, client_id: str, client_secret: str) -> None:
self.client_secret = client_secret
self.logger = logging.getLogger(__name__)

async def renew_token(self):
async def _renew_token(self):
oauth = TwitchOauth(self.client_id, self.client_secret)
return await oauth.get_access_token()

async def get_headers(self):
async def _get_headers(self):
headers = {
'Client-ID': self.client_id,
'Authorization': 'Bearer ' + await self.renew_token()
'Authorization': 'Bearer ' + await self._renew_token()
}
return headers

async def check_stream_live(self, streamer_name: str) -> TwitchStreamData:
headers = await self.get_headers()
"""
Check if stream is live.
Parameters
----------
streamer_name : :class:`str`
The streamer_name of the Twitch Live channel.
Returns
-------
:class:`TwitchStreamData`
An instance of the TwitchStreamData class containing information about the live stream.
If the stream is not live, an empty TwitchStreamData instance is returned.
"""
headers = await self._get_headers()
async with aiohttp.ClientSession() as session:
async with session.get('https://api.twitch.tv/helix/streams?user_login=' + streamer_name, headers=headers) as stream:
stream_data = await stream.json()

if not stream_data['data']:
self.logger.log(25, f"{streamer_name} is not live.")
return False
return TwitchStreamData()
else:
self.logger.log(25, f"{streamer_name} is live!")
return TwitchStreamData(**stream_data['data'][0])
48 changes: 47 additions & 1 deletion tystream/async_api/youtube.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,24 @@ def __init__(self, api_key: str) -> None:
self.logger = logging.getLogger(__name__)

async def _get_channel_id(self, username: str) -> str:
"""
Get the ID of a YouTube channel by its username.
Parameters
----------
username : :class:`str`
The username of the YouTube channel.
Returns
-------
:class:`str`
The ID of the YouTube channel.
Raises
------
:class:`NoResultException`
If no channel is found for the given username.
"""
oauth = YoutubeOauth(self.api_key)

if await oauth.validation_token():
Expand All @@ -31,6 +49,20 @@ async def _get_channel_id(self, username: str) -> str:
raise NoResultException("Not Found Any Channel.")

async def _get_live_id(self, channelid: str) -> str:
"""
Get the ID of the live stream for a YouTube channel.
Parameters
----------
channelid : :class:`str`
The ID of the YouTube channel.
Returns
-------
:class:`str`
The ID of the live stream if a live stream is found.
False if no live stream is found.
"""
url = f"https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={channelid}&eventType=live&type=video&key={self.api_key}"

async with aiohttp.ClientSession() as session:
Expand All @@ -42,6 +74,20 @@ async def _get_live_id(self, channelid: str) -> str:
return False

async def check_stream_live(self, username: str) -> YoutubeStreamData:
"""
Check if stream is live.
Parameters
----------
username : :class:`str`
The username of the YouTube channel.
Returns
-------
:class:`YoutubeStreamData`
An instance of the YoutubeStreamData class containing information about the live stream.
If the stream is not live, an empty YoutubeStreamData instance is returned.s
"""
channelId = await self._get_channel_id(username)
LiveId = await self._get_live_id(channelId)

Expand All @@ -58,7 +104,7 @@ async def check_stream_live(self, username: str) -> YoutubeStreamData:
return YoutubeStreamData(id=LiveId, **data)
else:
self.logger.log(20, f"{username} is not live.")
return False
return YoutubeStreamData()



99 changes: 95 additions & 4 deletions tystream/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,40 @@

@dataclass(frozen=True)
class Thumbnail:
"""
A map of thumbnail images associated with the Youtube video. The value is an object that contains other information about the thumbnail.
Attributes
----------
url: :class:`str`
The image's URL.
width: :class:`int`
The image's width.
height: :class:`int`
The image's height.
"""
url: str
width: int
height: int

@dataclass(frozen=True)
class Thumbnails:
"""
A map of thumbnail images associated with the Youtube video. The key is the name of the thumbnail image.
Attributes
----------
default: :class:`Thumbnail`
The default thumbnail image. The default thumbnail for a video – or a resource that refers to a video, such as a playlist item or search result – is 120px wide and 90px tall. The default thumbnail for a channel is 88px wide and 88px tall.
medium: :class:`Thumbnail`
A higher resolution version of the thumbnail image. For a video (or a resource that refers to a video), this image is 320px wide and 180px tall. For a channel, this image is 240px wide and 240px tall.
high: :class:`Thumbnail`
A high resolution version of the thumbnail image. For a video (or a resource that refers to a video), this image is 480px wide and 360px tall. For a channel, this image is 800px wide and 800px tall.
standard: :class:`Thumbnail`
An even higher resolution version of the thumbnail image than the high resolution image. This image is available for some videos and other resources that refer to videos, like playlist items or search results. This image is 640px wide and 480px tall.
maxres: :class:`Thumbnail`
The highest resolution version of the thumbnail image. This image size is available for some videos and other resources that refer to videos, like playlist items or search results. This image is 1280px wide and 720px tall.
"""
default: Thumbnail
medium: Thumbnail
high: Thumbnail
Expand All @@ -20,6 +48,45 @@ class Thumbnails:

@dataclass
class TwitchStreamData:
"""
Twitch Stream Resource Dataclass.
Attributes
----------
id: :class:`int`
An ID that identifies the stream.
user_id: :class:`int`
The ID of the user that’s broadcasting the stream.
user_login: :class:`str`
The user’s login name.
user_name: :class:`str`
The user’s display name.
game_id: :class:`int`
The ID of the category or game being played.
game_name: :class:`str`
The name of the category or game being played.
type: :class:`str`
The type of the stream.
title: :class:`str`
The stream’s title. Is an empty string if not set.
viewer_count: :class:`str`
The number of users watching the stream.
started_at: :class:`datetime`
The UTC date and time (in RFC3339 format) of when the broadcast began.
language: :class:`str`
The language that the stream uses.
thumbnail_url: :class:`str`
A URL to an image of a frame from the last 5 minutes of the stream.
is_mature: :class:`bool`
A Boolean value that indicates whether the stream is meant for mature audiences.
tag_ids: :class:`List`
Deprecated list of tag IDs for the stream.
This list is deprecated and may not be present.
tags: List[:class:`str`]
The tags applied to the stream.
url: :class:`str`
The stream’s url.
"""
id: int = field(default=None)
user_id: int = field(default=None)
user_login: str = field(default=None)
Expand All @@ -32,23 +99,47 @@ class TwitchStreamData:
started_at: datetime = field(default=None)
language: str = field(default=None)
thumbnail_url: str = field(default=None)
is_mature: bool = field(repr=False, default_factory=bool, default=None) # deprecated flag
tag_ids: List = field(repr=False, default_factory=list) # deprecated flag too
tags: List[str] = field(default_factory=list)
is_mature: bool = field(repr=False, default_factory=bool, default=None)
tag_ids: List = field(repr=False, default_factory=list, default=None) # deprecated flag too
tags: List[str] = field(default_factory=list, default=None)

def __post_init__(self):
self.url = "https://www.twitch.tv/" + self.user_login

@dataclass
class YoutubeStreamData:
"""
Youtube Stream Resource Dataclass.
Attributes
----------
id: :class:`str`
The ID that YouTube uses to uniquely identify the video.
publishedAt: :class:`datetime`
The date and time that the video was published.
channelId: :class:`str`
The ID that YouTube uses to uniquely identify the channel that the video was uploaded to.
title: :class:`str`
The video's title.
description: :class:`str`
The video's description.
thumbnails: :class:`Thumbnails`
A map of thumbnail images associated with the video.
channelTitle: :class:`str`
Channel title for the channel that the video belongs to.
tags: List[:class:`str`]
A list of keyword tags associated with the video. Tags may contain spaces.
url: :class:`str`
The video's url.
"""
id: str = field(default=None)
publishedAt: datetime = field(default=None)
channelId: str = field(default=None)
title: str = field(default=None)
description: str = field(default=None)
thumbnails: Thumbnails = field(default=None)
channelTitle: str = field(default=None)
tags: List[str] = field(default_factory=list)
tags: List[str] = field(default_factory=list, default=None)

def __post_init__(self):
self.url = "https://www.youtube.com/watch?v=" + self.id
24 changes: 19 additions & 5 deletions tystream/twitch.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,25 +16,39 @@ def __init__(self, client_id: str, client_secret: str, session: Optional[request
self.logger = logging.getLogger(__name__)
self.session = requests.Session() or session

def renew_token(self):
def _renew_token(self):
oauth = TwitchOauth(self.client_id, self.client_secret, self.session)
return oauth.get_access_token()

def get_headers(self):
def _get_headers(self):
headers = {
'Client-ID': self.client_id,
'Authorization': 'Bearer ' + self.renew_token()
'Authorization': 'Bearer ' + self._renew_token()
}
return headers

def check_stream_live(self, streamer_name: str) -> TwitchStreamData:
headers = self.get_headers()
"""
Check if stream is live.
Parameters
----------
streamer_name : :class:`str`
The streamer_name of the Twitch Live channel.
Returns
-------
:class:`TwitchStreamData`
An instance of the TwitchStreamData class containing information about the live stream.
If the stream is not live, an empty TwitchStreamData instance is returned.
"""
headers = self._get_headers()
stream = requests.get('https://api.twitch.tv/helix/streams?user_login=' + streamer_name, headers=headers)
stream_data = stream.json()

if not stream_data['data']:
self.logger.log(25, f"{streamer_name} is not live.")
return False
return TwitchStreamData()
else:
self.logger.log(25, f"{streamer_name} is live!")
return TwitchStreamData(**stream_data['data'][0])
48 changes: 47 additions & 1 deletion tystream/youtube.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,24 @@ def __init__(self, api_key: str, session: Optional[requests.Session] = None) ->
self.logger = logging.getLogger(__name__)

def _get_channel_id(self, username: str) -> str:
"""
Get the ID of a YouTube channel by its username.
Parameters
----------
username : :class:`str`
The username of the YouTube channel.
Returns
-------
:class:`str`
The ID of the YouTube channel.
Raises
------
:class:`NoResultException`
If no channel is found for the given username.
"""
oauth = YoutubeOauth(self.api_key)

if oauth.validation_token():
Expand All @@ -32,6 +50,20 @@ def _get_channel_id(self, username: str) -> str:
raise NoResultException("Not Found Any Channel.")

def _get_live_id(self, channelid: str) -> str:
"""
Get the ID of the live stream for a YouTube channel.
Parameters
----------
channelid : :class:`str`
The ID of the YouTube channel.
Returns
-------
:class:`str`
The ID of the live stream if a live stream is found.
False if no live stream is found.
"""
url = f"https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={channelid}&eventType=live&type=video&key={self.api_key}"

response = self.session.get(url)
Expand All @@ -43,6 +75,20 @@ def _get_live_id(self, channelid: str) -> str:
return False

def check_stream_live(self, username: str) -> YoutubeStreamData:
"""
Check if stream is live.
Parameters
----------
username : :class:`str`
The username of the YouTube channel.
Returns
-------
:class:`YoutubeStreamData`
An instance of the YoutubeStreamData class containing information about the live stream.
If the stream is not live, an empty YoutubeStreamData instance is returned.s
"""
channelId = self._get_channel_id(username)
LiveId = self._get_live_id(channelId)

Expand All @@ -58,7 +104,7 @@ def check_stream_live(self, username: str) -> YoutubeStreamData:
return YoutubeStreamData(id=LiveId, **data)
else:
self.logger.log(20, f"{username} is not live.")
return False
return YoutubeStreamData()



0 comments on commit 80e5da5

Please sign in to comment.