Reply to tweets in tweepy - python

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.

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)

Python/Tweepy retweet following twitter accounts

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.

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

python Time a try except

My problem is very simple.
I have a try/except code. In the try I have some http requests attempts and in the except I have several ways to deal with the exceptions I'm getting.
Now I want to add a time parameter to my code. Which means the try will only last for 'n' seconds. otherwise catch it with except.
In free language it would appear as:
try for n seconds:
doSomthing()
except (after n seconds):
handleException()
this is mid-code. Not a function. and I have to catch the timeout and handle it. I cannot just continue the code.
while (recoveryTimes > 0):
try (for 10 seconds):
urllib2.urlopen(req)
response = urllib2.urlopen(req)
the_page = response.read()
recoveryTimes = 0
except (urllib2.URLError, httplib.BadStatusLine) as e:
print str(e.__unicode__())
print sys.exc_info()[0]
recoveryTimes -= 1
if (recoveryTimes > 0):
print "Retrying request. Requests left %s" %recoveryTimes
continue
else:
print "Giving up request, changing proxy."
setUrllib2Proxy()
break
except (timedout, 10 seconds has passed)
setUrllib2Proxy()
break
The solution I need is for the try (for 10 seconds)
and the except (timeout, after 10 seconds)
Check the documentation
import urllib2
request = urllib2.Request('http://www.yoursite.com')
try:
response = urllib2.urlopen(request, timeout=4)
content = response.read()
except urllib2.URLError, e:
print e
If you want to catch more specific errors check this post
or alternatively for requests
import requests
try:
r = requests.get(url,timeout=4)
except requests.exceptions.Timeout as e:
# Maybe set up for a retry
print e
except requests.exceptions.RequestException as e:
print e
More about exceptions while using requests can be found in docs or in this post
A generic solution if you are using UNIX:
import time as time
import signal
#Close session
def handler(signum, frame):
print 1
raise Exception('Action took too much time')
signal.signal(signal.SIGALRM, handler)
signal.alarm(3) #Set the parameter to the amount of seconds you want to wait
try:
#RUN CODE HERE
for i in range(0,5):
time.sleep(1)
except:
print 2
signal.alarm(10) #Resets the alarm to 10 new seconds
signal.alarm(0) #Disables the alarm

Categories