I'm currently creating a text based console program in python and I want to add a command to display the current weather using a zip code. I have tried googling it extensively and can't seem to find anything good. The solutions that would work for what I'm trying to do are all using technology I'm not familiar with that are used to make actual apps with python. There is currently no UI and I'm a beginner in python so the more readable and easily understandable the solution the better.
#import statements
import math#import math
import os#access the operating system
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os.path
import time
#end import statement
# welcome user
print("welcome to geeko an all in one desktop helper!")
#end welcome
#variables
username = input("Please enter your username: " )#gets username
sudo = False # sets sudo to false indicating normal privledges
if (username == "Caelin"): # if the user enters the sudo username prompt them for a password
sudoPassword = input("enter sudo password: ")# prompt for passcode
sudoLn = False #sets sudo line mode to false. this line mode is used for sudo commands
pi = math.pi
loc_id = 'USAL0504'
def wrongLineError():
if(sudoLn):
print("You are on the sudo line this is purely for special commands normal commands don't work here type \"switch\" to switch to cmd.ln")
elif(sudoLn == False and sudo == False):
print("You do not have sudo priviledges")
elif(sudoLn == False and sudo == True):
print("to use sudo commands you must be on the sudo line mode type \'switch\' to switch to the sudo line")
def sendEmailMessageOnly(message, password, recipient):
send_to_email = recipient # Who you are sending the message to
server = smtplib.SMTP('smtp.gmail.com', 587) # Connect to the server
server.starttls() # Use TLS
server.login(email, password) # Login to the email server
server.sendmail(email, send_to_email , message) # Send the email
server.quit() # Logout of the email server
def sendFormattedEmail(password, recipient, subject, message):
msg = MIMEMultipart()
msg['From'] = email
msg['To'] = recipient
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email, password)
text = msg.as_string()
server.sendmail(email, recipient, text)
server.quit()
def sendMultipleFormattedEmails(password, recipients, subject, message):
for recipientEmail in recipients:
msg = MIMEMultipart()
msg['From'] = email
msg['To'] = recipientEmail
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email, password)
text = msg.as_string()
server.sendmail(email, recipientEmail, text)
server.quit()
#end variables
print ("Hello " + username + "!")# say special welcome
#check if user is root if so alert them and give them sudo status else alert them and leave sudo at a default of false
if(username == "Caelin" and sudoPassword == "bigGlassRemote"):
print("Welcome! you are the root user and therefore have elevated priviledges")
email = input('please enter your email: ')
password = input("please enter your email password: ")
print('logging into email...')
time.sleep(1)
print("logged into email!")
sudo = True
else:
print("You are not the root user and have normal priviledges")
while(True): #run an infinite loop prompting the user for command line inputs
if(sudoLn == False):
command = input(username + "-cmd.ln: ") # if sudo line mode if off use the cmd.ln prompt
else:
command = input(username + "-cmd.sudo: ") # otherwise prompt with cmd.sudo to indicate you are using sudo line mode
if(command == 'welcome'):
if(sudoLn == False): # checks if you are on cmd line
print("Hello " + username) # if the welcome command is used say hello *username*
else: # if you are the sudo line
wrongLineError()
elif(command == "switch"): # if the command is switch
if(sudo): # then check for sudo priviledges
# togles sudoLn
if(sudoLn):
sudoLn = False
else:
sudoLn = True
else:
wrongLineError()
elif(command == 'add'):
if(sudoLn == False):
num1 = input("type the first number to add here: ")
num2 = input("type the second number to add here: ")
ans = float(num1) + float(num2)
if(ans == round(ans)):
print(int(ans))
else:
print(ans)
else:
wrongLineError()
elif(command == 'subtract'):
if(sudoLn == False):
num1 = input("type the first number to subtract here: ")
num2 = input("type the second number to subtract here: ")
ans = float(num1) - float(num2)
if(ans == round(ans)):
print(int(ans))
else:
print(ans)
else:
wrongLineError()
elif(command == "multiply"):
if(sudoLn == False):
num1 = input("type the first number to multiply here: ")
num2 = input("type the second number to multiply here: ")
ans = float(num1) * float(num2)
if(ans == round(ans)):
print(int(ans))
else:
print(ans)
else:
wrongLineError()
elif(command == "divide"):
if(sudoLn == False):
num1 = input("type the first number to divide here: ")
num2 = input("type the second number to divide here: ")
ans = float(num1)/float(num2)
if(ans == round(ans)):
print(int(ans))
else:
print(ans)
else:
wrongLineError()
elif(command == "area of circle"):
if(sudoLn == False):
r = input("type the radius here: ")
ans = pi*(float(r)**2)
if(ans == round(ans)):
print(int(ans))
else:
print(ans)
else:
wrongLineError()
elif(command == "area of rectangle"):
if(sudoLn == False):
l = input("type the length here: ")
h = input("type the width here: ")
ans = float(l)*float(h)
if(ans == round(ans)):
print(int(ans))
else:
print(ans)
else:
wrongLineError()
elif(command == "area of triangle"):
l = input("type the length here: ")
h = input ("type the height here: ")
ans = (float(l) * float(h))/2
if(ans == round(ans)):
print(int(ans))
else :
print(ans)
elif(command == 'pi'):
if(sudoln):
print(pi)
else:
wrongLineError()
elif(command == "edit file anywhere"):
if(sudoLn):
path = input("enter the path to the file (if the file doesen't exist it will be created): ")
file = open(path, "w+")
Exit = False
while(not Exit):
write = input("type what you would like to be written on the document. type !#exit to return to the the command line: ")
if(write == "!#exit"):
file.close()
Exit = True
else:
file.write(write)
else:
wrongLineError()
elif(command == "delete file anywhere"):
if(sudoLn):
path = input("enter the path to the file you wish to delete: ")
os.remove(path)
print(path + "has been removed")
else:
wrongLineError()
elif(command == 'send unformatted email'):
if(sudoLn):
recipient = input('enter the recipient\'s email address: ')
msg = input("enter the content of the email: ")
print('Sending email...')
sendEmailMessageOnly(msg, password, recipient)
print('Email sent!')
else:
wrongLineError()
elif(command == "send formatted email"):
if(sudoLn):
subject = input('enter the subject line: ')
recipient = input('enter the recipient\'s email address. type multiple to send an email to multiple recipients: ')
if(recipient == 'multiple'):
sendMultiple = True
repeat = True
i = 1
recipient = []
while(repeat):
newRecipient = input('recipient%s\'s email address. type !#continue to continue to select a message and send the email: ' % i)
if(newRecipient == '!#continue'):
repeat = False
else:
recipient.append(newRecipient)
i += 1
message = input("enter the content of the email: ")
print('Sending email...')
if(not sendMultiple):
sendFormattedEmail(password, recipient, subject, message)
else:
sendMultipleFormattedEmails(password, recipient, subject, message)
print("Email sent!")
else:
wrongLineError()
elif(command == "help"):
if(sudoLn):
print(username + """-sudo.ln command help:
>>edit file anywhere > input(s): path > Takes a file path and edits that file.
If the file doesn't already exist it is created.
If you wish to edit a file in the same location as geeko simply enter the name and leave out the path.
>>delete file anywhere > input(s): path > Takes a file path and deletes the file with that path.
If you wish to delete a file in the same location as geeko simply enter the name and leave out the path.
>>send unformatted email > input(s): recipient, message > Sends an email to the recipient containing the message you entered.
>> send formatted email > input(s): recipient, subject line, message > Sends an email to the recipient with the entered subject line and message.
This also enters To and From information into the email.
>>help > no inputs > Shows this help message.
A different message is shown for cmd.ln and sudo.ln.
>>close > input(s): confirmation > If confirmed exits out of geeko.
END %s-sudo.ln HELP""" % username)
else:
print(username + """-cmd.ln command help:
>>add > input(s): first number, second number > Adds two numbers together.
>>subtract > input(s): first number, second number > Subtracts the second number from the first number.
>>multiply > input(s): first number, second number > Multiplies the two numbers together.
>>divide > input(s): first number, second number > Divides the first number by the second number.
>>area of rectangle > input(s): length, width > Calculates the area of a rectangle with the given length and width.
>>area of triangle > input(s): length, height > Calculates the area of a triangle with the given length and height.
>>area of circle > input(s): radius > Calculates the area of a triangle with the given radius.
>>pi > no inputs > Prints the first 16 digits of pi
>>welcome > no inputs > Gives you a special welcome.
>>print reversed sentence > input(s): sentence > Prints the sentence backwards.
>>help > no inputs > Shows this help message.
The help message is different in cmd.ln and sudo.ln.
>>close > input(s): confirmation > If confirmed exits out of geeko.
END %s-cmd.ln HELP""" % username )
elif(command == 'print reversed sentence'):
sentence = input("enter the senctence you want to reverse: ")
sentence = sentence[::-1]
print(sentence)
elif(command == 'weather'):
get_weather(loc_id)
elif(command == "close"):
confirmedOrDenied = False
while(not confirmedOrDenied):
confirmation = input("are you sure you want to close geeko [Y/N]: ")
if(confirmation == 'y' or confirmation == 'Y'):
exit()
elif(confirmation == 'n' or confirmation == 'N'):
confirmedOrDenied = True
print("cancelled")
else:
print('invalid response please enter Y or N')
else:
print(command + ' is not a valid command make sure everything is spelled correctly') # if no registered command was entered return invalid command
There are 2 main ways to do this.
The first one is to webscrape, using requests and beautifulsoup4. This can most easily be done from google, since if you search "weather {city-name}" it gives you a summary of the weather there.
The second is to use an api such as openweathermap, for which there is a great geeksforgeeks tutorial on:
Related
I'm creating a program that activates the timer after receiving the time, ID, and password through the socket.
and when i input "minute" value, I have winError 10053.
I can't understand, why name and hour can be sent, not minute?
this is client code
declStart = input("if you want to login, enter "login" ") # GUI 생기면 버튼으로 대체
if declStart=="login":
while True:
cname = str(input('enter name :'))
if ' ' in cname:
print('Spaces are not allowed.')
continue
client_sock.send(cname.encode())
is_possible_name = client_sock.recv(1024).decode()
if is_possible_name == 'yes':
client_sock.send('!enter'.encode())
goaltime_hour = int(input('goaltime(hour): '))
client_sock.send((str(goaltime_hour)).encode())
goaltime_min = int(input('goaltime(min): '))
client_sock.send((str(goaltime_min)).encode())
goaltime_sec = int(input('goaltime(sec): '))
client_sock.send((str(goaltime_sec)).encode())
elif is_possible_name == 'overlapped':
print('[SYSTEM] The name already exists.')
elif len(client_sock.recv(1024).decode()) == 0:
print('[SYSTEM] The server has been disconnected.')
client_sock.close()
os._exit(1)
while True:
if goaltime_hour <= 0 and goaltime_min <= 0:
print('Please enter the time')
continue
elif (str(type(goaltime_hour)) != "<class 'int'>") or (str(type(goaltime_min)) != "<class 'int'>"):
print("Please enter the int")
continue
else: break
pw = input("enter password")
client_sock.send((str(pw)).encode())
print("login completed. \n ")
break
server
class timeuser:
name: str=None
goaltime_hour: int=None
goaltime_min: int=None
goaltime_sec: int=None
currsecond: int=0
while True:
count = count + 1
conn, addr = server_sock.accept()
client=timeuser()
while True:
username = conn.recv(1024).decode()
if not username in member_name_list:
conn.send('yes'.encode())
break
else:
conn.send('overlapped'.encode())
client.name = username
clientHour = int(conn.recv(1024).decode()) # 시간수신
client.goaltime_hour = clientHour
clientMin = int(conn.recv(1024).decode()) # 분수신
client.goaltime_min = clientMin
clientsec = int(conn.recv(1024).decode()) # 초수신
client.goaltime_sec = clientsec
you can see entire code here :
https://github.com/whataLIN/Pysoc_myStudyTimer
I deleted All other data transmission and reception processes except hour and name, Then it worked fine.
I want to get other data with no error..
Error 10053 is "Connection reset" (WSAECONNRESET). It means the server closed its socket.
That is probably because the client sends !enter and the server tries to read it as a number and crashes. If you looked at the terminal where the server was running, you would see it crash.
i'm trying to implement login attempt system to my current code, but i don't know where i should tick it. Can someone suggest anything? I would like to give three attempts to login, if user fails to login, system will lock user out. I just dont know where to position the code properly.
granted = False
def grant():
global granted
granted = True
def login(name,password):
success = False
file = open("user_details.txt","r")
for i in file:
a,b = i.split(",")
b = b.strip()
if(a==name and b==password):
success=True
break
file.close()
if(success):
print("Login Succesful")
grant()
else:
print("wrong username or password")
The better way to do this problem is by having a JSON file instead of a txt file. You can have the file in this format:
{
"username": {
"password": "",
"attempts": 0,
}
}
In the login() function increment and write the count of attempts if the password is wrong.
And before the function begins read the JSON and check if the attempts value is greater than 3. If it is greater send an appropriate message else to continue the login action and ask for the password.
Your code had some minor errors which I have handled here:
import re
granted = False
def grant():
global granted
granted = True
def login(name,password):
success = False
file = open("user_details.txt","r")
for i in file:
if i.count(',') > 0: # check whether i has at least one ','
a,b = i.split(",")
b = b.strip()
if(a==name and b==password):
success=True
break
file.close()
if(success):
print("Login Succesful")
grant()
else:
print("wrong username or password")
def register(name,password):
file = open("user_details.txt","a")
file.write( "\n"+name[0]+","+password) # name is an array so only the first element is stored.
file.close()
grant()
def access(option):
global name
if(option=="login"):
name = input("Enter your name: ")
password = input("enter your password: ")
login(name,password)
else:
print("Enter yor name and password to register")
name = input("Please enter your name: ").lower().split()
if len(name) > 1:
first_letter = name[0][0]
three_letters_surname = name[-1][:3].rjust(3, 'x')
name = '{}{}'.format(first_letter, three_letters_surname)
print(name)
while True:
password = input("Enter a password: ")
if len(password) < 8:
print("Make sure your password is at lest 8 letters")
elif re.search('[0-9]',password) is None:
print("Make sure your password has a number in it")
elif re.search('[A-Z]',password) is None:
print("Make sure your password has a capital letter in it")
else:
print("Your password seems fine")
break
register (name,password)
def begin():
global option
print("Welcome to Main Menu")
option = input("Login or Register (login,reg): ")
if(option!="login" and option!="reg"):
begin()
begin()
access(option)
if(granted):
print("Welcome to main hub")
print("#### Details ###")
print("Username:",name)
This is a login system where the user types in their details and then this code verifies if the user exists
counter = 0
def validation():
global counter
print("Sorry, this username or password does not exist please try again")
counter += 1
if counter == 3:
print("----------------------------------------------------")
print("You have been locked out please restart to try again")
sys.exit()
def verify_login(username, password, login_data):
for line in login_data:
if ("username: " + username + " password: " + password) == line.strip():
return True
return False
check_failed = True
while check_failed:
with open("accountfile.txt","r") as username_finder:
print("Could player 1 enter their username and password")
username1=input("Please enter your username ")
password1=input("Please enter your password ")
if verify_login(username1, password1, username_finder):
print("you are logged in")
Right now the code looks in the text file for this format:
username: (username) password: (password)
But now I want to add a hash code for every user so the format in the file looks like this:
49ad2322f9a401e9e3c4ae7694b6b1f1 username: (username) password: (password)
How would I change the verfiy_login to make it look for a random 32
characters at the beginning of every user?
Instead of reconstructing the line using "username: " + username + " password: " + password then comparing it to the line from the text file, you can parse it by first splitting the string then unpacking the tokens. By splitting the line, you get access to the hash, username, and password individually as variables.
def verify_login(username, password, login_data):
for line in login_data:
hsh, _, username_from_file, _, password_from_file = line.strip().split()
if len(hsh) == 32 and username == username_from_file and password == password_from_file:
return True
return False
Unpacking a token into _ is a convention saying that "we will dump this value".
Here are simple login scripts.
I have little bugs.
In a text file write:
name :test
password :123321
admin :0
I want to do:
if password and username exist then
#do code
else
#do code
import os
import sys
print "Hello to login - login(username,password)"
login = 0
att = 1
while login == 0:
#Check if user login/exist
Log = raw_input("Enter username: ")
if os.path.isfile(Log + ".txt"):
userfile = (Log+".txt")
f = open(userfile,"r")
Pass = raw_input("enter password: ")
Lines = f.readlines()
Password1 = Lines[1].split(":")
Passwordl = Lines[1].strip()
if Passwordl[10:] == Pass:
login = 1
break
elif att == 3:
print "you try to log in more then 3 time, user locked"
break
else:
print "username not exist or pass wrong"
att += 1
if login == 1:
print "Welcome "
You're problem is indenting- you want to indent everything from Log= to be within the while loop
import os
import sys
print "Hello to login - login(username,password)"
login = 0
att = 1
while login == 0:
#Check if user login/exist
Log = raw_input("Enter username: ")
if os.path.isfile(Log + ".txt"):
userfile = (Log+".txt")
f = open(userfile,"r")
Pass = raw_input("enter password: ")
Lines = f.readlines()
Password1 = Lines[1].split(":")
Passwordl = Lines[1].strip()
if Passwordl[10:] == Pass:
login = 1
break
elif att == 3:
print "you try to log in more then 3 time, user locked"
break
else:
print "username not exist or pass wrong"
att += 1
I have got this code:
import smtplib
import os
import time
import sys
import argparse
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
class smsGatewaying:
def login_gmail(self,user,password):
self.server = smtplib.SMTP("smtp.gmail.com", 587)
self.server.starttls()
try:
gmail_user = args.gmail_user
gmail_password = args.gmail_password
except SMTPAuthenticationError:
print "SMTP authentication went wrong. Most probably the server didn't accept the username/password combination provided."
finally:
if gmail_password < '1':
print 'Insert a password!'
gmail_password = getpass.getpass(prompt="Insert the GMail password: ")
else:
self.server.login(gmail_user, gmail_password)
print 'Login successfully.'
time.sleep(0.75)
x.select_country()
def select_country(self):
print 'Insert country: '
country = raw_input()
if country == 'Italy' or country == 'italy':
italian_carriers = ['number#sms.vodafone.it',
'39number#timnet.com']
select_carriers = raw_input("Select carriers: ")
if select_carriers == 'Vodafone' or select_carriers == 'vodafone':
number = 0
elif select_carriers == 'TIM' or select_carriers == 'tim' or select_carriers == 'Tim':
number = 1
else:
print "L'operatore telefonico selezionato non è disponibile."
time.sleep(0.80)
x.select_country()
x.send_message_normal(italian_carriers[number])
else:
sys.exit()
def send_message_normal(self, carriers):
msg = MIMEMultipart()
msg['sender'] = raw_input("Insert sender: ")
msg['telephone'] = input("Insert telephone number: ")
text = raw_input("Insert text: ")
msg.attach = (MIMEText(text))
carriers.replace('number',str(msg['telephone']))
final = raw_input("Are you sure?[Y/N] ")
if final == 'y' or final == 'Y':
self.server.sendmail(msg['sender'],str(msg['telephone']),text)
elif final == 'n' or final == 'N':
exit_ = raw_input("Do you want to exit?[Y/N] ")
if exit_ == 'Y' or exit_ == 'y':
print 'Run main script...'
newWorkingDirectory = '../BRES.py'
os.path.join(os.path.abspath(sys.path[0]), newWorkingDirectory)
os.system('python BRES.py')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("gmail_user", type=str)
parser.add_argument("gmail_password",type=str)
args = parser.parse_args()
x = smsGatewaying()
print 'Welcome to SMS Gatewaying service! Multiple countries and multiple carriers are available.'
time.sleep(1)
x.login_gmail(args.gmail_user,args.gmail_password)
After the trying to send message to a number, I got this error on shell:
smtplib.SMTPRecipientsRefused: {'29403983292209': (553, "5.1.2 We
weren't able to find the recipient domain. Please check for any\n5.1.2
spelling errors, and make sure you didn't enter any spaces,
periods,\n5.1.2 or other punctuation after the recipient's email
address. a6sm58887940eei.10 - gsmtp")}
I tried all, but without solutions :(
Consider this line:
self.server.sendmail(msg['sender'],str(msg['telephone']),text)
What do you think the value of msg['telephone'] is at this point? Try printing out the value of each of the parameters to self.server.sendmail(). I believe that you will discover that msg[telephone] is the telephone number. It is not an email address.
Try using these two lines instead of the ones you have:
to = carriers.replace('number',str(msg['telephone']))
and
self.server.sendmail(msg['sender'],to,text)
After a lot of searching and crying... the error is ovoked by the email from where you are trying to send.
In my case this one was down, once changed by a functional one the mail came out as usual.
I made tests directly in console, changing the data by normal text and changing one by one until it came out.