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?
3
Answers
See this Stack Overflow post on how the youtube thumbnail URL is structured.
Use this post to see how you can programmatically download the thumbnail locally with the
requests
library.Then you can use Tweepy’s update_with_media() to upload it as part of the tweet.
The end result will look something like this:
As pointed out, the issue was that the URL was using two forward slashes for the path, as can be seen in the screenshot.
I know this was asked almost a year ago but I recently was having trouble with this and found a solution which worked for me.
http://youtube.com/watch?v=%5BYOUR VIDEO ID]&feature=emb_title
For example, this YouTube video:
https://www.youtube.com/watch?v=KUh2O8HylUM
Would need to be formatted as:
http://youtube.com/watch?v=KUh2O8HylUM&feature=emb_title