I am trying to pull tweets using Twitter Developer API V2. My access level is Elevated. This is how my code looks like:
import tweepy
consumerKey = "*********mc7K"
consumerSecret = "*******BZNB"
accessToken = "*****-****9eeT"
accessTokenSecret = "****sWAa"
bearerToken="****VRqn"
client = tweepy.Client(wait_on_rate_limit=True, bearer_token=bearerToken, consumer_key=consumerKey, consumer_secret=consumerSecret, access_token=accessToken, access_token_secret=accessTokenSecret)
tweets = client.search_all_tweets(query=search_query, tweet_fields=['context_annotations', 'created_at'], max_results=10)
This throws me an error saying:
When authenticating requests to the Twitter API v2 endpoints, you must
use keys and tokens from a Twitter developer App that is attached to a
Project. You can create a project via the developer portal.
But if I use tweets = client.search_recent_tweets(query=search_query, tweet_fields=['context_annotations', 'created_at']), it works fine.
What am I missing here?
Tweepy - TWITTER API V2 REFERENCE
Client.search_all_tweets
This endpoint is only available to those users who have been approved
for the Academic Research product track.
The full-archive search endpoint returns the complete history of
public Tweets matching a search query; since the first Tweet was
created March 26, 2006.
The Tweets returned by this endpoint count towards the Project-level Tweet cap.
Related
I'm trying to use the Twitter API in Python. I got elevated access, set up my app in the Developer Portal, and authenticated OAuth 1.0.
When I write code I always receive the following error: Stream encountered HTTP error: 403. What am I doing wrong?
import tweepy
api_key = ""
api_key_secret = ""
access_token = ""
access_token_secret = ""
stream = tweepy.Stream(api_key,api_key_secret, access_token, access_token_secret)
stream.filter(track=["President"])```
You will need to use Twitter API v2 for this (Tweepy supports it, but you will need to update your code). Regardless of elevated access, after April 29 2022, new applications can no longer access v1.1 streaming.
New Twitter Developer Apps:
will not be able to gain access to v1.1 statuses/sample and v1.1
statuses/filter
https://twittercommunity.com/t/deprecation-announcement-removing-compliance-messages-from-statuses-filter-and-retiring-statuses-sample-from-the-twitter-api-v1-1/170500
Also answered here.
i'm trying to create my first Twitter bot using Twitter API V.2 and Tweepy. So i can post simple text Tweets but i haven't found how to post tweets with medias (pictures) so how can i do that ? (I saw that some people say "you can't post media tweets using twitter API v2... You need to use API V 1.1 " so if it's true how can i use Twitter API V1.1 instead of API V2 ? )
Thank you if you can help me ^^
Here is my actual code :
from io import BytesIO
from PIL import Image
import tweepy
from tweepy import API
consumer_key = "APP_KEY"
consumer_secret = "APP_SECRET_KEY"
access_token = "TOKEN"
access_token_secret = "SECRET_TOKEN"
client = tweepy.Client(
consumer_key=consumer_key,
consumer_secret=consumer_secret,
access_token=access_token,
access_token_secret=access_token_secret
)
response = client.create_tweet(
text="Just a dummy tweet",
# in_reply_to_tweet_id= 1484105392598749186 <--- Reply to a tweet by ID
)
print(f"https://twitter.com/user/status/{response.data['id']}")
If you are managing an Essential project, you need to apply for Elevated (it's free) in your project located on your Twitter Developer Portal, this is because an Elevated project can use both v1.1 and v2 (Essential only v2).
Once your submission is accepted, you must verify to allow read and write functions on your project (Developer Platform -> Project & Apps -> YOUR_PROJECT -> Development -> user authentication settings) selecting "OAuth 1.0a" and selecting "Read and Write".
Now, you can tweet media with the following code:
auth = tweepy.OAuth1UserHandler(
consumerKey,
consumerSecret,
accessToken,
accessTokenSecret
)
api = tweepy.API(auth)
media = api.media_upload(filename="./assets/twitter-logo.png")
print("MEDIA: ", media)
tweet = api.update_status(status="Image upload", media_ids=
[media.media_id_string])
print("TWEET: ", tweet)
For uploading media, you need to use the function media_upload (update_status_with_media is deprecated). This functions returns an Media object that have the attribute media_id_string, which is the element you need to make a tweet with a pic.
I have tried to authenticate Twitter API several times in different ways and I keep getting an authentication error. I have tried requesting the latest elevated version as well but I cannot get it to work.
This is my code:
import tweepy
# Variables that contains the credentials to access
Twitter API
ACCESS_TOKEN =
ACCESS_SECRET =
CONSUMER_KEY =
CONSUMER_SECRET =
# Setup access to API
def connect_to_twitter_OAuth():
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
api = tweepy.API(auth)
return api
# Create API object
api = connect_to_twitter_OAuth()
# tweets from my stream
public_tweets = api.home_timeline()
for tweet in public_tweets:
print(tweet.text)
This is the result:
TweepError: [{'message': 'You currently have Essential access which includes access to Twitter API v2 endpoints only. If you need access to this endpoint, you’ll need to apply for Elevated access via the Developer Portal. You can learn more here: https://developer.twitter.com/en/docs/twitter-api/getting-started/about-twitter-api#v2-access-leve', 'code': 453}]
I have tried the following tutorials but I cannot get the authentication to work. The tutorials did not mention elevated access and I'm not sure if there is a way to do this without:
https://gist.github.com/alexdeloy/fdb36ad251f70855d5d6
https://www.pythoncentral.io/introduction-to-tweepy-twitter-for-python/
https://towardsdatascience.com/my-first-twitter-app-1115a327349e
https://towardsdatascience.com/tweepy-for-beginners-24baf21f2c25
I have also looked at other stack overflow questions and answers and nothing seems to work.
I just want to get tweets from a specific user.
I tried using tweepy and TwitterAPI but both those solutions do not work because I have Essential access to Twitter developer account and not Elevated (elevated app got rejected).
Basically doing:
tweepy:
# authorization of consumer key and consumer secret
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
# set access to user's access key and access secret
auth.set_access_token(access_token, access_token_secret)
# calling the api
api = tweepy.API(auth)
# the ID of the status
id = 1272771459249844224
# fetching the status
status = api.get_status(id)
# fetching the text attribute
text = status.text
Twitter API:
r = api.request('statuses/show/:%d' % 210462857140252672)
print(r.text)
Both of those solutions do not work. I think all the solutions that include access keys stuff will not work.
I also tried some web scraping but it also does not work. This is what I tried:
from lxml import html
import requests
page = requests.get('https://twitter.com/UniteAlbertans/status/572342978255048705')
print(page.text)
tree = html.fromstring(page.content)
tree.xpath('//span[#class="css-901oao css-16my406 r-poiln3 r-bcqeeo r-qvutc0"]/text()')
But I do not think that works because when I print the page text I do not even see the text of the tweet.
Could someone help me how I could get the text of the tweet given tweet ID through code?
Thank you so much :)
This works using Tweepy and the v2 Twitter API (documentation here):
Client.get_tweet(id)
If you have Essential Access, then you can just use the Tweepy Twitter API v2 methods. So generally, you can't access tweepy.API, instead you have to find a way with tweepy.Client.
To get the text of a tweet by tweet id, try:
import tweepy
# token for twitter developers
client = tweepy.Client(
bearer_token="<bearer_token>",
consumer_key="<consumer_key>",
consumer_secret="<consumer_secret>",
access_token="<access_token>",
access_token_secret="<access_token_secret>",
)
# find tweet by id
tweet = client.get_tweet(id=<tweet_id_here>)
# extract data from tweet
text = tweet.data
print(text)
Be sure, that you have installed the latest version of tweepy. In my case i had tweepy version 4.4.0.
I have looked at all the Python Twitter API wrappers that I could find on Bitbucket, Github and PyPi, but have been unable to find one which allows you to connect to Twitter if you already have the authentication token.
I am aware that I can generate the authentication token using an OAuth token, OAuth token secret, Twitter Token and Twitter Secret; but I would like to skip that processing + not prompt users who already have accounts.
The tweepy library seems popular; but lacks documentation...
Would someone be able to show me a tweet postage which uses Tweepy (or any other Python Twitter library) that uses only the authentication token?
EDIT: I ended up getting to work right with Twython.
You have to store the access token and secret returned by the provider after authentication and use them in the subsequent requests to read or write. I have been using rauth (https://github.com/litl/rauth) and highly recommend it.
EDIT
Assuming you have already have a valid access token and a secret you can create a service object and read or write data using the twitter API (skipping the authentication steps). I have included the necessary steps from the rauth documentation below:
twitter = OAuth1Service(
name='twitter',
consumer_key='YOUR_CONSUMER_KEY',
consumer_secret='YOUR_CONSUMER_SECRET',
request_token_url='https://api.twitter.com/oauth/request_token',
access_token_url='https://api.twitter.com/oauth/access_token',
authorize_url='https://api.twitter.com/oauth/authorize',
header_auth=True)
params = {'include_rts': 1, # Include retweets
'count': 10} # 10 tweets
response = twitter.get('https://api.twitter.com/1/statuses/home_timeline.json',
params=params,
access_token=access_token,
access_token_secret=access_token_secret,
header_auth=True)