Python socket server new line issue - python

so I am making a socket server in python but every time a message is sent it does a new line like this
Rank: Admin
Rank Password: **Censored**
Nickname: SomeoneElse
[Admin
] Testusername
: hello
but what I want it to Receive is
[Admin] Testusername: hello
but every time the code is asking for the nickname rank and message with %s it does a new line here is the code being used
def rank(conn, prefix="Rank: "):
conn.send(prefix)
return conn.recv(512)
def nickname(conn, prefix="Nickname: "):
conn.send(prefix)
return conn.recv(512)
rank = rank(conn)
nickname = nickname(conn)
message = conn.recv(512)
if message:
reply = "[%s] %s: %s" % (rank, nickname, message)
broadcast(reply, conn)
else:
remove(conn)
def broadcast(message, connection):
for cons in bc:
if cons != connection:
try:
cons.sendall(message)
except:
cons.close()
remove(cons)
def remove(connection):
if connection in bc:
bc.remove(connection)
that is the code to the message system why is it doing a new line every time %s is used? btw I removed the other code cause its irrelevant to my question
I changed nickname to "nickname" so and it showed this
[Admin
] nickname: hi

Related

ERROR: imaplib.IMAP4.error: UID command error: BAD [b'Command Argument Error. 11']

I made a program to run a function every time a new email is received. The IMAP server, connection and inbox work as intended. it is also not an issue with the whole '"Inbox"' vs 'Inbox' format. I have tried almost everything I could think of with little to no success.
My code:
def connect():
global connected
#sets up connection with imap server
connection = imaplib.IMAP4_SSL("outlook.office365.com")
try:
(retcode, capabilities) = connection.login(login, secure_password)
except:
print(sys.exc_info()[1])
sys.exit(1)
print("connection successful")
connected = True
return connection
def disconnect(connection):
connection.logout()
connected = False
connection = connect()
while connected == True:
print("Searching for new Emails...")
connection.select(mailbox = "Inbox", readonly=False)
# test section start
result, data_for_update = connection.uid('search', None, "ALL")
ids = data_for_update[0]
id_list = ids.split()
if data_for_update[0].split()[-1] == latest_email_uid:
print('No new emails found. search again in 5 minutes')
time.sleep(300)
else:
result, data_for_update = connection.uid('fetch', latest_email_uid, '(RFC822)')
raw_email = data_for_update[0],[1]
latest_email_uid == data_for_update[0].split()[-1]
print('New email found')
time.sleep(300)
I tried to program to run the code above. But when I run it, it returns this error:
\lib\imaplib.py", line 1055, in _command_complete
raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.IMAP4.error: UID command error: BAD [b'Command Argument Error. 11']

python sockets, trying to make a log in interaction betwen server and client

Hello so i have my server with a database (dictironay) and another passworddatabase
import socket
import sys
from _thread import *
host = ""
port = 8000
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket Created")
try:
serversocket.bind((host, port))
except socket.error as e:
print(str(e))
sys.exit()
database = {"name1" :{"hair" : "red", "size" : 1.50}}
password_database = {"name1": "1234",
"name2": "4321"}
def client_thread(conn): #threader client
welcome = "Welcome to the server. Type something and hit enter \n"
conn.send(welcome.encode("UTF-8"))
login(conn)
while True: # NOT IMPORTANT KEEP READING
data = conn.recv(24)
reply = data.decode("UTF-8")
if reply == "1":
menu1 = "Menu 1: Buy \n"
conn.send(menu1.encode("UTF-8"))
else:
wrong = "wrong option \n"
conn.send(wrong.encode("UTF-8"))
def login(conn): #MY LOGIC PROBLEM IS HERE
log = "Log in MENU: \n"
logi = log.encode("UTF-8")
conn.send(logi)
us = "Username: \n"
use = us.encode("UTF-8")
conn.send(use)
userr = conn.recv(24)
user = userr.decode("UTF-8")
pa = "Password: \n"
pasw = pa.encode("UTF-8")
conn.send(pasw)
passr = conn.recv(24)
passw = passr.decode("UTF-8")
tries = 0
while tries < 3:
if user in passwordDictionary and passwordDictionary[user] == passw:
print("Logged in")
menu()
else:
print("Wrong Username Or Password \n")
tries += 1
print("You failed the login too many times, blocking you out")
conn.close()
while 1: # NOT IMPORTANT
conn, addr = serversocket.accept()
print("Connected with " + addr[0] + ":" + str(addr[1]))
start_new_thread(client_thread, (conn, ))
serversocket.close()
Whats working:
The server is working fine, i'm having troubles doing the login on the client side.
client.py ==> client DOESNT go into the if data == Log in menu
is there a better way to do this?
#! /usr/bin/python3
import socket
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 8000))
print("Connected")
datae = clientsocket.recv(24)
data = datae.decode("UTF-8")
clientsocket.send(datae)
while data != "!q":
if data == "Log in MENU: \n":
usere = input()
user = usere.encode("UTF-8")
clientsocket.send(user)
What would be the best way to create an log in interaction with the server?
the server has the usernames and passwords, i need to log in and then i need to edit the database depending on what user was chossen, but i'm having a hard time doing the algorithm
theres problems with the code you provided... however ill assume it actually works for you somehow and rather than copy paste you manually typed it
you are recieveing the first message here
datae = clientsocket.recv(24)
data = datae.decode("UTF-8") # GOT A MESSAGE
You then have the message datae = b'Welcome to the server. '
which does not match "Log in MENU: \n", and data != "!q" so it goes back into your loop and checks if data == "Log in MENU: \n" it doesnt so it repeats ... but you never get the next message instead try something like this second message
data = ""
while data != "!q":
if data == "Log in MENU: \n":
usere = input()
user = usere.encode("UTF-8")
clientsocket.send(user)
data = clientsocket.recv(24).decode("UTF-8") # GET THE NEXT MESSAGE!
but even then you are going to have problems because your server continues to write so you will get something like "Log in MENU: \nUsername" or something .... basically you need to work out a better message passing scheme than recv(24)
To avoid Errors try using a header with something like 64 Bytes wich always is the first message send. This Header is then used to send the actual length of the following message to the server. For example:
def send_response(conn, msg):
message = msg.encode(FORMAT)
send_length = len(str(len(message)).encode(FORMAT))
res_len = bytes(len(message)) + (b' ' * (HEADER - send_length))
print(f"[SENDING MESSAGE] {msg}")
conn.send(res_len)
conn.send(response)

Chat Client/Server problems on Python

Me and a friend of mine are doing a chat room with python, basically he's doing the server part and I'm doing the GUI and Client part, I don't know why the app just stop to work without any reason showing the Windows message "Python is not responding"
This is the Server code:
#max name length=9999
#max message types=100
#max groupmsg recipients = 9999
#max msg length =8191 characters
import socket
import threading
import sys
def find_users(): #Continously Searches For New Clients
while True:
user, client_address = connector.accept()
threading.Thread(target=new_user, args=(user,)).start()
def new_user(identity):
while True:
print(identity)
name_length=identity.recv(4).decode() #max user name length =9999
username=identity.recv(int(name_length)).decode()
password=identity.recv(8192).decode()
if username in user_details and password == user_details[username]: #correct credentials
client_details[usename]=identity
identity.sendall('y'.encode())
break
elif username in user_details: #incorrect password
print('Please Re-enter The User Details')
identity.sendall('n'.encode())
else: #New user
user_details[username]=password
client_details[username]=identity
identity.sendall('y'.encode())
break
pubmsg(username+' has connected')
active_users.append(username)
identity.settimeout(5)
try:
while True: #waits for incoming messages
msgtype= identity.recv(2).decode() #identifies message type, max types =100
if msgtype == '01': #public message
communication = identity.recv(8192).decode()
pubmsg(str(username + ' >>> ' + communication))
elif msgtype == '02': #private message
direction=[]
recipno=identitiy.recv(4) #defines max group msg recipients
for y in range(0,recipno): #repeats once per recipient
recip_name_length=identity.recv(4).decode()
recip_name=identity.recv(recip_name_length).decode()
direction.append(recip_name)
gmsg=identity.recv(8192).decode()
groupmsg(gmsg,direction)
except Exception as e:
active_users.remove(username)
del client_details[username]
pubmsg(username+' disconnected')
identity.close()
sys.exit()
def pubmsg(Group_message):
print(Group_message)
for person in client_details:
client_details[person].sendall(Group_message.encode())
def groupmsg(Direct_message,recipients,sender):
gmsg=sender +' (to '
for person in recipients: #repeats once per recipient
gmsg+=person+', '
gmsg=gmsg.rstrip(', ')
gmsg=gmsg + ')' + ' >>> ' + Direct_message
for person in recipients:
client_details[person].sendall(gmsg)
user_details={}
client_details={}
active_users=[]
connector = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ('Launching Server')
connector.bind(('localhost', 5000)) #Links socket to server address
connector.listen(10)
threading.Thread(target=find_users).start()
For the client and the GUI I'm putting here only the function called by the button "Connect" of the GUI (the ones that are creating problems), the GUI uses the QT Libraries
This is the code called by the button:
def client_connect(self):
ip_address = str(self.ipText.toPlainText())
port = int(self.portText.toPlainText())
nickname = self.nameText.toPlainText()
password = 'hello'
connect = threading.Thread(target = connection_thread, args = (ip_address, port, nickname, password))
connect.start()
This is the thread function:
def connection_thread(address, port, nickname, password):
nickname = nickname.encode()
password = password.encode()
while True:
try:
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.connect((address, port))
c.sendall('{0:0=4d}'.format(len(nickname)).encode())
c.sendall(nickname)
c.sendall(password)
answr = c.recv(2).decode()
if answr == 'y':
msg_box("CONNECTED", "Now you are connected to the server.")
while True:
time.sleep(2)
c.sendall('03'.encode())
message_received =c.recv(8192).decode()
self.chatList.addItem(message_received)
except Exception as e:
msg_box("CONNECTION FAILED", "Connection to server failed, try again.")
break
From the server code the connection of my client arrives but, the client stop working without showing the msg_box that says that we are connected.
When you say connect.join() you wait for the thread connect to finish, but it is in an infinite loop, so it is not done until the connection closes.

python irc can't identify with irc server

Where am I going wrong here. as far as i can tell this should work.
import socket, string
#some user data, change as per your taste
SERVER = 'irc.freenode.net'
PORT = 6667
NICKNAME = 'echoquote'
CHANNEL = '#python'
PASSWORD = 'nope'
import time
#open a socket to handle the connection
IRC = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#open a connection with the server
def irc_conn():
IRC.connect((SERVER, PORT))
#simple function to send data through the socket
def send_data(command):
IRC.send(command + '\n')
#join the channel
def join(channel):
send_data("JOIN %s" % channel)
#send login data (customizable)
def login(nickname, username='user', password = None, realname='Pythonist', hostname='Helena', servername='Server'):
send_data("USER %s %s %s %s" % (username, hostname, servername, realname))
send_data("NICK " + nickname)
send_data("nickserv identify %s %s\r\n" % (NICKNAME, PASSWORD))
time.sleep(3)
irc_conn()
login(NICKNAME)
join(CHANNEL)
while (1):
buffer = IRC.recv(1024)
msg = string.split(buffer)
message = ' '.join(msg[3:])
message = ''.join([x for x in message if x in string.printable])
if message:
print message + '\n'
if msg[0] == "PING": #check if server have sent ping command
send_data("PONG %s" % msg[1]) #answer with pong as per RFC 1459
if msg [1] == 'PRIVMSG' and msg[2] == NICKNAME:
filetxt = open('/tmp/msg.txt', 'a+') #open an arbitrary file to store the messages
nick_name = msg[0][:string.find(msg[0],"!")] #if a private message is sent to you catch it
message = ' '.join(msg[3:])
filetxt.write(string.lstrip(nick_name, ':') + ' -> ' + string.lstrip(message, ':') + '\n') #write to the file
filetxt.flush() #don't wait for next message, write it now!
send_data("nickserv identify %s %s\r\n" % (NICKNAME, PASSWORD))
There is no nickserv command in IRC. This is an alias in some IRC clients, and all it does is send a private message to NickServ. Read the IRC specification, and stop reinventing wheels — use an existing IRC library, eg. twisted.words, or an existing IRC bot solution.

TypeError: 'int' object has no attribute '__getitem__' - Error recieved in IRC weather bot in Python

Okay, so I've got a bit of Python IRC Bot code, and I recently added a weather command to it, but it doesn't seem to work... heres the code
# Import some necessary libraries.
import socket
import time
import httplib
def commands(nick,channel,message):
if message.find('!test')!=-1:
ircsock.send('PRIVMSG %s :%s: test complete\r\n' % (channel,nick))
elif message.find('!help')!=-1:
ircsock.send('PRIVMSG %s :%s: My other command is test.\r\n' % (channel,nick))
elif message.find('!sex')!=-1:
ircsock.send('PRIVMSG %s :%s: But why?\r\n' % (channel,nick))
elif message.find('!quit')!=-1:
ircsock.send('QUIT :For the bones of the weak shall support me\r\n')
die('Quit command given')
elif message.find('!op')!=-1:
ircsock.send('MODE %s +o :%s\n' % (channel,nick))
elif message.find('!deop')!=-1:
ircsock.send('MODE %s -o :%s\n' % (channel,nick))
elif message.find('!weather')!=-1:
tmp = message.find(':!weather')
city = tmp[1].strip()
reqest_str = '/laika_zinas/?city=' + city
c = httplib.HTTPConnection("www.1188.lv")
c.request("GET", reqest_str)
ra = c.getresponse()
datas = ra.read()
temp, wind = tpars(datas)
ircsock.send('PRIVMSG %s :%s: [+] Temp: '+ temp +' C | Wind: '+ wind +' m/s' % (channel,nick))
c.close()
# Some basic variables used to configure the bot
server = "n0cht.bawx.net" # Server
channel = "#python" # Channel
botnick = "PyleDrivr" # Your bots nick
def ping(ircmsg): # This is our first function! It will respond to server Pings.
ircsock.send("PONG "+ ircmsg +"\n")
print("Ping replied\n\r")
def sendmsg(chan , msg): # This is the send message function, it simply sends messages to the channel.
ircsock.send("PRIVMSG "+ chan +" :"+ msg +"\n")
def joinchan(chan): # This function is used to join channels.
ircsock.send("JOIN "+ chan +"\n")
ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ircsock.connect((server, 6667)) # Here we connect to the server using the port 6667
ircsock.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :PyleDrivr\n") # user authentication
ircsock.send("NICK "+ botnick +"\n") # here we actually assign the nick to the bot
joinchan(channel) # Join the channel using the functions we previously defined
while 1: # Be careful with these! it might send you to an infinite loop
ircmsg = ircsock.recv(2048) # receive data from the server
ircmsg = ircmsg.strip('\n\r') # removing any unnecessary linebreaks.
print(ircmsg) # Here we print what's coming from the server
if ircmsg.find(' PRIVMSG ')!=-1:
nick=ircmsg.split('!')[0][1:]
channel=ircmsg.split(' PRIVMSG ')[-1].split(' :')[0]
commands(nick,channel,ircmsg)
if ircmsg.find("PING :") != -1: # if the server pings us then we've got to respond!
ping(ircmsg)
Now, when I run the bot, it works just fine, but then this happens when I issue the command:
<wh0r3[mint]> !weather 99654
* PyleDrivr has quit (Client exited)
And here's what the term shows:
:wh0r3[mint]!~wh0r3#n0cht-D1D272D.gci.net PRIVMSG #lobby :!weather 99654
Traceback (most recent call last):
File "pyledrivr.py", line 65, in <module>
commands(nick,channel,ircmsg)
File "pyledrivr.py", line 22, in commands
city = tmp[1].strip()
TypeError: 'int' object has no attribute '__getitem__'
I have no idea what this means or how to fix it. and ideas?
This line:
tmp = message.find(':!weather')
assigns an integer to tmp: the position at which the string ':!weather' was found in message (see find). It may not even be found at all, since you check in the line above that '!weather' is in message, not ':!weather'.
Then you try and access tmp[1]. But tmp is just a number; it doesn't have a [1].
If you want to get the substring of message that follows '!weather', you could do this:
city = message[message.find('!weather')+8:].strip()
(8 being the length of '!weather')
Or you might find it easier to use split:
city = message.split('!weather')[1].strip()

Categories

Resources