0

Хотел подружить один API с Discord, но выдаёт ошибку, когда ввожу команду ">>profile {ник игрока}". Ошибка:

Traceback (most recent call last):
  File "C:\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\Артем\Desktop\VimeBot.py", line 16, in profile
    await ctx.send(f"""```Ник: {str(profile['username'])}
TypeError: string indices must be integers

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Python39\lib\site-packages\discord\ext\commands\bot.py", line 902, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Python39\lib\site-packages\discord\ext\commands\core.py", line 864, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: string indices must be integers

Функция, которая отвечает за эту команду:

async def profile(ctx, arg1):
    profile = requests.get(f"https://api.vimeworld.ru/user/name/{arg1}").text
    jsonprofile = json.loads(profile)
    await ctx.send(f"""```Ник: {str(profile['username'])}
ID: {profile['id']}```""")
1
  • 2
    а что должно выдать "profile['username'])" если profile это обычная строка? Неужели вам непонятен текст ошибки? 25 апр 2021 в 22:45

1 ответ 1

2
profile = requests.get(f"https://api.vimeworld.ru/user/name/{arg1}").text
jsonprofile = json.loads(profile)
await ctx.send(f"""```Ник: {str(profile['username'])}

Судя по вашему коду, у вас элементарная описка. Вам нужно было обращаться к jsonprofile['username']. Но ещё более правильно сразу получать json из request, а не парсить как json "вручную" текст ответа на запрос, судя по всему задумка была именно такая изначально. Кроме того, в ответе приходит список пользователей, по нему нужно итерироваться:

profile = requests.get(f"https://api.vimeworld.ru/user/name/{arg1}").json() # <-- изменено
for user in profile: # <-- добавлен цикл
    await ctx.send(f"""```Ник: {user['username']} # <-- изменено
3
  • Всё равно не работает. Выдаёт ошибку: Ignoring exception in command profile: Traceback (most recent call last): File "C:\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped ret = await coro(*args, **kwargs) File "C:\Users\Артем\Desktop\VimeBot.py", line 15, in profile await ctx.send(f"""```Ник: {str(profile['username'])} TypeError: list indices must be integers or slices, not str
    – OniShlange
    26 апр 2021 в 12:50
  • @OniShlange Я проверил, по счастью я угадал с именем пользователя "123" и получил ответ. У вас там список в json, а внутри уже словарь. Я немного поменял ответ.
    – CrazyElf
    26 апр 2021 в 14:44
  • Теперь всё работает, спасибо!
    – OniShlange
    26 апр 2021 в 14:46

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.