< Node.js > twitter API v2のツイート取得
環境設定
You will need to have Node.js installed to run this code. All Node.js examples use needle as the HTTP client, which needs to be npm installed. For OAuth with user context requests, you'll need to install the got and oauth-1.0a packages.
npm install needle npm install got npm install oauth-1.0a
コード
const needle = require('needle'); // The code below sets the bearer token from your environment variables // To set environment variables on macOS or Linux, run the export command below from the terminal: // export BEARER_TOKEN='YOUR-TOKEN' const token = process.env.BEARER_TOKEN const endpointUrl = "https://api.twitter.com/2/tweets/search/recent"; async function getRequest() { // Edit query parameters below // specify a search query, and any additional fields that are required // by default, only the Tweet ID and text fields are returned const params = { 'query': 'from:アカウント名 -is:retweet -is:reply', //リツイートとリプライを除く // 'tweet.fields': 'author_id' } const res = await needle('get', endpointUrl, params, { headers: { "User-Agent": "v2RecentSearchJS", "authorization": `Bearer ${token}` } }) if (res.body) { return res.body; } else { throw new Error('Unsuccessful request'); } } (async () => { try { // Make request const response = await getRequest(); console.dir(response, { depth: null }); } catch (e) { console.log(e); process.exit(-1); } process.exit(); })();