I would like to start using twitter apis without tweepy. Does anyone have a code example to get
twitter api and for example a function getting the last 20 tweets from a user?
I am new and i dont understand de twitter apis documentation. I have been using tweepy very well but sometimes i have problems
Thanks for reaching out. Do you have a code sample you’ve been working with that you are having trouble with?
1 Like
Sometimes i request for 5000 tweets and i get 3800 or i get two or three tweets with the same datetime.
Also, i dont why the apis documentation says that i can only retrieve tweets with 30-day endpoint and with tweepy i can get tweets from more than 30 days?
def get_tweets(user, n):
import tweepy
from tweepy import OAuthHandler
import json
'''Devuelve los ultimos n favoritos del usuario indicado.
Info Favorito:
-texto
-fecha y horario del favorito
-Usuario del tweet al cual se le puso "me gusta"
-Hashtags presentes en el tweet
Pre: user = type str. Example: 'lebowskichill', WITHOUT "@"
n = type int.
Pos: Devuelve una lista de diccionarios
'''
tweets_extraidos = []
j = 0 #Cantidad de tweets extraidos
api = create_twitter_api() # Twitter Api
try:
for data in tweepy.Cursor(api.user_timeline, user, tweet_mode= "extended").items(n):
record = {} #Contenedor de favorito
data=json.dumps(data._json,indent=2) #Paso de tweepy.models.Status a una String de JSON
js=json.loads(data) #Paso del String de json a un dict de json
#Modifico tiempo del tweet a timezone Argentina
from datetime import datetime, timedelta
delta_t = timedelta(hours = 3) #Diferencia de horario #UTC/GMT -3 hours
cadena_horario_fecha = js['created_at']
date_object = datetime.strptime(cadena_horario_fecha, '%a %b %d %H:%M:%S %z %Y') #Transformo a date object
date_object = date_object - delta_t #Tranformo a huso horario Bs As
#Recoleccion de fecha y horario de favorito
record['created_at'] = date_object
if 'quoted_status' in js.keys():
#Obtengo el texto del usuario estudiado y el texto del quote
record['text'] = js['full_text']
record['quoted_text'] = js['quoted_status']['full_text']
#Datos del usuario estudiado
record['arroba_name'] = js['user']['screen_name']
record['user_name'] = js['user']['name']
record['user_id'] = js['user']['id']
#Datos del usuario quoted
record['quoted_arroba_name'] = js['quoted_status']['user']['screen_name']
record['quoted_user_name'] = js['quoted_status']['user']['name']
record['quoted_user_id'] = js['quoted_status']['user']['id']
#Informo que es un quoted_tweet
record['type'] = 'quoted'
else: #Tweet unico (Retweet o tweet)
#En caso de ser un Tweet:
if 'RT @' not in js['full_text']:
record['text'] = js['full_text'] #Extraigo texto del "tweet"
#Datos del usuario del tweet
record['arroba_name'] = js['user']['screen_name']
record['user_name'] = js['user']['name']
record['user_id'] = js['user']['id']
#Si es una respuesta o un tweet unitario:
if js['in_reply_to_screen_name'] == None:
record['type'] = 'tweet'
else:
record['type'] = 'reply'
#En caso de ser un Retweet:
else:
record['text'] = js['retweeted_status']['full_text'] #Extraigo texto de "retweet"
#Datos del usuario retweetiado
record['arroba_name'] = js['retweeted_status']['user']['screen_name']
record['user_name'] = js['retweeted_status']['user']['name']
record['user_id'] = js['retweeted_status']['user']['id']
record['type'] = 'retweet'
#El tweet o retweet al no ser quoted_tweets:
record['quoted_arroba_name'] = False
record['quoted_user_name'] = False
record['quoted_user_id'] = False
record['quoted_text'] = False
#Recolección de Hashtags:
hashtags = []
for d in js['entities']['hashtags']:
hashtags.append(d['text'])
record['hashtags'] = hashtags
#Meto tweet en la lista
tweets_extraidos.append(record)
j+=1 #Se extrajo un nuevo tweet
finally: #Si me paso de solicitudes
#Requests disponibles luego de utilizar api.favorites
data2=api.rate_limit_status()
print('Api.favorites solicitudes restantes:', data2["resources"]['statuses']['/statuses/user_timeline']['remaining'])
print(f'Se extrajeron {j} tweets')
return tweets_extraidos
Just to be clear here:
- the user timeline v1.1 API (Twitter API) provides up to 3200 Tweets, which could be more than 30 days … this is based on the code sample you’ve provided.
- you mention “30 day endpoint”, this is a premium search feature that Tweepy does not (to my knowledge?) support.
- in the future, as we move to v2 API, Tweepy may not support the current functionality, you may want to seek out a library that works with the modern API.
Tweepy itself is not provided or supported by Twitter, so for some of these questions you would be best checking with the community around that library.
As @IgorBrigadir said there are indeed other Python libraries, including TwitterAPI.
2 Likes
system
Closed
#9
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.