async def _hug(ctx: SlashContext, user): if user == ctx.author: await ctx.send("I´ll hug you, " + user.name + " ❤") api_key = "FYnnroJUfSDgDB2fGpZX4EQhLq9g3bDu" api_instance = giphy_client.DefaultApi() api_response = api_instance.gifs_search_get(api_key, 'anime hug', limit=100, rating='g') lst = list(api_response.data) giff = random.choice(lst) if giff == 'https://media.giphy.com/media/FT2Xc3nUTYCQ0/giphy.gif': return if giff == 'https://media.giphy.com/media/ddk1FDgb2AHSw/giphy.gif': return if giff == 'https://media.giphy.com/media/45Lg3ECIw25Fe/giphy.gif': return if giff == 'https://media.giphy.com/media/Z7x24IHBcmV7W/giphy.gif': return emb = discord.Embed( title=f"{client.user.name} hugs {user.name} :white_heart:", color=0xfffffa) emb.set_image(url=f'https://media.giphy.com/media/{giff.id}/giphy.gif') await ctx.send(embed=emb) else: api_key = "FYnnroJUfSDgDB2fGpZX4EQhLq9g3bDu" api_instance = giphy_client.DefaultApi() api_response = api_instance.gifs_search_get(api_key, 'anime hug', limit=100, rating='g') lst = list(api_response.data) giff = random.choice(lst) if giff == 'https://media.giphy.com/media/FT2Xc3nUTYCQ0/giphy.gif': return if giff == 'https://media.giphy.com/media/ddk1FDgb2AHSw/giphy.gif': return if giff == 'https://media.giphy.com/media/45Lg3ECIw25Fe/giphy.gif': return emb = discord.Embed( title=f"{ctx.author.name} hugs {user.name} :white_heart:", color=0xfffffa) emb.set_image(url=f'https://media.giphy.com/media/{giff.id}/giphy.gif') await ctx.send(embed=emb)
def find_details_of_image_by_id(): ''' Returns details about one gif image speficied by id. The information are represented as dictionaries. For example, the results for find_details_of_image_by_id with id 'mCRJDo24UvJMA' would be: {'frames': '4', 'height': '362', 'mp4': 'https://media2.giphy.com/media/mCRJDo24UvJMA/giphy.mp4', 'mp4_size': '30656', 'size': '78285', 'url': 'https://media2.giphy.com/media/mCRJDo24UvJMA/giphy.gif', 'webp': 'https://media2.giphy.com/media/mCRJDo24UvJMA/giphy.webp', 'webp_size': '99552', 'width': '500'} ''' api_instance = giphy_client.DefaultApi() api_key = 'zU47hZF9SKUIc9AtzAhp4sWSZQudHAsU' # str | Giphy API Key. gif_id = sys.argv[2] try: # Get GIF by ID Endpoint api_response = api_instance.gifs_gif_id_get(api_key, gif_id) pprint(api_response.data.images.original) except ApiException as e: print("Exception when calling DefaultApi->gifs_gif_id_get: %s\n" % e)
def random_gif(self, req: str): api_instance = giphy_client.DefaultApi() #api_key = 'XPY9nG1Z28Ypu2mK8wrHGEzC8UAZW1Ts' api_response = api_instance.gifs_search_get(self.giphy_key, req.strip(), lang='ru') data = api_response.data result = choice(data) return result.images.original.url
def gifUrl(): # create an instance of the API class api_instance = giphy_client.DefaultApi() api_key = 'iJKajUqoVS09YBIEgUFcEUdj4ceh0XX0' # str | Giphy API Key. limit = 1 # int | The maximum number of records to return. (optional) (default to 25) rating = 'g' # str | Filters results by specified rating. (optional) fmt = 'json' # str | Used to indicate the expected response format. Default is Json. (optional) (default to json) try: # Trending GIFs Endpoint gifType = ['gif', 'sticker'] choice = random.choice(gifType) # decide se é gif ou sticker if choice == 'gif': url = api_instance.gifs_random_get( api_key, rating=rating, fmt=fmt).data.fixed_height_downsampled_url # para gifs normais else: url = api_instance.stickers_random_get( api_key, rating=rating, fmt=fmt).data.fixed_height_downsampled_url # para stickers # print(api_response) return (url, choice) except ApiException as e: print("Exception when calling DefaultApi->gifs_trending_get: %s\n" % e)
def __init__(self, client): self.client = client self.reddit = praw.Reddit(client_id='id', client_secret='secret', user_agent='user') self.giphy_token = "token" self.api_instance = giphy_client.DefaultApi()
def handler(event, context): api_key = os.environ.get('giphy_api_key') gif_width = int(os.environ.get('gif_width', '800')) tag = os.environ.get('giphy_tag', 'vaporwave') api_intance = giphy_client.DefaultApi() try: random_gif = api_intance.gifs_random_get(api_key, tag=tag) gif_id = random_gif.data.id width = int(random_gif.data.image_width) scale_ratio = gif_width / width width = int(width * scale_ratio) height = int(int(random_gif.data.image_height) * scale_ratio) except ApiException: gif_id = os.environ.get('default_gif_id', '3oz8xZ1t7hxPfe19M4') width = gif_width height = gif_width embed_url = f'https://giphy.com/embed/{gif_id}' return { 'statusCode': 200, 'headers': { 'Content-Type': 'text/html' }, 'body': utils.get_html(embed_url, width, height) }
def gifsearch(): """De gebruiker kan gifs zoeken.""" # Als de gebruiker via POST kwam. if request.method == "POST": gifsearch = request.form.get("searchgif") if len(gifsearch) == 0: return apology("Fill in a keyword!") model.key() api_key = os.environ.get("API_KEY") # Geeft de API key mee. api_instance = giphy_client.DefaultApi() q = gifsearch limit = 15 # Returned de gifs. try: api_response = api_instance.gifs_search_get(api_key, q, limit=limit) return render_template("gif.html", api_response=api_response) except ApiException as e: return apology ("No gifs selected") # Als de gebruiker via GET de route bereikt heeft. else: return redirect(url_for("homepage"))
async def _meme(self, ctx, *, query): """Get the perfect GIF using GIPHY's special sauce algorithm Uses GIPHY's [translate endpoint](https://developers.giphy.com/docs/api/endpoint#translate) """ api_instance = giphy_client.DefaultApi() api_key = self._config['giphy']['api-key'] try: api_response = api_instance.gifs_translate_get(api_key, query) if api_response.data.url is not None and len( api_response.data.url) != 0: # embed = discord.Embed() # embed.set_image(url=api_response.data.embed_url) msg = f'{ctx.message.author.mention} here\'s your {query} meme, you {Insult.random()}: {api_response.data.url}' await ctx.send(msg) else: msg = f'#rule34fail {ctx.message.author.mention}' await send_as_embed(ctx.send, msg) except ApiException as e: print( f'Exception when calling DefaultApi->gifs_translate_get with query [{query}]: {e}\n' ) msg = 'something went wrong' await send_as_embed(ctx.send, msg)
def index(): gifs = [] error = None search = request.args.get("search", "") try: offset = int(request.args.get("offset", "0")) except ValueError: error = "Invalid offset" if offset < 0: error = "Invalid offset" if error: flash(error) elif search != "": try: giphy = giphy_client.DefaultApi() giphy_key = current_app.config["GIPHY_KEY"] # TODO: Make this async resp = giphy.gifs_search_get(giphy_key, search, limit=6, offset=offset, rating="g", lang="en", fmt="json") gifs = resp.data current_app.logger.info(gifs[0]) except Exception as e: current_app.logger.error("Error loading gifs from giphy: %s" % e) return abort(500) return render_template("search/index.html", gifs=gifs, search=search, offset=offset)
def main(IMAGE): app = ClarifaiApp() model = app.public_models.general_model if 'http' in IMAGE: response = response_from_url(model, IMAGE) else: if os.path.isfile(IMAGE): response = response_from_file(model, IMAGE) else: return pd.DataFrame({}) concepts = {concept['name']: concept['value'] for concept in response} api_instance = giphy_client.DefaultApi() query = '' for concept in concepts: query = query + concept + ' ' print 'QUERY: %s' % query giflist = GIFS_from_query(query, api_instance) giflist = [gif.images.downsized.url for gif in giflist] concepts = pd.DataFrame.from_dict(concepts, orient='index').reset_index() concepts = clean_concepts(concepts) concepts['tempkey'] = 1 ranked_gifs = {url: get_metric(url, model, concepts) for url in giflist} ranked_gifs = pd.DataFrame.from_dict( ranked_gifs, orient='index').sort_values(by=0, ascending=False) return ranked_gifs
def sms_reply(): api_instance = giphy_client.DefaultApi() api_key= 'W5yCq7xTGzQ3e' body = request.values.get('Body', None) resp = MessagingResponse() if body == 'dog' or body == 'Dog' or body == 'cat' or body == 'Cat': number = request.values.get('From', None) msg = "" if number in numbers: numbers[number] += 1 else: numbers[number] = 1 if numbers[number] % 3 == 0: n = random.randint(0,5) msg += "ACC (Animal Care Centers of NYC) is an organization that helps homless and abandoned animals, including dogs and cats. In 2017, " + stats[n] + " Please help us by visiting our website and donating." tag = body api_response = api_instance.gifs_random_get(api_key, tag=tag) url = api_response.data.url msg = url + "\n" + msg resp.message(msg) else: resp.message("Would you like a dog gif or a cat gif? Please respond with 'dog' or 'cat'") return str(resp)
def __init__(self, tag, format='json', rating='g'): self.tag = tag self.rating = rating self.format = format self.apiInstance = giphy_client.DefaultApi() self.apiKey = 'pIxY5SeVYIdXrIxsIFqQnpZMRPesMZux' self.logFile = 'sentGifs.txt'
def handler(event=None, context=None): api_key = os.environ['GIPHY_API_KEY'] giphy_api = giphy_client.DefaultApi() query = 'back to the future' lang = 'en' fmt = 'json' gif_url = "" api_resp = giphy_api.gifs_search_get(api_key, query, limit=50, offset=0, rating='g', lang=lang, fmt=fmt) random_int = random.randint(0, 49) gif_url = api_resp.data[random_int].images.downsized_large.url body_text = gen_html_body(gif_url) print gif_url response = { "statusCode": 200, "headers": { 'Content-type': 'text/html', 'Cache-Control': 'no-store, no-cache, must-revalidate', }, "body": body_text, } return response
async def _random_meme(self, ctx, *, query=None): """Get a random GIF. query is optional Uses GIPHY's [random endpoint](https://developers.giphy.com/docs/api/endpoint#random) """ api_instance = giphy_client.DefaultApi() api_key = self._config['giphy']['api-key'] try: api_response = api_instance.gifs_random_get(api_key, tag=query) if api_response.data.url is not None and len( api_response.data.url) != 0: msg = f'{ctx.message.author.mention} here\'s your random{" "+ query if query is not None else ""} meme, you {Insult.random()}: {api_response.data.url}' await ctx.send(msg) else: print( f'No URL in response when calling DefaultApi->gifs_random_get' ) msg = f'I done goofed {ctx.message.author.mention}... try again' await send_as_embed(ctx.send, msg) except ApiException as e: print(f'Exception when calling DefaultApi->gifs_random_get: {e}\n') msg = 'something went wrong' await send_as_embed(ctx.send, msg)
def get_giphy(tag): # create an instance of the API class api_instance = giphy_client.DefaultApi() api_key = get_giphy_key() # str | Giphy API Key. q = tag limit = 25 offset = 0 rating = 'g' lang = 'en' fmt = 'json' try: # Search Endpoint api_response = api_instance.gifs_search_get(api_key, q, limit=limit, offset=offset, rating=rating, lang=lang, fmt=fmt) except ApiException as e: print("Exception when calling DefaultApi->gifs_search_get: %s\n" % e) data = api_response.to_dict() return data['data'][0]['url']
def index(): """Application index""" # Load environment variables load_dotenv() application_name = os.environ.get("YOLO_APP_NAME", "Yolo cat") header_bg_color = os.environ.get("YOLO_HEADER_BG_COLOR", "red") header_color = os.environ.get("YOLO_HEADER_COLOR", "white") api_key = os.environ.get("YOLO_GIPHY_API_KEY") client = giphy_client.DefaultApi() gif_id = None errors = [] try: response = client.gifs_random_get(api_key, tag=application_name, rating="g", fmt="json") gif_id = response.data.id except giphy_client.rest.ApiException as err: logging.error("An exception occurred while calling Giphy API: %s\n" % err) errors.append(json.loads(err.body).get("message")) return render_template( "index.html", header_bg_color=header_bg_color, header_color=header_color, application_name=application_name, gif_id=gif_id, errors=errors, )
def index(): gifs = [] error = None more = True try: offset = int(request.args.get("offset", "0")) except ValueError: error = "Invalid offset" if offset < 0: offset = 0 gif_ids = db.get_starred_gifs(g.user["id"], 7, offset) if len(gif_ids) < 7: # There are no more items to load more = False else: # We only want the first 6 gif_ids = gif_ids[:-1] for gif_id in gif_ids: try: giphy = giphy_client.DefaultApi() giphy_key = current_app.config["GIPHY_KEY"] # TODO: do this async resp = giphy.gifs_gif_id_get(giphy_key, gif_id) gifs.append(resp.data) except Exception as e: current_app.logger.error("Error loading gif from giphy: %s" % e) return abort(500) return render_template("star/index.html", gifs=gifs, offset=offset, more=more)
def gif(message, param): api_instance = giphy_client.DefaultApi() try: api_key = config.bot['giphy']['api_key'] rating = config.bot['giphy']['rating'] lang = config.bot['giphy']['lang'] except: common.send_message('Failed to get giphy configurationn') q = param limit = 1 offset = 0 fmt = 'json' try: # Search Endpoint api_response = api_instance.gifs_search_get( api_key, q, limit=limit, offset=offset, rating=rating, lang=lang, fmt=fmt, ) pprint(api_response.data) common.send_message('*' + q + '*', api_response.data[0].images.original.url) except(ApiException, e): print('Exception when calling DefaultApi->gifs_search_get: %s\n' \ % e)
def getTrending(): default_return_obj = { 'query': 'kittens', 'timestamp': 0, 'embed_url': ['https://giphy.com/embed/DBucugVBKhvTW'] } try: # create an instance of the Giphy API class api_instance = giphy_client.DefaultApi() api_key = config.api_key # str | Giphy API Key. api_response = api_instance.gifs_trending_get(api_key) embedUrls = [] # Loop through gifs and create array of embed urls for elem in api_response.data: embedUrls.append(elem.embed_url) data = {} data['embed_url'] = embedUrls data['query'] = 'Trending' data['timestamp'] = time.time() pprint.pprint(data) return (data) except ApiException as e: print("Exception when calling DefaultApi->gifs_search_get: %s\n" % e) return (default_return_obj) except IndexError as e: print('empty response from giphy returned %s\n' % e) return (default_return_obj)
async def gif(self, token, args, msg): api_instance = giphy_client.DefaultApi() api_response = api_instance.gifs_search_get(token, args.replace(" ", "+"), limit=15, lang='en', fmt='json') await msg.channel.send( random.choice([d.images.original.url for d in api_response.data]))
def get_giphy( q, # str | Search query term or prhase. api_key="dc6zaTOxFJmzC", # str | Giphy API Key. limit=1, # int | The maximum number of records to return. (optional) (default to 25) offset=0, # int | An optional results offset. Defaults to 0. (optional) (default to 0) rating="g", # str | Filters results by specified rating. (optional) lang="en", # str | Specify default country for regional content; use a 2-letter ISO 639-1 country code. See list of supported languages <a href = \"../language-support\">here</a>. (optional) fmt="json", ): try: api_instance = giphy_client.DefaultApi() # Search Endpoint api_response = api_instance.gifs_search_get(api_key, q, limit=limit, offset=offset, rating=rating, lang=lang, fmt=fmt) results = api_response.to_dict()["data"] if results: first_result_id = results[0]["id"] return "https://media.giphy.com/media/{}/giphy.gif".format( first_result_id) else: return "" except ApiException as e: print("Exception when calling DefaultApi->gifs_search_get: %s\n" % e) return ""
def giphy(rating): api_instance = giphy_client.DefaultApi() try: api_response = api_instance.gifs_random_get( deserialize('giphy-key'), rating=rating, fmt='json') return api_response.data.image_url except ApiException as e: print(f'Exception when calling DefaultApi->gifs_search_get: {e}')
def search_giphy(search_string): api_key = '0HFudAoHZusm36vnycTndAskLN1uIeQJ' giphy = giphy_client.DefaultApi() try: api_response = giphy.gifs_search_get(api_key, search_string, limit=1) return api_response.data[0].images.original.url except ApiException as e: print("Exception when calling DefaultApi->gifs_search_get: %s\n" % e)
async def im(self, ctx, channel_id: int, message_id: int): channel = self.bot.get_channel(channel_id) if channel is not None: try: message = await channel.fetch_message(message_id) for i in range( len(message. content[message.content.lower().index("i'm") + 3:].split("."))): im = message.content[message.content.lower().index("i'm") + 3:].split(".")[i] print("*" + im + "*") if not re.compile("^\s*$").match(im): print("breaking") break delete_after = 60 await message.reply( f"Hi{im}, I'm Bjørn! Have you heard about Viking Rally?") if message.guild.id == 689381329535762446 and \ message.guild.get_role(699975448263786558) in message.author.roles: # Viking Rally role await message.channel.send( "Oh yeah, of course you do, you're helping organise it! Anyhow, no time " "like the present for some promotion.", delete_after=delete_after) if not (datetime.now().month == 2 and datetime.now().year == 2021): await self.info(message.channel, delete_after=delete_after) # torments Nathan if message.author.id == int(os.getenv("DISCORD_ID_NATHAN")): nathan = self.bot.get_user( int(os.getenv("DISCORD_ID_NATHAN"))) try: query = "mwahahaha" gifs = giphy_client.DefaultApi().gifs_search_get( os.getenv("GIPHY_TOKEN"), query, limit=10, rating='g') lst = list(gifs.data) gif = random.choices(lst)[0].url await nathan.send(gif) await nathan.send(file=File("GIPHY.gif")) except ApiException as e: return f"Exception when calling DefaultApi->gifs_search_get: {e}\n" except errors.NotFound: ctx.send(f"Unable to find message with ID {message_id}.") except errors.Forbidden: await ctx.send( f"Unfortunately I can't send stuff to {channel.name} :cry:" ) else: ctx.send(f"Unable to find channel with ID {channel_id}.")
def __init__(self, base_url=__BASE_URL, api_key=__api_key): self.base_url = base_url self.api_key = api_key self.api_instance = giphy_client.DefaultApi() self.fmt = 'json' self.lang = 'en' self.limit = 10 self.offset = 0 self.rating = 'g' self.result_list = []
def download_random_gif(tags): giphy_api = giphy_client.DefaultApi() open(const.GIF_FILE_NAME, "w") gif_url = (giphy_api.gifs_search_get(environ["GIPHY_API_KEY"], random.choice(tags), limit=3, offset=3, fmt="json").data[random.choice( range(3))].images.original.url) urllib.request.urlretrieve(gif_url, const.GIF_FILE_NAME)
def giphy(tag): api_instance = giphy_client.DefaultApi() api_key = open(".giphy-api-key.txt", "r").read().rstrip() fmt = 'json' rating = 'g' try: api_response = api_instance.gifs_random_get(api_key, tag=tag, rating=rating, fmt=fmt) return api_response.data.image_url except ApiException as e: print("Exception when calling DefaultApi->gifs_search_get: %s\n" % e)
def search(term: str = '', key: str = '', limit: int = 1, rating: str = 'g', lang: str = 'en') -> dict: ''' Search for gifs on Giphy Parameters ---------- key: Client private key term: Search term limit: Limit of resources rating: Results by specified rating lang: Language for regional content Usage ----- >>> search(key='', term='') Return ------ Dict containing gif data ''' if term == '' or key == '': raise Exception( 'Couldn\'t find the {0}key{1} or the {0}term{1}'.format( '\033[31m', '\033[37m')) response = giphy.DefaultApi().gifs_search_get(key, term, limit=limit, rating=rating, lang=lang) try: if response.meta.status == 200: return response.to_dict() return {} except Exception as e: raise Exception(str(e))
def giphy_search(giphy_query): giphy_api_key = '4KDg2aAkejtT7elNuhrVqF4ArlKMi6wO' rating = 'r' limit = 1 api_instance = giphy_client.DefaultApi() msg = api_instance.gifs_search_get( giphy_api_key, giphy_query, limit=limit, rating=rating).data[0].images.original.url # post_image(msg) post_message(msg)
async def find_gif(self, query): try: giphy_token = 'TOKEN' api_instance = giphy_client.DefaultApi() response = api_instance.gifs_search_get(giphy_token, query, limit=50, rating='g') lst = list(response.data) gif = random.choices(lst) return gif[0].url except ApiException as e: return "Exception when calling DefaultApi->gifs_search_get: %s\n" % e