import random
import sys
import threading
import logging
import discord
from asyncio import sleep
from os import walk

from discord import user, member
from discord import FFmpegPCMAudio
from discord.ext import commands

threading.current_thread().name = "main"
logging.basicConfig(stream=sys.stdout, filemode='w', level='INFO',
                    format='%(asctime)s - %(levelname)s - %(threadName)s - %(message)s')


intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='$', guild_subscriptions=True, intents=intents)
f = []
for filenames in walk('audio'):
    f.extend(filenames)
    break
f = f[2]


@bot.event
async def on_voice_state_update(member, before, after):
    # channel = bot.get_channel(783729824896122930)
    _role = 929729495370461205
    _memb = 375664768087752714
    _bot_id = 946819004314570852
    role = discord.utils.find(lambda r: r.name == 'тарковчане', member.roles)
    if before.channel is None and role in member.roles:
        track = random.randint(0, len(f) - 1)
        audio_source = FFmpegPCMAudio(f'audio/{f[track]}')
        logging.error(f'{track}\t\t{f[track]}')
        if not bot.voice_clients:
            await sleep(1)
            _channel = after.channel
            vc = await after.channel.connect()
            if not vc.is_playing():
                vc.play(audio_source, after=None)
            while vc.is_playing():
                await sleep(0.5)
            await sleep(1)
            await vc.disconnect()
    if before.channel is None and member.id == _memb:
        track = random.randint(0, len(f) - 1)
        audio_source = FFmpegPCMAudio(f'audio/{_memb}/bear2_enemy_scav3.wav')
        logging.error(f'{track}\t\t\t{f[track]}')
        if not bot.voice_clients:
            await sleep(1)
            _channel = after.channel
            vc = await after.channel.connect()
            if not vc.is_playing():
                vc.play(audio_source, after=None)
            while vc.is_playing():
                await sleep(0.5)
            await sleep(1)
            await vc.disconnect()


@bot.event
async def on_member_join(member):
    if member.bot == 0:
        role = discord.utils.get(member.guild.roles, id=734358428939452486)
    else:
        role = discord.utils.get(member.guild.roles, id=734358434945826858)
    logging.info(f"Adding to {member} role {role}")
    await member.add_roles(role)


@bot.event
async def on_ready():
    logging.info(f'Bot started')


bot.run('OTQ2ODE5MDA0MzE0NTcwODUy.YhkP6Q.dhFqi2MJMrxzHt5FtjK5Cl-5BI8')
