如何用Ruby调用Twitter Keyword Insights API获取每日关键词推文数?
解决
undefined method 'keywords'错误的方案 这个错误的核心原因很明确:你用的twitter Ruby gem只支持Twitter的普通REST API(比如发推文、获取公开推文这类操作),但你要调用的Keyword Insights API属于Twitter Ads API体系,这个gem根本没有封装Ads API的相关方法,自然会报方法不存在的错误。
下面是正确的解决步骤:
1. 切换到官方的Twitter Ads Ruby SDK
首先卸载原来的twitter gem(如果不需要保留的话),安装专门适配Ads API的twitter-ads gem:
gem uninstall twitter gem install twitter-ads
2. 配置Ads API客户端
注意:Twitter Ads API需要你拥有Twitter Ads账号权限,认证信息和普通REST API一致,但还需要指定你的Ads Account ID(可在Twitter Ads平台的账户设置中找到)。
示例配置代码:
require 'twitter-ads' require 'yaml' # 关闭SSL验证(仅测试环境临时使用,生产环境不建议) OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE Encoding.default_external = 'UTF-8' # 初始化Ads客户端 client = TwitterAds::Client.new( consumer_key: 'YOUR_CONSUMER_KEY', consumer_secret: 'YOUR_CONSUMER_SECRET', access_token: 'YOUR_ACCESS_TOKEN', access_token_secret: 'YOUR_ACCESS_TOKEN_SECRET' ) # 设置你的Ads Account ID(替换成你自己的真实ID) account = client.accounts('YOUR_ADS_ACCOUNT_ID')
3. 正确调用Keyword Insights API
根据官方文档要求,调用时需要指定时间粒度、关键词、时间范围等参数,示例代码如下:
# 调用Keyword Insights获取指定关键词的每日推文数量 response = TwitterAds::Audience::KeywordInsights.search( account, granularity: 'DAY', # 时间粒度设置为每日 keywords: ['Ruby'], # 要查询的关键词,支持数组传入多个关键词 start_time: 7.days.ago.utc, # 查询的起始时间(必须为UTC时间) end_time: Time.now.utc # 查询的结束时间(必须为UTC时间) ) # 遍历并输出结果 response.each do |insight| puts "日期: #{insight.date}, 推文数量: #{insight.tweet_volume}" end
关键注意事项
- 确保你的Twitter账号已开通Ads权限,否则会返回权限不足的错误
- API限制查询时间范围不能超过30天,且
start_time和end_time必须为UTC时间 - 关键词需以数组形式传入,支持同时查询多个关键词
内容的提问来源于stack exchange,提问作者丶 Limeー来夢 丶
相关产品推荐
相关产品推荐

