Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

python - Getting Errors when trying to log Server Chat info in on_message [discord.py]

So, I'm making a server bot, and I'm trying to make the bot log user messages when they send a file.

...
with open("messages.txt", "w") as f:
        f.write(f'{message.author.name}: "{message.content}" {time.strftime("%H:%I:%M")} {message.guild.name}
')
...

Its somewhat working for some users, but I keep getting errors when others send messages. "UnicodeEncodeError: 'charmap' codec can't encode character 'u2615' in position 0: character maps to " And sometimes it will just clear the file.

Thanks!

question from:https://stackoverflow.com/questions/66053234/getting-errors-when-trying-to-log-server-chat-info-in-on-message-discord-py

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use unicode to parse non-ascii strings. ('u2615' is decoded as ? in UTF-8)

open("messages.txt", "w", encoding='utf-8')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...