Giter Club home page Giter Club logo

tenorjs's Introduction

! Important !

TenorJS v1.0.10 includes small patches to ensure the wrapper doesn't break following the release of Tenor's V2 API. TenorJS v2 will be coming soon, until then, please report any issues that arise and I'll try to get to them as soon as possible.

If you get a "couldn't send request" error, it's most likely because you need to get a new API key here.

TenorJS

https://api.travis-ci.org/Jinzulen/TenorJS.svg?branch=master Known Vulnerabilities Scrutinizer Code Quality

CodeFactor Maintainability NPM Weekly Downloads

https://nodei.co/npm/tenorjs.png

TenorJS is a basic NodeJS wrapper around the Tenor API.

This is an unofficial third-party product that isn't in any way affiliated or sponsored by Tenor.

IMPORTANT UPDATE: v1.0.7 is now out! See what's new via this changelog!

1. Installation

TenorJS can be easily installed via NPM: npm i tenorjs.

Alternatively, you can download the ZIP from here and require it in your project.

2. Usage & Guides

  • Attribution: First thing's first, I want to get something out of the way, attribution. To comply with Tenor's own policies, any content pulled from Tenor and published via this library has to be labeled in any one of these ways:
  1. Powered By Tenor - to be used in the GIF browsing experience
  2. Search Tenor - to be used as the placeholder text in the search bar
  3. Via Tenor - to be used in the footer of a shared GIF

Attribution logos are provided by Tenor and can be found in this Dropbox folder. - Tenor's API terms can also be found here.

Alright, now that that's out of the way, let's take a look at some code.

  • Call TenorJS

GIF of an Anime character doing 1337 h4x0r stuff.

  1. First thing we need to do is call TenorJS and initialize it by passing it the necessary configuration parameters, which in this case is, the Tenor developer API key and the necessary filters and locale configuration. You can get the developer API key by signing up for a free developer account here.

  2. Tenor offers a content filter in its API as well, the content filter takes one of these four values: off, low, medium, high. - You can manually configure its level when initializing the library, as demonstrated below.

  3. Tenor offers developers the option to set a custom locale for localization purposes, the locale can be configured when initializing the library (as demonstrated below). -- The full list of supported languages by Tenor's API can be found here.

  4. Tenor also offers developers a way to minimize the number of media types/formats returned with each API response via their media content filter. You can configure the library to use either the basic (nanomp4, tinygif, tinymp4, gif, mp4, and nanogif) or minimal (tinygif, gif, and mp4) media content filters when initializing the client. Keep in mind that if you don't configure it, the library is set to use the minimal filter by default.

  5. In order to alleviate some pressure off of developers and ensure not to inconvenience them by adding one more task to their schedule, native date formatting has been implemented into TenorJS as of v1.0.6! To aid developers further with matters concerning localization, TenorJS allows them to set custom date formats, however, if they don't; TenorJS will by default use the date format shown in the example below.

const Tenor = require("tenorjs").client({
    "Key": "YOUR DEVELOPER KEY HERE", // https://developers.google.com/tenor/guides/quickstart
    "Filter": "off", // "off", "low", "medium", "high", not case sensitive
    "Locale": "en_US", // Your locale here, case-sensitivity depends on input
    "MediaFilter": "minimal", // either minimal or basic, not case sensitive
    "DateFormat": "D/MM/YYYY - H:mm:ss A" // Change this accordingly
});

2.1 Trending:

  • Fetching trending GIFs:
// Tenor.Trending.GIFs("LIMIT HERE")
Tenor.Trending.GIFs("2").then(Results => {
      Results.forEach(Post => {
            console.log(`Item #${Post.id} (${Post.created}) @ ${Post.url}`);
      });
}).catch(console.error);
// Item #11672604 (Created: 19/04/2018 - 7:28:09 PM) @ https://tenor.com/W8JY.gif.
  • Fetching a list of trending search terms:
Tenor.Trending.Terms().then(Results => {
      // Will return an array but for the sake
      // of the example, I joined the results
      // with a comma.
      console.log(Results.join(", "));
}).catch(console.error);
// happy birthday boyfriend, tuesday, karl lagerfeld, lunch, happy birthday girlfriend, yes, waiting for an answer, good afternoon, love ya too, love you, bernie sanders, crushed it, feel the bern, love, bernie, dentist, jonas brothers, excited, full moon, goodday

2.2.a Search:

  • Fetching GIF(s) using specific ID(s):

Notice #1: This function takes up to 50 IDs max.

Notice #2: The IDs object always has to be an array. So Find(["ID"]) not Find("ID").

Tenor.Search.Find(["9411482", "5152678", "12175525"]).then(Results => {
      Results.forEach(Post => {
            console.log(`Item ${Post.id} (Created: ${Post.created}) @ ${Post.url}`);
      });
}).catch(console.error);
// Item #9411482 (Created: 6/08/2017 - 12:12:42 PM) @ https://tenor.com/NEwg.gif
// Item #5152678 (Created: 4/03/2016 - 4:41:07 AM) @ https://tenor.com/vMBS.gif
// Item #12175525 (Created: 16/07/2018 - 14:47:34 PM) @ https://tenor.com/ZfzB.gif
  • Fetching a GIF using a specific keyword:

As of v1.0.6, TenorJS automatically checks the JSON response and replaces an empty title object with "Untitled" when necessary.

// Tenor.search.Query("SEARCH KEYWORD HERE", "LIMIT HERE")
Tenor.Search.Query("hug", "3").then(Results => {
      Results.forEach(Post => {
            console.log(`Item #${Post.id} (Created: ${Post.created}) @ ${Post.url}`);
      });
}).catch(console.error);
// Item #12535134 (Created: 18/09/2018 - 10:04:49 AM) @ https://tenor.com/0K7K.gif
// Item #10383031 (Created: 28/11/2017 - 22:43:48 PM) @ https://tenor.com/RJgp.gif
// Item #12254044 (Created: 31/07/2018 - 8:24:33 AM) @ https://tenor.com/ZzZ2.gif
  • Fetching a list of the available categories or "tags":

As of v1.0.6, you can now choose to specify the type of categories you want to list. The three type options are: trending, featured and emoji.

Tenor.Categories.List("trending").then(Results => {
      Results.forEach(Category => {
            console.log(`- Category Name: ${Category.name}\n- Category Image: ${Category.image}\n- Category Data Path: ${Category.path}\n--------`);
      });
}).catch(console.error);
//- Category Name: #happybirthdayboyfriend
//- Category Image: https://media.tenor.com/images/00b123588ce51ba097861bf2fe936064/tenor.gif
//- Category Data Path: https://api.tenor.com/v1/search?tag=happy%20birthday%20boyfriend&locale=en_US&safesearch=moderate&key=[DEVELOPER KEY]
//--------
//- Category Name: #tuesday
//- Category Image: https://media.tenor.com/images/470d285f0497561fa8d28daee557f0fc/tenor.gif
//- Category Data Path: https://api.tenor.com/v1/search?tag=tuesday&locale=en_US&safesearch=moderate&key=[DEVELOPER KEY]
// [...]
  • Fetching GIFs from a specific category or "tag":

For a list of the available categories/tags, refer yourself to the previous method: Tenor.Categories.List().

// Tenor.Categories.Find("CATEGORY OR TAG HERE", "LIMIT HERE")
Tenor.Categories.Find("excited", "3").then(Results => {
      Results.forEach(Post => {
            console.log(`Item #${Post.id} (Created: ${Post.created}) @ ${Post.url}`);
      });
}).catch(console.error);
// Item #7212866 (Created: 11/11/2016 - 7:53:02 AM) @ https://tenor.com/EqyI.gif
// Item #5878976 (Created: 20/08/2016 - 12:00:54 PM) @ https://tenor.com/yPym.gif
// Item #11207973 (Created: 27/02/2018 - 17:56:51 PM) @ https://tenor.com/VbRV.gif

2.2.b Autocomplete & Search Suggestions

  • Autocompleting the user's input:
// Tenor.Suggest.Autocomplete("SEARCH INPUT")
Tenor.Suggest.Autocomplete("hu").then(Results => {
      console.log(Results);
}).catch(console.error);
// [ 'hug', 'hungry', 'hugs', 'hungover', 'huh', 'hungergames' ]
  • Search suggestions:
// Tenor.Suggest.Suggestions("SEARCH INPUT")
Tenor.Suggest.Suggestions("anime").then(Results => {
      console.log(Results.join(", "));
}).catch(console.error);
// anime kiss, anime love, anime hug, anime sad, anime cry, anime blush, naruto, pokemon

2.3 Random GIF:

  • Fetching random GIFs:
Tenor.Search.Random("food", "3").then(Results => {
      Results.forEach(Post => {
            console.log(`Item ${Post.id} (Created: ${Post.created}) @ ${Post.url}`);
      });
}).catch(console.error);
// Item 7677199 (Created: 31/01/2017 - 20:43:51 PM) @ https://tenor.com/GnlX.gif
// Item 9176226 (Created: 9/07/2017 - 18:59:40 PM) @ https://tenor.com/MFjO.gif
// Item 8448338 (Created: 30/04/2017 - 20:55:24 PM) @ https://tenor.com/JBXG.gif

3. Useful Links

4. Contributors

  • Jin (Find me on Discord @ Jin#8303). @NPM

5. Dependencies

6. Developer's Notes

  • This library is the product of sheer boredom and curiosity, it is released as-is without any guarantees of any kind on my part. I am not responsible for what anyone does with it.
  • If you've made something cool using TenorJS, then feel free to get in touch and I'll include a type of "Integrations" section in this README to give it a spotlight and highlight it to everyone.

7. TO-DO List

  1. Caching.

tenorjs's People

Contributors

jinzulen avatar rianfuro avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

tenorjs's Issues

Unable to visualize GIFs

Description
The GIF does not load when it's requested. (Using DiscordJS)

To Reproduce
Steps to reproduce the behavior:

  1. Import TenorJS
  2. Make a random search
  3. Add the link to the Discord Embed (For example)
  4. Call the embed on Discord
    Expected behavior
    The GIF should be shown on Discord in the embed

Actually, the GIF does not load.
Screenshots
image
The image shows the else statement, but it changes nothing as it's just a copy-paste. (The only one edit is that the embed description is not the username by the mention.
Additional context
Code:

        const tenor = require("tenorjs").client({
            "Key": config.tenor,
            "Filter": "off",
            "Locale": "en_US",
            "MediaFilter": "basic",
            "DateFormat": "D/MM/YYYY - H:mm:ss A"
        });

        if (msg.mentions.users.first()) {
            var user = msg.mentions.users.first();
            if (!msg.guild.member(user)) return msg.channel.send(":x: Cet utilisateur n'est pas sur le serveur !");

            tenor.Search.Random("anime kiss", 1).then(gif => {
                var embed = new discord.MessageEmbed()
                    .setAuthor(msg.author.username, msg.author.avatarURL())
                    .setColor(randomColor())
                    .setDescription(`${msg.author.username} fait un bisou à ${user.username} 😊`)
                    .setImage(gif[0].url)
                    .setTimestamp(new Date())
                    .setFooter("FlamesBot©", bot.user.avatarURL())
                msg.channel.send(embed);
            });
        }

Exception when fetching too much data

Describe the bug
When a query is issued with a high enough limit, the library throws the following exception:

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at IncomingMessage.<anonymous> (/<snip>/node_modules/tenorjs/src/Tools/Utilities.js:52:38)
    at IncomingMessage.emit (events.js:314:20)
    at IncomingMessage.Readable.read (_stream_readable.js:513:10)
    at flow (_stream_readable.js:986:34)
    at resume_ (_stream_readable.js:967:3)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)

Judging from the underlying code, the problem seems to be that the library is expecting to receive the full response at once. However, with a high enough limit the response will be too big and will not be received in full by the first data event, causing the JSON parser to fail

To Reproduce
Steps to reproduce the behavior:

  1. Call tenor.Search.Query with a high limit (50 in my tests was more than high enough, happened with as low as 20)
    await tenor.Search.Query('meme', 50), as an example

Expected behavior
Library should not break because the response is too large

Additional information
My config, for what it's worth:

const tenor = require("tenorjs").client({
  Key: keys.tenor,
  Filter: "off",
  Locale: "en_US",
  MediaFilter: "minimal",
  DateFormat: 'YYYY-MM-DD - hh:mm:ss'
});

Tenor gives me no gifs. Just a poop image instead

errortenor
everything's alright. No error no nothing at all. but when I embed this tenor API gifs. It shows me this instead of choosing a random gif and giving it to me. Someone solve it
am getting this type of error when i used the tenor api. Is there any fix? please tell me. I am in need of this..please

how to find Post.media.gif ?

Hello dear creator!
I'm gonna ask you to help me with something I can't do.
My problem is: we pull the post from the results. media in post. I want to pull the gif to media but after "post.media" I can't pull the [objects] in it.

1-Tenor.Search.Random("anime hug", "1").then(Results => { Results.forEach(Post => {
2-var mediax = Post.media okey we see console.log then see medias but
3- var gif = mediax.gif finally wee saw error or undefined
i saw undefined.

Can you help me with how? Is there a mistake in me I wasn't sure?

Screenshots
Adsız
Adsız2

SyntaxError: Unexpected end of JSON input

Describe the bug
"SyntaxError: Unexpected end of JSON input" returned after queries

To Reproduce
Steps to reproduce the behavior:
Using the tenorjs client while filter is set on high and locale is set to en_US some API queries will return an "Unexpected end" of the JSON Input.
This seems to occur whenever I am calling queries in quick succession but the query term that has always replicated this issue is "lol", which works fine on the tenor website but creates this error within using the API.

Screenshots
image

Additional context
I'm using handlebars, nodemon, and express for this as part of a class project.
1.0.7 is the version I am using.

TenorJS can't find the configuration file.

An error will appear on an app's first run using TenorJS v1.0.6 with the following error message: Error: Cannot find module '../../tenor_config.json'.

Describe the bug
TenorJS can not locate the configuration file it's supposed to create on its first run or when the client's configuration parameters (developer key, etc) have been modified.

To Reproduce
Steps to reproduce the behavior:

  1. Upgrade to TenorJS v1.0.6/Download TenorJS v1.0.6.
  2. Configure the client by setting the necessary configuration parameters (developer key, etc).
  3. Call any function whatsoever (Trending terms, GIFs by IDs, etc) and run the app.
  4. App crashs with the message Error: Cannot find module '../../tenor_config.json'.

Expected behavior
TenorJS creates a configuration based on the configuration keys a user has set for the client (developer key, content and media filter level, etc), followed directly by the summoned function resolving as intended and returning whichever result the user expects (GIFs, trending terms, autocomplete, etc).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.