简体   繁体   English

使用Javascript的Twitter API

[英]Twitter api using Javascript

im looking to make for a Twitter API that shows a certain term lets say "cheese" to appear on a html webpage showing a list of the latests tweets that mentioned cheese and is updated so any new tweets using cheese appear in the list. 我正在寻找一种显示某个术语的Twitter API,让说“ cheese”的出现在html网页上,该网页显示了提及奶酪的最新推文列表,并进行了更新,因此使用奶酪的任何新推文都将出现在列表中。 Can anyone help me on doing this. 谁能帮助我做到这一点。 I know people will suggest PHP but i only want to use Javascript. 我知道人们会建议使用PHP,但我只想使用Javascript。

I suggest you to use node-twitter npm package, which should significantly simplify the task. 我建议您使用node-twitter npm软件包,该软件包可以显着简化任务。 Link here 连结这里

You can use it as follows ( nodeJS code follows): 您可以按以下方式使用它(遵循nodeJS代码):

 import Twitter from 'twitter'; var client = new Twitter({ consumer_key: keys.consumer_key, consumer_secret: keys.consumer_secret, access_token_key: keys.access_token_key, access_token_secret: keys.access_token_secret }); module.exports.getLatestTweetsByHashtag = function(hashtags, callback){ //here hashtags is an array in the form: [#cheese, #bacon] var hashtagsToString = hashtags.join(" "); var encodedHashtags = encodeURIComponent(hashtags).replace(/%20/g, '+'); client.get('search/tweets.json', { q: encodedHashtags, result_type: 'recent', include_entities: true }, function(error, tweets, response) { if (error) return callback(error); else return callback(undefined, tweets.statuses); }); } 

The result can be retrieved from the method using callback (feel free to 'promisify` it if you wish) 可以使用回调从方法中检索结果(如果愿意,可以随意“承诺”)

Use as follows: 用法如下:

 require('./my-twitter-module').getLatestTweetsByHashtag(['#cheese'], function(err, tweets){ //do error handling //pass it back to client side, tweets are already json object res.json(tweets); }); 

This will give you the list of most recents tweets containing all of the hashtags included in the array 这将为您提供包含数组中包含的所有#标签的最新推文列表

EDIT In case if you are looking for streaming API implementation: 编辑如果您正在寻找流式API实现:

 client.stream('statuses/filter', {track: 'cheese'}, function(stream) { stream.on('data', function(tweet) { console.log(tweet.text); }); stream.on('error', function(error) { throw error; }); }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM