Commit fc5a8b23 authored by Otthorn's avatar Otthorn 🤔

put gif bot in seperate file and clean up

parent 996df4b3
import random
import json
from urllib.request import urlopen
from urllib.parse import quote_plus
import configparser
from log_time import log_time
from matrix_bot_api.matrix_bot_api import MatrixBotAPI
from matrix_bot_api.mcommand_handler import MCommandHandler
def gif_search(query, api_key, limit):
query = quote_plus(query) # make the query browser compliant
data = json.loads(urlopen(""+query+"&api_key="+api_key+"&limit="+limit).read())
random_id = random.randint(0, int(limit) -1 )
id = data['data'][random_id]['id']
url_gif = ""+id+"/giphy.gif"
mime = "image/gif" # mime type of the image
data_bytes = urlopen(url_gif).read()
return data_bytes, mime
class MyMatrixBotAPI(MatrixBotAPI):
def __init__(self, username, password, server, api_key, limit, rooms=None):
super().__init__(username, password, server, rooms=None)
self.api_key = api_key
self.limit = limit
def gif_callback(self, room, event):
args = event['content']['body'].split()
query = " ".join(args[1:])
print("[{}] GIF called with query={} in room={}".format(log_time(), query, room.display_name))
data, mime = gif_search(query, self.api_key, self.limit)
mxc_url = self.client.upload(data, mime)
room.send_image(mxc_url, query, mimetype=mime)
def main():
# Load the configuration
config = configparser.ConfigParser()"config.ini")
username = config.get("Gif", "username")
password = config.get("Gif", "password")
server = config.get("Gif", "server")
api_key = config.get("Gif", "api_key")
limit = config.get("Gif", "limit")
# Start bot
bot = MyMatrixBotAPI(username, password, server, api_key, limit)
# Created handler
gif_handler = MCommandHandler("gif", bot.gif_callback)
# Start polling
print("gif_bot started")
while True:
if __name__ == "__main__":
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment