Stacked in a loop creating friendship with tweepy - python

So Im trying to follow users, but the problem is that it works on every user except the last one that I have in my to_follow.txt:
Chile_Temblores
Aguas_Antof
costaneranorte_
onemichile
Edelaysen
Chilquinta600
CGE_Clientes
Frontel_
EnelClientesCL
javi1597
The code that Im using is the following:
def createFriends(api):
accounts = open("to_follow.txt", "r")
friends = api.friends_ids()
print("friends:", friends)
follow = accounts().split('\n')
print (follow)
for account in follow:
if account not in follow:
api.destroy_friendship(account)
for account in follow:
if account not in friends:
print("account: ", account)
fuentes.append(account)
api.create_friendship(account)
print("friendship created")
print(fuentes)
accounts.close()
So when I print what is happening, it stops in javi1597 and it does not exit de execution, Where is the problem?

I think you should have used the variable "accounts" instead of using the file name "to_follow" as a method:
def createFriends(api):
accounts = open("to_follow.txt", "r")
friends = api.friends_ids()
print("friends:", friends)
print(accounts)
for account in accounts:
if account not in friends:
print("account: ", account)
fuentes.append(account)
api.create_friendship(account)
print("friendship created")
print(fuentes)
accounts.close()
Else I don't understand where the function to_follow() is coming from and why you don't use the created variable "accounts".
Edit: I refactored your code. You don't have to split the file but can directly iterate over the rows with "for in".
Edit 2: When you trying to add the last element "javi1597" it could be possible, that it also contains the "end of file" and it should be removed before you pass it into your API. Only an idea.

Related

Does anyone know how to download only new images from an instagram profile in python using instaloader?

I'm doing a project where I use the instaloader API for python and I want to download images from the feed and stories of a profile, but I want the loop code to only download the images if they are new...
In the documentation it says about the LatestStamps(latest_stamps_file) class, but I can't use it...
Can someone help me?
import instaloader
ig = instaloader.Instaloader(save_metadata=False, download_video_thumbnails=False)
user = "USER"
password = "PASSWORD"
profile_name = input ("Enter Instagram Profile Name: ")
print ("Downloading Media...")
ig.login(user, password)
ig.download_profile(profile_name, download_stories_only=True,profile_pic=False)
print ("Stories Download Completed!")
There is a key word argument called fast_update docs said it's the same as using --fast-update flag:
For each target, stop when encountering the first already-downloaded picture. This flag is recommended when you use Instaloader to update your personal Instagram archive.
So, in your case, you need to replace this line
ig.download_profile(profile_name, download_stories_only=True,profile_pic=False)
To this:
ig.download_profile(profile_name, download_stories_only=True, profile_pic=False, fast_update=True)

How do I add user input to a list and able to see it?

I am trying to make a sign up system in python 3.7 but I don't know how to permanently add a users login to a list and not having to sign up for the same account every time you open the program.
I was not able to make up a solution to this problem.
Usernames = ['User1', 'User2']
Passwords = ['password123', 'password123']
print('Type SU to Sign Up or type LI to Log In!')
UOption = input('Option>> ')
if UOption == 'SU':
SI = True
LI = False
if SI == True:
print('Signing Up!')
SUUsername = input('Username>> ')
SUEmail = input('Email>> ')
SUPassword = input('Password>> ')
Usernames.append(SUUsername)
Emails.append(SUEmail)
Passwords.append(SUPassword)
LI = True
SI = False
I am expecting when I get this working that the user will be able to sign up once then be able to log in if they reopen the program without having to sign up again.
You could use the pickle module:
Firstly, to create the necessary files, run the following code in the folder that your program is saved in:
import pickle
pickle.dump([],open("usernames.dat","wb"))
pickle.dump([],open("emails.dat","wb"))
pickle.dump([],open("passwords.dat","wb"))
In your program, add:
import pickle
at the start of the program
Replace the lines:
Usernames = ['User1', 'User2']
Emails = ['Email1', 'Email2'] # I'm assuming this line has just been missed off your question
Passwords = ['password123', 'password123']
With:
Usernames = pickle.load(open("usernames.dat","rb"))
Emails = pickle.load(open("emails.dat","rb"))
Passwords = pickle.load(open("passwords.dat","rb"))
To read from the files
And finally add these lines at the end of your program to update the files with the new user's details
pickle.dump(Usernames,open("usernames.dat","wb"))
pickle.dump(Emails,open("emails.dat","wb"))
pickle.dump(Passwords,open("passwords.dat","wb"))
This is a link to more details on how to use pickles, if your interested
https://www.tutorialspoint.com/python-pickling
For source code including these edits see here:
https://pastebin.com/H4ryP6cT

How to find a string among many strings in a line

I have a requirement to find the user from the log.
I have a line of code from my log file. One of the strings in the line is a userid. I have the list of all userid also.
Is there any easy way to identify the userid mentioned in the line.
Eg: Calling Business function ProcessSOMBFCommitment_Sourcing from F4211FSEditLine for ND9074524. Application Name [P421002], Version [] (BSFNLevel = 3)
Here, ND9074525 is the user id. My intention is to identify the user from the line.
Other possible userid can be AB9074158, AC9074168, AD9074123, AE9074152
I do not want to loop through all the possible userid. I thought of creating a list of all userid's and find the userid used in line by some method. Not sure if it exists.
You can use this regex to fetch the user id:
[A-Z]{2}\d{7}
And then check against valid user ids.
Regex Demonstration
Code:
import re
users = ['AB9074158', 'AC9074168', 'AD9074123', 'AE9074152']
s = 'Calling Business function ProcessSOMBFCommitment_Sourcing from F4211FSEditLine for ND9074524. Application Name [P421002], Version [] (BSFNLevel = 3)'
pat = '[A-Z]{2}\d{7}'
user_id = re.search(pat, s).group(0)
print(user_id)
if user_id in users:
print("User accepted!")
else:
print("User not accepted")
Output:
'ND9074524'
'User not accepted'
Use a regex to find all strings that match the pattern of a userid; then you can see if any of them are actual userids.

Django model not saving to database

Ok, a project that a small team I am working on is new to django and developing a webapp, when all of a sudden we lost all ability to add a model object into the database. We are all at a complete loss. Below is where we are in debugging currently.
views.py
def postOp(request):
if request.method == 'POST':
operation = request.POST.get("operation","noop")
#Registered user operations
if request.user.is_authenticated():
username = request.session.get("member","Guest")
user = ToolUser.objects.get(name=username)
zipcode = user.location
.
.
#AddTool
if operation == "addTool":
toolName = request.POST.get("toolName","N/A")
toolDesc = request.POST.get("toolDesc","N/A")
print("In addtools")
user.submitTool(toolName, toolDesc)
print("SUBITTED")
return HttpResponseRedirect("tools")
model
def submitTool(self, Nname, Ndescription):
print("IN SUBMIT ")
t = Tool(name=Nname, owner=self.id, shed=self.id, description=Ndescription, currOwner=0, location=self.location)
print("tool made :", t.name, ", ", t.owner, ", ", t.shed, ", ", t.description, \
", ",t.currOwner ,", ", t.location)
t.save()
print("saving tool")
It appears that it gets all the way to the t.save(), then breaks. using a seperate tool to view the database, it is clearly not getting saved to the table. BUT with the following output to the terminal, it does appear to be creating this instance.
terminal output:
In addtools
IN SUBMIT
tool made : tooltest , 2 , 2 , description , 0 , 12345
EDIT: forgot to update this, found the problem, turns out one field was empty, and django refuses to save something that has empty fields.
So wait, you have a model function called saveTool() but you're calling user.savetool (which I presume is django.contrib.auth.user)? If you say that resolves, then fine.
It's probably better to just populate the object in the postOp() function and save it there. If saveTool() were indeed part of the model class you'd be instantiating a model object, and then calling a method to instantiate another function.
My point is that from a style perspective, the code is needlessly complex, or this requires more data to really work out what's happening there.

Python - Multiple Login Combinations

Basically, I've made a basic login program that accepts user input. But, it currently only allows one username and password combo. I'm trying to make it accept multiple usernames and passwords but don't know how to. I am new to python and I know my code is terrible/messy. This is what I've been trying to get it to accept multiple login combinations:
output = open("logfile.txt", 'a')
login = input("please enter the correct username and password\n")
a = ("username password")("username1 password1")
if a in login:
print("successfully logged in")
import time
localtime = time.asctime(time.localtime(time.time()))
output.write("Somebody successfully logged in at ")
output.write(localtime)
output.write("\n")
output.close()
else:
print("access denied.")
import time
output = open("logfile.txt", "a")
localtime = time.asctime(time.localtime(time.time()))
output.write("Somebody unsuccessfully logged at ")
output.write(localtime)
output.write("\n")
output.close()
`
When I just add another 'if' block, it runs the else block aswell. Also, when I just have 'a' value "username password" it works. The problem is when I try to have multiple values I believe.
Try
a = set(("username password","username1 password1"))
if login in a:
and it should work as you expect.
Why is left as an exercise (hint: print the value of a).
You don't want a = ("username password")("username1 password1") and if a in login:.
You want to set a to an iterable of some sort, the code you currently have actually produces a TypeError because you are trying to call a string (putting something in brackets doesn't make it a tuple, you need to add a trailing comma).
What you want instead is something like a = ["username password", "username1 password1"], doe create a list with all the valid usernames and passwords. You then want to check if the input - login - is in that list, so do if login in a: instead.

Categories