Python/Tweepy retweet following twitter accounts - python

I am trying to create a twitter bot using tweepy/python to use as a filter account, to retweet relevant tweets.
I am able to search for tweets that contain a certain word/# etc but was wondering if there is code to enable the account (of which the app is registered with) to retweet all tweets of the accounts it is following.
Please find attached code underneath.
user = api.me()
print(user.name)
def main():
search = ("example1")
numberofTweets = 5
for tweet in tweepy.Cursor(api.search, search).items(numberofTweets):
try:
tweet.retweet()
print("Tweet Retweeted")
except tweepy.TweepError as e:
print(e.reason)
except StopIteration:
break
main()
def main2():
search = ("example2")
numberofTweets = 5
for tweet in tweepy.Cursor(api.search, search).items(numberofTweets):
try:
tweet.retweet()
print("Tweet Retweeted")
except tweepy.TweepError as e:
print(e.reason)
except StopIteration:
break
main2()
while True:
time.sleep(15)

api.update_status("#" + username + " " + certain_word, in_reply_to_status_id = tweetId)
You can take a look at this tutorial.

Related

Tweepy auto run

Can some help me understand why when I run this code once it is done it doesn't continue to loop? I want it to run every 12 hrs or so.
def searchBot():
for tweet in tweets:
try:
tweet.retweet()
tweet.favorite()
print ("Done")
time.sleep(5)
except tweepy.TweepError as e:
print (e.reason)
time.sleep(5)
while True:
searchBot()
time.sleep(11)

How big can the list argument of twitter api.statuses.lookup() be?

I am using the twitter api to retrieve tweets by ID.I have 13 ids. However tweets of only 8 ids are displayed. (There is no error though). The code is as follows
from tweepy import OAuthHandler
import tweepy
import TwitterCredentials
def status_lookup(api, filename):
id_list = [591672103788621824, 591673483832270848,91675312032776192,591677980394393600, 591678618935267328, 591679831399477248, 591681597054652416, 591681654047023104,591681941017100288, 591693321111744513,591712699421052928, 591712700138291201, 591714830446301184]
tweets = api.statuses_lookup(id_list)
# tweets = []
# tweets.extend(api.statuses_lookup(ids))
a = len(tweets)
print(a)
try:
for tweet in tweets:
print("New Tweet : ", tweet.text)
with open(filename, 'a', encoding="utf-8") as tf:
for tweet in tweets:
tf.write("New Tweet:" + ":" + tweet.text + "\n")
return True
except BaseException as e:
print("Error on_data %s" % str(e))
return True
if __name__ == '__main__':
# print(len(id_list))
fetched_tweets_filename = "Rtweets.txt"
auth=OAuthHandler(TwitterCredentials.CONSUMER_KEY,TwitterCredentials.CONSUMER_SECRET)
auth.set_access_token(TwitterCredentials.ACCESS_TOKEN,TwitterCredentials.ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)
status_lookup(api, fetched_tweets_filename)
I am clueless! Please help!
The list of IDs passed to that method allows for up to 100 Tweet IDs.
I just checked this and it looks like for the five IDs not returned, the user accounts have been suspended and the Tweets are no longer available.

Reply to tweets in tweepy

So I have searched all over the place and all the solutions that were presented to me all posted a new tweet and didnt actually reply to the tweets I have collected. My goal is for the script to reply to the 2 tweets I retrieve but for some reason nothing works, I would really appreciate if anyone could help solve this.
while True:
for tweet in tweepy.Cursor(api.user_timeline,
since='2017-12-24',
screen_name='something'
).items(2):
try:
if not tweet.retweeted:
tweet.retweet()
m = "Something"
t = api.update_status(status=m, in_reply_to_status_id=tweet.id)
print("Something, Working...")
sleep(10)
except tweepy.TweepError as e:
print(e.reason)
sleep(5)
break
except StopIteration:
break
I tried "in_reply_to_status_id" as it was stated in the tweepy documentation but it doesn't work either, it simply tweets it out instead of replying.
When replying, prefix the #UserName to the status:
while True:
for tweet in tweepy.Cursor(api.user_timeline,
since='2017-12-24',
screen_name='something'
).items(2):
try:
if not tweet.retweeted:
tweet.retweet()
m = "#UserName Something" # <---
t = api.update_status(status=m, in_reply_to_status_id=tweet.id)
print("Something, Working...")
sleep(10)
except tweepy.TweepError as e:
print(e.reason)
sleep(5)
break
except StopIteration:
break
Notice that I set:
m = "#UserName Something"
with the #UserName prefix.

How to auto follow someone with Twython

I am making a bot that automatically re-tweets and favorites anything containing the keyword 'Australia'
I am successfully able to re-tweet and favorite the tweet automatically, but I have no idea how to follow them automatically (follow everyone I re-tweet automatically)
search_results = twitter.search(q='Australia', count=10)
try:
for tweet in search_results["statuses"]:
try:
twitter.retweet(id = tweet["id_str"])
twitter.create_favorite(id = tweet["id_str"])
twitter.create_friendship(user_id=?????)
except TwythonError as e:
print (e)
except TwythonError as e:
print (e)
After lot of trying found this. Try the below
twitter = Twython(consumer_key,consumer_secret, access_token, access_secret)
search_results = twitter.search(q='Australia', count=10)
try:
for tweet in search_results["statuses"]:
try:
twitter.retweet(id = tweet["id_str"])
twitter.create_favorite(id = tweet["id_str"])
st=tweet["entities"]["user_mentions"]
if st != []:
twitter.create_friendship(screen_name=st[0]["screen_name"])
except TwythonError as e:
print e
except TwythonError as e:
print e
use screen_name to follow the respective handle.

Tweepy Twitter get all tweet replies of particular user

I am trying to get all replies of this particular user. So this particular user have reply_to_user_id_str of 151791801. I tried to print out all the replies but I'm not sure how. However, I only manage to print out only 1 of the replies. Can anyone help me how to print out all the replies?
My codes are:
for page in tweepy.Cursor(api.user_timeline, id="253346744").pages(1):
for item in page:
if item.in_reply_to_user_id_str == "151791801":
print item.text
a = api.get_status(item.in_reply_to_status_id_str)
print a.text
First, find the retweet thread of your conversation with your service provider:
# Find the last tweet
for page in tweepy.Cursor(api.user_timeline, id="253346744").pages(1):
for item in page:
if item.in_reply_to_user_id_str == "151791801":
last_tweet = item
The variable last tweet will contain their last retweet to you. From there, you can loop back to your original tweet:
# Loop until the original tweet
while True:
print(last_tweet.text)
prev_tweet = api.get_status(last_tweet.in_reply_to_status_id_str)
last_tweet = prev_tweet
if not last_tweet.in_reply_to_status_id_str:
break
It's not pretty, but it gets the job done.
Good luck!
user_name = "#nameofuser"
replies = tweepy.Cursor(api.search, q='to:{} filter:replies'.format(user_name)) tweet_mode='extended').items()
while True:
try:
reply = replies.next()
if not hasattr(reply, 'in_reply_to_user_id_str'):
continue
if str(reply.in_reply_to_user_id_str) == "151791801":
logging.info("reply of :{}".format(reply.full_text))
except tweepy.RateLimitError as e:
logging.error("Twitter api rate limit reached".format(e))
time.sleep(60)
continue
except tweepy.TweepError as e:
logging.error("Tweepy error occured:{}".format(e))
break
except StopIteration:
break
except Exception as e:
logger.error("Failed while fetching replies {}".format(e))
break

Categories