如何在电报中记录 unicode 昵称?

How to log unicode nicknames in telegram?

我正在制作电报机器人,我想记录使用它的人的昵称。 让它变得简单:

import logging
logging.basicConfig(filename='tgbot.log', level=logging.INFO)

def log(m: Message):
    username = m.from_user.username
    logging.info(username)

但是,如果昵称中的人有表情符号,或者来自其他语言的字母,它会给我这样的错误

UnicodeEncodeError: 'charmap' codec can't encode characters. Character maps to undefined

或者像这样

UnicodeEncodeError: 'ascii' codec can't encode characters. Ordinal not in range(128)

如何解决这个问题并记录这些昵称?


我试过logging.info(username.encode('utf-8'))但是后来像\xe2\xad\x95这样的字节字符被写入了日志文件,但是我想直接将这些字符写入日志文件

据我所知,我的问题的解决方案是,是时候将 python 更新到 3.9 版了,但是因为我有 3.7 版,所以我通过标准流将日志记录到文件中,因为不可能在日志库中明确指定编码

def log(m: Message):
    username = m.from_user.username
    f = open('bot.log', 'a', encoding='utf-8')
    f.write(username)
    f.close()