Пример #1
0
def get_streams():
    streams = {}
    ClientID = 'g3v9rj6v0t5cuthn57g3s9sd1sngmz'
    width = 640
    height = 360
    helix = twitch.Helix(ClientID)

    for user in helix.users(usernames):
        try:
            user.stream.type
        except twitch.helix.resources.streams.StreamNotFound:
            print('None')
            continue
        print(user.stream.data)

        if res['data'] != []:
            stream_id = res['data'][0]['id']
            streams[stream_id] = {}
            streams[stream_id]['username'] = user
            streams[stream_id]['url'] = 'https://www.twitch.tv/' + user
            streams[stream_id]['game'] = res['data'][0]['user_name']
            streams[stream_id]['status'] = res['data'][0]['title']
            streams[stream_id]['preview_l'] = res['data'][0]['thumbnail_url']
            streams[stream_id]['preview_l'] = streams[stream_id][
                'preview_l'].replace('{width}', '640')
            streams[stream_id]['preview_l'] = streams[stream_id][
                'preview_l'].replace('{height}', '360')
            print(streams[stream_id]['preview_l'.format(width, height)])
Пример #2
0
    def test_video(self):
        responses.add(
            responses.GET,
            'https://api.twitch.tv/helix/videos?id=471855782',
            match_querystring=True,
            json={
                'data': [{
                    'id': '471855782',
                    'user_id': '26301881',
                    'user_name': 'sodapoppin',
                    'title': '2 days til Classic, passing the time til then. ',
                    'description': '',
                    'created_at': '2019-08-24T21:34:03Z',
                    'published_at': '2019-08-24T21:34:03Z',
                    'url': 'https://www.twitch.tv/videos/471855782',
                    'thumbnail_url': '',
                    'viewable': 'public',
                    'view_count': 329,
                    'language': 'en',
                    'type': 'archive',
                    'duration': '2h14m55s'
                }],
                'pagination': {
                    'cursor': 'eyJiIjpudWxsLCJhIjp7Ik9mZnNldCI6MX19'
                }
            })

        helix = twitch.Helix('client-id', use_cache=True)

        # Get display name to display name
        self.assertEqual(helix.video('471855782').user_name, 'sodapoppin')
Пример #3
0
    def __init__(self, video_id: str = None):

        # Check if data should be loaded from an input file or form the Twitch API
        if app.cli.arguments.input:
            if Path(app.cli.arguments.input).is_file():
                with open(app.cli.arguments.input, 'r',
                          encoding='utf-8') as file:
                    json_data = json.load(file)

                    # Check if JSON format is valid
                    if 'video' not in json_data or 'comments' not in json_data:
                        print('Error: Invalid JSON file.')
                        exit(1)

                    # Set metadata and comments
                    self.metadata = json_data['video']
                    self.comments = Video.comment_generator(
                        json_data['comments'])

                    if app.cli.arguments.verbose:
                        print('Loaded json data form input file')
            else:
                print('Error: Unable to find {}'.format(
                    app.cli.arguments.input))
                exit(1)

        else:
            # Download from Twitch API
            helix = twitch.Helix(client_id=app.config.settings['client_id'],
                                 use_cache=True)
            video: helix.Video = helix.video(video_id)
            self.metadata: dict = api.video(video_id)
            self.comments = self.comment_generator_from_api(video)
Пример #4
0
    def test_user(self):
        helix = twitch.Helix(client_id='id',
                             bearer_token='token',
                             use_cache=True)

        # Get display name to display name
        self.assertEqual(helix.user('zarlach').display_name, 'Zarlach')
Пример #5
0
 def refreshToken(self):
     cfg = configparser.ConfigParser()
     cfg.read("config/config.ini")
     settings = cfg["settings"]
     client_id = settings["client_id"]
     secret = settings["secret"]
     if not client_id or not secret:
         print("Unable to find credentials")
     else:
         try:
             authorizeRequest = requests.post(self._oauthURL + "token",
                                              params={
                                                  "client_id":
                                                  client_id,
                                                  "client_secret":
                                                  secret,
                                                  "grant_type":
                                                  "client_credentials"
                                              },
                                              timeout=2)
             if (authorizeRequest.status_code == requests.codes.ok):
                 response = json.loads(authorizeRequest.text)
                 self._accessToken = response["access_token"]
                 self._helix = twitch.Helix(client_id, secret, True, None,
                                            True, self._accessToken)
             else:
                 print("Unable to complete post request for token")
         except requests.exceptions.Timeout:
             print("Request for refresh token timed out")
def create_client(twitch_id=os.environ['twitch_id'],
                  twitch_secret=os.environ['twitch_secret']):
    client = twitch.Helix(client_id=twitch_id,
                          client_secret=twitch_secret,
                          use_cache=True,
                          cache_duration=timedelta(minutes=30))
    return client
Пример #7
0
    def test_custom_user_cache(self):
        helix = twitch.Helix('client-id', use_cache=True)
        helix.users(['zarlach', 'sodapoppin'])

        # Users have custom caching, such that url should not be cached
        self.assertFalse(
            helix.api.SHARED_CACHE.has(
                'GET:https://api.twitch.tv/helix/users?login=zarlach'))

        # Cache entries by login name and id number
        self.assertTrue(
            helix.api.SHARED_CACHE.has('helix.users.login.zarlach'))
        self.assertTrue(helix.api.SHARED_CACHE.has('helix.users.id.24250859'))

        self.assertTrue(
            helix.api.SHARED_CACHE.has('helix.users.login.sodapoppin'))
        self.assertTrue(helix.api.SHARED_CACHE.has('helix.users.id.26301881'))

        # Flush cache to remove
        helix.api.flush_cache()

        # Check cache flush
        self.assertFalse(
            helix.api.SHARED_CACHE.has('helix.users.login.zarlach'))
        self.assertFalse(helix.api.SHARED_CACHE.has('helix.users.id.24250859'))

        self.assertFalse(
            helix.api.SHARED_CACHE.has('helix.users.login.sodapoppin'))
        self.assertFalse(helix.api.SHARED_CACHE.has('helix.users.id.26301881'))
Пример #8
0
    def run(self):
        try:
            helix = twitch.Helix(self.twitch_id)
            vod = helix.video(self.vod_num)

            if vod is None:
                self.status = 'error'
                return

            start = datetime.datetime.strptime(vod.created_at[:19],
                                               '%Y-%m-%dT%H:%M:%S')

            duration = self.str2sec(vod.duration)
            file_name = './static/download/' + self.vod_num
            with open(file_name + '.tmp', 'w', encoding='utf8') as f:
                f.write('comment_time' + '\n')

                for comment in vod.comments:
                    comment_time = datetime.datetime.strptime(
                        comment.updated_at[:19], '%Y-%m-%dT%H:%M:%S')
                    comment_sec = int((comment_time - start).total_seconds())
                    f.write(str(comment_sec) + '\n')
                    with lock:
                        self.progress = round(comment_sec / duration * 100, 2)

            os.rename(file_name + '.tmp', file_name + '.csv')
            self.status = 'complete'
            return

        # 기타 error가 발생한 경우
        except Exception as ex:
            print('Downloader ERROR')
            print(ex)
            self.status = 'error'
            return
Пример #9
0
def main():
    helix = twitch.Helix('', use_cache=True)
    global lastmsg, msg
    lastmsg = datetime.datetime.now()
    msg = queue.Queue(100)
    sess = gpt2.start_tf_sess()
    gpt2.load_gpt2(sess, run_name=run_name)

    while not msg.full():
        newmsg = genmsg(sess)
        print(newmsg)
        msg.put(newmsg)

    for channel in textchannels:
        chat = twitch.Chat(channel="#" + channel,
                           nickname='WoodenLongboard',
                           oauth="",
                           helix=helix)
        chats[channel] = chat
        chats[channel].subscribe(handle_message)

    print("Finished init")

    while True:
        if not msg.full():
            msg.put(genmsg(sess))
Пример #10
0
async def task_check_live_status(bot):
    """
  Checks if the best streamers are live on Twitch every few seconds
  This will be executed every 30 seconds
  --
  bot: interactions.Client
  """
    print("checking live status")

    if "twitch_channel" in db.keys():
        helix = twitch.Helix(Constants.TWITCH_ID, Constants.TWITCH_SECRET)
        for streamer_name in Constants.STREAMERS:
            stream = get_live_status(streamer_name, helix=helix)
            if stream is not None:
                if streamer_name not in db["is_currently_live"].keys(
                ) or streamer_name not in db[
                        "previous_live_message_time"].keys():
                    db["is_currently_live"][streamer_name] = False
                    db["previous_live_message_time"][streamer_name] = 0

                if not db["is_currently_live"][streamer_name]:
                    db["is_currently_live"][streamer_name] = True
                    await send_new_live_message(bot, stream, streamer_name)

            else:
                db["is_currently_live"][streamer_name] = False
Пример #11
0
    def test_video(self):
        helix = twitch.Helix(client_id='id',
                             bearer_token='token',
                             use_cache=True)

        # Get display name to display name
        self.assertEqual(helix.video('471855782').user_name, 'sodapoppin')
Пример #12
0
    def test_users(self):
        # Should returned cached data from above
        helix = twitch.Helix('client-id', use_cache=True)

        for user, display_name in zip(helix.users([24250859, 'sodapoppin']),
                                      ['Zarlach', 'sodapoppin']):
            self.assertEqual(user.display_name, display_name)
Пример #13
0
    def test_cache(self):
        helix = twitch.Helix('client-id', use_cache=True)

        helix.api.SHARED_CACHE.set('key', {'data': 'value'})

        # Entry in shared cache
        self.assertTrue(helix.api.SHARED_CACHE.has('key'))

        # Not expired
        self.assertFalse(helix.api.SHARED_CACHE.expired('key'))

        # Expiration
        helix.api.SHARED_CACHE.set('key-with-expiration', {'data': 'value'},
                                   duration=timedelta(seconds=-1))

        # Key is expired
        self.assertTrue(helix.api.SHARED_CACHE.expired('key-with-expiration'))

        # Unable to retrieve expired value
        self.assertFalse(helix.api.SHARED_CACHE.get('key-with-expiration'))

        # Has key, but expired
        self.assertTrue(helix.api.SHARED_CACHE.has('key-with-expiration'))

        # Clean expired keys
        helix.api.SHARED_CACHE.clean()
        self.assertFalse(helix.api.SHARED_CACHE.has('key-with-expiration'))

        # Flush cache
        helix.api.SHARED_CACHE.flush()
        self.assertFalse(helix.api.SHARED_CACHE.has('key'))
Пример #14
0
    def test_user(self):
        responses.add(
            responses.GET,
            'https://api.twitch.tv/helix/users?login=zarlach',
            match_querystring=True,
            json={
                'data': [{
                    'id': '24250859',
                    'login': '******',
                    'display_name': 'Zarlach',
                    'type': '',
                    'broadcaster_type': '',
                    'description': '',
                    'profile_image_url':
                    'https://static-cdn.jtvnw.net/jtv_user_pictures/zarlach-profile_image-1cb98e7eadb5918a-300x300.png',
                    'offline_image_url':
                    'https://static-cdn.jtvnw.net/jtv_user_pictures/zarlach-channel_offline_image-f2d036ac9582d793-1920x1080.png',
                    'view_count': 1664
                }]
            })

        helix = twitch.Helix('client-id', use_cache=True)

        # Get display name to display name
        self.assertEqual(helix.user('zarlach').display_name, 'Zarlach')
Пример #15
0
 def __init__(self, client_id=None):
     self._client_id = client_id or settings.TWITCH_CLIENT_ID
     self.client = twitch.Helix(self._client_id,
                                use_cache=True,
                                cache_duration=timedelta(minutes=30))
     self.channel = self.client.user("overwatchleague")
     self.videos = self.filter_by_full_matches(
         self.get_channel_videos(type="highlight"))
Пример #16
0
    def test_first_videos(self):
        # Should returned cached data from above
        helix = twitch.Helix('client-id', use_cache=True)

        for video, user_name in zip(
                helix.user('sodapoppin').videos(first=2),
            ['sodapoppin', 'sodapoppin']):
            self.assertEqual(video.user_name, user_name)
Пример #17
0
 def __init__(self, channel):
     self.chat = twitch.Chat(channel=channel,
                             nickname='bot',
                             oauth='oauth:la6kj4pn3vzfdvvkfrg8y5eqvbuxjk',
                             helix=twitch.Helix(
                                 client_id='hqiwd4o8a3mf6l7t7l0xge8qt7ksob',
                                 use_cache=True))
     self.chat.subscribe(handle_message)
Пример #18
0
def twitchLive():
    import twitch
    helix = twitch.Helix(client_id=Config.TWITCH_CLIENT_ID,
                         use_cache=True,
                         bearer_token=Config.TWITCH_BEARER_TOKEN)
    twitch.Chat(channel=Config.TWITCH_CHANNEL,
                nickname=Config.TWITCH_NICKNAME,
                oauth=Config.TWITCH_OAUTH_TOKEN).subscribe(
                    lambda message: twitchChat(message, helix))
Пример #19
0
 def get_twitch(self, user):
     twitch_id = self.bot.config.data.get("config").get("TWITCH_CLIENT_ID")
     helix = twitch.Helix(twitch_id)
     live_flag = False
     try:
         helix.user(user).stream().type
         live_flag = True
     except twitch.helix.streams.StreamNotFound:
         live_flag = False
     return live_flag
Пример #20
0
 def assign_core(self, core):
     if not self.enabled:
         return False
     super().assign_core(core)
     self.helix = twitch.Helix('jqqxdo6tewc80vot6w66mkzfnso558',
                               '7tsxcnw9efuxbjk3q2r8ebdx54k01c')
     self.chat = twitch.Chat(channel='#cheeseypi',
                             nickname='cheeseyquichebot',
                             oauth='oauth:948piogkdqxbti42c8pwu0grd5zily',
                             helix=self.helix)
     self.chat.subscribe((lambda message: self.receivedMessage(message)))
     return True
Пример #21
0
def get_vod_info(vod_num, twitch_id='9k8fhtcsrjfgip3v1jrs1ut33yzs7c'):
    try:
        helix = twitch.Helix(twitch_id)
        vod = helix.video(vod_num)

        # 유효한 vod가 아닌 경우
        if vod is None:
            return ''

        return vod.user_name + ': ' + vod.title
    except:
        return ''
Пример #22
0
    def __init__(self, channel):#api:webhook.api):
        self.channel = channel
        # self.api = api
        # self._id = self.api.user_id(channel) #la6kj4pn3vzfdvvkfrg8y5eqvbuxjk   qxhcdwsgg5m3qm7or17f3lo51soznk
        # self.api.sub_streamchange(self._id)

        self.helix=twitch.Helix(client_id='hqiwd4o8a3mf6l7t7l0xge8qt7ksob', use_cache=True)
        self.chat = twitch.Chat(channel=channel,
                       nickname='bot',
                       oauth='oauth:la6kj4pn3vzfdvvkfrg8y5eqvbuxjk',
                       helix=self.helix)
        self.buf = []
Пример #23
0
 async def twitch(self, ctx, user="******"):
     twitch_id = self.bot.config.data.get("config").get("TWITCH_CLIENT_ID")
     helix = twitch.Helix(twitch_id)
     try:
         await ctx.send(helix.user(user).stream().type)
         game_id = helix.user(user).stream().game_id
         title = helix.user(user).stream().title
         test = helix.game(id=game_id)
         await ctx.send(f"<https://twitch.tv/{user}>")
         await ctx.send(f"Title: {title}")
         await ctx.send(f"Streaming: {test.name}")
     except twitch.helix.streams.StreamNotFound:
         await ctx.send("Not Live")
Пример #24
0
    def test_download(self):
        httpretty.register_uri(
            method=httpretty.GET,
            uri='https://api.twitch.tv/helix/users?login=zarlach',
            match_querystring=True,
            body=json.dumps({
                'data': [{
                    'id': '24250859',
                    'login': '******',
                    'display_name': 'Zarlach',
                    'type': '',
                    'broadcaster_type': '',
                    'description': '',
                    'profile_image_url':
                    'https://static-cdn.jtvnw.net/jtv_user_pictures/zarlach-profile_image-1cb98e7eadb5918a-300x300.png',
                    'offline_image_url':
                    'https://static-cdn.jtvnw.net/jtv_user_pictures/zarlach-channel_offline_image-f2d036ac9582d793-1920x1080.png',
                    'view_count': 1664
                }]
            }))

        httpretty.register_uri(
            method=httpretty.GET,
            uri='https://api.twitch.tv/helix/users?login=sodapoppin',
            match_querystring=True,
            body=json.dumps({
                'data': [{
                    'id': '26301881',
                    'login': '******',
                    'display_name': 'sodapoppin',
                    'type': '',
                    'broadcaster_type': 'partner',
                    'description':
                    'Wtf do i write here? Click my stream, or i scream.',
                    'profile_image_url':
                    'https://static-cdn.jtvnw.net/jtv_user_pictures/sodapoppin-profile_image-10049b6200f90c14-300x300.png',
                    'offline_image_url':
                    'https://static-cdn.jtvnw.net/jtv_user_pictures/7ed72b04-897e-4a85-a3c9-2a8ba74aeaa7-channel_offline_image-1920x1080.jpg',
                    'view_count': 276164750
                }]
            }))

        helix = twitch.Helix('client-id', use_cache=True)

        # Login to display name
        self.assertEqual(helix.user('zarlach').display_name, 'Zarlach')

        # Should returned cached data from above
        for user, display_name in zip(helix.users(24250859, 'sodapoppin'),
                                      ['Zarlach', 'sodapoppin']):
            self.assertEqual(user.display_name, display_name)
Пример #25
0
    def test_custom_cache(self):
        httpretty.register_uri(
            method=httpretty.GET,
            uri='https://api.twitch.tv/helix/users?login=sodapoppin&login=zarlach',
            match_querystring=True,
            body=json.dumps({
                'data': [{'id': '24250859',
                          'login': '******',
                          'display_name': 'Zarlach',
                          'type': '',
                          'broadcaster_type': '',
                          'description': '',
                          'profile_image_url': 'https://static-cdn.jtvnw.net/jtv_user_pictures/zarlach-profile_image-1cb98e7eadb5918a-300x300.png',
                          'offline_image_url': 'https://static-cdn.jtvnw.net/jtv_user_pictures/zarlach-channel_offline_image-f2d036ac9582d793-1920x1080.png',

                          'view_count': 1664},
                         {'id': '26301881',
                          'login': '******',
                          'display_name': 'sodapoppin',
                          'type': '',
                          'broadcaster_type': 'partner',
                          'description': 'Wtf do i write here? Click my stream, or i scream.',
                          'profile_image_url': 'https://static-cdn.jtvnw.net/jtv_user_pictures/sodapoppin-profile_image-10049b6200f90c14-300x300.png',
                          'offline_image_url': 'https://static-cdn.jtvnw.net/jtv_user_pictures/7ed72b04-897e-4a85-a3c9-2a8ba74aeaa7-channel_offline_image-1920x1080.jpg',
                          'view_count': 276164750}]
            })
        )

        helix = twitch.Helix('client-id', use_cache=True)
        helix.users('zarlach', 'sodapoppin')

        # Users have custom caching, such that url should not be cached
        self.assertFalse(helix.api.SHARED_CACHE.has('GET:https://api.twitch.tv/helix/users?login=zarlach'))

        # Cache entries by login name and id number
        self.assertTrue(helix.api.SHARED_CACHE.has('helix.users.login.zarlach'))
        self.assertTrue(helix.api.SHARED_CACHE.has('helix.users.id.24250859'))

        self.assertTrue(helix.api.SHARED_CACHE.has('helix.users.login.sodapoppin'))
        self.assertTrue(helix.api.SHARED_CACHE.has('helix.users.id.26301881'))

        # Flush cache to remove
        helix.api.flush_cache()

        # Check cache flush
        self.assertFalse(helix.api.SHARED_CACHE.has('helix.users.login.zarlach'))
        self.assertFalse(helix.api.SHARED_CACHE.has('helix.users.id.24250859'))

        self.assertFalse(helix.api.SHARED_CACHE.has('helix.users.login.sodapoppin'))
        self.assertFalse(helix.api.SHARED_CACHE.has('helix.users.id.26301881'))
Пример #26
0
def main():
    # pdb.set_trace()
    chat = twitch.Chat(
        channel='isaiahmonday',  # adjust this for your channel name
        nickname='bot',

        # awd contains an oauth key which is not shared publicly. Create your own awd.txt file
        oauth=open("awd.txt").read(),

        # adjust this for your client ID
        helix=twitch.Helix(client_id='lmpf9a1btnphwvvy879gqly1voc4ak',
                           use_cache=True))

    chat.subscribe(handle_message)
    app.run()
Пример #27
0
 def start(self):
     for _, channel in utils.getChannels():
         self.active_chats[channel] = twitch.Chat(
             channel='#{}'.format(channel),
             nickname=config.BOT_NAME,
             oauth=config.OAUTH_TOKEN,
             helix=twitch.Helix(client_id=config.CLIENT_ID, use_cache=True))
         self.active_chats[channel].subscribe(self.messageHandler)
         events = utils.getEvents(channel)
         glob.events[channel] = eventHandler.MessagePoster(
             chat=self.active_chats[channel])
         for message, interval in events:
             glob.events[channel].addEvent(message, interval)
         logging.info("JOINED #{}".format(channel))
     logging.info("Succesfully started")
Пример #28
0
    def test_custom_video_cache(self):
        helix = twitch.Helix('client-id', use_cache=True)
        _ = helix.video(471855782)

        # Videos have custom caching, such that url should not be cached
        self.assertFalse(
            helix.api.SHARED_CACHE.has(
                'GET:https://api.twitch.tv/helix/videos?id=471855782'))

        # Cache entries by video id
        self.assertTrue(helix.api.SHARED_CACHE.has('helix.video.471855782'))

        # Flush cache to remove
        helix.api.flush_cache()

        # Check cache flush (cache should be empty)
        self.assertFalse(helix.api.SHARED_CACHE.has('helix.video.471855782'))
Пример #29
0
def main():
    if len(sys.argv) < 2 or len(sys.argv) > 3:
        usage()
        sys.exit()

    client_id = sys.argv[1]
    browser = 'google-chrome'
    if len(sys.argv) == 3:
        browser = sys.argv[2]
    DROPSENABLED_TAGID = "c2542d6d-cd10-4532-919b-3d19f30a768b"

    while True:
        stream_to_watch = ""
        stream_to_watch_id = -1

        # Find a drops-enabled Valorant stream
        helix = twitch.Helix(client_id=client_id)
        for stream in helix.streams(game_id=516575):
            if DROPSENABLED_TAGID in stream.data['tag_ids']:
                # subprocess.check_call(['google-chrome', 'https://twitch.tv/' + stream.data['user_name']])
                stream_to_watch = stream.data['user_name']
                stream_to_watch_id = stream.data['user_id']
                print("gonna watch " + stream_to_watch)
                webbrowser.get(browser).open('https://twitch.tv/' +
                                             stream.data['user_name'])
                # os.system("google-chrome " + "https://twitch.tv/" + stream.data['user_name'])
                break
        print("watching " + stream_to_watch)

        # Watch the stream until it isnt live
        if stream_to_watch != "":
            live = True
            while live:
                print(stream_to_watch + " still live")
                # Heartbeat every 20 seconds to check that its live
                try:
                    b = helix.streams(user_id=stream_to_watch_id)
                except StreamNotFound:
                    break
                if len(b._data) >= 1:
                    live = b._data[0].type == "live"
                else:
                    live = False
                time.sleep(20)

            os.system("pkill chrome")
Пример #30
0
    def __init__(self):
        self.helix_api = twitch.Helix(client_id=Settings().config['client_id'], use_cache=True)

        self.formats: List[str] = []
        self.whitelist: List[str] = []
        self.blacklist: List[str] = []

        # Populate format list according to whitelist and blacklist
        if 'all' in Arguments().formats and 'all' in Settings().config['formats']:
            self.blacklist = Settings().config['formats']['all']['whitelist'] or []
            self.whitelist = Settings().config['formats']['all']['blacklist'] or []

            # Append formats to list if they can be used
            self.formats = [format_name for format_name in Settings().config['formats'].keys() if
                            self._can_use_format(format_name)]

        else:
            self.formats = [format_name for format_name in Arguments().formats if self._can_use_format(format_name)]