首页 > 解决方案 > Discord.py 文件记录,更改消息数量

问题描述

我有用于不和谐频道记录的代码。它基本上获取频道中的最后 10,000 条消息,并使用 !log 命令创建一个包含这些消息的 .txt 文件。但是,我将如何使它如此可选地用户可以在!log 之后键入一个数字,并且它将记录该数量的先前消息?EG:它自己的“!log”记录最后 10,000 条消息,但“!log 100”将记录最后 100 条消息。但我不知道该怎么做。

这是我的代码:

@commands.has_any_role('Logger', 'logger')
@bot.command()
async def log(ctx):
    try:
        channel = ctx.message.channel
        await ctx.message.delete()
        await channel.send(ctx.message.author.mention+" Creating a log now. This may take up to 5 minutes, please be patient.")
        messages = await ctx.channel.history(limit=10000).flatten()
        numbers = "\n".join([f"{message.author}: {message.clean_content}" for message in messages])
        f = BytesIO(bytes(numbers, encoding="utf-8"))
        file = discord.File(fp=f, filename='Log.txt')
        await channel.send(ctx.message.author.mention+" Message logging has completed.")
        await channel.send(file=file)
    except:
        embed = discord.Embed(title="Error creating normal log:", description="The bot doesn't have necessary permissions to make this log type. Please confirm the bot has these permissions for this channel: View Channel, Read and Send Messages, Attatch Files (used for sending the log file), Manage Messages (used for deleting the command the user sends when making a log).", color=0xf44336)
        await channel.send(embed=embed)

有关如何制作的任何帮助,以便他们可以选择提供一个数字,然后记录该数量,这将有很大帮助。谢谢!

标签: discord.py

解决方案


将要记录的消息数作为参数

...
@bot.command()
async def log(ctx, limit: int=1000):
...

然后使用参数的值

    ...
    messages = await ctx.channel.history(limit=limit).flatten()
    ...

文档:https ://discordpy.readthedocs.io/en/latest/ext/commands/commands.html#parameters


推荐阅读