Search code examples
pythonbotsdiscorddiscord.pytwitch

Is there a way of checking a streamer is live on twitch with or without an api?


I'm developing a discord bot in py. But i can't seem to figure out how to check if a user is live on twitch. When i check for their stream title. I could make the bot announce the streams if the word stream was in it. But the bot kept checking it over and over again breaking the channel. What other solution is there to check for a streamer being live? I couldnt figure out how the api works


Solution

  • A common approach using python Requests library, this will be able to tell you IF a user is live:

    import requests
    
    CLIENT_ID = 'my-twitch-client-id'
    OAUTH_TOKEN = 'my-twitch-oauth-token'
    
    def is_user_live(username):
        endpoint = 'https://api.twitch.tv/helix/streams'
        my_headers = {
            'Client-ID': CLIENT_ID,
            'Authorization': f'Bearer {OAUTH_TOKEN}'
        }
        my_params = {'user_login': username}
        response = requests.get(endpoint, headers=my_headers, params=my_params)
        data = response.json()['data']
        if len(data) == 0:
            return False
        return data[0]['type'] == 'live'
    

    What I'd recommend for your bot is that you subscribe to the events webhook when you initialize the bot. You will need to create a webserver to handle the POST requests that Twitch will send you, this will be able to tell you WHEN a user goes live. A cruuude example using Flask:

    import requests
    import json
    from flask import request
    
    CLIENT_ID = 'my-twitch-client-id'
    OAUTH_TOKEN = 'my-twitch-oauth-token'
    MY_SECRET = 'an-arbitrary-secret'
    
    app = your_flask_app()
    
    @app.route('/my_webhook/<user_id>')
    def my_webhook(user_id):
        check_secret(request) # sha256 of your secret and content-length
        data = request.get_json()['data']
        if len(data) > 0:
           your_bot.user_is_live(data)
        else:
           your_bot.user_is_offline(data)
        return 'OK'
    
    def subscribe_to_webhook(user_id):
        endpoint = 'https://api.twitch.tv/helix/webhooks/hub'
        topic = 'https://api.twitch.tv/helix/streams'
        my_headers = {
            'Client-ID': CLIENT_ID,
            'Authorization': f'Bearer {OAUTH_TOKEN}'
        }
        payload = {
            'hub.callback': f'http://my_server.url/my_webhook/{user_id}',
            'hub.mode': 'subscribe',
            'hub.topic': f'{topic}?user_id={user_id}',
            'hub.lease_seconds': 864000,
            'hub.secret': MY_SECRET
        }
        response = requests.post(endpoint, headers=my_headers, data=json.dumps(payload))
        return response.ok