import requests
import time
from twitchio.ext import commands
from twitchio.client import Client
from twitchio import Message

# Replace with your Twitch client ID and OAuth token
TWITCH_CLIENT_ID = 'your_client_id'
TWITCH_OAUTH_TOKEN = 'your_oauth_token'
TWITCH_LOGIN = 'your_login_name'
TWITCH_CHANNEL = 'twitch_channel_name'

# Keep track of the current stream status
stream_live = False

CHECK_INTERVAL = 60  # seconds


def is_stream_live():
    url = f'https://api.twitch.tv/helix/streams?user_login={TWITCH_LOGIN}'
    headers = {
        'Client-ID': TWITCH_CLIENT_ID,
        'Authorization': f'Bearer {TWITCH_OAUTH_TOKEN}'
    }
    response = requests.get(url, headers=headers)
    data = response.json()
    print(data)
    if data.get('data') and data['data'][0].get('type') == 'live':
        return True
    return False


def send_message(msg):
    bot = commands.Bot(
        irc_token='your_irc_token',
        client_id='your_client_id',
        nick='your_bot_name',
        prefix='!',
        initial_channels=[TWITCH_CHANNEL]
    )
    bot.run()
    bot._ws.send_privmsg(TWITCH_CHANNEL, msg)


def main():
    stream_live = False
    while True:
        live = is_stream_live()
        if live != stream_live:
            stream_live = live
            msg = 'The stream has started! Get in here for good times!' if live else 'The stream has ended. Hope you enjoyed!'
            send_message(msg)
            print(msg)
        time.sleep(CHECK_INTERVAL)


if __name__ == '__main__':
    main()
