2015-06-29 23 views
12

Sto usando il seguente codice per lo streaming di messaggi diretti ricevuti da mio account Twitter -:Streaming Twitter messaggi diretti

from tweepy import Stream 
from tweepy import OAuthHandler 
from tweepy import API 

from tweepy.streaming import StreamListener 

# These values are appropriately filled in the code 
consumer_key = "" 
consumer_secret = "" 
access_token = "" 
access_token_secret = "" 

class StdOutListener(StreamListener): 

    def __init__(self): 
     self.tweetCount = 0 

    def on_connect(self): 
     print("Connection established!!") 

    def on_disconnect(self, notice): 
     print("Connection lost!! : ", notice) 

    def on_data(self, status): 
     print("Entered on_data()") 
     print(status, flush = True) 
     return True 

    def on_direct_message(self, status): 
     print("Entered on_direct_message()") 
     try: 
      print(status, flush = True) 
      return True 
     except BaseException as e: 
      print("Failed on_direct_message()", str(e)) 

    def on_error(self, status): 
     print(status) 

def main(): 

    try: 
     auth = OAuthHandler(consumer_key, consumer_secret) 
     auth.secure = True 
     auth.set_access_token(access_token, access_token_secret) 

     api = API(auth) 

     # If the authentication was successful, you should 
     # see the name of the account print out 
     print(api.me().name) 

     stream = Stream(auth, StdOutListener()) 

     stream.userstream() 

    except BaseException as e: 
     print("Error in main()", e) 

if __name__ == '__main__': 
    main() 

sono in grado di ottenere il mio nome stampato così come la "Connessione stabilita!" Messaggio.
Ma ogni volta che invio un messaggio diretto al mio profilo dal profilo del mio amico, non viene chiamato alcun metodo.
Anche se ogni volta che tweet qualcosa dal mio profilo, viene stampato correttamente dal programma.

Io e il mio amico ci seguiamo entrambi su Twitter, quindi non ci dovrebbero essere problemi con le autorizzazioni dei messaggi diretti.

Qual è il modo corretto per farlo?

Inoltre, se non può essere eseguito in Tweepy, sono pronto per utilizzare qualsiasi altra libreria Python.

Sto usando Tweepy 3.3.0 e Python 3.4 su Windows 7.

risposta

6

Il codice fornito nella questione è davvero corretto.
Il problema era che avevo dimenticato di rigenerare il token di accesso e il segreto dopo aver modificato i permessi dell'applicazione su "Leggere, scrivere e inviare messaggi".

Nota: i messaggi diretti arrivano nel metodo on_data() piuttosto che il metodo on_direct_message().

0

Un'altra soluzione è non sovrascrivere il metodo on_data. È così che ho ottenuto il tuo esempio di codice per funzionare nel mio caso.

Il metodo on_data dell'oggetto tweepy.streaming.StreamListener contiene tutta la gestione dei dati json e la chiamata di altri metodi, come on_direct_message, che io e te ci aspettavamo.

0

Ecco una versione funzionante del codice nel 2017

from twitter import * 
import os 

import oauth 

#Create a new Twitter app first: https://apps.twitter.com/app/new 


APP_KEY,APP_SECRET = 'H3kQtN5PQgRiA0ocRCCjqjt2P', '51UaJFdEally81B7ZXjGHkDoDKTYy430yd1Cb0St5Hb1BVcDfE' 
# OAUTH_TOKEN, OAUTH_TOKEN_SECRET = '149655407-TyUPMYjQ8VyLNY5p7jq0aMy8PjtFtd7zkIpDh3ZA', 'IUVpiDpoVmdO75UaHOTinAv5TOsAQmddttNENh9ofYuWO' 


MY_TWITTER_CREDS = os.path.expanduser('my_app_credentials') 
if not os.path.exists(MY_TWITTER_CREDS): 
    oauth_dance("crypto sentiments", APP_KEY, APP_SECRET, 
       MY_TWITTER_CREDS) 

oauth_token, oauth_secret = read_token_file(MY_TWITTER_CREDS) 

auth = OAuth(
    consumer_key=APP_KEY, 
    consumer_secret=APP_SECRET, 
    token=oauth_token, 
    token_secret=oauth_secret 
) 

twitter_userstream = TwitterStream(auth=auth, domain='userstream.twitter.com') 
for msg in twitter_userstream.user(): 
    if 'direct_message' in msg: 
     print (msg['direct_message']['text'])