Get a Twitter user's timeline with tweepy

0

I have to get the timeline of my twitter profile and the one of a user that we want with tweepy and take the date , the author and the text or.

I have the following code, but it shows me only the text of my timeline:

import tweepy

#Credenciales de desarrollador que se obtienen en https://apps.twitter.com/
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
ACCESS_TOKEN = ''
ACCESS_TOKEN_SECRET = ''


auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

api = tweepy.API(auth)

opcion = int(input("\nMENU\n\t"+
           "1.Mostrar mi TimeLine\n"+"Que quieres hacer: "));

while(opcion !=7):
    if(opcion == 1):
         for status in tweepy.Cursor(api.user_timeline).items(20):
                 print status.text+'\n'
         break;

How can I get the date and the author out?

And how can I do the same but with another user who wants to? Ask us for a user's name and take the data out of it.

    
asked by FJSevilla 10.12.2016 в 20:42
source

2 answers

2

To obtain a user's timeline, you only have to specify its screen_name passing it as a parameter to api.user_timeline() . You can see the list of parameters and their meanings in the API documentation .

To obtain the date, the author and the text simply access the attribute you want, in your case:

  • status.created_at returns the date and time in type datetime .
  • status.author.screen_name returns a string with the name (screen_name) of the tweet. You can get much more information about the author, such as id, language, location, profile image, followers, etc. You can do print(status.author) to see the information returned.
  • status.text : returns a string with the text itself of the tweet

I'll give you a basic example based on your code so you can see how it works:

For Python 3.x:

import tweepy

CONSUMER_KEY = '*****'
CONSUMER_SECRET = '******'
ACCESS_TOKEN = '******'
ACCESS_TOKEN_SECRET = '******'

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

api = tweepy.API(auth)


def get_stuff(nombre=None):
    stuff = tweepy.Cursor(api.user_timeline, screen_name = nombre, include_rts = True)
    return stuff

def get_tweets(stuff, n):
    for status in stuff.items(n):
        print(status.created_at, status.author.screen_name, status.text)

menu = '''
MENU
\t1.Mostrar mi TimeLine
\t2.Mostrar Timeline de otro usuario
\t3.Salir

Que quieres hacer: '''


opcion = 0
while not opcion == '3':

    opcion = input(menu)

    if opcion == '1':
        n = int(input('Cuantos tweets desea obtener: '))
        stuff = get_stuff()
        get_tweets(stuff, n)

    elif opcion == '2':
        nombre = input('Ingrese el nombre del usuario: ')
        n = int(input('Cuantos tweets desea obtener: '))
        stuff = get_stuff(nombre)
        get_tweets(stuff, n)

    else:
        print('Opción no válida')

For Python 2.X:

# -*- coding: utf-8 -*-

import tweepy

CONSUMER_KEY = 'Ifdw98rDoyw8K9KCnQTVvgvNt'
CONSUMER_SECRET = 'hif0sSJ4nHdVBm7R7ldQlEPiUEw6WTgqgvSvpSBo0BPCEbj8Yf'
ACCESS_TOKEN = '564045096-WCVSX3KicrOw0f1uu3J4yAwa9dnYO7S8O9ZIpv3c'
ACCESS_TOKEN_SECRET = 'D4wLAiu4Wa3qwEihV6RqO8SCZ5apGKN9NFKir4Cx264EO'

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

api = tweepy.API(auth)


def get_stuff(nombre=None):
    stuff = tweepy.Cursor(api.user_timeline, screen_name = nombre, include_rts = True)
    return stuff

def get_tweets(stuff, n):
    for status in stuff.items(n):
        print '{0} {1} {2}'.format(
            status.created_at.strftime("%d/%m/%Y %H:%M:%S"),
            status.author.screen_name.encode('utf8'),
            status.text.encode('utf8')
            )

menu = '''
MENU
\t1.Mostrar mi TimeLine
\t2.Mostrar Timeline de otro usuario
\t3.Salir

Que quieres hacer: '''


opcion = ''
while not opcion == '3':

    opcion = raw_input(menu)

    if opcion == '1':
        n = input('Cuantos tweets desea obtener: ')
        stuff = get_stuff()
        get_tweets(stuff, n)

    elif opcion == '2':
        nombre = raw_input('Ingrese el nombre del usuario: ')
        n = input('Cuantos tweets desea obtener: ')
        stuff = get_stuff(nombre)
        get_tweets(stuff, n)

    else:
        print('Opción no válida')

Example using option 2 to get the 5 tweets from the StackOverflow twitter:

MENU
    1.Mostrar mi TimeLine
    2.Mostrar Timeline de otro usuario
    3.Salir

Que quieres hacer: 2
Ingrese el nombre del usuario: StackOverflow
Cuantos tweets desea obtener: 5
2016-12-06 23:29:57 StackOverflow RT @spolsky: Anil Dash is the New CEO at Fog Creek Software https://t.co/IVnVhRc94t https://t.co/5GkdcaLR0S
2016-12-06 15:45:43 StackOverflow @anildash @FogCreek https://t.co/z1LInUtGK7
2016-12-06 14:46:13 StackOverflow Congratulations to our friends at @FogCreek for launching #Gomix today, and to @anildash for his new role: https://t.co/CgSY6wXL3S
2016-12-05 23:06:05 StackOverflow RT @Nick_Craver: So does anyone else countdown in seconds, or is that just us? https://t.co/JNuIppNUvD https://t.co/j2VHnKTrTh
2016-12-05 23:05:42 StackOverflow RT @sklivvz: Hey, I got interviewed by JUG.ru about Stack Overflow. And there's a picture of a rocket. https://t.co/RDRU8kK2kh
    
answered by 11.12.2016 в 05:20
0

I leave you another version that processes the information you want with python 2.X:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import tweepy
from os import environ
CONSUMER_SECRET = environ["CONSUMER_SECRET"]
ACCESS_TOKEN = environ["ACCESS_TOKEN"]
ACCESS_TOKEN_SECRET = environ['ACCESS_TOKEN_SECRET']


auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

api = tweepy.API(auth)

def print_tweet(status):
    print """
--------------------------------------------
Por: {0}
- {1}
Fecha: {2}
""".format(status.author.screen_name,
            status.text.encode('utf8'),
            status.created_at.strftime("%d/%b/%Y"))

opcion = ""
while(opcion !=7):
    opcion = int(input("""\nMENU\n
        1. Mostrar mi TimeLine
        2. Timeline de un usuario especifico
        7. Salir
        Que quieres hacer : """));
    if(opcion == 1):
        for status in tweepy.Cursor(api.user_timeline).items(2):
            print_tweet(status)
    elif(opcion == 2):
        screen_name = str(raw_input("nombre de usuario: "))
        for status in api.user_timeline(screen_name=screen_name):
            print_tweet(status)

Ignore the part where you input the keys from the environment variables, add the "encode (utf8)" so that you can correctly display all the tweets.

Result:

MENU

        1. Mostrar mi TimeLine
        2. Timeline de un usuario especifico
        7. Salir
        Que quieres hacer : 1

--------------------------------------------
Por: UrielAero
- RT @pragdave: Emailing by students notes on their grades. Programming by pipeline. Transformative!

#myelixirstatus https://t.co/iGR5FO6qsl
Fecha: 08/Dec/2016


--------------------------------------------
Por: UrielAero
- RT @plataformatec: This week we are releasing a beta with all chapters of our free Ecto 2.0 ebook.
Grab your copy |> https://t.co/UUw5YhJk…
Fecha: 07/Dec/2016


MENU

        1. Mostrar mi TimeLine
        2. Timeline de un usuario especifico
        7. Salir
        Que quieres hacer :
    
answered by 11.12.2016 в 05:45