from discord.ext import commands
from random import choice
from cogs.utils.chat_formatting import box
import aiohttp
import html
import re
import urllib


class Geico:
    """A 15-minute call could save you 15 percent (or more) on car insurance."""
    def __init__(self, bot):
        self.bot = bot

    @commands.command(name="bash", pass_context=True, no_pm=True)
    @commands.cooldown(3, 60, commands.BucketType.user)
    async def _bash(self, ctx, num: int=1):
        """Retrieves a quote from bash.org. num can be specified for number of quotes. Max is 5."""
        regex = ["<p class=\"qt\">([^`]*?)<\/p>", "<br \/>"]
        if num > 5:
            num = 5
            await self.bot.reply("Heck naw brah. 5 is max. Any more and you get killed.")
        for i in range(num):
            async with aiohttp.request("GET", 'http://bash.org/?random') as resp:
                test = str(await resp.text())
                subs = re.findall(regex[0], test)
                brsub = re.sub(regex[1], "", subs[0])
                subs2 = html.unescape(brsub)
                await self.bot.say(box(subs2))

    @commands.command(name="quotes", pass_context=True, no_pm=True)
    @commands.cooldown(3, 60, commands.BucketType.user)
    async def _quotes(self, ctx, *, author: str):
        """Retrieves a specified number of quotes from a specified author. Max number of quotes at a time is 5.
        Examples:
        [p]quotes Morgan Freeman; 5
        [p]quotes Margaret Thatcher; 2"""
        regex = [" <a href=\"\/quotes\/authors\/([^`]*?).html\">", "title=\"view quote\">([^`]*?)<\/a>"]
        option = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'}
        try:
            author = author.split('; ')
            title = author[0]
            number = int(author[1])
            if number > 5:
                number = 5
                await self.bot.reply("Heck naw brah. 5 is max. Any more and you get killed.")
            uri = 'http://www.brainyquote.com/search_results.html?q='
            quary = title.lower()
            encode = urllib.parse.quote_plus(quary, encoding='utf-8', errors='replace')
            uir = uri + encode
            async with aiohttp.request("GET", uir, headers=option) as resp:
                test = str(await resp.text())
                author_find = re.findall(regex[0], test)
                author_url = 'http://www.brainyquote.com/quotes/authors/' + author_find[0]
                for i in range(number):
                    async with aiohttp.request("GET", author_url) as resp:
                        test = str(await resp.text())
                        quote_find = re.findall(regex[1], test)
                        random_quote = choice(quote_find)
                        while author in random_quote:
                            random_quote = choice(quote_find)
                        await self.bot.say(box(random_quote))

        except IndexError:
            await self.bot.say("Your search is not valid, please follow the examples."
                               "Make sure the names are correctly written\n"
                               "[p]quotes Margaret Thatcher; 5\n[p]quotes Morgan Freeman; 5")


def setup(bot):
    n = Geico(bot)
    bot.add_cog(n)

@@ -117,16 +117,31 @@
 %0Aimport 
+asyncio%0Aimport 
 html%0Aimp
@@ -150,22 +150,8 @@
 t re
-%0Aimport urllib
 %0A%0A%0Ac
@@ -1105,16 +1105,55 @@
 (subs2))
+%0A                await asyncio.sleep(1)
 %0A%0A    @c
@@ -1547,59 +1547,8 @@
 ex =
- %5B%22 %3Ca href=%5C%22%5C/quotes%5C/authors%5C/(%5B%5E%60%5D*?).html%5C%22%3E%22,
  %22ti
@@ -1580,17 +1580,16 @@
 ?)%3C%5C/a%3E%22
-%5D
 %0A       
@@ -1593,107 +1593,58 @@
     
-option = %7B'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'%7D
+url = 'http://www.brainyquote.com/quotes/authors/'
 %0A   
@@ -1925,216 +1925,84 @@
   ur
-i = 'http://www.brainyquote.com/search_results.html?q='%0A            quary = title.lower()%0A            encode = urllib.parse.quote_plus(quary, encoding='utf-8', errors='replace')%0A            uir = uri + encode
+l = url + title.lower()%5B0%5D + %22/%22 + title.lower().replace(%22 %22, %22_%22) + %22.html%22
 %0A   
@@ -2049,26 +2049,10 @@
 %22, u
-ir, headers=option
+rl
 ) as
@@ -2124,22 +2124,21 @@
     
-author
+quote
 _find = 
 re.f
@@ -2125,32 +2125,41 @@
    quote_find = 
+list(set(
 re.findall(regex
@@ -2162,114 +2162,18 @@
 egex
-%5B0%5D
 , test)
+))
 %0A
-                author_url = 'http://www.brainyquote.com/quotes/authors/' + author_find%5B0%5D%0A    
     
@@ -2224,365 +2224,300 @@
     
-    async with aiohttp.request(%22GET%22, author_url) as resp:%0A                        test = str(await resp.text())%0A                        quote_find = re.findall(regex%5B1%5D, test)%0A                        random_quote = choice(quote_find)%0A                        while author in random_quote:%0A                            random_quote = choice(quote_find)%0A      
+random_quote = choice(quote_find)%0A                quote_find.remove(random_quote)%0A                while random_quote == title:%0A                    random_quote = choice(quote_find)%0A                random_quote = random_quote.replace(%22&#39;%22, %22'%22) if %22&#39;%22 in random_quote else random_quote%0A
     
@@ -2520,34 +2520,32 @@
                 
-  
 await self.bot.s
@@ -2565,16 +2565,55 @@
 _quote))
+%0A                await asyncio.sleep(1)
 %0A%0A      

Optimize bandwidth usage