【问题标题】:Discord.py file logging, change number of messagesDiscord.py 文件记录,更改消息数量
【发布时间】:2021-03-20 04:01:51
【问题描述】:

我有这段代码,用于记录不和谐频道。它基本上获取频道中的最后 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


    【解决方案1】:

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

    ...
    @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

    【讨论】:

    • 这行不通,limit 参数是一个字符串,TextChannel.history 只接受一个整数作为限制 kwarg。你也应该为它设置一个默认值
    • limit 现在是int 类型,limit 的默认值为 1000,现在应该可以使用了。
    猜你喜欢
    • 2021-05-17
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多