How to auto follow someone with Twython - python

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.

Related

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 change an argument programmatically if connection error?

I am calling an API. While making requests I hit the maximum number of tries and I get a connection error. I would like to edit the url programmatically by incrementing the number in the url. I do know how to change the arguments programmatically but not sure how to change/increment an argument when I hit connection error.
My language of usage is Python and I am using requests library.
Code Snippet
Libraries importing
from requests.auth import HTTPBasicAuth
import requests
from requests.exceptions import ConnectionError
```def make_request(data , id=None):
url = "http://server001.net:8080/?id="
result = {}
if id:
response = requests.get(url +id , auth=HTTPBasicAuth('uname', 'pass'))
return response
else :
for line in data:
try:
response = requests.get(url +line , auth=HTTPBasicAuth('uname', 'pass'))
result = html_parser2(response)
if result:
write_csv(result)
else:
pass
except ConnectionError as e:
print (e)```
Expected output
url = "http://server001.net:8080/?id="
url_edited = "http://server002.net:8080/?id="
Only if I hit the maximum number of tries, i.e I get an exception or
else keep requesting the same url.
One of the options is to enclose the try..except block with a while loop.
Besides, may be you should put your first requests.get into try..except block too.
Also try to avoid multiple unrelated operations in one try..except block, i.e. execute write_csv after successful connection only.
def make_request(data , id=None):
url = 'http://server001.net:8080/?id={}'
connection_failed = False
response = None
if id:
try:
response = requests.get(url.format(id) , auth=HTTPBasicAuth('uname', 'pass'))
except ConnectionError as e:
print('id = {}, e: {}'.format(id, e))
else:
for line in data:
while not connection_failed:
try:
response = requests.get(url.format(line) , auth=HTTPBasicAuth('uname', 'pass'))
except ConnectionError as e:
connection_failed = True
print('line = {}, e: {}'.format(id, e))
else:
result = html_parser2(response)
if result:
write_csv(result)
return response
def make_request(data , id=None):
url = 'http://server001.net:8080/?id={}'
response = None
if id:
try:
response = requests.get(url.format(id) , auth=HTTPBasicAuth('uname', 'pass'))
except ConnectionError as e:
print('id = {}, e: {}'.format(id, e))
else:
for line in data:
try:
response = requests.get(url.format(line) , auth=HTTPBasicAuth('uname', 'pass'))
except ConnectionError as e:
print('line = {}, e: {}'.format(id, e))
else:
result = html_parser2(response)
if result:
write_csv(result)
break
return response

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.

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: Handling requests exceptions the right way

I recently switched from urlib2 to requests and I'm not sure how to deal with exceptions. What is best practice? My current code looks like this, but is not doing any good:
try:
response = requests.get(url)
except requests.ConnectionError , e:
logging.error('ConnectionError = ' + str(e.code))
return False
except requests.HTTPError , e:
logging.error('HTTPError = ' + str(e.reason))
return False
except requests.Timeout, e:
logging.error('Timeout')
return False
except requests.TooManyRedirects:
logging.error('TooManyRedirects')
return False
except Exception:
import traceback
logging.error('generic exception: ' + traceback.format_exc())
return False
Since it looks bad as a comment, have you tried:
try:
# some code
except Exception as e:
print e

Categories