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)
Related
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.
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.
I have a Python script with a loop.
If the code cannot find a specified element: (driver.find_element_by_xpath), he should print: "No Button". And then he should restart the loop.
But when I run the code, it will print "No button" BUT then it continues the script instead of retry/loop.
not_found=True
while not_found:
try:
browser=browser.open(link)
except HTTPError, e:
print 'The server couldn\'t fulfill the request.'
except URLError, e:
print 'Connection reset by peer'
sys.stdout.write('\a')
sys.stdout.flush()
new=0
time.sleep(5)
search_k="just some text to look for"
source="output.txt"
if not search_string(search_k, source):
print "this is a message reminder"
startstr='search text"'
endstr='" />'
file='output.txt'
prijs=float(get_html_string(file,startstr,endstr))
search_s="just some text in .txt"
filez="blee.txt"
search_z="texttt"
search_q="texttttttt"
if search_string(search_s, filez) and not search_string(search_z, filez) and not search_string(search_q, filez) and rule <= maxprijs:
driver.get(link)
try:
elem = driver.find_element_by_xpath("//input[#type='submit' and #value='submit']")
elem.click()
except NoSuchElementException:
print"No Button"
time.sleep(2)
new=0 #LOOP SCRIPT IGNORES?
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
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