import discord
import mimetypes
import pkg_resources
import random
import re
import yaml

from boarbot.common.botmodule import BotModule
from boarbot.common.events import EventType

QUERY_RE = re.compile('[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)+')
MEMES_YAML = pkg_resources.resource_string('boarbot.modules.memelink', 'memes.yaml').decode()
MEMES = yaml.load(MEMES_YAML)

class MemeLinkModule(BotModule):
    async def handle_event(self, event_type: EventType, args):
        if event_type != EventType.MESSAGE:
            return

        message = args[0] # type: discord.Message
        if message.author.bot:
            return # Ignore bots

        query = self.extract_query(message.clean_content)
        if not query:
            return
        url = self.get_meme(query)
        if not url:
            return

        msg = '**%s**: %s' % (query, url)
        await self.client.send_message(message.channel, msg)

    def extract_query(self, message_text: str) -> str:
        match = QUERY_RE.search(message_text)
        if not match:
            return None

        return match.group(0)

    def get_meme(self, query: str) -> str:
        query = query.lower()
        meme_name, ext = query.split('.', 1)
        mimetype = mimetypes.guess_type(query)[0] or ''

        for meme in MEMES:
            if meme.get('type') and meme['type'] not in mimetype:
                continue

            if meme_name in meme['names']:
                return random.choice(meme['urls'])

        return None

@@ -361,16 +361,51 @@
 _YAML)%0A%0A
+LIST_MEMES_COMMAND = 'list memes'%0A%0A
 class Me
@@ -671,16 +671,178 @@
 e bots%0A%0A
+        if self.client.user.mentioned_in(message) and LIST_MEMES_COMMAND in message.clean_content:%0A            await self.list_memes(message)%0A            return%0A%0A
         
@@ -1679,16 +1679,16 @@
 rls'%5D)%0A%0A
-
         
@@ -1679,28 +1679,829 @@
 rls'%5D)%0A%0A        return None%0A
+%0A    async def list_memes(self, message: discord.Message):%0A        query = message.clean_content.split(LIST_MEMES_COMMAND, 1)%5B1%5D.strip() # type: str%0A        output_lines = %5B%5D%0A        for meme in MEMES:%0A            for name in meme%5B'names'%5D:%0A                if query in name:%0A                    break%0A            else: # query not in any names, skip this meme%0A                continue%0A%0A            output = '- '%0A            if meme.get('type'):%0A                output = '- (%25s) ' %25 meme%5B'type'%5D%0A            output += ', '.join(meme%5B'names'%5D)%0A            output_lines.append(output)%0A%0A        if output_lines:%0A            reply = '%60%60%60' + '%5Cn'.join(output_lines) + '%60%60%60'%0A        else:%0A            reply = '%60No memes found for %22%25s%22%60' %25 query%0A        await self.client.send_message(message.channel, reply)%0A

Add meme listing command