import asyncio
import json
import websockets
import http.client

TOKEN = 'MTMyNzcxNDM3MTEyMzgxMDMwNA.GwLjEd.quGP0FA5gHRe1xLyuYq-ANuJ5cRuRQ6dhJiojI'

def get_gateway_url():
    conn = http.client.HTTPSConnection("discord.com")
    headers = {
        'Authorization': f'Bot {TOKEN}'
    }
    conn.request("GET", "/api/v10/gateway/bot", headers=headers)
    response = conn.getresponse()
    data = json.loads(response.read().decode('utf-8'))
    return data['url']

async def connect_to_gateway():
    gateway_url = get_gateway_url()
    ws_url = f"{gateway_url}?v=10&encoding=json"

    async with websockets.connect(ws_url) as ws:
        print('Connected to the Discord Gateway')

        # Identify the bot
        identify_payload = {
            'op': 2,
            'd': {
                'token': TOKEN,
                'properties': {
                    '$os': 'linux',
                    '$browser': 'my_library',
                    '$device': 'my_library'
                },
                'intents': 32767  # Enable all intents (adjust as needed)
            }
        }
        await ws.send(json.dumps(identify_payload))

        while True:
            message = await ws.recv()
            data = json.loads(message)
            print('Received message:', data['t'])

            # Handle specific events
            if data['op'] == 0:  # Event
                event_type = data['t']
                event_data = data['d']

                if event_type == 'GUILD_SCHEDULED_EVENT_CREATE':
                    print('New guild event created:', event_data)
                elif event_type == 'GUILD_SCHEDULED_EVENT_UPDATE':
                    print('Guild event updated:', event_data)
                elif event_type == 'GUILD_SCHEDULED_EVENT_DELETE':
                    print('Guild event deleted:', event_data)
                elif event_type == 'GUILD_SCHEDULED_EVENT_USER_ADD':
                    print('User added to guild event:', event_data)
                elif event_type == 'GUILD_SCHEDULED_EVENT_USER_REMOVE':
                    print('User removed from guild event:', event_data)
                elif event_type == 'GUILD_SCHEDULED_EVENT_START':
                    print('Guild event started:', event_data)

            elif data['op'] == 1:  # Heartbeat request
                heartbeat_payload = {
                    'op': 1,
                    'd': data['s']
                }
                await ws.send(json.dumps(heartbeat_payload))

            elif data['op'] == 10:  # Hello
                heartbeat_interval = data['d']['heartbeat_interval'] / 1000
                asyncio.create_task(heartbeat(ws, heartbeat_interval))

            elif data['op'] == 11:  # Heartbeat ACK
                print('Heartbeat acknowledged')

            else:
                print('Unknown opcode:', data['op'])

async def heartbeat(ws, interval):
    while True:
        heartbeat_payload = {
            'op': 1,
            'd': None
        }
        await ws.send(json.dumps(heartbeat_payload))
        print('Sent heartbeat')
        await asyncio.sleep(interval)


asyncio.get_event_loop().run_until_complete(connect_to_gateway())