ttezel / twit

Twitter API Client for node (REST & Streaming API)
4.32k stars 573 forks source link

How to update monitored IDs without reconnecting everytime to twitter? #550

Closed DaliborTrampota closed 2 years ago

DaliborTrampota commented 3 years ago

This is my function to monitor tweets. It works just fine but my bot gained more users who use this feature and everytime they add someone to their follow list it runs this function with update = true and it gets all the IDs including the new one and creates new stream. What I'd love is to update the stream IDs without making new one. It wouldn't be an issue but it sometimes takes few minutes to reconnect and it prints into log like 3-10times "Attempting to connect to twitter"


let stream;
module.exports = async (bot, update) => {
    if(bot.config.isBeta)
        return;

    let IDs = await guildModel.find({}).select({twitterNames: 1, _id: 0});
    IDs = IDs.reduce((acc, g) => acc.concat(g.twitterNames), [])
    IDs = Array.from(new Set(IDs)).map(h => h.id);

    if(!IDs.length)
        if(stream)
            return stream.stop();
        else if(stream && update)
            stream.stop();
        else if(!update)
            return

    stream = T.stream("statuses/filter", { follow: IDs })
    stream.on("connect", (req) => bot.logger.status(`Attempting to connect to twitter`))
    stream.on("connected", (res) => bot.logger.status(`Successfully connected to twitter stream API`))

    stream.on("tweet", async (tweet) => {
        if(bot.func.isReply(tweet))
            return;

        let tweetEmbed = `@${tweet.user.name} tweeted: https://twitter.com/i/status/${tweet.id_str}`
        let guilds = bot.twitterNames.get(tweet.user.screen_name);
        for(let id of guilds)
            if(bot.twitterLogChats[id])
                bot.channels.resolve(bot.twitterLogChats[id]).send(tweetEmbed);
    })
}
DaliborTrampota commented 2 years ago

Dead closing.