【问题标题】:(Discord.py) Make a logger which saves conversations the bot is in(Discord.py) 制作一个记录器来保存机器人所在的对话
【发布时间】:2019-11-19 01:26:17
【问题描述】:

如何在 discord.py 中创建一个记录器机器人,将对话保存到文本文件中。

例如,机器人将所有聊天记录保存在一个名为“chatlogs”的文件夹中,并且每次有人说出机器人可以看到的内容时,机器人都会将其记录在一个名为 Server A 的文件中。 strong>ServerA.txt 并且当 Server B 添加我的机器人时,它会生成一个名为 ServerB.txt 的文件并保存所有 Server B 里面的对话。

【问题讨论】:

    标签: python logging discord discord.py


    【解决方案1】:

    on_message 事件中,以追加模式打开文件并写入最新消息。

    from discord.ext import commands
    
    bot = commands.Bot(command_prefix='!')
    
    @bot.event
    async def on_message(message):
        guild = message.guild
        if guild:
            path = "chatlogs/{}.txt".format(guild.id)  
            with open(path, 'a+') as f:
                print("{0.timestamp} : {0.author.name} : {0.content}".format(message), file=f)
        await bot.process_commands(message)
    
    bot.run("token")
    

    【讨论】:

    • @AlexWollan 它应该。
    • 但是我要怎么做呢,在加入一个新的公会时创建一个新的文本文件?并在删除机器人时删除文本文件?
    • 您是否尝试运行此代码?它已经在需要时创建了一个新文件。要删除该文件,您将编写一个 on_bot_remove 事件来删除具有该名称的文件。请注意,目前我们只使用服务器名称,因此如果服务器更改其名称,事件将被记录到不同的文件中。您可以通过使用服务器 ID 作为文件名来防止这种情况发生。
    • 我将 @client.event 更改为 @bot.event 但我在使用 bot 时得到了这个(我使用 bot,因为我一直在我的代码中使用它。)这是我的错误 @bot.event() TypeError: event() missing 1 required positional argument: 'coro' 另外我将如何使用服务器 ID?
    • 你用@bot.event()而不是@bot.event装饰
    猜你喜欢
    • 2021-02-16
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    • 2023-03-15
    • 2021-04-28
    • 1970-01-01
    • 2020-06-26
    相关资源
    最近更新 更多