Rapptz / discord.py

An API wrapper for Discord written in Python.
http://discordpy.rtfd.org/en/latest
MIT License
14.83k stars 3.75k forks source link

TypeError : Object of type _MissingSentinel is not JSON serializable is not supposed to happen when trying to synchronize slash commands globally. #9542

Closed ithri012 closed 1 year ago

ithri012 commented 1 year ago

Summary

it raises an TypeError: "Object of type _MissingSentinel is not JSON serializable" when I try to sync the app commands in all the guilds.

Reproduction Steps

To reproduce the error, you will have to try to sync the slash commands on the on_ready() event without putting any arguments, like this:

@client.event
async def on_ready():
    # Load the cogs ....

    await client.tree.sync() # (Without anything between brackets)

Minimal Reproducible Code

import discord, os
from discord.ext import commands

client = commands.Bot(command_prefix=PREFIX, help_command=None, intents=discord.Intents.all())

@client.event
async def on_ready():
    for dossier in os.listdir("./cogs"):
        if not dossier.endswith(".py"):
            for filename in os.listdir(f"./cogs/{dossier}"):
                if filename.endswith(".py"):
                    try: await client.load_extension(f"cogs.{dossier}.{filename[:-3]}")
                    except: raise KeyError(f"\n{filename} a un problème !\n")

    await client.tree.sync()
    print(f"\n{NAME} est prêt\n")
client.run(TOKEN)

Expected Results

Le résultat attendu est que le bot démarre normalement, sans aucun problème, et que les slash commands se sync sur toutes les guildes

Actual Results

Le bot ne démarre pas, et ne sync rien. à la place, une erreur est générée comme quoi _MissingSentinel n'est pas JSON serializable.

Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 466, in _run_event     
    await coro(*args, **kwargs)
  File "c:/Users/User/Desktop/Documents/Devellopement/Python/Côté BOT/main.py", line 21, in on_ready
    await client.tree.sync()
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\app_commands\tree.py", line 989, in sync
    data = await self._http.bulk_upsert_global_commands(self.client.application_id, payload=payload)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\http.py", line 557, in request
    kwargs['data'] = utils._to_json(kwargs.pop('json'))
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\utils.py", line 620, in _to_json        
    return json.dumps(obj, separators=(',', ':'), ensure_ascii=True)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 234, in dumps
    return cls(
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type _MissingSentinel is not JSON serializable

PS : Je suppose que cela est dû au fait que quand une guild n'est pas mise, cette dernière est remplacée par MISSING, et donc _MissingSentinel est un resultat de cela, et n'est donc pas sensé passer par le bout de code kwargs['data'] = utils._to_json(kwargs.pop('json'))

Intents

discord.Intents.all()

System Information

C:\Users\User>python -m discord -v

Checklist

Additional Context

No response

Amrinder-S commented 1 year ago

Not sure if you want this but, this is how you do it:

from discord import app_commands
# stuff goes here
tree = app_commands.CommandTree(client)
# stuff goes there
@client.event
async def on_ready():
    print("Bot started")
    await tree.sync(guild=discord.Object(id=GUILD_ID_OF_THE_SERVER))

I believe if you omit the id=GUILD_ID of the server, it will sync with all the servers etc.

Eternity71529 commented 1 year ago

what version of discord.py are you on? pip show discord.py

a couple of things I should address regarding that snippet

No767 commented 1 year ago

Your dpy version is quite out of date (latest is 2.3.2 as of writing), so please consider upgrading to the latest version. As mentioned beforehand, do not sync or even do anything in ,on_ready events. Load exts in setup_hook, and consider manually syncing instead.

This is not a dpy issue at all.

Rapptz commented 1 year ago

It's hard to tell what's going on here but MISSING shouldn't surface in the library unless you're explicitly doing it in places where it isn't expected. Your discord.py version is quite old too. Please update the library before opening an issue.