首页 > 解决方案 > Discord.py 存储和输出记录/警告

问题描述

所以目前我正在尝试创建一个黑名单(基本上是一个警告命令)命令,服务器所有者可以使用该命令发布他们处理的禁令。我试图重写我原来的警告命令,但问题是输出不是我想要的那样,如果我确实想修复它,我不得不重写大部分代码,这就是我想做的原因一个新的命令。

所以我在制作命令时面临的问题是接受多个参数。

例如:(列入黑名单的过程)

User: >blacklist (user/id)

BOT: Gamertag?

User: *Sends an Xbox username*

BOT: Banned from?

User: *Sends server name*

BOT: Reason for the ban?

User: *Sends ban reason*

这是机器人和用户将要进行的对话的示例。最主要的是能够保存用户的响应并将所有内容作为嵌入发送。我目前有这个:

@commands.command()
async def blacklist(self, ctx):
 embed = discord.Embed(title = "Blacklist Report")
 #Then something here to collect responses

注意:我可以很好地创建嵌入,但只需要帮助收集用户的响应。任何帮助都会很棒!

标签: pythondiscord.py

解决方案


我决定向您发送 2 个我一直用来帮助您的功能

def check_message(author: discord.User, channel: discord.TextChannel, forbid: bool = False):
    def check(message: discord.Message):
        if forbid and message.channel.id == channel.id and message.author.id != author.id and message.author.id != bot.user.id:
            embed = discord.Embed(title='**ERROR**', description=f'Only {author.mention} can send message here', colour=discord.Colour.red())
            asyncio.ensure_future(message.delete())
            asyncio.ensure_future(channel.send(embed=embed, delete_after=20))

        return message.author.id == author.id and channel.id == message.channel.id

    return check

async def get_answer(ctx: discord.TextChannel, user: discord.User, embed: discord.Embed, timeout: Optional[int] = None, delete_after: bool = False) -> Optional[str]:
    message: discord.Message = await ctx.send(embed=embed)

    try:
        respond: discord.Message = await bot.wait_for('message', check=check_message(user, ctx), timeout=timeout)

        if delete_after:
            await try_delete(message)
            await try_delete(respond)

        return respond.content
    except asyncio.TimeoutError:
        if delete_after:
            await try_delete(message)

        return None

你甚至不需要打电话check_message,你只需要等待get_answer并得到你想要的字符串

这是一个例子:

@commands.command('example')
async def example(self, ctx):
    embed = discord.Embed(title='What is your name?')
    response = await get_answer(ctx.channel, ctx.author, embed)
    print(f'His name was {response}') # or any other thing you want to use it for

timeout允许您在几秒钟后关闭进程而没有响应并继续代码,在这种情况下,您将获得此None函数的输出。

允许您在delete_after超时或收到回复后删除问题消息和回复以保持聊天清晰。


推荐阅读