How to get the full text in Tweepy v2 search - twitter

I'm trying yo get the full text in twitter search using Tweepy v2. I used search_recent_tweets(), but it returns only truncated tweets.
import tweepy
import credentials
client = tweepy.Client(credentials.bearer_token)
query = 'policy'
response = client.search_recent_tweets(query, tweet_fields = ["created_at", "text", "source"], max_results=10)
tweets = response.data
tweets[0]['text']
The output is:
"RT #saletan: I wasn't aware of this policy till it happened to my
son. I told the story below.\n\nSix weeks after they locked his
account, he…"

Related

Empty response from Twitter API v2 using Tweepy with organic_metrics

I am trying to download tweets by a specific user from Twitter API v2 using Tweepy. For some reason, when I add organic_metrics to tweet_fields I get an empty response. If I remove organic_metrics I receive tweets as a response as expected.
Here is an MWE.
import configparser
from pprint import PrettyPrinter
import tweepy
import logging
# Read Twitter authentication information from settings.ini
config = configparser.RawConfigParser()
config.read("settings.ini")
logging.basicConfig(level=logging.INFO)
_logger = logging.getLogger(__name__)
_logger.setLevel(logging.DEBUG)
pp = PrettyPrinter()
# Setup access to API
def connect_to_twitter_OAuth():
client = tweepy.Client(
consumer_key=config["AUTHENTICATION"]["CONSUMER_KEY"],
consumer_secret=config["AUTHENTICATION"]["CONSUMER_SECRET"],
access_token=config["AUTHENTICATION"]["ACCESS_TOKEN"],
access_token_secret=config["AUTHENTICATION"]["ACCESS_SECRET"],
wait_on_rate_limit=True,
)
_logger.debug("Authenticated with Twitter with user context.")
return client
# Create API object
api = connect_to_twitter_OAuth()
tweet_fields = [
"id",
"text",
"conversation_id",
"created_at",
"in_reply_to_user_id",
"organic_metrics",
]
paginator = tweepy.Paginator(
api.get_users_tweets,
user_id,
max_results=5,
tweet_fields=tweet_fields,
user_auth=True,
)
_logger.debug("Retrieving tweets from user.")
for tweet in paginator.flatten(limit=250):
pp.pprint(tweet)
_logger.debug("Tweet retrieved.")
Any thoughts?
"Non-public, organic, and promoted metrics are only available for Tweets that have been created within the last 30 days."
https://developer.twitter.com/en/docs/twitter-api/metrics
This is why you cannot paginate through responses. Hope this answers some of your confusion!

How to retrieve conversations and replies of old tweets using Tweepy from conversation_id?

I have the Academic Research access to Twitter's API and have been using Tweepy to access the API. My problem is I cannot retrieve the tweets from older tweets
This is the code attempting to retrieve the tweets using the conversation_id, from 2014
# https://twitter.com/NintendoAmerica/status/535462600294035456
start_time = '2014-11-01T00:00:00Z'
end_time = '2014-12-12T00:00:00Z'
tweets = client.search_all_tweets(query = 'conversation_id:535462600294035456', max_results = 500, start_time=start_time, end_time=end_time)
and the output is:
Response(data=[<Tweet id=535465221679489024 text='#NintendoAmerica #Pokemon [this was a link I had to remove]'>], includes={}, errors=[], meta={'newest_id': '535465221679489024', 'oldest_id': '535465221679489024', 'result_count': 1})
which is only one seemingly random tweet amongst many.
However, when I tried running the same code on a more recent tweet, it retrieved all the tweets. I do not have to specify a start/end time because it's a tweet from the past 30 days.
# https://twitter.com/380kmh/status/1545477360916373504
tweets = client.search_all_tweets(query = 'conversation_id:1545477360916373504', max_results = 500)
the output was complete (shortened, I removed the tweets):
Response(data=[...], meta={'newest_id': '1546465585093087235', 'oldest_id': '1545477768229670912', 'result_count': 18})
I followed Tweepy's documentation here, using Client.search_all_tweets:
https://docs.tweepy.org/en/stable/client.html#tweepy.Client.search_all_tweets
I also tried using Postman to retrieve the tweets but it came out empty, even though I followed the documentation here:
https://developer.twitter.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-all#tab0
Query: https://api.twitter.com/2/tweets/search/all?query=conversation_id%3A537923834557771776&start_time=2014-11-01T00:00:00.000Z&end_time=2014-12-18T00:00:00.000Z&tweet.fields=in_reply_to_user_id,text
Output:
{
"meta": {
"result_count": 0
}
}
What am I doing wrong?

Check if a certain user has tweeted

Is it possible to write a script for twitter that checks when the last time a certain user has tweeted?
Preferably using python.
Yes, it is possible. Here is how using TwitterAPI.
from TwitterAPI import TwitterAPI
SCREEN_NAME = 'justinbieber'
CONSUMER_KEY = 'XXXX'
CONSUMER_SECRET = 'XXXX'
ACCESS_TOKEN_KEY = 'XXXX'
ACCESS_TOKEN_SECRET = 'XXXX'
api = TwitterAPI(CONSUMER_KEY,
CONSUMER_SECRET,
ACCESS_TOKEN_KEY,
ACCESS_TOKEN_SECRET)
r = api.request('statuses/user_timeline', {'screen_name':SCREEN_NAME, 'count':1})
for item in r:
print(item['created_at'])
There is a python library for accessing the Twitter API called Tweepy
More info on the API can be found here: https://dev.twitter.com
An older post but may be relevant: streaming api with tweepy only returns second last tweet and NOT the immediately last tweet

how to get all tweets past and present with particular # tag or # tag

I am trying to make an application for an organization which will required to fetch all past as well present tweets with some particular hashtag like #airtel, #airtel etc, how should I get past tweet, I am able to fetch the present tweet with the following url : "https://api.twitter.com/1.1/search/tweets.json?q=%23airtel"
Thanks
You can get up to a maximum of 100 tweets with the twitter rest api see the following twitter documentation. The best you can do is use the count parameter https://api.twitter.com/1.1/search/tweets.json?q=%23airtel&count=100
After various search on Google I found some useful library for fetching tweets e.g:
TwitterSearch [https://github.com/ckoepp/TwitterSearch], you would I find the twitter profile # https://twitter.com/twittersearch
Tweepy [https://github.com/tweepy/tweepy], you could find more info at http://www.tweepy.org/
I have implemented using both. Tweepy implementation is as follows:
import tweepy
import json
consumer_key = "get"
consumer_secret = "From"
access_token = "Twitter"
access_token_secret = "site"
# Authenticate twitter Api
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
#made a cursor
c = tweepy.Cursor(api.search, q='%23Coursera')
c.pages(15) # you can change it make get tweets
#Lets save the selected part of the tweets inot json
tweetJson = []
for tweet in c.items():
if tweet.lang == 'en':
createdAt = str(tweet.created_at)
authorCreatedAt = str(tweet.author.created_at)
tweetJson.append(
{'tweetText':tweet.text,
'tweetCreatedAt':createdAt,
'authorName': tweet.author.name,
})
#dump the data into json format
print json.dumps(tweetJson)
If any one have problem, let me know, will provide git repo for this.
Thanks
Krishna

Tweepy user_search api is very slow

After two days of unsuccessful attempt to use twitter gem I have decided to use tweepy of python for a task. (My original attempt was with ruby and I posted the question here)
My task is to collect all those actresses who have a verified account on twitter. I have taken the list of actresses from wikipedia.
Everything looks fine till now. I have started hitting twitter REST api with each name and I check whether it is a verified account or not.
The only problem I have is that the response is very slow. It takes about 12-15 seconds for every request. Am I doing something wrong here or is it how it is suppose to be.
Below is my code in its entirety :
import tweepy
consumer_key = 'xxx'
consumer_secret = 'xxx'
access_token_key = 'xx-xx'
access_token_secret = 'xxx'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token_key, access_token_secret)
api = tweepy.API(auth)
actresses = []
f = open('final','r')
for line in f:
actresses.append(line)
f.close()
print actresses
for actress in actresses:
print actress
users = api.search_users(actress)
for u in users:
if u.verified == True and u.name == actress:
print u.name + " === https://twitter.com/" + u.screen_name
Also is there any better way to extract the verified actresses using that list?
Unfortunately, there is no faster way to do it, given that you only know the actresses' full names, and not their screen names. Each request will take a long time, as Twitter needs to return the results of users matching the query (there may be quite a few). Each one needs to be loaded and examined, which can take a while, depending on how many results were returned.

Resources