使用表情符号Discord.py写入文件message.content时出现问题

时间:2020-02-23 20:08:47

标签: discord.py discord.py-rewrite

这是我尝试写下包含表情符号的帖子的message.content时遇到的错误。我该如何避免呢?

discord.ext.commands.errors.CommandInvokeError:命令引发了异常:UnicodeEncodeError:'charmap'编解码器无法在位置编码字符'\ U0001f609' 81:字符映射到

谢谢。

这是我正在使用的代码:

async def posts(ctx):
    f = open("file.txt", "w")
    for channel in ctx.guild.text_channels:
        f.write(message.content + "\n")

    f.close()

1 个答案:

答案 0 :(得分:0)

问题是您不使用utf-8编码。 open()函数使用的标准编码不支持表情符号。因此就是错误。

要解决此问题,您需要在代码中添加encoding="utf-8"

async def posts(ctx):
    f = open("file.txt", "w", encoding="utf-8")
    for channel in ctx.guild.text_channels:
        f.write(message.content + "\n")

    f.close()