Last active
December 10, 2018 02:37
-
-
Save ignacio-chiazzo/aeb2337e416ac326503b86833f6dd0fc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pylint: disable-msg=too-many-arguments | |
from urllib.parse import urlencode | |
import requests | |
class GiphyApiException(Exception): | |
pass | |
class Giphy: | |
API_ENDPOINT = 'http://api.giphy.com/v1/gifs' | |
NOT_FOUND = 'https://media.giphy.com/media/11gZBGuDnYwdpu/giphy.gif' | |
API_KEY = '<API_KEY>' # FIX ME: Add me to hidden file | |
def translate(self, terms=None, prefix=None): | |
# Given terms return the image related to that terms and GOT | |
assert terms, 'You must provide terms' | |
if prefix: | |
terms += terms | |
params = {'s': terms} | |
return self.__fetch('translate', **params) | |
def search(self, terms, prefix="", limit=32, offset=32, | |
rating="g", lang="en", fmt="json"): | |
# Replicates the search found on GIPHY. | |
assert terms, 'You must provide terms' | |
if prefix: | |
terms += terms | |
params = {'q': terms, limit: limit, offset: offset, | |
rating: rating, lang: lang, fmt: fmt} | |
return self.__fetch('search', **params) | |
def trending(self, limit=32, offset=32, rating="g", fmt="json"): | |
# Pulls in the best GIFs from around the internet, | |
# hand curated by the GIPHY editorial team. | |
params = {limit: limit, offset: offset, rating: rating, fmt: fmt} | |
return self.__fetch('trending', **params) | |
def random(self, tag, rating="g", fmt="json"): | |
# returns a single random GIF, optionally limited to a specified tag. | |
assert tag, 'You must provide a tag' | |
params = {tag: tag, rating: rating, fmt: fmt} | |
return self.__fetch('random', **params) | |
def get_gif_by_id(self, gif_id): | |
assert gif_id, 'You must provide a gif id' | |
return self.__fetch(gif_id) | |
@staticmethod | |
def got_terms(text): | |
# Append the word GOT with the text passed by | |
return "Game-of-thrones-" + text.replace(' ', '-') | |
# private | |
def __fetch(self, method=None, **params): | |
# Given the method and params execute the request to giphy | |
url = self.__url(method) | |
try: | |
resp = requests.get(url, params=params) | |
resp.raise_for_status() | |
resp = resp.json() | |
if 'data' in resp and 'embed_url' in resp['data']: | |
return resp['data'] | |
return {'error': "Something went wrong. Please try again later."} | |
except requests.exceptions.HTTPError as e: | |
# FIX ME: Log exception | |
print(e) | |
return {'error': str(e)} | |
def __url(self, method): | |
url = self.API_ENDPOINT + "/" + method | |
return url + urlencode({'?api_key': self.API_KEY}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment