Reputation: 175
I have the following code, where I start a stream to a user, and when he makes a new tweet, I want to make 3 replies to that tweet, in order. However, the bot works ok, it finds the latest tweet, and it starts replying like crazy, randomly, without stopping. What am I doing wrong ?
class MyStreamListener(StreamListener):
def on_data(self, data):
### here i get the statusid from json
### I have 3 replies in messages.txt which i want to reply 1 by 1 to the latest tweet (statusid)
file = open("messages.txt", "r")
content = file.readlines()
for line in content:
api.update_status(line, statusid)
def on_error(self, status):
print(status)
if __name__ == '__main__':
listener = MyStreamListener()
twitterStream = Stream(auth, listener)
twitterStream.filter(follow=['xxxx'])
Thank you !
Upvotes: 1
Views: 881
Reputation: 144
The reason for the loop is that the 'follow' stream returns all replies to the followed user (as well as retweets of, and by, the user), so you need to exclude these before continuing to the reply lines. See the Twitter Documentation.
For example, if using on_data()
rather than on_status()
, check this from_creator()
before proceeding with the rest of the on_status()
function (note that on_status()
returns deletions etc., which will throw an error in this function so handle appropriately):
def from_creator(status):
status = json.loads(status)
if "retweeted_status" in status:
return False
elif status["in_reply_to_status_id"] != None:
return False
elif status["in_reply_to_screen_name"] != None:
return False
elif status["in_reply_to_user_id"] != None:
return False
else:
# status is an origin Tweet by the followed user!
return True
If using on_status()
, it would be:
def from_creator(status):
if hasattr(status, 'retweeted_status'):
return False
elif status.in_reply_to_status_id != None:
return False
elif status.in_reply_to_screen_name != None:
return False
elif status.in_reply_to_user_id != None:
return False
else:
# status is an origin Tweet by the followed user!
return True
Upvotes: 0
Reputation: 3148
Tip : you must mention the user at the beginning of your answer to reply correctly. Here is the full code :
import tweepy
class MyStreamListener(tweepy.StreamListener):
def on_status(self, status):
file = open("messages.txt", "r")
content = file.readlines()
for line in content:
print("answering @" + status.user.screen_name + " tweetID " + status.id_str + " with : " + line.rstrip())
api.update_status(status="@" + status.user.screen_name + " " + line, in_reply_to_status_id=status.id)
consumer_key = '***'
consumer_secret = '***'
access_token = '***'
access_token_secret = '***'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
myStream = tweepy.Stream(auth, MyStreamListener())
myStream.filter(follow=['xxx'])
Upvotes: 1