Entity2k3
Entity2k3

Reputation: 76

How to receive DMs and log them to a text file?

I managed to get my bot to send DMs to people by providing their ID and a message I want to send. The problem is that people respond to the bot and I would like to receive the messages to my console window (where at the same time exceptions/errors are being listed). I tried using following code but it returned that it does not have an attribute 'message':

@client.event(pass_context=True)
async def on_message(ctx):
    print(f"{ctx.author} said: {ctx.message}")
    await ctx.send(f"Hi, I'm an automated message. I cannot receive any information on your message. All I might get is: {ctx}")
    log = open("commands/info/logging/logmsg.txt", "a")
    log.writelines(f"{ctx.author} has sent: {ctx.message}")

ERROR:

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\MODERATED\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 312, in _run_event
    await coro(*args, **kwargs)
  File "showmessages.py", line 18, in on_message
    print(f"{ctx.author} said: {ctx.message}")
AttributeError: 'Message' object has no attribute 'message'

Upvotes: 0

Views: 54

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 60944

on_message receives a Message object as it's input, not a Context object.

@client.event
async def on_message(message):
    if message.author.bot:
        return # ignore our own messages
    print(f"{message.author} said: {message.content}")
    await message.channel.send(f"Hi, I'm an automated message. I cannot receive any information on your message. All I might get is: {message}")
    log = open("commands/info/logging/logmsg.txt", "a")
    log.writelines(f"{message.author} has sent: {message.content}")

Note that this currently will trigger on all the messages the bot can "see"

Upvotes: 1

Related Questions