Search code examples
pythonpython-3.xtwitteryoutubetweepy

Post Tweet with YouTube Video URL using Tweepy


I notice that if I Tweet normally (from the browser) with a message followed by a YouTube video link, Twitter displays the video's thumbnail, as follows:

However, if I use the following code to send the Tweet instead:

import tweepy
import json
youtube_url = r'https://www.youtube.com/watch?v=tj-fmOnbBpU&t=0s'
# account tokens
twitter_keys = json.load(open('twitter_keys.json'))
auth = tweepy.OAuthHandler(twitter_keys["consumer_key"], twitter_keys["consumer_secret"]) # authentication of consumer key and secret
auth.set_access_token(twitter_keys["access_token"], twitter_keys["access_token_secret"]) # authentication of access token and secret
api = tweepy.API(auth)
twitter_text = "My message " + youtube_url 
api.update_status(status ="{}".format(twitter_text)) # send a tweet

I get something like this:

As you can see, Twitter doesn't show the preview for the URL, even after a few days. I don't understand why this is. How can I fix my code so that the Tweet sent through the API shows the preview of the YouTube video link?


Solution

  • As pointed out, the issue was that the URL was using two forward slashes for the path, as can be seen in the screenshot.