示例#1
0
def test_get_user_follows_raises_attribute_exception_if_no_param_is_set():
    responses.add(
        responses.GET,
        "{}users/follows".format(BASE_HELIX_URL),
        body=json.dumps(example_get_clips_response),
        status=200,
        content_type="application/json",
    )

    client = TwitchHelix("client id")
    with pytest.raises(TwitchAttributeException):
        client.get_user_follows()
    assert len(responses.calls) == 0
示例#2
0
def test_get_clips_raises_attribute_exception_for_invalid_clip_ids():
    responses.add(responses.GET,
                  '{}clips'.format(BASE_HELIX_URL),
                  body=json.dumps(example_get_clips_response),
                  status=200,
                  content_type='application/json')

    client = TwitchHelix('client id')
    kwargs = {'clip_ids': ['12345'] * 101}
    with pytest.raises(TwitchAttributeException):
        client.get_clips(**kwargs)

    assert len(responses.calls) == 0
示例#3
0
def test_get_top_games_raises_attribute_exception_for_invalid_params():
    responses.add(responses.GET,
                  '{}games/top'.format(BASE_HELIX_URL),
                  body=json.dumps(example_get_top_games_response),
                  status=200,
                  content_type='application/json')

    client = TwitchHelix('client id')

    kwargs = {'page_size': 101}
    with pytest.raises(TwitchAttributeException):
        client.get_top_games(**kwargs)

    assert len(responses.calls) == 0
示例#4
0
def test_get_top_games_returns_api_cursor():
    responses.add(
        responses.GET,
        "{}games/top".format(BASE_HELIX_URL),
        body=json.dumps(example_get_top_games_response),
        status=200,
        content_type="application/json",
    )

    client = TwitchHelix("client id")
    games = client.get_top_games()

    assert len(responses.calls) == 1
    assert isinstance(games, APICursor)
示例#5
0
def test_get_streams_metadata_returns_api_cursor():
    responses.add(
        responses.GET,
        "{}streams/metadata".format(BASE_HELIX_URL),
        body=json.dumps(example_get_streams_metadata_response),
        status=200,
        content_type="application/json",
    )

    client = TwitchHelix("client id")
    streams_metadata = client.get_streams_metadata()

    assert len(responses.calls) == 1
    assert isinstance(streams_metadata, APICursor)
示例#6
0
def test_get_streams_metadata_raises_attribute_exception_for_invalid_params(param, value):
    responses.add(responses.GET,
                  '{}streams/metadata'.format(BASE_HELIX_URL),
                  body=json.dumps(example_get_streams_metadata_response),
                  status=200,
                  content_type='application/json')

    client = TwitchHelix('client id')

    kwargs = {param: value}
    with pytest.raises(TwitchAttributeException):
        client.get_streams_metadata(**kwargs)

    assert len(responses.calls) == 0
示例#7
0
def test_get_user_follows_returns_api_cursor():
    responses.add(
        responses.GET,
        "{}users/follows".format(BASE_HELIX_URL),
        body=json.dumps(example_get_user_follows_response),
        status=200,
        content_type="application/json",
    )

    client = TwitchHelix("client id")
    user_follows = client.get_user_follows(to_id=23161357)

    assert len(responses.calls) == 1
    assert isinstance(user_follows, APICursor)
示例#8
0
def test_get_clips_raises_attribute_exception_if_no_param_is_set():
    responses.add(responses.GET,
                  '{}clips'.format(BASE_HELIX_URL),
                  body=json.dumps(example_get_clips_response),
                  status=200,
                  content_type='application/json')

    client = TwitchHelix('client id')
    with pytest.raises(TwitchAttributeException) as e:
        client.get_clips()

    assert ('At least one of the following parameters must be provided '
            '[broadcaster_id, clip_ids, game_id]') in str(e)
    assert len(responses.calls) == 0
示例#9
0
def test_get_videos_raises_attribute_exception_for_invalid_params(
        param, value):
    responses.add(responses.GET,
                  '{}videos'.format(BASE_HELIX_URL),
                  body=json.dumps(example_get_videos_cursor_response),
                  status=200,
                  content_type='application/json')

    client = TwitchHelix('client id')

    kwargs = {'game_id': '123456', param: value}
    with pytest.raises(TwitchAttributeException):
        client.get_videos(**kwargs)

    assert len(responses.calls) == 0
示例#10
0
def test_get_videos_raises_attribute_exception_for_invalid_video_ids():
    responses.add(
        responses.GET,
        "{}videos".format(BASE_HELIX_URL),
        body=json.dumps(example_get_videos_response),
        status=200,
        content_type="application/json",
    )

    client = TwitchHelix("client id")
    kwargs = {"video_ids": ["12345"] * 101}
    with pytest.raises(TwitchAttributeException):
        client.get_videos(**kwargs)

    assert len(responses.calls) == 0
示例#11
0
def test_get_videos_passes_correct_params_when_video_ids_are_set():
    responses.add(responses.GET,
                  '{}videos'.format(BASE_HELIX_URL),
                  body=json.dumps(example_get_videos_response),
                  status=200,
                  content_type='application/json')

    client = TwitchHelix('client id')
    videos = client.get_videos(video_ids=['234482848'])

    assert len(responses.calls) == 1
    assert isinstance(videos, list)
    video = videos[0]
    assert isinstance(video, Video)
    assert responses.calls[0].request.url == 'https://api.twitch.tv/helix/videos?id=234482848'
示例#12
0
class Twitch:
    """Twitch enables interaction with the twitch.tv API to get info on
    Heroes of the Storm streams."""

    def __init__(self):
        self._client = TwitchHelix(
            client_id=os.environ["TWITCH_CLIENT_ID"],
            client_secret=os.environ["TWITCH_CLIENT_SECRET"],
        )
        self._client.get_oauth()

    # TODO: doesn't use pagination, limited to 100 streams by twitch
    def _get_streams(self):
        games = self._client.get_games(names=["Heroes of the Storm"])
        game_id = games[0]["id"]
        return self._client.get_streams(game_ids=[game_id], page_size=100)

    def _format_stream(self, stream):
        """Takes a stream dict as found in API responses and formats it
        for the sidebar."""

        display_name = stream["user_name"].strip()
        status = stream["title"].strip()
        viewers = str(stream["viewer_count"])
        url = "https://www.twitch.tv/{}".format(stream["user_login"])

        return "* [{0} ~~{1}~~ ^{2}]({3})\n\n".format(
                display_name,
                status,
                viewers,
                url)

    # TODO: omg get this outta here
    def sidebar_text(self):
        streams = self._get_streams()

        # Choose top five streams
        top_streams_formatted = [self._format_stream(s) for s in streams[:5]]
        top_streams_text = "".join(top_streams_formatted)

        # Choose five randomly chosen streams
        random_streams = random.sample(streams[5:], 5)
        random_streams_formatted = [self._format_stream(s) for s in random_streams]
        random_streams_text = "".join(random_streams_formatted)

        return "Top\n\n{0}\nDiscover\n\n{1}".format(
                top_streams_text,
                random_streams_text)
示例#13
0
def test_get_games_returns_list_of_game_objects():
    responses.add(responses.GET,
                  '{}games'.format(BASE_HELIX_URL),
                  body=json.dumps(example_get_games_response),
                  status=200,
                  content_type='application/json')

    client = TwitchHelix('client id')
    games = client.get_games()

    assert len(responses.calls) == 1
    assert isinstance(games, list)
    game = games[0]
    assert isinstance(game, Game)
    assert game.id == example_get_games_response['data'][0]['id']
    assert game.name == example_get_games_response['data'][0]['name']
示例#14
0
def get_uptime():
    """
    Returns a string of the current uptime

    Returns:
        str: Contains the current amount of uptime for the channel
    """
    # Set up twitch API call and get stream info
    client = TwitchHelix(client_id=settings.get_client_id(),
                         client_secret=settings.get_client_secret())
    client.get_oauth()
    stream = client.get_streams(user_logins=settings.get_channel())._queue[0]
    # Get stream start time (API sends UTC time) and calculate uptime
    start_time = stream["started_at"]
    uptime = datetime.utcnow() - start_time
    return str(uptime).split(".")[0]
示例#15
0
def test_get_games_raises_attribute_exception_for_invalid_params(param, value):
    responses.add(
        responses.GET,
        "{}games".format(BASE_HELIX_URL),
        body=json.dumps(example_get_games_response),
        status=200,
        content_type="application/json",
    )

    client = TwitchHelix("client id")

    kwargs = {param: value}
    with pytest.raises(TwitchAttributeException):
        client.get_games(**kwargs)

    assert len(responses.calls) == 0
示例#16
0
def test_get_user_follows_raises_attribute_exception_for_invalid_params():
    responses.add(
        responses.GET,
        "{}users/follows".format(BASE_HELIX_URL),
        body=json.dumps(example_get_top_games_response),
        status=200,
        content_type="application/json",
    )

    client = TwitchHelix("client id")

    kwargs = {"from_id": 23161357, "page_size": 101}
    with pytest.raises(TwitchAttributeException):
        client.get_user_follows(**kwargs)

    assert len(responses.calls) == 0
示例#17
0
def test_get_clips_returns_list_of_clip_objects_when_clip_ids_are_set():
    responses.add(responses.GET,
                  '{}clips'.format(BASE_HELIX_URL),
                  body=json.dumps(example_get_clips_response),
                  status=200,
                  content_type='application/json')

    client = TwitchHelix('client id')
    clips = client.get_clips(clip_ids=['AwkwardHelplessSalamanderSwiftRage'])

    assert len(responses.calls) == 1
    assert isinstance(clips, list)
    clip = clips[0]
    assert isinstance(clip, Clip)
    assert clip.id == example_get_clips_response['data'][0]['id']
    assert clip.broadcaster_id == example_get_clips_response['data'][0]['broadcaster_id']
    assert clip.created_at == datetime(2017, 11, 30, 22, 34, 18)
示例#18
0
def test_get_clips_passes_correct_params_when_clip_ids_are_set():
    responses.add(responses.GET,
                  '{}clips'.format(BASE_HELIX_URL),
                  body=json.dumps(example_get_clips_response),
                  status=200,
                  content_type='application/json')

    client = TwitchHelix('client id')
    clips = client.get_clips(clip_ids=['AwkwardHelplessSalamanderSwiftRage'])

    assert len(responses.calls) == 1
    assert isinstance(clips, list)
    clip = clips[0]
    assert isinstance(clip, Clip)
    assert responses.calls[0].request.url == (
        'https://api.twitch.tv/helix/clips?id=AwkwardHelplessSalamanderSwiftRage'
    )
示例#19
0
def test_get_videos_returns_list_of_video_objects_when_video_ids_are_set():
    responses.add(responses.GET,
                  '{}videos'.format(BASE_HELIX_URL),
                  body=json.dumps(example_get_videos_response),
                  status=200,
                  content_type='application/json')

    client = TwitchHelix('client id')
    videos = client.get_videos(video_ids=['234482848'])

    assert len(responses.calls) == 1
    assert isinstance(videos, list)
    video = videos[0]
    assert isinstance(video, Video)
    assert video.id == example_get_videos_response['data'][0]['id']
    assert video.title == example_get_videos_response['data'][0]['title']
    assert video.created_at == datetime(2018, 3, 2, 20, 53, 41)
示例#20
0
def test_get_games_returns_list_of_game_objects():
    responses.add(
        responses.GET,
        "{}games".format(BASE_HELIX_URL),
        body=json.dumps(example_get_games_response),
        status=200,
        content_type="application/json",
    )

    client = TwitchHelix("client id")
    games = client.get_games()

    assert len(responses.calls) == 1
    assert isinstance(games, list)
    game = games[0]
    assert isinstance(game, Game)
    assert game.id == example_get_games_response["data"][0]["id"]
    assert game.name == example_get_games_response["data"][0]["name"]
示例#21
0
def test_get_top_games_next_returns_game_object():
    responses.add(responses.GET,
                  '{}games/top'.format(BASE_HELIX_URL),
                  body=json.dumps(example_get_top_games_response),
                  status=200,
                  content_type='application/json')

    client = TwitchHelix('client id')
    games = client.get_top_games()

    game = games.next()

    assert len(responses.calls) == 1
    assert isinstance(games, APICursor)
    assert games._cursor == example_get_top_games_response['pagination']['cursor']

    assert isinstance(game, Game)
    assert game.id == example_get_top_games_response['data'][0]['id']
    assert game.name == example_get_top_games_response['data'][0]['name']
示例#22
0
def test_get_streams_metadata_next_returns_stream_metadata_object():
    responses.add(responses.GET,
                  '{}streams/metadata'.format(BASE_HELIX_URL),
                  body=json.dumps(example_get_streams_metadata_response),
                  status=200,
                  content_type='application/json')

    client = TwitchHelix('client id')
    streams_metadata = client.get_streams_metadata()

    metadata = streams_metadata.next()

    assert len(responses.calls) == 1
    assert isinstance(streams_metadata, APICursor)
    assert streams_metadata._cursor == example_get_streams_metadata_response['pagination']['cursor']

    assert isinstance(metadata, StreamMetadata)
    assert metadata.user_id == example_get_streams_metadata_response['data'][0]['user_id']
    assert metadata.game_id == example_get_streams_metadata_response['data'][0]['game_id']
示例#23
0
def test_get_streams_metadata_passes_all_params_to_request():
    responses.add(
        responses.GET,
        "{}streams/metadata".format(BASE_HELIX_URL),
        body=json.dumps(example_get_streams_metadata_response),
        status=200,
        content_type="application/json",
    )

    client = TwitchHelix("client id")
    streams_metadata = client.get_streams_metadata(
        after="eyJiIjpudWxsLCJhIjp7Ik9mZnNldCI6MjB9fQ==",
        before="eyJiIjp7Ik9mZnNldCI6MH0sImEiOnsiT2Zmc2V0Ijo0MH19==",
        community_ids=[
            "848d95be-90b3-44a5-b143-6e373754c382",
            "fd0eab99-832a-4d7e-8cc0-04d73deb2e54",
        ],
        page_size=100,
        game_ids=["417752", "29307"],
        languages=["en"],
        user_ids=["23161357"],
        user_logins=["lirik"],
    )

    metadata = streams_metadata.next()

    assert len(responses.calls) == 1
    assert isinstance(streams_metadata, APICursor)
    assert isinstance(metadata, StreamMetadata)

    url = responses.calls[0].request.url
    assert url.startswith("https://api.twitch.tv/helix/streams/metadata?")
    assert "after=eyJiIjpudWxsLCJhIjp7Ik9mZnNldCI6MjB9fQ%3D%3D" in url
    assert "before=eyJiIjp7Ik9mZnNldCI6MH0sImEiOnsiT2Zmc2V0Ijo0MH19%3D%3D" in url
    assert "community_id=848d95be-90b3-44a5-b143-6e373754c382" in url
    assert "community_id=fd0eab99-832a-4d7e-8cc0-04d73deb2e54" in url
    assert "first=100" in url
    assert "game_id=417752" in url
    assert "game_id=29307" in url
    assert "language=en" in url
    assert "user_id=23161357" in url
    assert "user_login=lirik" in url
示例#24
0
def canales_de_cliente(username):
    helix = TwitchHelix(client_id='vnsbdjciw4fcif1k57w1c07a65wk03',
                        oauth_token='oauth:17qyf4koyvfdqjs4me7zr451lccmtn')
    HEADS = {
        "Accept": "application/vnd.twitchtv.v5+json",
        "Client-ID": "vnsbdjciw4fcif1k57w1c07a65wk03"
        #"Authorization" : "OAuth 17qyf4koyvfdqjs4me7zr451lccmtn"
    }
    nombre = username
    URL = "https://api.twitch.tv/kraken/users?login={}".format(nombre)
    r = requests.get(url=URL, headers=HEADS)
    temp = r.json()
    id = temp["users"][0]["_id"]
    namefollows = []
    t = helix.get_user_follows(from_id=id)
    namefollows = []
    for i in t:
        namefollows.append(i["to_name"])
    #print(namefollows)
    return namefollows
示例#25
0
def test_get_videos_next_returns_video_object(param, value):
    responses.add(responses.GET,
                  '{}videos'.format(BASE_HELIX_URL),
                  body=json.dumps(example_get_videos_cursor_response),
                  status=200,
                  content_type='application/json')

    client = TwitchHelix('client id')

    kwargs = {param: value}
    videos = client.get_videos(**kwargs)
    video = videos.next()

    assert len(responses.calls) == 1
    assert isinstance(videos, APICursor)
    assert videos._cursor == example_get_videos_cursor_response['pagination']['cursor']

    assert isinstance(video, Video)
    assert video.id == example_get_videos_cursor_response['data'][0]['id']
    assert video.title == example_get_videos_response['data'][0]['title']
    assert video.created_at == datetime(2018, 3, 2, 20, 53, 41)
示例#26
0
def test_get_streams_next_returns_stream_object():
    responses.add(responses.GET,
                  '{}streams'.format(BASE_HELIX_URL),
                  body=json.dumps(example_get_streams_response),
                  status=200,
                  content_type='application/json')

    client = TwitchHelix('client id')
    streams = client.get_streams()

    stream = streams.next()

    assert len(responses.calls) == 1
    assert isinstance(streams, APICursor)
    assert streams._cursor == example_get_streams_response['pagination']['cursor']

    assert isinstance(stream, Stream)
    assert stream.id == example_get_streams_response['data'][0]['id']
    assert stream.game_id == example_get_streams_response['data'][0]['game_id']
    assert stream.title == example_get_streams_response['data'][0]['title']
    assert stream.started_at == datetime(2017, 8, 14, 16, 8, 32)
示例#27
0
def test_get_clips_next_returns_clip_object(param, value):
    responses.add(responses.GET,
                  '{}clips'.format(BASE_HELIX_URL),
                  body=json.dumps(example_get_clips_cursor_response),
                  status=200,
                  content_type='application/json')

    client = TwitchHelix('client id')

    kwargs = {param: value}
    clips = client.get_clips(**kwargs)
    clip = clips.next()

    assert len(responses.calls) == 1
    assert isinstance(clips, APICursor)
    assert clips._cursor == example_get_clips_cursor_response['pagination']['cursor']

    assert isinstance(clip, Clip)
    assert clip.id == example_get_clips_cursor_response['data'][0]['id']
    assert clip.broadcaster_id == example_get_clips_cursor_response['data'][0]['broadcaster_id']
    assert clip.created_at == datetime(2017, 11, 30, 22, 34, 17)
示例#28
0
def test_get_user_follows_next_returns_follow_object():
    responses.add(responses.GET,
                  '{}users/follows'.format(BASE_HELIX_URL),
                  body=json.dumps(example_get_user_follows_response),
                  status=200,
                  content_type='application/json')

    client = TwitchHelix('client id')
    user_follows = client.get_user_follows(to_id=23161357)

    follow = user_follows.next()

    assert len(responses.calls) == 1
    assert isinstance(user_follows, APICursor)
    assert user_follows.cursor == example_get_user_follows_response['pagination']['cursor']
    assert user_follows.total == example_get_user_follows_response['total']

    assert isinstance(follow, Follow)
    assert follow.from_id == example_get_user_follows_response['data'][0]['from_id']
    assert follow.to_id == example_get_user_follows_response['data'][0]['to_id']
    assert follow.followed_at == datetime(2017, 8, 22, 22, 55, 24)
示例#29
0
def test_get_top_games_next_returns_game_object():
    responses.add(
        responses.GET,
        "{}games/top".format(BASE_HELIX_URL),
        body=json.dumps(example_get_top_games_response),
        status=200,
        content_type="application/json",
    )

    client = TwitchHelix("client id")
    games = client.get_top_games()

    game = games.next()

    assert len(responses.calls) == 1
    assert isinstance(games, APICursor)
    assert games._cursor == example_get_top_games_response["pagination"]["cursor"]

    assert isinstance(game, Game)
    assert game.id == example_get_top_games_response["data"][0]["id"]
    assert game.name == example_get_top_games_response["data"][0]["name"]
示例#30
0
def test_get_streams_metadata_passes_all_params_to_request():
    responses.add(responses.GET,
                  '{}streams/metadata'.format(BASE_HELIX_URL),
                  body=json.dumps(example_get_streams_metadata_response),
                  status=200,
                  content_type='application/json')

    client = TwitchHelix('client id')
    streams_metadata = client.get_streams_metadata(
        after='eyJiIjpudWxsLCJhIjp7Ik9mZnNldCI6MjB9fQ==',
        before='eyJiIjp7Ik9mZnNldCI6MH0sImEiOnsiT2Zmc2V0Ijo0MH19==',
        community_ids=[
            '848d95be-90b3-44a5-b143-6e373754c382',
            'fd0eab99-832a-4d7e-8cc0-04d73deb2e54'
        ],
        page_size=100,
        game_ids=['417752', '29307'],
        languages=['en'],
        user_ids=['23161357'],
        user_logins=['lirik']
    )

    metadata = streams_metadata.next()

    assert len(responses.calls) == 1
    assert isinstance(streams_metadata, APICursor)
    assert isinstance(metadata, StreamMetadata)

    url = responses.calls[0].request.url
    assert url.startswith('https://api.twitch.tv/helix/streams/metadata?')
    assert 'after=eyJiIjpudWxsLCJhIjp7Ik9mZnNldCI6MjB9fQ%3D%3D' in url
    assert 'before=eyJiIjp7Ik9mZnNldCI6MH0sImEiOnsiT2Zmc2V0Ijo0MH19%3D%3D' in url
    assert 'community_id=848d95be-90b3-44a5-b143-6e373754c382' in url
    assert 'community_id=fd0eab99-832a-4d7e-8cc0-04d73deb2e54' in url
    assert 'first=100' in url
    assert 'game_id=417752' in url
    assert 'game_id=29307' in url
    assert 'language=en' in url
    assert 'user_id=23161357' in url
    assert 'user_login=lirik' in url