首页 > 解决方案 > 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”,我希望它将未知消息保存到现有文本文件中。不使用客户端命令或代码。

标签: pythondiscorddiscord.py

解决方案


我知道你要求不要接收代码,但我将不得不这样做。这部分:

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()

您似乎是初学者,所以不要担心。我记得我还是初学者的时候。


推荐阅读