【问题标题】:Twitter search API getting errorsTwitter 搜索 API 出现错误
【发布时间】:2020-07-09 22:03:59
【问题描述】:

我正在尝试收集推特搜索结果。 我正在使用带有 Nodejs 的 twitter 搜索 API。 从 twitter api 网站https://developer.twitter.com/en/docs/labs/recent-search/quick-start 中给出的“快速启动”开始,但我一直在收到我的请求中的错误。

这是我的代码:

  
const https = require('https');
const request = require('request');
const util = require('util');

const get = util.promisify(request.get);
const post = util.promisify(request.post);

const consumer_key = 'xxxxxxx';                             // Add your API key here
const consumer_secret = 'xxxxxx'; // Add your API secret key here

const bearerTokenURL = new URL('https://api.twitter.com/oauth2/token');
const searchURL = new URL('https://api.twitter.com/labs/2/tweets/search');

async function bearerToken (auth) {
  const requestConfig = {
    url: bearerTokenURL,
    auth: {
      user: consumer_key,
      pass: consumer_secret,
    },
    form: {
      grant_type: 'client_credentials',
    },
  };

  const response = await post(requestConfig);
  return JSON.parse(response.body).access_token;
}

(async () => {
  let token;
  const query = 'obama';
  const maxResults = 10;

  try {
    // Exchange your credentials for a Bearer token
    token = await bearerToken({consumer_key, consumer_secret});
  } catch (e) {
    console.error(`Could not generate a Bearer token. Please check that your credentials are correct and that the Filtered Stream preview is enabled in your Labs dashboard. (${e})`);
    process.exit(-1);
  }

  const requestConfig = {
    url: searchURL,
    qs: {
      query: query,
      max_results: maxResults,
      format: 'compact',
    },
    auth: {
      bearer: token,
    },
    headers: {
      'User-Agent': 'LabsRecentSearchQuickStartJS',
    },
    json: true,
  };

  try {
    const res = await get(requestConfig);  
    console.log(res.statusCode);
    console.log(res);
    if (res.statusCode !== 200) {
      throw new Error(res.json);
      return;
    }

    console.log(res.json);
  } catch (e) {
    console.error(`Could not get search results. An error occurred: ${e}`);
    process.exit(-1);
  }
})();

我的错误:

正文:{ 错误:[[对象]], title: '无效请求', detail: '您请求的一个或多个参数无效。', type: 'https://api.twitter.com/labs/2/problems/invalid-request' }, [Symbol(kCapture)]: false } 无法获得搜索结果。一个 发生错误:错误

【问题讨论】:

  • 永远不要在您在线发布的代码中包含您的消费者密钥和密码。您现在应该在 Twitter 开发者仪表板中重新生成它们,以避免其他人窃取和滥用它们。

标签: node.js api twitter


【解决方案1】:

此脚本中有一个错误需要我们修复。如果您删除format: 'compact', 行,那么这将起作用 - 该参数在 Labs v2 中不再有效。

【讨论】:

  • 工作!!但是这个例子在 twitter“开始”的例子中存在吗?
  • 这是一个错误,我已经提出了修复它的请求。很抱歉让您失望了!
猜你喜欢
  • 2020-06-05
  • 1970-01-01
  • 1970-01-01
  • 2012-10-28
  • 2012-07-19
  • 2016-07-26
  • 2011-04-29
  • 2013-04-11
  • 1970-01-01
相关资源
最近更新 更多