python - Discord.py 将未知频道消息保存到 txt 文件中
问题描述
async def on_message(self, message):
if message.author == self.user:
return
if message.content.lower() == 'hi':
await message.channel.send('hello')
if message.content.lower() == '':
f = open("Path/To/Your/File.txt", "w") # 'r' for reading and 'w' for writing
f.write("" + f.name) # Write inside file
f.close()
如果有人在不和谐频道中发送消息,并且消息不包含单词“hi”,我希望它将未知消息保存到现有文本文件中。不使用客户端命令或代码。
解决方案
我知道你要求不要接收代码,但我将不得不这样做。这部分:
if message.content.lower() == '':
f = open("Path/To/Your/File.txt", "w")
f.write(""+f.name)
f.close()
似乎检查用户是否发送空白消息(应该是不可能的,因为您必须发送一些不和谐的东西),并以写入模式打开 Path/To/Your/File.txt,并以它的名称写入(文件。文本)。此外,lower() 使文本小写,这不是必需的,因为您不能没有大写。此外,Path/To 意味着您必须创建三个文件夹,path、to 和 your,然后将 File.txt 放入您的。您应该将 file.txt 放在当前文件夹中,然后将 /Path/To 更改为 file.txt。它不检查机器人是否没有响应。
您应该完全删除该部分。
第 1 步:
创建一个名为 log.txt 的文件。
第二步:
将该部分代码替换为:
#checks if the bot has a response
knownmessages = ["hi"] #you can add more
if message.content not in knownmessages:
f = open("log.txt", "a") #or what you called it. also a for append, it would overwrite otherwise.
f.write(message.content + "\n") #\n means new line
f.close()
您似乎是初学者,所以不要担心。我记得我还是初学者的时候。
推荐阅读
- r - 拆分面板回归在 R 中得到一个独特的结果
- javascript - 在反应本机应用程序中动态填充网格内的行和列
- spring - Spring Hibernate - 使用@Formula从基于其他表的最大值中获取列值
- r - 在 summary.lm(P.for.trend) :本质上完美契合:总结可能不可靠;如何处理?
- loopback4 - Loopback 4 - 循环模型的 Field 对象以动态打开/关闭某些字段
- c - 在 C 中的链表中搜索
- python - 是否可以让 numpy 数组值和对象属性都指向内存中的同一位置?
- javascript - Plotly JavaScript:自定义 y 轴上的刻度或标签
- vue.js - 如何将工具提示添加到 d3.js 路径?
- c# - 错误:(416)请求的范围不满足。在 POST 请求上