Why does my function not execute when the condition is met? - python

I'm trying to make a login form for my server application and have stumbled onto an invisible error (the worst kind). I have a tries variable that increments by 1 every time the user enters the username incorrectly. When the tries variable reaches 3, the program should then execute the block() function. My issue is that it doesn't.
All my .txt files are blank so there's not an error there and everything seems fine. Please help because I'm pulling my hair out!
Here's the code:
import socket
import time
import sys
import os
tries = 0
def server():
def block():
#get host ip
ipBlock = socket.gethostbyname(socket.gethostname())
#create black list
ipBlackList = open("ipBlackList.txt", "w")
ipBlackList.close()
#read black list
ipBlackList = open("ipBlackList.txt", "r")
isBlocked = ipBlackList.readlines()
ipBlackList.close()
#disable account for 60 seconds
if ipBlock in isBlocked:
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print('Your account has been temporarily disabled. Please
try again in '+timer, end=" seconds.\r")
time.sleep(1)
t -= 1
os.remove('ipBlackList.txt')
print('\nYour account has been re-enabled. You may log in
now.')
time.sleep(2)
t = 60
countdown(int(t))
block()
print("Enter administrator login details: ")
def usernameLogin():
#global vars
global tries
if tries == 3:
#read black list
ipBlackList = open("ipBlackList.txt", "r")
isBlocked = ipBlackList.readlines()
ipBlackList.close()
#get host ip
ipBlock = socket.gethostbyname(socket.gethostname())
if ipBlock not in isBlocked:
ipBlackList = open("ipBlackList.txt", "w")
ipBlackList.write(ipBlock)
ipBlackList.close()
block()
username = input("\nUsername: ")
#check if username exists
usernames = open("usernames.txt", "r")
checkUser = usernames.readlines()
usernames.close()
if username not in checkUser:
print("That username doesn't exist. Please try again.")
tries += 1
print(tries)
time.sleep(2)
usernameLogin()
print("im in")
time.sleep(3)
usernameLogin()
server()

In fact, your code do execute the block() function when tries==3, but in the begining of the block() you recreate the black list file, then you read the empty file and as a result the condition if ipBlock in isBlocked: is always false.
So, I've placed the commands that create the file out of the block(). Also, I've changed the remove of the black list file in the countdown() function and recreate but not delete it, because your code try to read it again when restarts to ask the username. Also I've set tries == 0 when block() ends. Also, the indentation at the end of countdown() was incorrect.
import socket
import time
import sys
import os
tries = 0
def server():
def block():
#get host ip
ipBlock = socket.gethostbyname(socket.gethostname())
#read black list
ipBlackList = open("ipBlackList.txt", "r")
isBlocked = ipBlackList.readlines()
ipBlackList.close()
#disable account for 60 seconds
if ipBlock in isBlocked:
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print('Your account has been temporarily disabled. Please \
try again in '+timer, end=" seconds.\r")
time.sleep(1)
t -= 1
#os.remove('ipBlackList.txt')
# Recreate an empty black list file
ipBlackList = open("ipBlackList.txt", "w")
ipBlackList.close()
print('\nYour account has been re-enabled. You may log in \
now.')
time.sleep(2)
t = 6
countdown(int(t))
#create black list file (empty)
ipBlackList = open("ipBlackList.txt", "w")
ipBlackList.close()
block()
print("Enter administrator login details: ")
def usernameLogin():
#global vars
global tries
if tries == 3:
#read black list
ipBlackList = open("ipBlackList.txt", "r")
isBlocked = ipBlackList.readlines()
ipBlackList.close()
#get host ip
ipBlock = socket.gethostbyname(socket.gethostname())
if ipBlock not in isBlocked:
ipBlackList = open("ipBlackList.txt", "w")
ipBlackList.write(ipBlock)
ipBlackList.close()
block()
tries = 0
username = input("\nUsername: ")
#check if username exists
usernames = open("/test/usernames.txt", "r")
checkUser = usernames.readlines()
usernames.close()
if username not in checkUser:
print("That username doesn't exist. Please try again.")
tries += 1
print(tries)
time.sleep(2)
usernameLogin()
print("im in")
time.sleep(3)
usernameLogin()
server()

Related

Python and Telethon - I can't get the channel but only the groups

I am trying to run a script that add members to my group from a CSV file automatically.
Everything works fine but I noticed that the script doesn't return the list of channels but only the list of groups.
Is this a restriction of Telegram or is there a way to do it?
Please see the code below:
`
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty, InputPeerChannel, InputPeerUser
from telethon.errors.rpcerrorlist import PeerFloodError, UserPrivacyRestrictedError
from telethon.tl.functions.channels import InviteToChannelRequest
import sys
import csv
import traceback
import time
api_id = 123456
api_hash = 'YOUR_API_HASH'
phone = '+111111111111'
client = TelegramClient(phone, api_id, api_hash)
client.connect()
if not client.is_user_authorized():
client.send_code_request(phone)
client.sign_in(phone, input('Enter the code: '))
input_file = sys.argv[1]
users = []
with open(input_file, encoding='UTF-8') as f:
rows = csv.reader(f,delimiter=",",lineterminator="\n")
next(rows, None)
for row in rows:
user = {}
user['username'] = row[0]
user['id'] = int(row[1])
user['access_hash'] = int(row[2])
user['name'] = row[3]
users.append(user)
chats = []
last_date = None
chunk_size = 200
groups=[]
result = client(GetDialogsRequest(
offset_date=last_date,
offset_id=0,
offset_peer=InputPeerEmpty(),
limit=chunk_size,
hash = 0
))
chats.extend(result.chats)
for chat in chats:
try:
if chat.megagroup== True:
groups.append(chat)
except:
continue
print('Choose a group to add members:')
i=0
for group in groups:
print(str(i) + '- ' + group.title)
i+=1
g_index = input("Enter a Number: ")
target_group=groups[int(g_index)]
target_group_entity = InputPeerChannel(target_group.id,target_group.access_hash)
mode = int(input("Enter 1 to add by username or 2 to add by ID: "))
for user in users:
try:
print ("Adding {}".format(user['id']))
if mode == 1:
if user['username'] == "":
continue
user_to_add = client.get_input_entity(user['username'])
elif mode == 2:
user_to_add = InputPeerUser(user['id'], user['access_hash'])
else:
sys.exit("Invalid Mode Selected. Please Try Again.")
client(InviteToChannelRequest(target_group_entity,[user_to_add]))
print("Waiting 60 Seconds...")
time.sleep(60)
except PeerFloodError:
print("Getting Flood Error from telegram. Script is stopping now. Please try again after some time.")
except UserPrivacyRestrictedError:
print("The user's privacy settings do not allow you to do this. Skipping.")
except:
traceback.print_exc()
print("Unexpected Error")
continue
`
Thank you!
I can add members to my groups but I cannot add members to my channels (the script doesn't read the list of channels on my tg account).

Python Imap.IMAP4_SSL Authenticate email and password in combolist error

Hello I need help with my code. It keeps giving me authentication-errors.
Can you check it out for me?
All I needed was the code to authenticate successfully and save the working login in a txt-file and the bad login (wrong password) in another txt-file. It works with smtp but keeps giving me an error on imap.
See the code below.
Thanks
The logins in accounts.txt are in the following format email:password
...
import imaplib
import ssl
import socket
import getpass
import re
import socks
import codecs
import unicodedata
import random
from multiprocessing.pool import ThreadPool
# PROXY_TYPE_HTTP
# PROXY_TYPE_SOCKS5
proxy_type = socks.PROXY_TYPE_HTTP
use_proxies = False
thead_count = 1
use_encrpytion = False
accounts = []
accounts_checked = 0
accounts_valid = []
accounts_invalid = []
proxies = []
def check_account(email, password):
try:
if (use_proxies):
proxy = random.choice(proxies)
proxy_host = proxy.split(':')[0]
proxy_port = int(proxy.split(':')[1])
socks.setdefaultproxy(proxy_type, proxy_host, proxy_port)
socks.wrapmodule(imaplib)
mailserver = imaplib.IMAP4_SSL(('mail.' + re.search('#((\w|\w[\w\-]*?\w)\.\w+)', email).group(1)), 993)
mailserver.login(str(email), str(password))
mailserver.close()
return True
except imaplib.IMAP4.error:
print ("Log in failed.")
return False
def get_status(account):
global accounts_checked, accounts
if (':' not in account):
return False
email = account.split(':')[0]
password = account.split(':')[1]
valid = check_account(email, password)
if (valid):
print("Valid: ", account)
f1 = open("connect.txt", "a+")
f1.write(account)
f1.close()
accounts_valid.append(account)
else:
f2 = open("not_connect.txt", "a+")
f2.write(account)
f2.close()
accounts_invalid.append(account)
accounts_checked += 1
print("(" + str(accounts_checked) + "/" + str(len(accounts)) + ")")
return valid
if __name__ == "__main__":
if (use_proxies):
print("Reading \"proxies.txt\"...")
with open("proxies.txt") as f:
for line in f:
if (':' in line):
proxies.append(line)
print("Found " + str(len(proxies)) + " proxies.")
print("Reading \"accounts.txt\"...")
with codecs.open("accounts.txt", encoding='utf-8') as f:
for line in f:
line = unicodedata.normalize('NFKD', line).encode('ascii','ignore').decode('ascii')
if (':' in line):
accounts.append(line.replace("\n", "").replace("\t", ""))
print("Found " + str(len(accounts)) + " accounts.")
print("Creating thread pool...")
pool = ThreadPool(thead_count)
results = pool.map(get_status, accounts)
pool.close()
pool.join()
print("Done checking, writing output...")
print("Completed!")
...
you should create a minimal example, in my case I cannot log in using
imaplib but I do not wrap with the socket stuff.. Why is the ssl
sockets not automatic?
def get_mail_client(email_address):
print(password)
mail = imaplib.IMAP4_SSL(SMTP_SERVER, SMTP_PORT)
mail.login(email_address, password)
return mail
def start(name):
# Use a breakpoint in the code line below to debug your script.
mailClient = get_mail_client(EMAIL)
status, messages = mailClient.select('INBOX')
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
print(messages)
print(messages[0])

Python program not writing anything to CSV file

Got thrown on this project with little python experience. Trying to write from an encoder to a csv. Weird thing is that the program wont even write a string into the file. Any advice is appreciated!
while not file_passed:
try:
file_name = input("Enter log file name: ")
# Add extension if not already given
if "." not in file_name:
file_name += ".csv"
log_file = open(file_name, "a")
print("log file open debug passed")
# Add header row to log file
if os.stat(log_file.name).st_size == 0:
log_file.write("time (ms), pressure, angle(rad) \n")
print("Logged header to file")
file_passed = True
except:
print("Invalid file, or could not open the file specified.\n-----")
Here is a snippet of what I have narrowed it down to I believe. You can see my little debug testing statements to see if its breaking into the correct if statements. It does print all of the debug statements so it seems to be breaking into the if with log_file.write("time(ms), pressure, angle(rad) \n")
EDIT: Tried adding a with before log_file.write("") line, program crashes on start when added. Here is the code in its entirety as I should have added to begin with my bad
import serial
from datetime import datetime
import os
pressure_passed = False
arduino_passed = False
file_passed = False
BAUD_RATE = 115200
GARBAGE_CYCLES = 3 # how many cycles to ignore before logging data
garbage_cycle = 0
# Save data to log file
def LogData(startTime, pressureData, arduinoData, file):
global garbage_cycle
if garbage_cycle < GARBAGE_CYCLES:
garbage_cycle += 1
else:
delta = datetime.now() - startTime
ms = delta.total_seconds() * 1000
dataString = "{:0.2f}, {}, {}\n".format(ms, pressureData, arduinoData)
file.write(dataString)
print(dataString, end = "")
# Get the COM port for the Mark-10 Series 5
while not pressure_passed:
try:
pressure_com = input("Enter Mark-10 Series 5 COM Port #: ")
pressure_ser = serial.Serial("COM" + str(pressure_com), BAUD_RATE)
pressure_passed = True
except:
print("Invalid COM Port, please enter a valid port.\n-----")
# Get the COM port for the Arduino
while not arduino_passed:
try:
arduino_com = input("Enter Ardunio COM Port #: ")
arduino_ser = serial.Serial("COM" + str(arduino_com), BAUD_RATE)
arduino_passed = True
except:
print("Invalid COM Port, please enter a valid port.\n-----")
# Get the name for the log file
while not file_passed:
try:
file_name = input("Enter log file name: ")
# Add extension if not already given
if "." not in file_name:
file_name += ".csv"
log_file = open(file_name, "a")
# Add header row to log file
if os.stat(log_file.name).st_size == 0:
log_file.write("time (ms), pressure, angle (deg)\n")
file_passed = True
except:
print("Invalid file, or could not open the file specified.\n-----")
start = datetime.now()
# Variables to read serial input
pressure_data = ""
last_pressure = ""
arduino_data = ""
last_arduino = ""
# Main program loop
# Serial is read from byte by byte to better sync the two devices
while True:
try:
x_changed = False
y_changed = False
# Read from Mark-10 serial if available
# x is a byte read from the serial line, converted to ascii
if pressure_ser.in_waiting > 0:
x = pressure_ser.read().decode('ascii')
x_changed = True
# Read from Arduino serial if available
# y is a byte read from the serial line, converted to ascii
if arduino_ser.in_waiting > 0:
y = arduino_ser.read().decode('ascii')
y_changed = True
# If new data received, check if we should log it
if x_changed:
if x == '\n': # New line detected, log the accumulated data
if last_pressure != pressure_data:
LogData(start, last_pressure, last_arduino, log_file)
last_pressure = pressure_data
pressure_data = ""
elif x != '\r': # Otherwise, add the read character to the string
pressure_data += x
if y_changed:
if y == '\n': # New line detected, log the accumulated data
if last_arduino != arduino_data:
LogData(start, last_pressure, last_arduino, log_file)
last_arduino = arduino_data
arduino_data = ""
elif y != '\r': # Otherwise, add the read character to the string
arduino_data += y
except Exception as e:
print(e)
if arduino_ser.isOpen():
arduino_ser.close()
if pressure_ser.isOpen():
pressure_ser.close()
log_file.close()
break

RFID scanner doesn't scan afterwards

I am very new to coding and I'm working on this project that I have no idea why is it not running as expected. I am sorry if I'm not posting this correctly because this is my first time posting on stackoverflow. Pardon my English if there's any point where I didn't explain it correctly.
This is a project supposed to be a security system one, where we work with RFID Scanner, Camera, LED, Servo and PIR Sensor.
The conditions are as, when the time is 7am to 11pm, the pir sensor would be off and when time is 11pm onwards to 7am in the morning, the PIR sensor and camera will be turned on. Where during anytime, as long as the number of people in the house is = 0 (determined by the RFID), the camera and PIR Sensor would turn on too.
I haven't got a chance to even test out my code's logic, because when I tried to run the code, an error occurs at the loop part. "Scan a registered card to skip registration" would print and "checkpoint" would print, but afterward the code just stops there. It is supposed to be listening to the RFID scanner to read for scans, but when I tapped my card on the RFID scanner there was no response. And my code just dies there. As I'm very new to coding and python, I don't know where the errors could be. Would appreciate the help given!!
import RPi.GPIO as GPIO
from time import sleep
import sys
import requests
from datetime import datetime
from mfrc522 import SimpleMFRC522 #RFID
import os
import pygame, sys
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from pygame.locals import *
import pygame.camera
width = 640
height = 480
#initialise pygame
pygame.init()
pygame.camera.init()
cam = pygame.camera.Camera("/dev/video0",(width,height))
no=0
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(24,GPIO.OUT) #LED
GPIO.setup(26,GPIO.OUT) #Servo
GPIO.setup(17,GPIO.IN) #PIR Sensor
current_time =datetime.now() #Current time
sleep(5)
reader = SimpleMFRC522() #RFID reader
auth = []
in_house =[]
p = open("presentlist.txt","a+")
p = open("presentlist.txt","r+")
present = 0
PIR_state =0
PWM=GPIO.PWM(26,50) #Set 50hz PWM output at GPIO26
PWM.start(12) #To edit to actual 3oclock (Locked)
fromaddr = "pythonprogramtest123#gmail.com" # change the email address accordingly
toaddr = "pythonprogramtest123#gmail.com" # Same email
#password: abcdefgpython
mail = MIMEMultipart()
mail['From'] = fromaddr
mail['To'] = toaddr
mail['Subject'] = "Attachment"
body = "Unusual movement detected"
print('Door Locked')
print("Hold card near the reader to register it in the database.")
print("Registration up to 10 cards")
print("Scan a registered card to skip registration")
for count in range (0,11):
print("checkpoint1")
id = reader.read_id()
id = str(id)
f = open("authlist.txt", "a+")
f = open("authlist.txt", "r+")
print("checkpoint2")
if f.mode == "r+":
auth=f.read()
if id not in auth:
f.write(id)
f.write('\n')
f.close()
pos = auth.count('\n')
print("New card with UID", id, "detected: registered as entry #",pos)
count = count +1
else:
number = auth.split('\n')
pos = number.index(id)
print("Card with UID", id, "already registered as entry #", pos)
count = 11
break
while (True):
id = reader.read_id()
id = str(id)
f = open("authlist.txt", "a+")
f = open("authlist.txt", "r+")
if current_time.hour >= 7 or current_time.hour <= 23 or present == 0: #awake or nobody in house
#RFID is on
if f.mode == "r+":
auth=f.read()
if id in auth and id not in in_house:
p.write(id)
p.write('\n')
p.close()
present = in_house.count('\n')
print("Recognition successful \n Allowing Access")
PWM.start(1) #Servo to actual 12 o clock position (Unlocking)
print("Door unlocked for 30 seconds. Tap once more to change to 1 minute")
if f.mode == "r+":
auth=f.read()
if id in auth:
print("Unlocking door for 1 minute")
sleep(60)
PWM.start(12) #To edit to actual 3oclock (Locked)
f.close()
else: #no tap detected
sleep(30)
PWM.start(12) #To edit to actual 3oclock (Locked)
f.close()
break
elif id in auth and id in in_house:
p.remove(id)
print("Recognition successful \n Allowing Access")
PWM.start(1) #Servo to actual 12 o clock position (Unlocking)
print("Door unlocked for 30 seconds. Tap once more to change to 1 minute")
if f.mode == "r+":
auth=f.read()
if id in auth:
print("Unlocking door for 1 minute")
sleep(60)
PWM.start(12) #To edit to actual 3oclock (Locked)
f.close()
else: #no tap detected
sleep(30)
PWM.start(12) #To edit to actual 3oclock (Locked)
f.close()
break
else:
print("Card not recognised \n Access Denied")
break
elif current_time.hour < 7 or current_time.hour > 23: #sleeping
id = reader.read_id()
id = str(id)
f = open("authlist.txt", "a+")
f = open("authlist.txt", "r+")
#RFID is on
if f.mode == "r+":
auth=f.read()
if id in auth:
print("Recognition successful \n Allowing Access")
PWM.start(1) #Servo to actual 12 o clock position (Unlocking)
print("Door unlocked for 30 seconds. Tap once more to change to 1 minute")
if f.mode == "r+":
auth=f.read()
if id in auth:
print("Unlocking door for 1 minute")
sleep(60)
PWM.start(12) #To edit to actual 3oclock (Locked)
else: #no tap detected
sleep(30)
PWM.start(12) #To edit to actual 3oclock (Locked)
break
else:
print("Card not recognised \n Access Denied")
break
#Camera
if GPIO.input(17): #read a HIGH i.e. motion is detected
#LED Blink
GPIO.output(24,1)
sleep(1)
GPIO.output(24,0)
sleep(1)
GPIO.output(24,1)
sleep(1)
GPIO.output(24,0)
if PIR_state==0:
print('detected HIGH i.e. motion detected')
PIR_state=1
#Camera
cam.start() #start
image = cam.get_image() #take pic
cam.stop()
no = no + 1
saved_img=pygame.image.save(windowSurfaceObj,'picture' + "{:03d}".format(no) + '.jpg')
#Thingspeak
print("Updating Thingpseak")
resp = requests.get("GET https://api.thingspeak.com/update?api_key=PQ44ZG5JR49ABODY&field1=0")
#Email
def sendMail(data):
mail.attach(MIMEText(body, 'plain'))
print (data)
dat='%s.jpg'%data
print (dat)
attachment = open(dat, 'rb')
image=MIMEImage(attachment.read())
attachment.close()
mail.attach(image)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "abcdefgpython")
text = mail.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
else: #read a LOW i.e. no motion is detected
if PIR_state==1:
print('detected LOW i.e. no motion detected')
PIR_state=0
sleep(1)
print("...")
break
sleep(2)

Telegram add scraped users from a csv file from a specific line to specific line

Please is somebody who can help to customize bellow code to make it able to add Telegram scraped users from a CSV file from a specific line to a specific line (ie: from line 13 to line 32 of the CSV file). I need it to avoid get account banned by telegram by adding my group users in my channel.
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty, InputPeerChannel, InputPeerUser
from telethon.errors.rpcerrorlist import PeerFloodError, UserPrivacyRestrictedError
from telethon.tl.functions.channels import InviteToChannelRequest
import sys
import csv
import traceback
import time
import random
api_id = 111111111 #Enter Your 7 Digit Telegram API ID.
api_hash = '0000000000000000000000' #Enter Yor 32 Character API Hash
phone = '+2000000000' #Enter Your Mobilr Number With Country Code.
client = TelegramClient(phone, api_id, api_hash)
async def main():
# Now you can use all client methods listed below, like for example...
await client.send_message('me', 'Hello !!!!!')
SLEEP_TIME_1 = 300
SLEEP_TIME_2 = 300
with client:
client.loop.run_until_complete(main())
client.connect()
if not client.is_user_authorized():
client.send_code_request(phone)
client.sign_in(phone, input('40779'))
users = []
with open(r"Scrapped.csv", encoding='UTF-8') as f: #Enter your file name
rows = csv.reader(f,delimiter=",",lineterminator="\n")
next(rows, None)
for row in rows:
user = {}
user['username'] = row[0]
user['id'] = int(row[1])
user['access_hash'] = int(row[2])
user['name'] = row[3]
users.append(user)
chats = []
last_date = None
chunk_size = 200
groups = []
result = client(GetDialogsRequest(
offset_date=last_date,
offset_id=0,
offset_peer=InputPeerEmpty(),
limit=chunk_size,
hash=0
))
chats.extend(result.chats)
for chat in chats:
try:
if chat.megagroup == True:
groups.append(chat)
except:
continue
print('Choose a group to add members:')
i = 0
for group in groups:
print(str(i) + '- ' + group.title)
i += 1
g_index = input("Enter a Number: ")
target_group = groups[int(g_index)]
target_group_entity = InputPeerChannel(target_group.id, target_group.access_hash)
mode = int(input("Enter 1 to add by username or 2 to add by ID: "))
n = 0
for user in users:
n += 1
if n % 80 == 0:
sleep(60)
try:
print("Adding {}".format(user['id']))
if mode == 1:
if user['username'] == "":
continue
user_to_add = client.get_input_entity(user['username'])
elif mode == 2:
user_to_add = InputPeerUser(user['id'], user['access_hash'])
else:
sys.exit("Invalid Mode Selected. Please Try Again.")
client(InviteToChannelRequest(target_group_entity, [user_to_add]))
print("Waiting for 120-180 Seconds...")
time.sleep(random.randrange(120, 180))
except PeerFloodError:
print("Getting Flood Error from telegram. Script is stopping now. Please try again after some time.")
print("Waiting {} seconds".format(SLEEP_TIME_2))
time.sleep(SLEEP_TIME_2)
except UserPrivacyRestrictedError:
print("The user's privacy settings do not allow you to do this. Skipping.")
print("Waiting for 30-60 Seconds...")
time.sleep(random.randrange(30, 60))
except:
traceback.print_exc()
print("Unexpected Error")
continue
Thanks by advance

Categories