首页 > 解决方案 > Node.js 中的 Twitter API 参数设置

问题描述

所以 Twitter 提供了一个现成的代码:

https://developer.twitter.com/en/docs/labs/tweets-and-users/quick-start/get-tweets

我正在尝试对其进行编辑以从特定帐户、主题标签中获取数据。

我发现它const params可以接受几个值:[ids,expansions,tweet.fields,media.fields,poll.fields,place.fields,user.fields]但是我找不到关于如何指向我要监控的特定 Twitter 帐户的示例语法。

我审查的页面:

https://developer.twitter.com/en/docs/twitter-api/fields

https://developer.twitter.com/en/docs/twitter-api/data-dictionary/object-model/tweet

提供我需要修改的代码片段:

//available params [ids,expansions,tweet.fields,media.fields,poll.fields,place.fields,user.fields]'
const params = {
  ids: '1138505981460193280',
  'tweet.fields': 'created_at',
};

标签: javascriptnode.jsresttwitter

解决方案


您可以找到如何检索和探索用户在本教程中发布的公共推文的时间线:https ://developer.twitter.com/en/docs/tutorials/explore-a-users-tweets

确保您拥有所有密钥和令牌以连接到 Twitter API 并对其进行身份验证。

您将需要调整您的查询以获得所需的正确推文。例如,对于@TwitterDev 帐户,您需要确保向其发出 GET 请求的端点是:https://api.twitter.com/2/tweets/search/recent?query=from:TwitterDev

这是 Node.js 的示例代码:

const needle = require('needle');

// The code below sets the bearer token from your environment variables
// To set environment variables on Mac OS X, 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
    const params = {
        'query': 'from:twitterdev -is:retweet', 
        'tweet.fields': 'author_id' 
    } 

    const res = await needle('get', endpointUrl, params, { headers: {
        "authorization": `Bearer ${token}`
    }})

    if(res.body) {
        return res.body;
    } else {
        throw new Error ('Unsuccessful request')
    }
}

(async () => {

    try {
        // Make request
        const response = await getRequest();
        console.log(response)

    } catch(e) {
        console.log(e);
        process.exit(-1);
    }
    process.exit();
  })();

推荐阅读