我想制作一个删除频道 discord.py 的命令

时间:2021-02-23 21:39:27

标签: discord.py

这是我目前得到的 据说“await”在异步函数之外,我只是对如何解决这个问题感到困惑。我从赠品命令中复制了部分代码,因为这是我唯一的问答代码来源


@commands.has_permissions(administrator = True)
async def cdelete(ctx):
  embed=discord.Embed(title = Which channel would you like to delete?)
await ctx.send(embed=embed)

answer = []

def check(m):

    return m.author == cx.author and m.channel == ctx.channel

    try:
        await client.wait_for('message', timeout=15, check=check)
    except asyncio.TimeoutError:
        await ctx.send("Timeout. Please run the command again")
    else:
        answer.append(message.content)
    try:
        c_id= int(answer[0][2:-1])
        await ctx.channel.delete
        await ctx.send("Channel Deleted")
    except:
        await ctx.send("Thats not a valid channel!")```

2 个答案:

答案 0 :(得分:2)

如果您只需要一个命令,那么只需执行带有频道名称的命令,您就可以轻松得多。您可以查看以下内容:

@client.command()
@commands.has_permissions(administrator=True)
async def cdelete(ctx, channel_name):
    """Deletes a channel by name or ID."""
    channel_id = int(''.join(i for i in channel_name if i.isdigit())) # Get channel ID
    existing_channel = client.get_channel(channel_id) # Get channel ID with defined method
    if existing_channel: # If channel with the name/ID exists
        await existing_channel.delete()
    else: # If the channel does not exist
        await ctx.send(f'**No channel named `{channel_name}` was found.**')

我们有一个方法来捕获通道 ID 并将其作为有效参数传入。如果 ID 或频道名称存在,我们将删除该频道。

您可以在此处提及频道或传递 ID。 用法为:cdelete #channel/ID

如果你想在没有输入通道/ID/名称的情况下避免长时间的控制台输出,你可以构建一个错误处理程序:

@cdelete.error
async def cdelete_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send("You need to name a channel.")

答案 1 :(得分:0)

您在这里遇到的问题是 check() 函数。根据文档,您只能在 async 函数中使用 await 。解决问题将def check(m):改成async def check(m):