import socket, sys, string
if len(sys.argv) !=4:
print ("UsageL ./ninjabot.py <server> <port> <channel>")
sys.exit(1)
irc = sys.argv[1]
port = int(sys.argv[2])
chan = sys.argv[3]
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((irc, port))
sck.send(b'NICK ninjabot\r\n')
sck.send(b'USER ninjabot ninjabot ninjabot :ninjabot Script\r\n')
sck.send('JOIN ' + " " + chan + '\r\n')
data = ''
while True:
data = sck.recv(1024)
if data.find('PING') != -1:
sck.send('PONG ' + data.split() [1] + '\r\n')
print (data)
print (data)
I get this error in sck.send('JOIN ' + " " + chan + '\r\n') but when i try this:
sck.send(b'JOIN ' + " " + chan + '\r\n')
I get TypeError: can't concat str to bytes
I know there's similar posts with this same issue, but none of those seem to help me.
This is due to the fact that b'JOIN' is of type bytes while " " as well as chan and "\r\n" are of type str.
2 corrections:
chan = sys.argv[3].encode()
sck.send(b'JOIN ' + b" " + chan + b'\r\n')
alternatively you could just:
sck.send(b'JOIN %s\r\n' % chan.encode())
this would be the best style. Similar corrections will be need to be made later in your snippet as well. socket.send is looking for a bytes string, so ensure that all strings which you pass it are either b"" or encoded otherwise using encode()
Related
Very new to coding. This was the initial code I was trying to get to run but have found it is incompatible with python 3 because of how it handles strings and bytes.
def opensocket():
s = socket.socket()
s.connect((HOST,PORT))
s.send("PASS " + PASS + "\r\n")
s.send("NICK " + IDENT + "\r\n")
s.send("JOIN #" + CHANNEL + "\r\n")
return s
I think I need to encode these strings into bytes but all the conversion methods I've tried have given errors. here are some i've tried.
def opensocket():
s = socket.socket()
s.connect((HOST,PORT))
s.send(b"PASS " + PASS + "\r\n")
s.send(b"NICK " + IDENT + "\r\n")
s.send(b"JOIN #" + CHANNEL + "\r\n")
and
def opensocket():
s = socket.socket()
s.connect((HOST,PORT))
s.send("PASS " + PASS + "\r\n".encode())
s.send("NICK " + IDENT + "\r\n".encode())
s.send("JOIN #" + CHANNEL + "\r\n".encode())
return s
both of these give errors saying the str can't be concatenated into bytes
any help?
edit: went through the suggested post but I'm gaining nothing from that. it looks so different and I'm so new to this that I can't even tell where the string was he was trying to convert
In the case that PASS, IDENT and CHANNEL are bytes:
def opensocket():
s = socket.socket()
s.connect((HOST,PORT))
s.send(b"PASS " + PASS + b"\r\n")
s.send(b"NICK " + IDENT + b"\r\n")
s.send(b"JOIN #" + CHANNEL + b"\r\n")
In the case that PASS, IDENT and CHANNEL are str:
def opensocket():
s = socket.socket()
s.connect((HOST,PORT))
s.send(b"PASS " + PASS.encode('ascii') + b"\r\n")
s.send(b"NICK " + IDENT.encode('ascii') + b"\r\n")
s.send(b"JOIN #" + CHANNEL.encode('ascii') + b"\r\n")
It's important to know what protocol you're using, to know what encoding actually to use. 'ascii' is a safe bet, but it means you're limited in to ASCII-only characters, so if the protocol actually specifies UTF-8 strings, you should do .encode('utf-8') instead.
I can't figure out how to transfer str to bytes in Python 3.
This is the client code:
import socket
import threading
tLock = threading.Lock()
shutdown = False
def receving(name, sock):
while not shutdown:
try:
tLock.acquire()
while True:
data, addr = socket.recvfrom(1024).decode()
print (data)
except:
pass
finally:
tLock.release()
host = '127.0.0.1'
port = 0
server = ('127.0.0.1',5000)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
s.setblocking(0)
rT = threading.Thread(target=receving, args=("RecvThread",s))
rT.start()
alias = input("Name: ")
message = input(alias + "-> ")
while message != 'q':
if message != '':
s.sendto(alias.encode() + ": " + message.encode(), server.encode())
tLock.acquire()
message = input(alias + "-> ")
tLock.release()
time.sleep(0.2)
shudown = True
rT.join()
s.close()
This is the error I get:
Traceback (most recent call last):
File "C:/Python34/client fixing.py", line 35, in <module>
s.sendto(alias.encode() + ": " + message.encode(), server.encode())
TypeError: can't concat bytes to str
>>>
This is because ":" is an str (string) object. You could just do b':':
s.sendto(alias.encode() + b": " + message.encode(), server.encode())
but you might find it simpler if you used str.format().encode()
s.sendto("{}: {}".format(alias, message).encode(), server.encode())
In the line
s.sendto(alias.encode() + ": " + message.encode(), server.encode())
": ", which is a string, is being concatenated with two bytestrings (we know they're bytestrings because .encode() is called on them. This is an error in Python3, but it can be fixed by calling .encode() on the string.
The second parameter to Socket.sendto should be an address. The exact type of the address depends on the socket's family. In this case you have correctly defined address as a tuple (server = ('127.0.0.1',5000)), but you are erroneously calling .encode() on it.
Try changing the line to:
s.sendto(alias.encode() + ": ".encode() + message.encode(), server)
and the error will be fixed.
I wrote a simple Python twitch bot following a video tutorial, but the tutorial didn't include whisper functionality. It can currently connect to the chat of the channel I specify, but when I try to have it send a whisper nothing happens. Here's the relevant code bits:
import socket
def openSocket():
s = socket.socket()
s.connect((HOST, PORT))
message = "PASS " + PASS + "\r\n"
s.send(message.encode('utf-8'))
message = "NICK " + USER + "\r\n"
s.send(message.encode('utf-8'))
message = "JOIN #" + CHAN + "\r\n"
s.send(message.encode('utf-8'))
return s
def sendMessage(s, message):
messageTemp = "PRIVMSG #" + CHAN + " :" + message + "\r\n"
s.send(messageTemp.encode('utf-8'))
print("Sent:" + messageTemp)
def sendWhisper(s, user, message):
messageTemp = "PRIVMSG #jtv :/w " + user + " " + message
s.send(messageTemp.encode('utf-8'))
import string
from Socket import sendMessage
def joinRoom(s):
readbuffer = ""
Loading = True
while Loading:
readbuffer = readbuffer + s.recv(1024).decode()
temp = readbuffer.split('\n')
readbuffer = temp.pop()
for line in temp:
print(line)
Loading = loadingComplete(line)
def loadingComplete(line):
if("End of /NAMES list" in line):
return False;
else: return True
I've been reading a little bit about connecting to some sort of group chat in order to make this work, but I'm confused and haven't found what I'm looking for. It seems like it should be an easy fix. Any help is appreciated.
You were very close. Where you messed up is there should not be a # in front of jtv:
def sendWhisper(s, user, message):
messageTemp = "PRIVMSG jtv :/w " + user + " " + message
s.send(messageTemp.encode('utf-8'))
So a few hours ago I decided to try my hands on sockets with python and build a simple irc bot. So far I'm having some trouble getting it connected to the server. I get the following erros:
b":irc.ku.cx 439 * :Please wait while we process your connection.\r\n:irc.ku.cx NOTICE AUTH :*** Couldn't look up your hostname (cached)\r\n"
b':irc.ku.cx NOTICE AUTH :*** Checking Ident\r\n'
b':irc.ku.cx NOTICE AUTH :*** No Ident response\r\n'
After that it stalls out. But about a minute of it running I suddenly get an endless amount of b"", each in a new line (probably something to do with the while loop in the code). This is my code:
import socket
server = 'irc.rizon.net'
channel = '#linux'
nick = 'MyBot'
port = 6667
ircsock = socket.socket()
ircsock.connect((server, port))
ircsock.send(bytes('"NICK " + nick', 'UTF-8'))
ircsock.send(bytes('"USER " + nick + " " + nick + " " + nick + " :" + nick', 'UTF-8'))
while True:
data = ircsock.recv(2048)
print (data)
if data.find(b"PING") != -1:
ircsock.send(b"PONG :" + data.split(':')[1])
Thanks for any help you guys can provide.
As icktoofay said, there are extra quotes in your code. Also, in IRC you need to add a line break (\r\n) to the end of every command.
Replace these lines:
ircsock.send(bytes('"NICK " + nick', 'UTF-8'))
ircsock.send(bytes('"USER " + nick + " " + nick + " " + nick + " :" + nick', 'UTF-8'))
with
ircsock.send(bytes("NICK " + nick + "\r\n", 'UTF-8'))
ircsock.send(bytes("USER " + nick + " " + nick + " " + nick + " :" + nick + "\r\n", 'UTF-8'))
and it should work.
By the way, I recommend using socket.makefile() instead, which handles buffering and encoding for you. Here's your code modified to use the file interface:
import socket
server = 'irc.rizon.net'
channel = '#linux'
nick = 'MyBot'
port = 6667
ircsock = socket.socket()
ircsock.connect((server, port))
handle = ircsock.makefile(mode='rw', buffering=1, encoding='utf-8', newline='\r\n')
print('NICK', nick, file=handle)
print('USER', nick, nick, nick, ':'+nick, file=handle)
for line in handle:
line = line.strip()
print(line)
if "PING" in line:
print("PONG :" + line.split(':')[1], file=handle)
Here, I use the print function which inserts spaces and newlines automatically.
if data.find('!search') != -1:
nick = data.split('!')[ 0 ].replace(':','')
conn = httplib.HTTPConnection("www.md5.rednoize.com")
conn.request("GET", "?q=" + arg)
response = conn.getresponse()
data = response.read()
result = re.findall('<div id="result" >(.+?)</div', data)
if result:
sck.send('PRIVMSG ' + chan + result + '\r\n')
else:
sck.send('PRIVMSG ' + chan + " :" ' could not find the hash' + '\r\n')
When I run this code I get this error:
conn.request("GET " + "?q=" + arg)
TypeError: cannot concatenate 'str' and 'list' objects
How can I fix this?
Where does arg come from? Do you know what it's supposed to contain?
arg is apparently a list, not a string. Try replacing arg with str(arg[0]) and see if that works.