"""!image <search term> return a random result from the google image search result for <search term>"""

try:
    from urllib import quote, unquote
except ImportError:
    from urllib.request import quote, unquote
import re
import requests
from random import shuffle

def image(searchterm, unsafe=False):
    searchterm = quote(searchterm)

    safe = "&safe=" if unsafe else "&safe=active"
    searchurl = "https://www.google.com/search?tbm=isch&q={0}{1}".format(searchterm, safe)

    # this is an old iphone user agent. Seems to make google return good results.
    useragent = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Versio  n/4.0.5 Mobile/8A293 Safari/6531.22.7"

    result = requests.get(searchurl, headers={"User-agent": useragent}).text

    images = re.findall(r'imgurl.*?(http.*?)\\', result)
    shuffle(images)

    if images:
        return unquote(images[0])
    else:
        return ""

def on_message(msg, server):
    text = msg.get("text", "")
    match = re.findall(r"!image (.*)", text)
    if not match:
        return

    searchterm = match[0]
    return image(searchterm.encode("utf8"))

@@ -261,16 +261,451 @@
 huffle%0A%0A
+def octal_to_html_escape(re_match):%0A    # an octal escape of the form '%5C75' (which ought to become '%253d', the%0A    # url-escaped form of %22=%22. Strip the leading %5C%0A    s = re_match.group(0)%5B1:%5D%0A%0A    # convert octal to hex and strip the leading '0x'%0A    h = hex(int(s, 8))%5B2:%5D%0A%0A    return %22%25%7B0%7D%22.format(h)%0A%0Adef unescape(url):%0A    # google uses octal escapes for god knows what reason%0A    return re.sub(r%22%5C%5C..%22, octal_to_html_escape, url)%0A%0A
 def imag
@@ -1255,42 +1255,49 @@
 s = 
-re.findall(r'imgurl.*?(http
+map(unescape, re.findall(r%22var u='(
 .*?)
-%5C%5C
 '
+%22
 , re
@@ -1301,16 +1301,17 @@
  result)
+)
 %0A    shu

update image for new google response