Skip to content

Commit

Permalink
Merge pull request #5 from williamkray/PR-v1.1.2
Browse files Browse the repository at this point in the history
Clean up code a bit, and introduce upload functionality
  • Loading branch information
TomCasavant authored Dec 17, 2020
2 parents 0006574 + bfa41bb commit ad85bbb
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 20 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ A simple [maubot](https://github.com/maubot/maubot) that generates a random gif
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
4. Choose a response type:
- message will send a regular message to the room
- reply will send a quoted reply message to the room
- upload will actually upload the GIF as an image to the room


## Usage
'!giphy word' - Bot replies with a link to a gif given the search term
Expand Down
9 changes: 6 additions & 3 deletions base-config.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
api_key: API_KEY_HERE
#Uncomment desired source for random gifs
# can be either trending or random
# note: this is only used when no query is passed!
source: trending
#source: random
#Uncomment desired response type, either a quoted reply or just a new message
# desired response type:
# message: regular message containing url to gif
# reply: reply-message containing url to gif
# upload: image upload to the room
response_type: message
#response_type: reply
52 changes: 36 additions & 16 deletions giphy.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from typing import Type
import urllib.parse
import random
from mautrix.types import RoomID, ImageInfo
from mautrix.util.config import BaseProxyConfig, ConfigUpdateHelper
from maubot import Plugin, MessageEvent
from maubot.handlers import command
Expand All @@ -19,6 +20,24 @@ async def start(self) -> None:
await super().start()
self.config.load_and_update()

async def send_gif(self, room_id: RoomID, gif_link: str, query: str, info: dict) -> None:
resp = await self.http.get(gif_link)
if resp.status != 200:
self.log.warning(f"Unexpected status fetching image {url}: {resp.status}")
return None

data = await resp.read()
mime = info['mime']
filename = f"{query}.gif" if len(query) > 0 else "giphy.gif"
uri = await self.client.upload_media(data, mime_type=mime, filename=filename)

await self.client.send_image(room_id, url=uri, file_name=filename,
info=ImageInfo(
mimetype=info['mime'],
width=info['width'],
height=info['height']
))

@classmethod
def get_config_class(cls) -> Type[BaseProxyConfig]:
return Config
Expand All @@ -44,20 +63,21 @@ async def handler(self, evt: MessageEvent, search_term: str) -> None:
data = await response.json()

# 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:
if response_type == "message":
await evt.respond(gif_link, allow_html=True) # Respond to user
else:
await evt.reply(gif_link, allow_html=True) # Reply to user
try:
gif_link = data['data']['images']['original']['url']
info = {}
info['width'] = data['data']['images']['original']['width']
info['height'] = data['data']['images']['original']['height']
info['mime'] = 'image/gif' # this shouldn't really change
except Exception as e:
await evt.respond("sorry, i'm drawing a blank")
return None

if response_type == "message":
await evt.respond(gif_link, allow_html=True) # Respond to user
elif response_type == "reply":
await evt.reply(gif_link, allow_html=True) # Reply to user
elif response_type == "upload":
await self.send_gif(evt.room_id, gif_link, search_term, info) # Upload the GIF to the room
else:
await evt.respond("something is wrong with my config, be sure to set a response_type")
2 changes: 1 addition & 1 deletion maubot.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ maubot: 0.1.0
id: casavant.tom.giphy

# A PEP 440 compliant version string.
version: 1.0.5
version: 1.1.2

# The SPDX license identifier for the plugin. https://spdx.org/licenses/
# Optional, assumes all rights reserved if omitted.
Expand Down

0 comments on commit ad85bbb

Please sign in to comment.