if data.find('PRIVMSG') != -1:
nick = data.split('!')[ 0 ].replace(':','')
text = ''
if data.count(text) >= 200:
sck.send('KICK ' + " " + chan + " :" 'flooding' + '\r\n')
I'm trying to code a flood protection for the bot, I want it to kick a user if he enters more then 200 characters, how can I make it so it can read the other lines instead of just the first line? and the code above doesn't work, it doesnt kick the user but if I change the sck.send() to sck.send('PRIVMSG ' + chan + " :" 'flooding' + '\r\n') it works.
fixed the kicking problem, and the code works now, but it only reads the first line, not sure how to make it read the other lines if the user keeps flooding the channel.
if data.find('PRIVMSG') != -1:
nick = data.split('!')[ 0 ].replace(':','')
text = ''
if data.count(text) >= 200:
sck.send('KICK ' + " " + chan + " " + nick + " :" 'flooding' + '\r\n')
As far as I remember, the colon is a reserved character in the IRC protocol. That is, the first colon in a server message denotes the start of user-supplied data (that's also why ":" is not allowed in nicks/channel names). Hence, it suffices to search for the first colon and calculate the length of the remaining string.
Furthermore, data.find('PRIVMSG') is pretty unreliable. What if a user types the word "PRIVMSG" in regular channel conversation? Go look up the IRC RFC, it specifies the format of PRIVMSGs in detail.
Besides, you should be a little more specific. What exactly is the problem you're facing? Extracting the nick? Calculating the message length? Connecting to IRC?
Related
I want to add a serial no every time a new user information gets appended in.
def get_info():
op = open('sign in info win.txt', 'a')
serialno here is written to show where i want to add sno.
this piece of code is non working
op.write('information-no - ' + serialno + ' Name = ' + enter_name.get() + ' Password = ' + enter_password.get() + '\n')
op.close()
message = messagebox
message.showwarning(title='Saved !', message='Information Saved.')
The code in your question should already do the job, so if you're looking for a way to create a serial number perhaps you could use random.
import random
def generate_serial(length=10):
characters = list(range(0, 9))
serial = ''
for c in range(length):
serial += str( random.choice(characters) )
return serial
# Your existing code
def get_info():
serialno = generate_serial() # generate a new serialno each time
op = open('sign in info win.txt', 'a')
op.write('information-no - ' + serialno + ' Name = ' + enter_name.get() + ' Password = ' + enter_password.get() + '\n')
op.close()
message = messagebox
message.showwarning(title='Saved !', message='Information Saved.')
Here's a sample of what sort of serial numbers this would produce:
'5570344311'
'3852070084'
'5115012613'
'1655833704'
'6875243550'
Please note that while unlikely, it's entirely possible that generate_serial() will produce the same serial number for more than one user. Longer serial numbers or ones that can also contain letters reduce this probability, but if you want unique serials for every user this is not the way to go!
This question already has answers here:
How do I print colored text to the terminal?
(64 answers)
Closed 1 year ago.
as maybe some of you know and regarding to shell scripts - tput is utility uses the terminfo database to make the values of terminal-dependent capabilities and information available to the shell
in my python script I have the following example: ( just a sample from long code )
for TOPIC in list:
if str(val) in TOPIC:
word = TOPIC.split()[1]
print ("Topic " + word + " is successfully configured")
else:
try:
word = TOPIC.split()[1]
print ("Topic " + word + " bad configuration")
except IndexError:
pass
I want to change the color from white to green on the following printing:
print ("Topic " + word + " is successfully configured")
or to change the color from white to red on:
print ("Topic " + word + " bad configuration")
is it possible to change the color in python3 as we did for example in bash scripts?
import os
os.system("")
RED = "\x1B["
GREEN = '\033[32m'
word = "random_topic_name"
print(GREEN+"Topic " + word + "successfully configured" )
print(RED+"Topic " + word + "bad configuration" )
I need help to manage special characters in python. I'm working with a FPE library (pyffx) to encrypt data. Well, when my software encrypts the data there are no problems. When the software decrypts the data, it changes the format for example, by transforming a single \ into \\\\. I tried to encode/decode with utf-8 and also to maintain the raw value of the string. Here you can find an example of the encryption:
Encrypted data phase: uc?WL7+&u3*RAZuYPW1hc%/8sqX0?CBMlCCV-\mPC^RQ3&EsMRt|UIjs8KRLpzCbTI=3uBQcGWx6eXdVeV?nZmqCZtE/UAA\F7dbkuCTubyjng.%6AfhWh3H6V/b.ic7msw|lw-kiUuxCxCjPP%Uj.94h.*?ugB2j?TnujjL\2^aA2iYHGax?AQb7.VA76QTFcd7Ds2YL5OjI8Ue^Kmm9kC5t20M=mu8TDG4XK5xIifkUZMfWYYRa3£mbH/mGtAw\pN5nLOD2zEI/£82T7EKUa-v%*-l^GFS1-92t0N?EU&d7NEm&d|mbgl|fIKA-n|fEFV0OQ?OO^NmfDxiVsboMFho
Decription phase: b'uc?WL7+&u3*RAZuYPW1hc%/8sqX0?CBMlCCV-\\\\mPC^RQ3&EsMRt|UIjs8KRLpzCbTI=3uBQcGWx6eXdVeV?nZmqCZtE/UAA\\\\F7dbkuCTubyjng.%6AfhWh3H6V/b.ic7msw|lw-kiUuxCxCjPP%Uj.94h.*?ugB2j?TnujjL\\\\2^aA2iYHGax?AQb7.VA76QTFcd7Ds2YL5OjI8Ue^Kmm9kC5t20M=mu8TDG4XK5xIifkUZMfWYYRa3\\xa3mbH/mGtAw\\\\pN5nLOD2zEI/\\xa382T7EKUa-v%*-l^GFS1-92t0N?EU&d7NEm&d|mbgl|fIKA-n|fEFV0OQ?OO^NmfDxiVsboMFho'
In attachment you can find the example code:
def fpeencryption(data):
e = pyffx.String(b'secret-key', alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.|/%&£+-*=?^\\", length=len(data))
print("Encription phase: " + str(data) + " size: " + str(len(data)))
encrypted = (e.encrypt(data))
print("Encrypted data phase: " + str((encrypted)) + " size: " + str(len(data)))
return (encrypted)
def fpedecryption(data):
e = pyffx.String(b'secret-key', alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.|/%&£+-*=?^\\", length=len(data))
print("Decription phase: " + str((data)))
decrypted = e.decrypt(data.decode("utf-8"))
print("Decr: " + str(decrypted))
return decrypted
Data is a simple string with symbols/numbers/letter. Could you please help me? Thanks
SOLUTION
I solved the problem by changing the alphabet to:
alphabet=string.ascii_letters+string.digits+SPECIAL_CHARS
I am stymied with something, and if I fix it one way, it breaks something else.
I have a set of data that lists file status by country. What I want to do is, for each country in the Country column, print all missing files by each status in the VisitStatus column. So for all rows where country=France, then for every visit that is "Complete", list the number of missing files.
There are two dataframes that I am concatenating into one combined set to work with and deliver final output. I am concat'ing df_s and df_ins into df_combined.
When I grab a set of unique values for the Country and VisitStatus columns to loop over, then try to write out the results per country to an Excel file workbook, quirks in the data kick out a 'duplicate sheetname' error. In one of the source dataframes, there is a status of "Do Not Review" in the VisitStatus column, but in the other source dataframe, it's named "Do not review", lowercase for the second two words. When they're concatenated, this kicks out unique values of "Do Not Review" and "Do not review". Then when the xslx writer tries to make the workbooks for the second one, it checks it against the existing workbooks DISREGARDING CASE, finds the first one, decides they are the same since it is ignoring case, and kicks out the error saying that the 'Do not review' worksheet already exists.
If I run replace() and change all the "Do not review" values in the VisitStatus column into "Do Not Review" so they all match and don't give two results for that when I call unique(), it breaks and gives me a KeyError on VisitStatus.
So far I have read thread after thread about this and haven't been able to solve this. I just tried running the replace() on the source dataframe, and then it throws an error saying that "status" is a float and can't be handled like a string.
I'm at a loss. Thanks in advance!
# COMBO
# Merge the screening and in study datasets
df_combined = pd.concat([df_s,df_ins], axis=0, ignore_index=True)
df_combined = df_combined.query('VisitStatus != "Hand Off Information"')
print(df_combined.columns.values)
print("---------------------------------------------------------------------------------")
# Display and save out country and missing file status
statuses = df_combined['VisitStatus'].unique()
countries = df_combined['Country'].unique()
for status in statuses:
print("X" + status + "X")
print('\n')
print (statuses)
for country in countries:
for status in statuses:
print('\n')
print("---> Missing Files for " + country + " all visits with status of: " + str(status))
df_cmb = df_combined[(df_combined.Country==country) & (df_combined.VisitStatus==status)]
print('\n')
numRows=df_cmb.shape[0]
if numRows > 0:
print("----> Number of visits in " + str(status) + " subset: " + str(numRows))
print("DRF Forms Missing: " + str(df_cmb['DRF-Form-Uploaded'].sum()) + " vs. " + str(numRows - df_cmb['DRF-Form-Uploaded'].sum()) + " collected")
print("CSSRS Forms Missing: " + str(df_cmb['CSSRS-Form-Uploaded'].sum()) + " vs. " + str(numRows - df_cmb['CSSRS-Form-Uploaded'].sum()) + " collected")
print("CDR Forms Missing: " + str(df_cmb['CDR-Form-Uploaded'].sum()) + " vs. " + str(numRows - df_cmb['CDR-Form-Uploaded'].sum()) + " collected")
print("CDR Audio Missing: " + str(df_cmb['CDR-Audio-Uploaded'].sum()) + " vs. " + str(numRows - df_cmb['CDR-Audio-Uploaded'].sum()) + " collected")
print("MMSE Forms Missing: " + str(df_cmb['MMSE-Form-Uploaded'].sum()) + " vs. " + str(numRows - df_cmb['MMSE-Form-Uploaded'].sum()) + " collected")
print("MMSE Audio Missing: " + str(df_cmb['MMSE-Audio-Uploaded'].sum()) + " vs. " + str(numRows - df_cmb['MMSE-Audio-Uploaded'].sum()) + " collected")
print("RBANS Forms Missing: " + str(df_cmb['RBANS-Form-Uploaded'].sum()) + " vs. " + str(numRows - df_cmb['RBANS-Form-Uploaded'].sum()) + " collected")
print("RBANS Audio Missing: " + str(df_cmb['RBANS-Audio-Uploaded'].sum()) + " vs. " + str(numRows - df_cmb['RBANS-Audio-Uploaded'].sum()) + " collected")
print("--------------------------------------")
print('\n')
else:
print("No " + status + " files/visits for " + country)
if country =="United States":
country="USA"
# something is borked in the next line - somehow there are two "Do Not Review" status types in the combined file, triggers an "already in use" for sheetname
df_cmb.to_excel(combo_writer, header=True, index=False, sheet_name=str(country)[:3] + "-by-" + str(status))
Oh lord. I'm answering my own question.
So I tinkered some more and nothing else made sense, so I started wondering if I was putting in the arguments for replace() correctly, and I had them backwards. I assumed the "Do not review" needed to be changed to "Do Not Review", but it was the other way around...I assumed incorrectly as to which source file data needed to be modified. Once I flipped them, it works.
I have a script which prints variables (set by user) perfectly.
os.system('clear')
print "Motion Detection Started"
print "------------------------"
print "Pixel Threshold (How much) = " + str(threshold)
print "Sensitivity (changed Pixels) = " + str(sensitivity)
print "File Path for Image Save = " + filepath
print "---------- Motion Capture File Activity --------------"
I now wish to email this code to myself to confirm when running. I have included in the script email using email.mimieText and multipart. But the output no longer shows the relative variables just the code.
body = """ Motion Detection Started \n Pixel Threshold (How much) = " + str(threshold) \n Sensitivity (changed Pixels) = " + str(sensitivity) \n File Path for Image Save = " + filepath """
Im sure it is the """ wrapper but unclear what i should use instead?
in python """ quotes mean to take everything between them literally.
The easiest solution here would be to define a string myString="", then at every print statement, instead of printing you can append to your string with myString=myString+"whatever I want to append\n"
It should be:
body = " Motion Detection Started \n Pixel Threshold (How much) = " + str(threshold) + \
"\n Sensitivity (changed Pixels) = " + str(sensitivity) + \
"\n File Path for Image Save = " + filepath
When you do the following, you're telling it everything there is part of the string (notice how the code highlights):
body = """ Motion Detection Started \n Pixel Threshold (How much) = " + str(threshold) \n Sensitivity (changed Pixels) = " + str(sensitivity) \n File Path for Image Save = " + filepath """
You need to actually add the variables to the string, like when you concatenated them in your print statement.
body = "Motion Detection Started \n Pixel Threshold (How much) = " + str(threshold) + " \n Sensitivity (changed Pixels) = " + str(sensitivity) + "\n File Path for Image Save = " + filepath
You can also do string formatting:
body = "Motion Detection Started\nPixel Threshold (How much) = {}\nSensitivity (changed Pixels) = {}\nFile Path for Image Save = {}".format(threshold, sensitivity, filepath)
In case you'd like the emails code to be a bit more reusable and robust, Template strings might help you. E.g., save the email text as a template in separate file, template.txt:
Motion Detection Started
------------------------------------------------------
Pixel Threshold (How much) = $threshold
Sensitivity (changed Pixels) = $sensitivity
File Path for Image Save = $filepath
---------- Motion Capture File Activity --------------
and in your code, create a class for sending emails together with 1 or more instances of the class (you can have more than 1 template):
import string
class DebugEmail():
def __init__(self, templateFileName="default_template.txt"):
with open(templateFileName) as f:
self.template = string.Template(f.read())
def send(self, data):
body = self.template.safe_substitute(data)
print(body) # replace by sending email
debugEmail1 = DebugEmail("template.txt")
# and test it like this:
threshold = 1
sensitivity = 1
debugEmail1.send(locals())
sensitivity = 200
filepath = "file"
debugEmail1.send(locals())