python - 如何检查用户是否提供了参数 discord.py

标签 python discord discord.py

我刚刚开始尝试学习如何在 discord.py 中编码。但是,我不确定如何检查用户是否在命令后提供了争论。 例如,如果用户键入 !kick,但后面没有标记用户,它应该给他们一条错误消息,如 “请标记用户”

所以我的问题是,如何检查用户在使用命令时是否标记了另一个用户,如果没有,给他们一个错误消息

这是我的代码:

#PyBot by RYAN#2302

import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
import chalk

bot = commands.Bot(command_prefix='!')

@bot.event
async def on_ready():
    print ("Ready when you are xd")
    print ("I am running on " + bot.user.name)
    print ("With the ID: " + bot.user.id)

@bot.command(pass_context=True)
async def ping(ctx):
    await bot.say(":ping_pong: Ping! :ping_pong:")
    print ("!ping")

@bot.command(pass_context=True)
async def info(ctx, user: discord.Member):
    await bot.say("The users name is: {}".format(user.name))
    await bot.say("The users ID is: {}".format(user.id))
    await bot.say("The users status is: {}".format(user.status))
    await bot.say("The users highest role is: {}".format(user.top_role))
    await bot.say("The user joined at: {}".format(user.joined_at))
    print ("!info")

@bot.command(pass_context=True)
async def kick(ctx, user: discord.Member):
    await bot.say(":boot: Cya, {}. Ya loser!".format(user.name))
    await bot.kick(user)
    print ("!kick on {}".format(user.name))

非常感谢任何帮助,谢谢!

最佳答案

user 参数提供默认值 None,然后检查是否使用了提交的值

@bot.command(pass_context=True)
async def kick(ctx, user: discord.Member = None):
if user:    
    await bot.say(":boot: Cya, {}. Ya loser!".format(user.name))
    await bot.kick(user)
    print ("!kick on {}".format(user.name))
else:
    await bot.say("Please tag a user to kick")

所有 Member 对象都是真实的,所以 if user: 唯一会失败的情况是没有提供用户。如果输入无法与用户匹配,则该命令将不执行任何操作,静默失败,除非我们还指定了一个错误监听器

@kick.error
async def kick_error(ctx, error):
    if isinstance(error, discord.ext.commands.BadArgument):
        await bot.say('Could not recognize user')

关于python - 如何检查用户是否提供了参数 discord.py,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48846859/

相关文章:

python - 将列表输出为列

python - 使用本地文件作为 set_thumbnail 嵌入 Discord.py

python - 在 Discord 中仅从 1 个 channel 发送消息(discord.py bot)

python - 如何使用 Python 中的 Discord 机器人获取用户输入?

python - 如何用 .sql 文件替换当前工作的 MySQL 数据库?

python - 在 Python 中反序列化 Avro 对象,而无需手头有 AVRO 架构

javascript - 如何在 Math.floor 中使用变量

python - discord.ext.commands.errors.CommandInvokeError : Command raised an exception: TypeError: __init__() missing 1 required positional argument: 'source'

ffmpeg - 如何使用 discord.py/ffmpeg 应用音频过滤器

python - 如何使用 API 与 Google Colab 交互?