from bs4 import BeautifulSoup
import urllib
import random
import asyncio
import aiohttp


_externals = { "running": False }


def _initialise(Handlers, bot=None):
    Handlers.register_user_command(["meme"])
    return []


@asyncio.coroutine
def _retrieve(url, css_selector, attribute):
    print("_retrieve(): getting {}".format(url))
    html_request = yield from aiohttp.request('get', url)
    html = yield from html_request.read()
    soup = BeautifulSoup(str(html, 'utf-8'))
    links = []
    for link in soup.select(css_selector):
        links.append(link.get(attribute))
    return links


def meme(bot, event, *args):
    if _externals["running"]:
        bot.send_html_to_conversation(event.conv_id, "<i>busy, give me a moment...</i>")
        return

    _externals["running"] = True

    try:
        parameters = list(args)
        if len(parameters) == 0:
            parameters.append("robot")

        links = yield from _retrieve("http://memegenerator.net/memes/search?q=" + "+".join(parameters), ".item_medium_small > a", "href")
        links = yield from _retrieve("http://memegenerator.net" + random.choice(links), ".item_medium_small > a", "href")
        links = yield from _retrieve("http://memegenerator.net" + random.choice(links), ".instance_large > img", "src")

        if len(links) > 0:
            jpg_link = links.pop()
            the_request = yield from aiohttp.request('get', jpg_link)
            image_data = yield from the_request.read()

            photoID = yield from bot._client.upload_image(image_data)
            yield from bot._client.sendchatmessage(event.conv.id_, None, imageID=photoID)
        else:
            bot.send_html_to_conversation(event.conv_id, "<i>couldn't find a suitable meme :(</i>")
    except Exception as e:
        bot.send_html_to_conversation(event.conv_id, "<i>oh-uh, something went wrong! try again</i>")
    finally:
        _externals["running"] = False

@@ -81,16 +81,31 @@
 aiohttp%0A
+import hangups%0A
 %0A%0A_exter
@@ -1177,32 +1177,33 @@
 a%22, %22href%22)%0A
+%0A
         
 links = yiel
@@ -1194,37 +1194,24 @@
     
-l
 in
-ks = yield from _retrieve(
+stance_link = 
 %22htt
@@ -1251,24 +1251,75 @@
 hoice(links)
+%0A        links = yield from _retrieve(instance_link
 , %22.instance
@@ -1529,16 +1529,233 @@
 read()%0A%0A
+            legacy_segments = %5B%0A                # hangups.ChatMessageSegment('link: ', is_italic=True),%0A                hangups.ChatMessageSegment(instance_link, hangups.SegmentType.LINK, link_target=instance_link)%5D%0A%0A
         
@@ -1883,20 +1883,60 @@
 nv.id_, 
-None
+%5Bseg.serialize() for seg in legacy_segments%5D
 , imageI
@@ -2041,24 +2041,33 @@
 d a 
-suitable meme :(
+nice picture :( try again
 %3C/i%3E
@@ -2157,35 +2157,37 @@
 %22%3Ci%3E
-oh-uh, something went wrong
+couldn't find a suitable meme
 ! tr

support for meme posting with both image and source link