【问题标题】:Discord bot python不和谐机器人 python
【发布时间】:2021-07-15 00:03:38
【问题描述】:

我需要 python 中的不和谐机器人方面的帮助。 我需要一个机器人来保存通过 dm 发送给它的每条消息

我试过了,但它只节省了时间和消息数量,而不是内容

async def update_stats():
    await bot.wait_until_ready()
    global messages

    while not bot.is_closed():
        try:
            with open("stats.txt", "a") as f: 
                f.write(f"Czas: {int(time.time())},Wiad: {messages}\n")
        
            messages = 0
            await asyncio.sleep (30)
        except Exception as e 
            print (e)
            await asyncio.sleep (30)

@bot.event
async def on_message(message):
    global messages
    messages += 1
    
bot.loop.create_task(update_stats())

【问题讨论】:

    标签: python discord discord.py bots


    【解决方案1】:

    是的,这是完全有效的,因为您只保存了消息的数量。您也应该保存这些消息。

    未经测试的代码(我现在没有完整的机器人环境):

    messages = 0
    messages_list = list()
    
    async def update_stats():
        await bot.wait_until_ready()
    
        while not bot.is_closed():
            try:
                with open("stats.txt", "a") as f: 
                    f.write(f"Czas: {int(time.time())}\n")
                    f.write("Messages:\n")
                    for message in messages_list:
                        f.write(message)
                    messages_list.clear()
                messages = 0
                await asyncio.sleep (30)
            except Exception as e 
                print (e)
                await asyncio.sleep (30)
    
    @bot.event
    async def on_message(message):
        messages += 1
        messages_list.append(message)
        
    bot.loop.create_task(update_stats())
    

    但是,如果你想在消息到达时保存,你只能写一个更简单的函数:

    @bot.event
    async def on_message(message):
        with open("stats.txt", "a") as f: 
            f.write(f"Czas: {int(time.time())}\n")
            f.write("New message:\n")
            f.write(message)
    

    另一个编辑:我记得,机器人不仅获取原始格式的消息,而且获取具有消息“上下文”的对象,因此函数应该如下所示:

    @bot.event
    async def on_message(message):
        if message.channel.id == message.author.dm_channel.id:
            with open("stats.txt", "a") as f: 
                f.write(f"Czas: {int(time.time())}\n")
                f.write("New message:\n")
                f.write(message.content)
    

    【讨论】:

      猜你喜欢
      • 2021-10-30
      • 2021-05-27
      • 2021-03-29
      • 2021-07-11
      • 2021-03-25
      • 2018-08-13
      • 1970-01-01
      • 2021-02-28
      • 2021-07-13
      相关资源
      最近更新 更多