Skip to content

Commit

Permalink
Merge pull request #7 from NicolasDerumigny/master
Browse files Browse the repository at this point in the history
Adding support for Tenor Gif Keyboard
  • Loading branch information
TomCasavant authored Oct 16, 2021
2 parents f09f544 + ab94fc1 commit 6cdb5cc
Show file tree
Hide file tree
Showing 5 changed files with 94 additions and 42 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*.mbp
*.tar
18 changes: 10 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@
A simple [maubot](https://github.com/maubot/maubot) that generates a random gif given a search term.

## 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
1. Get API key from [giphy](https://developers.giphy.com/docs/) and [tenor](https://tenor.com/gifapi)
2. Fill in `giphy_api_key` and `tenor_api_key` field in base-config.yaml config file or in online maubot config editor
3. Decide what (giphy) 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
- `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
'!giphy' - Bot replies with a link to a random gif
`!gif word` - Bot replies with a link to a gif given the search term
`!gif` - Bot replies with a link to a random gif

Also, `!giphy`, `!g` and `!tenor` may be used.
11 changes: 9 additions & 2 deletions base-config.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
api_key: API_KEY_HERE
#Uncomment desired source for random gifs
giphy_api_key: API_KEY_HERE
tenor_api_key: API_KEY_HERE
# Source of the gifs, can be either giphy or tenor
provider: tenor
# Number of results of the query in which the gif
# is randomly chosen. Set 1 for the top result.
# (tenor-only option)
num_results: 1
# Uncomment desired source for random gifs on giphy
# can be either trending or random
# note: this is only used when no query is passed!
source: trending
Expand Down
103 changes: 72 additions & 31 deletions giphy.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,39 +10,49 @@
# Setup config file
class Config(BaseProxyConfig):
def do_update(self, helper: ConfigUpdateHelper) -> None:
helper.copy("api_key")
helper.copy("giphy_api_key")
helper.copy("tenor_api_key")
helper.copy("provider")
helper.copy("source")
helper.copy("response_type")
helper.copy("num_results")


class GiphyPlugin(Plugin):
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:
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']
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']
))
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

@command.new("giphy")
@command.new(
"giphy",
aliases=("gif", "g", "tenor"),
)
@command.argument("search_term", pass_raw=True, required=False)
async def handler(self, evt: MessageEvent, search_term: str) -> None:
await evt.mark_read()
Expand All @@ -53,31 +63,62 @@ async def handler(self, evt: MessageEvent, search_term: str) -> None:
else:
source = "translate"

api_key = self.config["api_key"]
url_params = urllib.parse.urlencode({"s": search_term, "api_key": api_key})
response_type = self.config["response_type"]
# Get random gif url using search term
async with self.http.get(
"http://api.giphy.com/v1/gifs/{}?{}".format(source, url_params)
) as response:
data = await response.json()
if self.config["provider"] == "giphy":
api_key = self.config["giphy_api_key"]
url_params = urllib.parse.urlencode({"s": search_term, "api_key": api_key})
response_type = self.config["response_type"]
# Get random gif url using search term
async with self.http.get(
"http://api.giphy.com/v1/gifs/{}?{}".format(source, url_params)
) as response:
data = await response.json()

# Retrieve gif link from JSON response
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
# Retrieve gif link from JSON response
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("Blip bloop... Something is wrecked up here!")
return None

elif self.config["provider"] == "tenor":
api_key = self.config["tenor_api_key"]
url_params = urllib.parse.urlencode({"q": search_term, "key": api_key})
response_type = self.config["response_type"]
# Get random gif url using search term
async with self.http.get(
"https://g.tenor.com/v1/search?{}".format(url_params)
) as response:
data = await response.json()

# Retrieve gif link from JSON response
try:
image_num = random.randint(0, self.config["num_results"] - 1)
gif_link = data["results"][image_num]["media"][0]["gif"]["url"]
info = {}
info["width"] = data["results"][image_num]["media"][0]["gif"]["dims"][0]
info["height"] = data["results"][image_num]["media"][0]["gif"]["dims"][
1
]
info["mime"] = "image/gif" # this shouldn't really change
except Exception as e:
await evt.respond("Blip bloop... Something is wrecked up here!")
return None
else:
raise (Exception("Wrong provider:", self.config["provider"]))

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
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")
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: 2.0.0
version: 3.0.1

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

0 comments on commit 6cdb5cc

Please sign in to comment.