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
def getGameName(ctx, c_id, c_secret, channel): """ Returns a string containing the current game being played by the streamer """ client = TwitchHelix(client_id=c_id, client_secret=c_secret) client.get_oauth() game_name = '' try: stream = client.get_streams(user_logins=channel)._queue[0] game_id = stream["game_id"] game_info = client.get_games(game_ids=game_id) game_name = game_info[0]["name"] except Exception as E: print('Game info not available') return game_name
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)
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']
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"]
def test_get_games_passes_all_params_to_request(): 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( game_ids=['23161357', '12345678'], names=["PLAYERUNKNOWN'S BATTLEGROUNDS", 'World of Warcraft'], ) assert len(responses.calls) == 1 assert isinstance(games, list) assert isinstance(games[0], Game) url = responses.calls[0].request.url assert url.startswith('https://api.twitch.tv/helix/games?') assert 'id=23161357' in url assert 'id=12345678' in url assert 'name=PLAYERUNKNOWN%27S+BATTLEGROUNDS' in url assert 'name=World+of+Warcraft' in url
def test_get_games_passes_all_params_to_request(): 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( game_ids=["23161357", "12345678"], names=["PLAYERUNKNOWN'S BATTLEGROUNDS", "World of Warcraft"], ) assert len(responses.calls) == 1 assert isinstance(games, list) assert isinstance(games[0], Game) url = responses.calls[0].request.url assert url.startswith("https://api.twitch.tv/helix/games?") assert "id=23161357" in url assert "id=12345678" in url assert "name=PLAYERUNKNOWN%27S+BATTLEGROUNDS" in url assert "name=World+of+Warcraft" in url
for stream in islice(streams_iterator, 0, 5): print(stream) client = TwitchClient(client_id='x2nlpgpmb4nn6m1o1vby49mif3qeqy') users = client.users.translate_usernames_to_ids(['vektv', 'jukes','officialf0xey']) for user in users: print('{}: {}'.format(user.name, user.id)) client = TwitchHelix(client_id='x2nlpgpmb4nn6m1o1vby49mif3qeqy') streams_iterator = client.get_streams_metadata(page_size=100,user_ids=[77208443]) for stream in islice(streams_iterator, 0, 5): print(stream) client = TwitchHelix(client_id='x2nlpgpmb4nn6m1o1vby49mif3qeqy') games_iterator = client.get_top_games(page_size=100) for game in islice(games_iterator, 0, 10): print(game) print("\n") client = TwitchHelix(client_id='x2nlpgpmb4nn6m1o1vby49mif3qeqy') #games_iterator = client.get_games(game_ids=['509658'])#names=['Counter-Strike: Global Offensive']) games_iterator = client.get_games(names=["Counter-Strike: Global Offensive","FIFA 19","NHL 19"]) for game in islice(games_iterator, 0, 10): print(game) from twitch import TwitchClient client = TwitchClient('x2nlpgpmb4nn6m1o1vby49mif3qeqy') teams = client.teams.get_all() for t in islice(teams, 0, 10): print(t)
TWITCH_TOKEN = config[CONFIG_SECTION]['twitch_token'] WEBHOOK = config[CONFIG_SECTION]['webhook'] term_string = config[CONFIG_SECTION]['search_terms'] search_terms = [] for term in term_string.split(","): search_terms.append(term.lower()) if not os.path.exists(STATE_FILENAME): streams = {} else: with open(STATE_FILENAME, 'rb') as handle: streams = pickle.load(handle) helix = TwitchHelix(TWITCH_TOKEN) game = helix.get_games(names=[GAME])[0] log.info(f"Found game {game.id}") while True: try: log.debug("Starting loop") count = 0 for stream in helix.get_streams(page_size=100, game_ids=game.id): count += 1 if stream.user_id in streams: continue found = False title = stream.title.lower() for term in search_terms: if term in title:
def games(): client = TwitchHelix() games = client.get_games(game_ids=[493057], names=['World of Warcraft']) print(games)
from twitch import TwitchHelix import csv client = TwitchHelix(client_id='w2fwifqxprja6cvm1i251tyqbgd1ot') streams_iterator = client.get_streams(page_size=10) with open('filename.csv', 'w', newline='',encoding="utf-8") as csvfile: fieldnames = ['user_name','language', 'game_id', 'game_name', 'start_time(UTC Time)', 'view_count'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for stream in streams_iterator: game_top = client.get_games(game_ids=[stream['game_id']]) for name in game_top: writer.writerow({'user_name':stream["user_name"],'language': stream["language"], 'game_id':stream["game_id"], 'game_name': name['name'], 'start_time(UTC Time)': stream["started_at"], 'view_count': stream["viewer_count"]})