@AdvoKappa

Discord.ext.commands.errors.MissingRequiredArgument: users is a required argument that is missing, что делать?

Код такой:
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import json
import os

bot = commands.Bot(command_prefix='$')
os.chdir(r'D:\Sublime Text 3\testbot-master')

@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')

@bot.event
async def on_member_join(member):
    with open('users.json', 'r') as f:
        users = json.load(f)

    await update_data(users, member)

    with open('users.json','w') as f:
        json.dump(users, f)

@bot.event
async def on_message(message):
    await bot.process_commands(message)
    with open('users.json', 'r') as f:
        users = json.load(f)

        async def update_data(users, user):
            if not str(user.id) in users:
                users[str(user.id)] = {}
                users[str(user.id)]['experience'] = 0
                users[str(user.id)]['level'] = 1

        await update_data(users, message.author)
        await add_experience(users, message.author, 5)
        await level_up(users, message.author, message.channel)

    with open('users.json','w') as f:
        json.dump(users, f)

    if message.content == '!Rank':
        async def sent(users, user):
            experience = users[str(user.id)]['experience']
            lvl_start = users[str(user.id)]['level']
            lvl_end = int(experience ** (1/50))

            channel = message.channel
            await channel.send(':thumbsup: {}, Ваш уровень: {} :thumbsup: '.format(user.mention, lvl_end))
            users[str(user.id)]['level'] = lvl_end

async def add_experience(users, user, exp):
    users[str(user.id)]['experience'] += exp

async def level_up(users, user, channel):
    experience = users[str(user.id)]['experience']
    lvl_start = users[str(user.id)]['level']
    lvl_end = int(experience * (1/50))

    if lvl_start < lvl_end:
        await channel.send(channel, f":thumbsup: {user.mention}, вы повысились до {lvl_end} уровня! :thumbsup: ")
        users[user.id]["level"] = lvl_end

@bot.command(pass_content=True)
async def Rank(message, users, user):
    if message.content == '!Rank':
            experience = users[str(user.id)]['experience']
            lvl_start = users[str(user.id)]['level']
            lvl_end = int(experience ** (1/50))

            channel = message.channel
            await channel.send(':thumbsup: {}, Ваш уровень: {} :thumbsup: '.format(user.mention, lvl_end))
            users[str(user.id)]['level'] = lvl_end

Когда пишу обычное сообщение, всё работает, но когда пишу команду '$Rank', вылезает ошибка:
Ignoring exception in command Rank:
Traceback (most recent call last):
  File "C:\Users\denko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\denko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 790, in invoke
    await self.prepare(ctx)
  File "C:\Users\denko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 751, in prepare
    await self._parse_arguments(ctx)
  File "C:\Users\denko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 670, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "C:\Users\denko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 516, in transform
    raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: users is a required argument that is missing.
  • Вопрос задан
  • 3616 просмотров
Решения вопроса 1
discord.ext.commands первым аргументом в команду всегда передает commands.Context.

Вся суть расширения commands в отсутствии необходимости работы с обработкой сообщений и аргументов команд в них

Сделайте переменную users глобальной.

Например, объявив её после os.chdir(r'D:\Sublime Text 3\testbot-master'):
users = {}

В итоге, код команды должен выглядеть примерно так:
@bot.command()
async def Rank(ctx, user: discord.Member):
    experience = users[str(user.id)]['experience']
    lvl_start = users[str(user.id)]['level']
    lvl_end = int(experience ** (1/50))
    await ctx.send(':thumbsup: {}, Ваш уровень: {} :thumbsup:'.format(user.mention, lvl_end))
    users[str(user.id)]['level'] = lvl_end


Ошибка MissingRequiredArgument будет возникать в случае, если введенной команде не хватает аргументов:
!Rank вызовет в данном случае ошибку
!Rank @DiscordTag#0000 - нет

Если вам необходимо чтобы команда срабатывала без аргумента - сделайте его необязательным, задав стандартное значение, например "None" (не забудьте в данном случае обработать это самое None в коде самой команды):
@bot.command()
async def Rank(ctx, user: discord.Member = None):
    if not user:
        user = ctx.author
    ...


А так же:
В текущей версии discord.py аргумента pass_context у команд нет, аргумент контекста передается первым автоматически всегда

from discord.ext.commands import Bot - неиспользуемый импорт в этом коде
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы