Search code examples
pythontwitterbotstweepy

Make tweepy search for the newest mentions instead of the oldest


Today I wrote a twitter bot that replies anybody who mentions it with a random image from a folder.

The problem here is that I'm a newbie in python and I don't know how to make it funcitonal at all. When I started running it, the bot started replying all the mentions from other users (I'm using an old account a friend gave to me), and that's not precisely what I want, even if it's working, but not as I desire.

The bot is replying all the mentions from the very beggining and it won't stop until all these are replied (the bot is now turned off, I don't want to annoy anybody)

How can I make it to only reply to latest mentions instead of the first ones?

here's the code:

import tweepy
import logging
from config import create_api
import time
import os
import random
from datetime import datetime

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()

api = create_api()

imagePath = random.choice(os.listdir("images/"))

while True:
    for tweet in tweepy.Cursor(api.mentions_timeline).items():
        try:
            imagePath = random.choice(os.listdir("images/"))
            tweetId = tweet.user.id
            username = tweet.user.screen_name
            api.update_with_media('images/' + imagePath, "@" + username + " ", in_reply_to_status_id=tweet.id)
            print('Replying to ' + username + 'with ' + imagePath)

        except tweepy.TweepError as e:
            print(e.reason)
        except StopIteration:
            break
    time.sleep(12)

Thanks in advance.


Solution

  • I don't have the ability to test this code currently but this should work.

    Instead of iterating over every tweet, it turns the iterator that tweepy.Cursor returns into a list and then just gets the last item in that list.

    api = create_api()
    
    imagePath = random.choice(os.listdir("images/"))
    
    while True:
        tweet_iterator = tweepy.Cursor(api.mentions_timeline).items()
        latest_tweet = list(tweet_iterator)[-1]
        try:
            imagePath = random.choice(os.listdir("images/"))
            tweetId = latest_tweet.user.id
            username = latest_tweet.user.screen_name
            api.update_with_media('images/' + imagePath, "@" + username + " ", in_reply_to_status_id=latest_tweet.id)
            print('Replying to ' + username + 'with ' + imagePath)
    
        except tweepy.TweepError as e:
            print(e.reason)
        except StopIteration:
            break
        time.sleep(12)
    

    You will also want to keep track of what user you last replied to, so you don't just keep spamming the same person over and over.

    This isn't the most efficient way of doing it but should be easy enough to understand:

    latest_user_id = None
    while True:
        # Rest of the code
        try:
            if latest_user_id == latest_tweet.user.id:
                # don't do anything
            else:
               latest_user_id = latest_tweet.user.id
               # the rest of your code