節點的Twitter API客戶端
支持其餘的和流API。
npm install twit
var Twit = require ( 'twit' )
var T = new Twit ( {
consumer_key : '...' ,
consumer_secret : '...' ,
access_token : '...' ,
access_token_secret : '...' ,
timeout_ms : 60 * 1000 , // optional HTTP request timeout to apply to all requests.
strictSSL : true , // optional - requires SSL certificates to be valid.
} )
//
// tweet 'hello world!'
//
T . post ( 'statuses/update' , { status : 'hello world!' } , function ( err , data , response ) {
console . log ( data )
} )
//
// search twitter for all tweets containing the word 'banana' since July 11, 2011
//
T . get ( 'search/tweets' , { q : 'banana since:2011-07-11' , count : 100 } , function ( err , data , response ) {
console . log ( data )
} )
//
// get the list of user id's that follow @tolga_tezel
//
T . get ( 'followers/ids' , { screen_name : 'tolga_tezel' } , function ( err , data , response ) {
console . log ( data )
} )
//
// Twit has promise support; you can use the callback API,
// promise API, or both at the same time.
//
T . get ( 'account/verify_credentials' , { skip_status : true } )
. catch ( function ( err ) {
console . log ( 'caught error' , err . stack )
} )
. then ( function ( result ) {
// `result` is an Object with keys "data" and "resp".
// `data` and `resp` are the same objects as the ones passed
// to the callback.
// See https://github.com/ttezel/twit#tgetpath-params-callback
// for details.
console . log ( 'data' , result . data ) ;
} )
//
// retweet a tweet with id '343360866131001345'
//
T . post ( 'statuses/retweet/:id' , { id : '343360866131001345' } , function ( err , data , response ) {
console . log ( data )
} )
//
// destroy a tweet with id '343360866131001345'
//
T . post ( 'statuses/destroy/:id' , { id : '343360866131001345' } , function ( err , data , response ) {
console . log ( data )
} )
//
// get `funny` twitter users
//
T . get ( 'users/suggestions/:slug' , { slug : 'funny' } , function ( err , data , response ) {
console . log ( data )
} )
//
// post a tweet with media
//
var b64content = fs . readFileSync ( '/path/to/img' , { encoding : 'base64' } )
// first we must post the media to Twitter
T . post ( 'media/upload' , { media_data : b64content } , function ( err , data , response ) {
// now we can assign alt text to the media, for use by screen readers and
// other text-based presentations and interpreters
var mediaIdStr = data . media_id_string
var altText = "Small flowers in a planter on a sunny balcony, blossoming."
var meta_params = { media_id : mediaIdStr , alt_text : { text : altText } }
T . post ( 'media/metadata/create' , meta_params , function ( err , data , response ) {
if ( ! err ) {
// now we can reference the media and post a tweet (media will attach to the tweet)
var params = { status : 'loving life #nofilter' , media_ids : [ mediaIdStr ] }
T . post ( 'statuses/update' , params , function ( err , data , response ) {
console . log ( data )
} )
}
} )
} )
//
// post media via the chunked media upload API.
// You can then use POST statuses/update to post a tweet with the media attached as in the example above using `media_id_string`.
// Note: You can also do this yourself manually using T.post() calls if you want more fine-grained
// control over the streaming. Example: https://github.com/ttezel/twit/blob/master/tests/rest_chunked_upload.js#L20
//
var filePath = '/absolute/path/to/file.mp4'
T . postMediaChunked ( { file_path : filePath } , function ( err , data , response ) {
console . log ( data )
} )
//
// stream a sample of public statuses
//
var stream = T . stream ( 'statuses/sample' )
stream . on ( 'tweet' , function ( tweet ) {
console . log ( tweet )
} )
//
// filter the twitter public stream by the word 'mango'.
//
var stream = T . stream ( 'statuses/filter' , { track : 'mango' } )
stream . on ( 'tweet' , function ( tweet ) {
console . log ( tweet )
} )
//
// filter the public stream by the latitude/longitude bounded box of San Francisco
//
var sanFrancisco = [ '-122.75' , '36.8' , '-121.75' , '37.8' ]
var stream = T . stream ( 'statuses/filter' , { locations : sanFrancisco } )
stream . on ( 'tweet' , function ( tweet ) {
console . log ( tweet )
} )
//
// filter the public stream by english tweets containing `#apple`
//
var stream = T . stream ( 'statuses/filter' , { track : '#apple' , language : 'en' } )
stream . on ( 'tweet' , function ( tweet ) {
console . log ( tweet )
} )
var T = new Twit(config)
創建一個可用於向Twitter API提出請求的Twit
實例。
如果用用戶上下文進行認證, config
應為表格的對象:
{
consumer_key: '...'
, consumer_secret: '...'
, access_token: '...'
, access_token_secret: '...'
}
如果使用應用程序上下文進行身份驗證,則config
應為表格的對象:
{
consumer_key: '...'
, consumer_secret: '...'
, app_only_auth: true
}
請注意,僅使用應用程序的auth將不允許您對需要用戶上下文的API端點執行請求,例如發布推文。但是,可用的端點可以具有更高的速率限制。
T.get(path, [params], callback)
獲取任何REST API端點。
小路
登點的終點。指定path
值時,在末尾省略'.json' (即使用'search/Tweets'而不是'search/tweets.json' )。
參數
(可選)請求參數。
打回來
function (err, data, response)
data
是從Twitter收到的分析數據。response
是[http.incomingmessage](http://nodejs.org/api/http.html# http_http_incomingmessage)。 T.post(path, [params], callback)
發布任何REST API端點。與T.get()
使用相同的用法。
T.postMediaChunked(params, callback)
助手功能通過郵政媒體/上傳(塊)API發布媒體。 params
是包含file_path
鍵的對象。 file_path
是要上傳文件的絕對路徑。
var filePath = '/absolute/path/to/file.mp4'
T . postMediaChunked ( { file_path : filePath } , function ( err , data , response ) {
console . log ( data )
} )
您還可以通過T.POST()調用使用Post Media/上傳API,如果您希望對流媒體進行更細粒度的控制; [請參閱此處的示例](https://github.com/ttezel/twit/blob/master/tests/rest_chunked_upload.js# l20)。
T.getAuth()
獲取客戶的身份驗證令牌。
T.setAuth(tokens)
更新客戶的身份驗證令牌。
T.stream(path, [params])
與流媒體API一起使用。
小路
流端點要擊中。之一:
有關每個流端點的描述,請參見Twitter API文檔。
參數
(可選)請求參數。通過params
傳遞的任何數組都將轉換為逗號分隔字符串,使您可以執行諸如:
//
// I only want to see tweets about my favorite fruits
//
// same result as doing { track: 'bananas,oranges,strawberries' }
var stream = T . stream ( 'statuses/filter' , { track : [ 'bananas' , 'oranges' , 'strawberries' ] } )
stream . on ( 'tweet' , function ( tweet ) {
//...
} )
T.stream(path, [params])
保持連接的活力,並返回EventEmitter
。
發出以下事件:
每次在流中收到對象時發出。這是一個接收的事件,可用於處理流中接收到的任何數據,而不是使用以下記錄的更具體的事件。新版本2.1.0。
stream . on ( 'message' , function ( msg ) {
//...
} )
每次狀態(Tweet)進入流時發出。
stream . on ( 'tweet' , function ( tweet ) {
//...
} )
每當狀態(Tweet)刪除消息都會進入流中。
stream . on ( 'delete' , function ( deleteMessage ) {
//...
} )
每次限制消息都進入流。
stream . on ( 'limit' , function ( limitMessage ) {
//...
} )
每次位置刪除消息都進入流時發出。
stream . on ( 'scrub_geo' , function ( scrubGeoMessage ) {
//...
} )
當Twitter發出斷開消息時發出。如果您有多個連接到Twitter的API,則會發生這種情況。從Twitter接收到斷開的消息後, Twit
將關閉連接並發出此事件,並通過Twitter收到的消息詳細信息。
stream . on ( 'disconnect' , function ( disconnectMessage ) {
//...
} )
當對Twitter進行連接嘗試時發出。發射HTTP request
對象。
stream . on ( 'connect' , function ( request ) {
//...
} )
從Twitter收到響應時發出。發射HTTP response
對象。
stream . on ( 'connected' , function ( response ) {
//...
} )
安排了重新連接嘗試進行Twitter時發出。如果Twitter遇到問題或獲得利率有限,我們將根據Twitter的重新連接指南安排重新連接。最後一個HTTP request
和response
對像是在重新連接之前剩下的時間(以毫秒為單位)發出的。
stream . on ( 'reconnect' , function ( request , response , connectInterval ) {
//...
} )
此消息適用於使用高帶寬連接(例如FireHose)的客戶。如果您的連接落在後面,Twitter將為您排隊消息,直到您的隊列填充為止,此時他們將斷開您的連接。
stream . on ( 'warning' , function ( warning ) {
//...
} )
當Twitter在流中發出status_withheld
消息時發出。這意味著在某些國家 /地區保留了一條推文。
stream . on ( 'status_withheld' , function ( withheldMsg ) {
//...
} )
當Twitter在流中發送user_withheld
消息時發出。這意味著在某些國家 /地區保留了Twitter用戶。
stream . on ( 'user_withheld' , function ( withheldMsg ) {
//...
} )
當Twitter發送連接到用戶流時,Twitter發送[https://dev.twitter.com/streaming/messages-types-types-types-types-promes_messssages)時發出。此消息包含用戶朋友的列表,該列表表示為用戶ID數組。如果設置了stringify_friend_ids參數,則將列表序言作為字符串返回(而不是數字)。
var stream = T . stream ( 'user' , { stringify_friend_ids : true } )
stream . on ( 'friends' , function ( friendsMsg ) {
//...
} )
當直接消息發送給用戶時發出。不幸的是,Twitter尚未記錄此事件的用戶流。
stream . on ( 'direct_message' , function ( directMsg ) {
//...
} )
當Twitter發送回用戶流事件時發射。有關每個事件結構的更多信息,請參見Twitter文檔。
stream . on ( 'user_event' , function ( eventMsg ) {
//...
} )
此外,還為您提供以下用戶流活動以聆聽:
blocked
unblocked
favorite
unfavorite
follow
unfollow
mute
unmute
user_update
list_created
list_destroyed
list_updated
list_member_added
list_member_removed
list_user_subscribed
list_user_unsubscribed
quoted_tweet
retweeted_retweet
favorited_retweet
unknown_user_event
(對於不匹配以上任何一個的事件) stream . on ( 'favorite' , function ( event ) {
//...
} )
當API請求或響應錯誤發生時發出。發出一個Error
對象,具有屬性:
{
message : '...' , // error message
statusCode : '...' , // statusCode from Twitter
code : '...' , // error code from Twitter
twitterReply : '...' , // raw response data from Twitter
allErrors : '...' // array of errors returned from Twitter
}
在流上調用此功能以停止流式傳輸(與Twitter關閉連接)。
在其上調用.stop()
之後,調用此功能重新啟動流。注意:無需調用.start()
開始流式傳輸。 Twit.stream
call .start()
為您。
Twitter API中的任何內容:
轉到這裡創建一個應用並獲得OAuth憑據(如果您還沒有):https://apps.twitter.com/app/new
如果您只想相信一組特定的證書,則可以指定一系列受信任的證書指紋。當收到HTTP響應時,可以驗證證書已簽署,並且同行證書的指紋必須是您指定的值之一。默認情況下,將使用Node.js信任的“ root” CAS。
例如。
var twit = new Twit ( {
consumer_key : '...' ,
consumer_secret : '...' ,
access_token : '...' ,
access_token_secret : '...' ,
trusted_cert_fingerprints : [
'66:EA:47:62:D9:B1:4F:1A:AE:89:5F:68:BA:6B:8E:BB:F8:1D:BF:8E' ,
]
} )
創建兩個文件: config1.js
和config2.js
在twit
文件夾的根部。它們應包含兩套不同的OAuth憑據,以便使用TWIT(測試交互需要兩個帳戶)。他們倆都應該看起來像這樣:
module.exports = {
consumer_key: '...'
, consumer_secret: '...'
, access_token: '...'
, access_token_secret: '...'
}
然後運行測試:
npm test
您還可以舉辦以下示例:
node examples/rtd2.js
該示例是使用twit
編寫的名為RTD2的Twitter機器人。 RTD2發推文有關GitHub並策劃其社交圖。
常問問題
(麻省理工學院許可證)
版權(c)由tolga tezel [email protected]
特此免費授予任何獲得此軟件副本和相關文檔文件(“軟件”)的人,以無限制處理該軟件,包括無限制,使用,複製,修改,合併的權利,發布,分發,分佈和/或出售該軟件的副本,並允許提供該軟件的人,但要遵守以下條件:
上述版權通知和此許可通知應包含在軟件的所有副本或大量部分中。
該軟件是“原樣”提供的,沒有任何形式的明示或暗示保證,包括但不限於適銷性,特定目的的適用性和非侵權的保證。 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE軟體.
T.delete(...)
。parser-error
而不是error
事件。new
關鍵字; var t = Twit(config)
有效, var t = new Twit(config)
也有效。config.trusted_cert_fingerprints
設置信任證書指紋的數組。mime
添加為依賴性。stringify_friend_ids=true
用戶流時收到的friends_str
消息的Emit friends
事件。error
事件。retweeted_retweet
和favorited_retweet
用戶事件。T.postMediaChunked()
以使其變得容易。account/update_profile_image
和account/update_profile_background_image
路徑的http請求中。quoted_tweet
事件message
事件。connected
事件stream.stop()
和stream.start()
而不是發出start
和stop
事件disconnect
消息,請關閉流並與從Twitter接收到的斷開消息斷開disconnect
twit
。twit.stream()
。不再進行回調。它可以立即使用您可以聆聽的EventEmitter
返回。 readme.md中的Usage
部分已更新。閱讀。twit.stream()
具有簽名function (path, params, callback)