import discord
from discord.ext import commands
from os import getenv
from mcrcon import MCRcon

bot = commands.Bot(command_prefix='!')

@bot.command()
async def whitelist(ctx, arg):
    try:
        resp = command(f'whitelist add {arg}')
        if resp == f'Added {arg} to the whitelist':
            msg = "You have been whitelisted"
        elif resp == "Player is already whitelisted":
            msg = f'{arg} is alredy whitelisted'
        else:
            msg = f'Failed to add {arg}'
        
    except ConnectionRefusedError:
        msg = "Failed to add {arg}"
    except Exception as e:
        print("Discord error")
    finally:
        await ctx.send(msg)

def command(command):
    with MCRcon(getenv("RCON_HOST"), getenv("RCON_PASS"), int(getenv("RCON_PORT")) ) as mcr:
        resp = mcr.command(command)
        print(resp)
        return resp

def main():
    try:
        command("say hello")
        bot.run(getenv("DISCORD_TOKEN"))
    except ConnectionRefusedError:
        exit("RCON failed")
    except:
        exit("Discord error")
    

if __name__ == "__main__":
    main()