TypeError:无法将字节连接到str,尝试使用python3 [英] TypeError: can't concat bytes to str, trying to use python3
本文介绍了TypeError:无法将字节连接到str,尝试使用python3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,以下站点说明了如何使用套接字制作irc机器人,但它仅适用于python2,因此我尝试使其兼容,但出现标题中提到的错误.
So the following site explains how to make an irc bot, using socket, but it only works for python2, so I tried to make it compatible, but I get the error mentioned in the title.
这是我的代码:
import socket
# Some basic variables used to configure the bot
server = "irc.freenode.net" # Server
channel = "#volafile"
botnick = "Mybot" # Your bots nick
def ping(): # This is our first function! It will respond to server Pings.
ircsock.send(b"PONG :pingis\n")
def sendmsg(chan , msg): # to the channel.
ircsock.send(b"PRIVMSG "+ chan +b" :"+ msg +b"\n")
def joinchan(chan): # This function is used to join channels.
ircsock.send(b"JOIN "+ chan + b"\n")
def hello(): # This function responds to a user that inputs "Hello Mybot"
ircsock.send(b"PRIVMSG "+ channel + b" :Hello!\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(b"USER "+ botnick + b" "+ botnick + b" "+ botnick + b" :This bot is a result of a tutoral covered on http://shellium.org/wiki.\n") # user authentication
ircsock.send(b"NICK "+ botnick + b"\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(b'\n\r') # removing any unnecessary linebreaks.
print(ircmsg) # Here we print what's coming from the server
if ircmsg.find(b":Hello "+ botnick) != -1:
hello()
if ircmsg.find(b"PING :") != -1: # if the server pings us then we've got to respond!
ping()
错误消息:
Traceback (most recent call last):
File "irctest.py", line 23, in <module>
ircsock.send(b"USER "+ botnick + b" "+ botnick + b" "+ botnick + b" :This botis a result of a tutoral covered on http://shellium.org/wiki.\n") # user authentication
TypeError: can't concat bytes to str
推荐答案
botnick
不是字节值,而是字符串:
botnick
is not a bytes value but a string:
botnick = "Mybot"
通过在前面添加b
来使字节字面量:
Make that a bytes literal by adding a b
in front:
botnick = b"Mybot"
这篇关于TypeError:无法将字节连接到str,尝试使用python3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文