gpt4 book ai didi

java - 如何使用 twitter4j 处理速率限制?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:59:16 26 4
gpt4 key购买 nike

我经常在使用 twitter4j 时遇到以下异常:

2015-06-02 10:04:30,802 DEBUG [Twitter Stream consumer-1[Establishing connection]] TwitterBot(116): Got an exception 420:Returned by the Search and Trends API when you are being rate limited (https://dev.twitter.com/docs/rate-limiting).
Returned by the Streaming API:
Too many login attempts in a short period of time.
Running too many copies of the same application authenticating with the same account name.
Exceeded connection limit for user

因为我尽量避免被 Twitter 禁止,所以我想问一下,如果我的代码做错了什么:

我在 Stream API 上使用 StatusListener,它由我自己的 ID 和一些字符串值过滤。

如果某个状态符合条件,则会通过 Twitter 发送对此状态的回答。这种情况不会经常发生,因此这不应该是速率限制异常的问题。

整个过程都在 TomEE EJB 环境中运行,这是否重要?

@Startup
@Singleton
public class TwitterBot implements Service {

private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TwitterBot.class);

//this is fix for this twitter bot
public static final String TWITTER_BOT_NAME = "botname";
public static final long TWITTER_BOT_USER_ID = 99999L; //the bot's user id

private final TwitterStream twitterStream;
private final Twitter twitter;

public TwitterBot() {

this.twitterStream = new TwitterStreamFactory().getInstance();
this.twitter = TwitterFactory.getSingleton();
}


@PostConstruct
public void listen() {

StatusListener listener = new StatusListener() {
@Override
public void onStatus(Status status) {

//this is to avoid a circle... ignore tweets coming from ourselves.
if (status.getUser().getScreenName().equalsIgnoreCase(TWITTER_BOT_NAME)) {
return;
}

try {

//do something and update own status

StatusUpdate update = new StatusUpdate("Hello World!");
update.setInReplyToStatusId(status.getId());

twitter.updateStatus(update);

} catch (TwitterException e) {
logger.error("Could not complete twitter update, {}", e.getLocalizedMessage(), e);
}

}

//other Status Listener methods, which are not used (default implementation)
};

//filtering for ourselves here
long[] userFilter = {TWITTER_BOT_USER_ID};

String[] termFilter = {TWITTER_EXPERTIZER_BOT_NAME};

FilterQuery filter = new FilterQuery(0, userFilter, termFilter);

twitterStream.addListener(listener);

twitterStream.filter(filter);

}
}

关于这个How to handle rate limit using twitter4j to avoid being banned的答案告诉我,Streaming API 没有速率限制。

那么问题是什么? API文档中有解释吗?

提前致谢!

最佳答案

编辑:

问题与

有关
FilterQuery filter = new FilterQuery(0, userFilter, termFilter);

像这样使用查询会在 Twitter API 上产生某种轮询,因此会超出连接限制。

改为使用:

 FilterQuery filter = new FilterQuery(termFilter);

关于java - 如何使用 twitter4j 处理速率限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30593626/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com