Tweepy targeting a user for following - python

I find myself in need of a bot for following users on twitter.
When I say user I don't refer to a follower but to a random user that I will find with "Cursor". I'm trying to modify my twitter bot for liking on the timeline for a specific search into one that follows the users for that search. What I don't know how to implement is how do I exactly target a user from the timeline to "create_friendship()"? I'm not targeting a specific user so I don't want to have to specify the 'Id' or the "screen_name" etc.
Looking in Tweepy documentation I wasn't able to find a solution, maybe is under my nose but I'm a newbie and I could use some help.
This is the code for the twitter bot I use for liking tweets.
import tweepy
import time
auth = tweepy.OAuthHandler('','')
auth.set_access_token('','')
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
search = "The searc"
nrTweets = 100
for tweet in tweepy.Cursor(api.search, search).items(nrTweets):
try:
print('User succesfully followed')
tweet.favorite() #in here i should be able to create a friendship as i like
time.sleep(60)
except tweepy.TweepError as e:
print(e.reason)
except StopIteration:
break
How can I turn this bot in one that follow people in the same fashion in which I like tweets? (for a search with a specific keyword)

This is how I resolved if anyone cares.
# Write a function named collatz() that has one parameter named number. If
# number is even, then collatz() should print number // 2 and return this value.
# If number is odd, then collatz() should print and return 3 * number + 1
# Then write a program that lets the user type in an integer and that keeps
# calling collatz() on that number until the function returns the value 1.
# Add try and except statements to the previous project to detect whether the
# user types in a noninteger string. Normally, the int() function will raise a
# ValueError error if it is passed a noninteger string, as in int('puppy'). In the
# except clause, print a message to the user saying they must enter an integer.
try:
number = int(input(("Enter an integer number ")))
def collatz():
global number
if number % 2 == 0:
print(int(number/2))
number = (number/2)
elif number % 2 == 1:
print(int(3*number+1))
number = (3*number+1)
else:
return
while number != 1:
collatz()
except:
print("man, an integer number please! ")

Related

Is there a way to repeat a try and except block in python? ( getting attribute error when target not found )

I use the SIMBAD service a lot for looking up the coordinates of celestial objects. I thought I'd automate this using python. My first approach was using Selenium and having it run in Safari. However, this proved to be somewhat harder than doing it manually. About two days ago however I found out about astroquery and how it has SIMBAD built into it. So I thought I'd use that. It does work, but it keeps raising this Attribute Error and all of my attempts to fix it have resulted in a new bug. Here's the code: ( p.s I am using the astroquery library (( astroquery.simbad )) and a text formatter, rich ) :
from rich import print
from astroquery.simbad import Simbad
def ask_for(prompt, error_msg=None, _type=None):
""" While the desired prompt is not given, it repeats the prompt. """
while True:
inp = input(prompt).strip()
if not inp:
if error_msg:
print(error_msg)
continue
if _type:
try:
inp = _type(inp)
except ValueError:
if error_msg:
print(error_msg)
continue
return inp
def simbad_query():
not_target = True
while not_target:
try:
print(
'\nTo find the [blue]RA and Dec[/blue] of your target, please put it in here.')
print("If your target can't be found, it will automatically redirect you to the website to put it in again.")
target = ask_for('\nTarget name: ')
query = Simbad.query_object(f'{target}')
query.pprint()
except AttributeError:
print(
'\nThe target you gave was [red]not found[/red]. Please try again.')
print(
'\nTo find the [blue]RA and Dec[/blue] of your target, please put it in here.')
print("If your target can't be found, it will automatically redirect you to the website to put it in again.")
target = ask_for('\nTarget name: ')
query = Simbad.query_object(f'{target}')
query.pprint()

Why my for looping an index in python not give me correct output

I am new learner for python.I am trying to make a basic login accout check, and somehow, my code is not showing what I want. I have defined three user name, and when I run my code, if the first time I put an incorrect user name, the code show account not exit,but it is not shoing. I do not know why
I believe it is my for loop problem, because when I input a wrong account, my i index start at 0 and keep loop until the end index and compare the input username and the exist username in the list. Then after compare all the index if not found user name, then print account not exist, I try to fix this issue, but not find a correct way.
user1=[
{'id':'0001','name':'123','password':'a123', 'balance':0.00},
{'id':'0002','name':'456','password':'a456', 'balance':0.00},
{'id':'0003','name':'789','password':'a789', 'balance':0.00}
]
for x in range(0,4):
name = input('User Name:')
for i in range(len(user1)):
if name == user1[i]['name']:
password = input('Password:')
if password == user1[i]['password']:
print("Success login")
continue
if name != user1[i]['name']:
print("Account not exist, input new one")
If I input wrong user name; it should show account not exist input new one, then I put user name 456 then will ask the correct password.
Look at the logic of your loop body:
for i in range(len(user1)):
if name == user1[i]['name']:
password = input('Password:')
if password == user1[i]['password']:
print("Success login")
continue
if name != user1[i]['name']:
print("Account not exist, input new one")
Regardless of the input, you will never get to the second if statement: any time your program gets to that point, you tell it to continue with the next loop iteration. Try this instead:
for i in range(len(user1)):
if name == user1[i]['name']:
password = input('Password:')
if password == user1[i]['password']:
print("Success login")
else:
print("Account not exist, input new one")
Note that this will work better if you put the all of the accounts into a single dict, so you can access them directly:
user1 = {
'123': {'id':'0001', 'password':'a123', 'balance':0.00},
'456': {'id':'0002', 'password':'a456', 'balance':0.00},
'789': {'id':'0003', 'password':'a789', 'balance':0.00}
}
This allows you to directly access each account by name, rather than searching the entire list for the user trying to log in.

Custom Exception in Python - test value of a variable

I want to test if a condition is met for my python script to throw an exception.
I want to test if a variable is set. And if it contains the right value. Here is how my exception is written now:
try:
aws_account = input(colored("Enter the name of the AWS account you'll be working in: ", 'yellow'))
except:
print("That is not a valid Company AWS account.")
else:
I also want to test in the try: statement if the user input is in the format of: company-${aws_account}. Such as company-lab, company-stage, company-prod, etc.
How can I test if aws_account contains the correct value in the try: statement?

Get the top followed followers of a user in twitter using python-twitter

I want to get the top followed followers of a user in twitter using python-twitter. And that without getting the 'Rate limit exceeded' error message.
I can get followers of a user then get the number of folowers of each one, but the problem is when that user is big (thousands).
I use the following function to get the followers ids of a particular user:
def GetFollowerIDs(self, userid=None, cursor=-1):
url = 'http://twitter.com/followers/ids.json'
parameters = {}
parameters['cursor'] = cursor
if userid:
parameters['user_id'] = userid
json = self._FetchUrl(url, parameters=parameters)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return data
and my code is:
import twitter
api = twitter.Api(consumer_key='XXXX',
consumer_secret='XXXXX',
access_token_key='XXXXX',
access_token_secret='XXXXXX')
user=api.GetUser(screen_name="XXXXXX")
users=api.GetFollowerIDs(user)
#then i make a request per follower in users so that I can sort them according to the number of followers.
the problem is that when the user has a lot of followers i get the 'Rate limit exceeded' error message.
I think you need to get the results in chunks as explained in this link.
This is the work around currently shown on the github page. But if you would want an unlimited stream, you should upgrade the subscription for your twitter application.
def GetFollowerIDs(self, userid=None, cursor=-1, count = 10):
url = 'http://twitter.com/followers/ids.json'
parameters = {}
parameters['cursor'] = cursor
if userid:
parameters['user_id'] = userid
remaining = count
while remaining > 1:
remaining -= 1
json = self._FetchUrl(url, parameters=parameters)
try:
data = simplejson.loads(json)
self._CheckForTwitterError(data)
except twitterError:
break
return data
def main():
api = twitter.Api(consumer_key='XXXX',
consumer_secret='XXXXX',
access_token_key='XXXXX',
access_token_secret='XXXXXX')
user=api.GetUser(screen_name="XXXXXX")
count = 100 # you can find optimum value by trial & error
while(#users not empty):
users=api.GetFollowerIDs(user,count)
Or another possibility might be to try running Cron jobs in intervals as explained here.
http://knightlab.northwestern.edu/2014/03/15/a-beginners-guide-to-collecting-twitter-data-and-a-bit-of-web-scraping/
Construct your scripts in a way that cycles through your API keys to stay within the rate limit.
Cronjobs — A time based job scheduler that lets you run scripts at designated times or intervals (e.g. always at 12:01 a.m. or every 15 minutes).

How to identify more than one value in the method using suds python

Hi How to identify more than one value in the particular method.For example my method will take two values to send some balance(eg: amount and account number). I did for one value and I am getting errors if method has more than one value
url='http://www.testfire.net/bank/ws.asmx?WSDL'
client = Client(url)
print client
for method in client.wsdl.services[0].ports[0].methods.values():
print "the existing methods in webservice are:" +method.name
while True:
try:
s = raw_input("Enter the name of the method you want to scan: ")
name= getattr(client.service,s)
break
except suds.MethodNotFound as e:
print "Please enter a valid method."
value=raw_input("enter a value for method: ")
result=name(value)
print result
Pls provide suggestions

Categories

Resources