2013-02-25 45 views
4

我想使用R中的RCurl連接到Twitter的Streaming API,並且還能夠過濾關鍵字。然而,在Twitter API v1.1中對授權的新限制使得使用RCurl變得困難。Oauth使用R中的Twitter Streaming API(使用RCurl)

之前,代碼可以去像這樣從this page採取:

getURL("https://stream.twitter.com/1/statuses/filter.json", 
    userpwd="Username:Password", 
    cainfo = "cacert.pem", 
    write=my.function, 
    postfields="track=bruins") 

但現在,Twitter的新的API正在用戶的OAuth認證。我有一個令牌和祕密,我只需要把它放在這個代碼中進行授權。

謝謝!

+0

您是否嘗試過處理? http://cran.r-project.org/web/packages/twitteR/index.html – 2013-02-25 02:35:15

+0

@AndyBarbour,twitteR不幸處理流式API。這非常有用,但不是爲此目的:/ – 2013-02-25 03:43:01

+0

@ R-Enthusiast下面的解決方案適用於您嗎? – 2013-02-25 21:20:26

回答

7

你可以用pacakge ROAuth來做到這一點。我假設你已經使用Twitter註冊了你的應用程序並擁有一個API密鑰。我在Stack Overflow上將other questions拼湊在一起(該問題和相關答案還包含一些指向其他貢獻問題的鏈接)以及包ROAuthtwitteR的文檔。

library(RCurl) 
library(twitteR) 
library(ROAuth) 

requestURL <- "https://api.twitter.com/oauth/request_token" 
accessURL = "http://api.twitter.com/oauth/access_token" 
authURL = "http://api.twitter.com/oauth/authorize" 
consumerKey = "myconsumerkeystring" 
consumerSecret = "myconsumersecretstring" 
Cred <- OAuthFactory$new(consumerKey=consumerKey, 
          consumerSecret=consumerSecret, 
          requestURL=requestURL, 
          accessURL=accessURL, 
          authURL=authURL) 
    #The next command provides a URL which you will need to copy and paste into your favourite browser 
    #Assuming you are logged into Twitter you will then be provided a PIN number to type into the R command line 
Cred$handshake(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl")) 
    # Checks that you are authorised 
registerTwitterOAuth(Cred) 

我認爲,使用流API是通過使用`twitteR`包封裝streamR

HTH

+0

謝謝。 streamR包是完美的。 – 2013-02-26 02:22:18

+4

我做了你所說的,但得到這個錯誤: 錯誤:禁止 我該怎麼辦? – DSaad 2015-01-20 18:04:06