首页 > 解决方案 > 在将每条消息记录到文件时,如何让 discord.py 显示名称?

问题描述

我的问题是,我无法让我的机器人显示成员作者、日期和消息。这是错误:

忽略 on_message Traceback 中的异常(最近一次调用最后):文件“C:\Program Files (x86)\Python38-32\lib\site-packages\discord\client.py”,第 270 行,在 _run_event await coro(*args , **kwargs) 类型错误:on_message() 缺少 1 个必需的位置参数:'ctx'

我的代码:

@commands.Cog.listener()
    async def on_message(self, message, ctx):
        #await client.send_message(message.channel, discord.Message.author)
        messagestr = ""
        messagestr = ('{0.content}'.format(message))
        file_open()
        print(device_time()+" "+ctx.message.author+" "+"Message: "+messagestr)
        out1 = ""
        out1 = messagestr
        f1 = open('logs.txt','a')

        out1 = out1.replace('\n', '')
        out1 = (device_time()+" "+out1+'\r')
        f1.write(device_time()+" "+"Message: "+messagestr)
        f1.close()
        f1.close()

标签: python

解决方案


首先on_message discord.py 事件不需要ctx,它只需要message,这是直接导致错误的原因。

然后你使用+的python连接方法,这还不错,但是python的f-strings更好地格式化字符串,因为f-strings直接将变量类型转换为字符串(所以不需要使用str()函数)

此外,请考虑使用PEP-8 命名约定,这会使您的代码看起来更漂亮、更易于阅读。例如,你使用messagestr = "", 对于 python 的解释器,这没问题,不会抛出错误,但对于人类来说,这真的很难用,在 python 中你应该使用snake_case所以messagestr会变成message_str = None

这是我会做的:

@commands.Cog.listener()
    async def on_message(self, message):
        #await client.send_message(message.channel, str(message.author))
        message_str = message.content
        file_open()
        print(f'{device_time()} {message.author} Message: {messagestr}')
        out = message_str.replace('\n', '')
        file = open('logs.txt','a')

        out = f'{device_time()} {out} \r' #Note : message.created_at would be a useful function here to replace device_time()
        file.write(f'{device_time()} Message: {message_str}')
        file.close()

推荐阅读