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

时间:2015-06-02 10:33:10

标签: java twitter ejb twitter4j

我经常使用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文档中有解释吗?

提前谢谢!

1 个答案:

答案 0 :(得分:1)

编辑:

问题与

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

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

改为使用:

 FilterQuery filter = new FilterQuery(termFilter);