Twitch.tv IRC 机器人的 UnicodeEncodeError

UnicodeEncodeError with Twitch.tv IRC bot

所以我正在尝试编写一个简单的 Twitch.tv IRC 机器人程序。机器人读取频道中的传入消息,如果消息匹配特定模式,机器人将执行特定任务。我遇到的问题是,如果用户输入某些 unicode 字符(即如果用户输入“¯_(ツ)_/¯”,程序将抛出错误并崩溃:

用户代码未处理 UnicodeEncodeError

'charmap' 编解码器无法对位置 13 中的字符 '\xaf' 进行编码:字符映射到 < undefined >

现在,我希望我的程序能够处理这些输入,但我不知道要更改或添加什么到我的代码中才能启用它。这是我的代码:

http://pastebin.com/EBTaqpbZ(我不知道如何使用 Whosebug 代码粘贴)

我收到错误的主要代码部分是:

while True:                                                     #Main Loop
    response = s.recv(1024).decode("utf-8")
    if response == "PING :tmi.twitch.tv\r\n":                   #If Ping, return Pong
        s.send("PONG :tmi.twitch.tv\r\n".encode("utf-8"))
        print("Pong Successful")
    else:                                                       #Else, Decode User Message
        username = re.search(r"\w+", response).group(0)         #Gets User
        message = CHAT_MSG.sub("", response)                    #Gets Message
        print (username + ": " + message)                       #Prints User Message
        if message.find("!hello") != -1:                        #Simple Test command to see if Reading Chat Input
            chat ("Hello! I'm speaking!\r\n")
    time.sleep(1 / cfg.RATE)

错误似乎总是发生在代码行:print (username + ": " + message)

有谁知道我应该如何处理这些 un​​icode 字符?

(会用 link 对答案发表评论,但我还没有足够的声誉。)

那么,我假设您使用的是 windows?发生的情况是您的控制台使用的编码无法打印 unicode 字符,这会导致崩溃。

所以问题不在于代码本身,而在于所使用的工具。例如,当来自 linux 控制台的 运行 时,代码运行良好。解决此问题的一种方法似乎是使用 win-unicode-console to enable unicode input and output from windows console. See this answer 来更广泛地描述问题和解决方案。

如果您只是为了调试目的而需要打印,您也可以解决这个问题:

msg = username + ": " + message
print (msg.encode("utf-8")) 

然而,这不是真正的解决方案,输出将类似于

b'\xc2\xaf_(\xe3\x83\x84)_/\xc2\xaf\r\n'

对于您的示例字符串,不太方便。我建议阅读我 linked.

的答案