Koll
Koll

Reputation: 142

Storing messages into text file Discord.py

I am trying to make event that will write messages into text file.

Here is my code:

@bot.event
async def on_message(message):
    msg = message
    with open("data.txt", "r+") as n:
        n.write("\n"  +  "<" + str(msg)+ "|" + str(msg.author) + "|" + str(msg.author.id) + str(msg.created_at) + ">")

But when bot tries to write message into text file, it doesn't make new line and writes something like this:

<<Message id=907694705016442930 channel=<TextChannel id=901027376958406659 name='testing' position=0 nsfw=False news=False category_id=901027376958406657> type=<MessageType.default: 0> author=<Member id=624327590794100779 name='-Cosmos' discriminator='3798' bot=False nick=None guild=<Guild id=901027376958406656 name='Koll' shard_id=None chunked=True member_count=6>> flags=<MessageFlags value=0>>|-Cosmos#3798|6243275907941007792021-11-09 18:14:41.828000>.158000>

Upvotes: 2

Views: 1369

Answers (1)

Łukasz Kwieciński
Łukasz Kwieciński

Reputation: 15689

If you want to get the actual value of the message, use the content attribute. You should also use the a (append) mode to write at the end of the file (without truncating it)

@bot.event
async def on_message(message):
    msg = message
    with open("data.txt", "a") as n:
        n.write("\n" + "<" + msg.content + "|" + str(msg.author) + "|" + str(msg.author.id) + str(msg.created_at) + ">")

Upvotes: 3

Related Questions