Skip to content
Advertisement

I made a Twitter bot that automatically tweets Direct Messages:

I recently started to learn python, i had 0 knowledge on pyhton, and in the last few weeks i’ve been studying python and the twitter api.

I decided to work on a simple twitter bot, that automatically posts whatever people send on my direct messages, and i maneged to do so.

Here’s my code:

import tweepy
import json
import sys
import re
import time

print("acessing api...")

consumer_key = 'consumer_key'
consumer_secret = 'consumer_secret'

key = 'key'
secret = 'key_secret'

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(key, secret)
api = tweepy.API(auth, wait_on_rate_limit = True)

print('api accessed')

print('colecting dms')

direct_message = api.list_direct_messages()

text = direct_message[0].message_create["message_data"]["text"]

def send_tweet():
    print('sending tweet...')
    api.update_status('/bot: ' + text)
        
while True:
    send_tweet()
    time.sleep(30)
    

The code works, but not 100%, i’m able to extract the text from the Dm and use it on the api.update_status("/bot: " + text) but when it loops i get the following error:

tweepy.error.TweepError: [{'code': 187, 'message': 'Status is a duplicate.'}]

i’ve looked it up, and tried many things, for example:

while True:
    try:
        send_tweet()
        time.sleep(30)
    
    except tweepy.TweepError as error:
        if error.api_code == 187:
            print('duplicate message')
            
        else:
            print('waiting for new message')
            time.sleep(30)

All i want is a way to keep the code going and ignore messages and tweets that were already sent, also wait for new dm’s

Another thing that kept happening was that when i tried testing the extraction of the text, i kept getting the same text from the same dm, instead of getting a nother newer one.

Advertisement

Answer

Direct Messages stay in the Inbox even after your read or reply. It is best to delete a DM after you process it (in your case tweet it) so you don’t need to worry about it next time you fetch the messages.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement