Alexiscool
Alexiscool

Reputation: 13

Embed Tenor link with discord.py

How do I get the direct .gif link from a tenor shareable view link? Because I want a user to be able to give the bot a shareable view link, which would then be put into an embed. If I need to use the tenor API for that could anyone show me how?

@client.command()
async def gifembed(ctx, link):
    embed=discord.Embed(title="Here's your embed", color=0xb0ff70)
    embed.set_image(url=f"{link}")
    await ctx.respond(embed=embed)

Upvotes: 0

Views: 1106

Answers (2)

eientei 95
eientei 95

Reputation: 1

Tenor has changed their site since the accepted answer, making the code not return any results. Because of this reason, the get_gif_url function would now look like this:

import requests
import re
import json

def get_gif_url(view_url):
    # Get the gif data from the embed page
    embed_url = re.sub(r'/view/[^/?]+-(\d+)', r'/embed/\1', view_url)
    page_content = requests.get(embed_url).text
    gif_info = re.search(r'<script id="gif-json"[^>]+>(.+?)</script>', page_content)
    if not gif_info:
        return None
    
    # Parse the JSON data
    gif_info = json.loads(gif_info.group(1))
    return gif_info['media_formats']['gif']['url']

Upvotes: 0

Nicholas Obert
Nicholas Obert

Reputation: 1628

You can use Python's requests module to get the web page from the sharable view link. Then you can scan the page for the direct .gif link and send that to your bot users.

Here is an example test code to get the direct .gif URL from the view link:

import requests
import re
 
def find_gif_url(string):
    # Regex to find the URL on the c.tenor.com domain that ends with .gif
    regex = r"(?i)\b((https?://c[.]tenor[.]com/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))[.]gif)"
    return re.findall(regex, string)[0][0]

view_url = 'https://tenor.com/view/link-gif-6068206'

# Get the page content
r = requests.get(view_url)
# Find the URL of the gif
gif_url = find_gif_url(r.text)
print(gif_url)

So, you could pack that into a nice function like such:

def get_gif_url(view_url):

    # Get the page content
    page_content = requests.get(view_url).text

    # Regex to find the URL on the c.tenor.com domain that ends with .gif
    regex = r"(?i)\b((https?://c[.]tenor[.]com/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))[.]gif)"

    # Find and return the first match
    return re.findall(regex, page_content)[0][0]

From what I've seen by taking a look at tenor's website, the direct .gif link always seems to be the first URL that points to c.tenor.com ending in .gif, forgive me if I'm mistaken.

Hope this helps, cheers!

Upvotes: 0

Related Questions