from discord import Intents, Interaction, VoiceState, Member, FFmpegPCMAudio, VoiceClient
from discord.ext import commands


DISCORD_TOKEN = "MTQ0NzYyNjkxMDEzNzA2MTQ2Ng.GZ-Snw.suZpiacdFgR2hyD6KtqlpdTFVCRxv3kgGa9hS8"
PASTALANDIA = 929432463099461694
CASTIGO = 1429535766710714439
FILENAME = "sus_trimmed.mp3"

intents = Intents.default()
intents.voice_states = True
client = commands.Bot(command_prefix="/", intents=intents)
voice_client: VoiceClient

@client.event
async def on_ready():
    print(f"We have logged in as {client.user}")
    try:
        synced = await client.tree.sync()
        print(f"Synced {len(synced)} command(s)")
    except Exception as e:
        print(f"Failed to sync commands: {e}")


@client.tree.command(name="ping", description="Check the bot's latency.")
async def ping(interaction: Interaction):
    latency = client.latency * 1000
    await interaction.response.send_message(f"Pong! Latency: {latency:.2f}ms")


@client.event
async def on_voice_state_update(member: Member, before: VoiceState, after: VoiceState):
    global voice_client

    print("Event")
    if before.channel and before.channel.id == CASTIGO and (not after.channel or after.channel.id != CASTIGO):
        channel = before.channel
        if len(channel.members) <= 1:
            await voice_client.disconnect()

    if not (after.channel and after.channel.id == CASTIGO and (not before.channel or before.channel.id != CASTIGO)): return

    print("Yeee")
    channel = after.channel
    try:
        print("Connecting")
        voice_client = await channel.connect(self_deaf=True)
        print("Connected")
    except:
        return
    
    print("Sourcing")
    source = FFmpegPCMAudio(FILENAME)
    print("Starting")
    voice_client.play(source)
    print("Playing")


if __name__ == "__main__":
    client.run(DISCORD_TOKEN)
