import os
import asyncio
import inspect
import textwrap
import base64
from io import BytesIO

import tokage
import discord
from discord.ext import commands


class Utilities:
    def __init__(self, bot):
        self.bot = bot

    @commands.command(hidden=True, enabled=False)
    async def setavatar(self, ctx, picture):
        path = os.path.join("Bot Pics", picture)
        try:
            with open('%s' % path, 'rb') as f:
                await ctx.bot.user.edit(avatar=f.read())
            await ctx.send(":ok_hand: Avatar changed to %s" % picture.split(".")[0])
        except Exception:
            await ctx.send(":exclamation: File not found!")

    @commands.command(hidden=True, aliases=["eval", "evaluate"])
    @commands.is_owner()
    async def debug(self, ctx, *, code: str):
        """Evaluates code."""
        code = code.strip('`')
        python = '```py\n{}\n```'
        result = None

        env = {
            'bot': self.bot,
            'ctx': ctx,
            'message': ctx.message,
            'server': ctx.guild,
            'guild': ctx.guild,
            'channel': ctx.channel,
            'author': ctx.author,
            'history': await ctx.channel.history().flatten(),
            't_client': tokage.Client()
        }

        env.update(globals())

        try:
            result = eval(code, env)
            if inspect.isawaitable(result):
                result = await result
        except Exception as e:
            await ctx.send(python.format(type(e).__name__ + ': ' + str(e)))
            return

        await ctx.send(python.format(result))

    @commands.command(name="exec", hidden=True)
    @commands.is_owner()
    async def execute(self, ctx, *, code):
        if code.startswith("```") and code.endswith("```"):
            code = code.strip("```")
            if code.startswith("py\n"):
                code = code[3:]
        env = {
            'bot': self.bot,
            'ctx': ctx,
            'message': ctx.message,
            'server': ctx.guild,
            'guild': ctx.guild,
            'channel': ctx.channel,
            'author': ctx.author,
            'history': await ctx.channel.history().flatten(),
            't_client': tokage.Client()
        }
        env.update(globals())
        wrapped = 'async def func():\n%s' % textwrap.indent(code, '  ')
        try:
            result = exec(wrapped, env)
            func = env['func']
            await func()
            if result:
                await ctx.send(f"```{result}```")
        except Exception as e:
            await ctx.send(f"```{type(e).__name__ + ': ' + str(e)}```")

    @commands.command(aliased=["join", "inv"])
    async def invite(self, ctx):
        """Sends an invite link for the bot"""
        await ctx.send("https://discordapp.com/oauth2/authorize/?permissions=64&scope=bot&client_id=236176083861372928")

    class ByteString(commands.Converter):
        async def convert(self, ctx, arg):
            return bytes(arg, 'utf-8')

    @commands.command()
    async def img64(self, ctx, *, b64: ByteString):
        """Converts base64 to an image"""
        f = BytesIO(base64.decodebytes(b64))
        await ctx.send(file=discord.File(f, "img.png"))

def setup(bot):
    bot.add_cog(Utilities(bot))

@@ -258,23 +258,8 @@
 True
-, enabled=False
 )%0A  
@@ -298,16 +298,21 @@
  picture
+=None
 ):%0A     
@@ -319,26 +319,24 @@
    p
-ath
+ics
  = os.
-path.join
+listdir
 (%22Bo
@@ -346,84 +346,260 @@
 ics%22
-, picture)%0A        try:%0A            with open('%25s' %25 path, 'rb') as f:%0A     
+)%0A        fmt = %22Enter pic number to set:%5Cn%22%0A        for pic, i in enumerate(pics):%0A            fmt += f%22%5B%7Bi+1%7D%5D - %7Bpic%7D%5Cn%22%0A        img_msg = await ctx.send(fmt)%0A        check = lambda m: m.author == ctx.author and m.channel = ctx.channel%0A        try:%0A
     
@@ -608,48 +608,146 @@
     
+  msg =
  await 
-ctx
+self
 .bot.
-user.edit(avatar=f.read()
+wait_for(%22message%22, check=check, timeout=35)%0A        except asyncio.TimeoutError:%0A            await img_msg.delete(
 )%0A  
@@ -748,32 +748,39 @@
 e()%0A            
+return 
 await ctx.send(%22
@@ -783,150 +783,387 @@
 nd(%22
-:ok_hand: Avatar changed to %25s%22 %25 picture.split(%22.%22)%5B0%5D)%0A        except Exception:%0A            await ctx.send(%22:exclamation: File not found!%22)
+Timeout. Please try again later.%22)%0A        img_num = int(msg)-1%0A        if img_num %3E len(pics):%0A            await img_msg.delete()%0A            return await ctx.send(%22This image doesnt exist!%22)%0A        img_name = pics%5Bimg_num%5D%0A    %0A        with open(img_name, %22rb%22) as f:%0A            await ctx.bot.user.edit(avatar=f.read())%0A        await ctx.send(%22Changed image to %22 + img_name)%0A
 %0A%0A  

rework setavatar