ошибка попытки и исключения функции в боте discord

#python-3.x #discord.py

#python-3.x #discord.py

Вопрос:

Я не могу использовать функцию try в моем боте discord. Вместо перехода к функции except в терминале выводится сообщение об ошибке

 @client.command()
async def new(ctx, *, players):
    try:
        data = Team()
        data_output = data.team(players)
        team1 = data_output[0]
        team2 = data_output[1]
        response = "Team 1"
        response2 = "Team 2"
        
        await ctx.send(f'''{response} -- {team1}
{response2} -- {team2}''')

    except:
        await ctx.send('''Please use the command in the correct format
First the command by "/new"
and then the name of the players without and thing between
other than spaces

Example: /new p1 p2 p3 p4 p5 p6''')
 

Вывод

 File "C:UsersanimiAppDataLocalPackagesPythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0LocalCachelocal-packagesPython38site-packagesdiscordextcommandscore.py", line 542, in transform   
    raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: players is a required argument that is missing.
 

Здесь вместо печати отчета об ошибке предполагалось перейти к оператору except, но этого не произошло.

Может кто-нибудь, пожалуйста, подсказать мне, что я должен делать

Комментарии:

1. Что это за функция Team() ?

2. Совет: вы можете использовать n для перевода строк вместо фактического ввода новой строки. Другими словами, вы можете написать это await ctx.send(f'{response} -- {team1}n{response2} -- {team2}') , и это даст вам тот же результат

Ответ №1:

Для ошибок, вызванных discord.py библиотека вы должны использовать обработчик ошибок

 @client.command()
async def new(ctx, *, players):
    # Your code here


@new.error # <- the name of the command   .error
async def new_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send("Please use the command in the correct format")
 

Ссылка:

Ответ №2:

Обычно для обработки ошибок используется обработчик ошибок. Это может быть в форме декоратора или в глобальном событии on_command_error() .

Предложение try-except не будет работать в этом случае, потому что ошибка возникает не внутри инструкции try, а в вызываемой команде.

Ответ №3:

Это берет игроков и использует .split их для создания списка с именами, которые они используют split_list , чтобы разделить его пополам.

 def split_list(a_list):
    half = len(a_list)//2
    return a_list[:half], a_list[half:]


@client.command()
async def new(ctx, *, players):

    team1, team2 = split_list(players.split())
    response = "Team 1"
    response2 = "Team 2"

    await ctx.send(f'''{response} -- {''.join(team1)}
{response2} -- {''.join(team2)}''')
 

Ответ №4:

В discord вы никогда не указывали требуемый аргумент players . Вы можете сделать это необязательным и показать сообщение об ошибке, указав в аргументе параметр по умолчанию.

 @client.command()
async def new(ctx, *, players=None):
    if players:
        data = Team()
        data_output = data.team(players)
        team1 = data_output[0]
        team2 = data_output[1]
        response = "Team 1"
        response2 = "Team 2"
        
        await ctx.send(f'''{response} -- {team1}
{response2} -- {team2}''')

    else:
        await ctx.send('''Please use the command in the correct format
First the command by "/new"
and then the name of the players without and thing between
other than spaces

Example: /new p1 p2 p3 p4 p5 p6''')
 

Итак, в discord вы можете просто сделать это: /new и он возвращает ошибку.