diff --git a/README.md b/README.md index ffcc2b3..87af501 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,7 @@ A simple [maubot](https://github.com/maubot/maubot) that generates a random gif ## Setup 1. Get API key from [giphy](https://developers.giphy.com/docs/) 2. Fill in api_key field in base-config.yaml config file or in online maubot config editor +3. Decide what endpoint to get random gifs from (e.g. trending, random) in config file ## Usage '!giphy word' - Bot replies with a link to a gif given the search term diff --git a/base-config.yaml b/base-config.yaml index 17ff05e..0ba3127 100644 --- a/base-config.yaml +++ b/base-config.yaml @@ -1 +1,4 @@ api_key: API_KEY_HERE +#Uncomment desired source for random gifs +source: trending +#source: random diff --git a/giphy.py b/giphy.py index a4a30f6..d21d2de 100644 --- a/giphy.py +++ b/giphy.py @@ -1,13 +1,16 @@ from typing import Type import urllib.parse +import random from mautrix.util.config import BaseProxyConfig, ConfigUpdateHelper from maubot import Plugin, MessageEvent from maubot.handlers import command +# Setup config file class Config(BaseProxyConfig): def do_update(self, helper: ConfigUpdateHelper) -> None: helper.copy("api_key") + helper.copy("source") class GiphyPlugin(Plugin): @@ -26,13 +29,29 @@ async def handler(self, evt: MessageEvent, search_term: str) -> None: if not search_term: # If user doesn't supply a search term, set to empty string search_term = "" + source = self.config["source"] + else: + source = "translate" + api_key = self.config["api_key"] - url_params = urllib.parse.urlencode({"tag": search_term, "api_key": api_key}) + url_params = urllib.parse.urlencode({"s": search_term, "api_key": api_key}) # Get random gif url using search term async with self.http.get( - "http://api.giphy.com/v1/gifs/random?{}".format(url_params) + "http://api.giphy.com/v1/gifs/{}?{}".format(source, url_params) ) as response: data = await response.json() - gif_link = data.get("data", {}).get("image_url") - await evt.reply(gif_link, html_in_markdown=True) # Reply to user + # Retrieve gif link from JSON response + gif = data.get("data", {}) + gif_exists = True + if isinstance(gif, list): + # check if there were no results + if gif: + gif_link = random.choice(gif).get("url") + else: + gif_exists = False + else: + gif_link = gif.get("url") + + if gif_exists: + await evt.reply(gif_link, html_in_markdown=True) # Reply to user diff --git a/maubot.yaml b/maubot.yaml index 00e7b3f..21f773d 100644 --- a/maubot.yaml +++ b/maubot.yaml @@ -9,7 +9,7 @@ maubot: 0.1.0 id: casavant.tom.giphy # A PEP 440 compliant version string. -version: 1.0.1 +version: 1.0.3 # The SPDX license identifier for the plugin. https://spdx.org/licenses/ # Optional, assumes all rights reserved if omitted.