python - 在将每条消息记录到文件时,如何让 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()
解决方案
首先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()
推荐阅读
- python - 使用字典上的循环定义 tkenentry
- c# - 如何为基于方向运动输入移动的球实现动量?
- reporting-services - SSRS 慢但查询快 - 缓存
- c# - 谷歌云平台错误 access_denied
- c++ - 有没有办法在 C++ 中获取类模板并使用它来创建另一个模板?
- powershell - 在继续调用 PowerShell 脚本之前等待交互式“Enter-PSSession -Session $session”结束?
- azure-devops - 在特定日期运行的 Azure Pipelines 计划不起作用
- c# - 是否可以将 FormsAuthenticationTicket.UserData 传递给 ASP.net 中的 Razor 页面?
- python - 无法使用 Scrapy 抓取 HTTPS 网页
- javascript - 当人们点击表格中的关键字时,希望过滤表格行。(OnClick 代码更改下拉菜单选择)