繁体   English   中英

使用 discord.py 重写将消息 object 转换为带有表情符号的字符串

[英]Convert a message object to a string with emojis with discord.py rewrite

我正在尝试在 python 中创建一个机器人,它将服务器上的每条消息记录在 a.txt 文件中

@client.event
async def on_message(message):
    id = client.get_guild(Server ID)
    f= open('logs_messages.txt','a+')
    f.write(f'{message.author.id} \n \n')
    f.write(f'Date et heure {datetime.now()} \n \n')
    f.write(f'ID du channel:<#{message.channel.id}> \n \n')
    f.write(f'{message.content} \n \n \n \n')
    f.close

所以代码正在工作,当消息包含表情符号时执行,程序不写任何东西并返回:

File "C:\Users\psg97\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 312, in _run_event
    await coro(*args, **kwargs)
  File "bot.py", line 37, in on_message
    f.write(f'{message.content} \n \n \n \n')
  File "C:\Users\psg97\AppData\Local\Programs\Python\Python36\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f389' in position 0: character maps to <undefined>

有谁知道如何转换这些表情符号,以便将它们写入 .txt 文件?

使用utf-8将您的内容编码为

f.write(f'{message.content.encode('utf8')} \n \n \n \n')

您可以使用utf-8编码打开整个文件:

with open('logs_messages.txt','a+', encoding='utf-8') as f:
    f.write(f'{message.author.id} \n \n')
    f.write(f'Date et heure {datetime.now()} \n \n')
    f.write(f'ID du channel:<#{message.channel.id}> \n \n')
    f.write(f'{message.content} \n \n \n \n')
    f.close

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM