pythondiscorddiscord.pyctx

discord.py - Is there some way I can get ctx from an on_message event?


I want to recode my music bot (currently works with commands), so that a channel gets created. If you write any message in that channel, the bot is supposed to play the song from the message. For that I need to access stuff like voice_state, but on_message doesn't seem to provide that, while ctx does. Now I'm looking for any way to convert the message into a command, get ctx any other way or just access all the voice stuff somehow else.

Thanks in Advance.


Solution

  • There is, you can use Bot.get_context for this purpose. It's a coroutine.

    example:

    @bot.listen()
    async def on_message(message: discord.Message):
        ctx = await bot.get_context(message)
        command = bot.get_command('command name')
        await ctx.invoke(command, arg1, arg2, keywordarg1="something", keywordarg2="I like python")
    

    Positional arguments in command followed by keyword arguments. You don't need to provide ctx argument as ctx.invoke supplies that by default during command invocation

    and actually, no. You can use message.guild.voice_client for accessing the voice_client, ctx.voice_client is a shortcut to that. Also, for accessing author's voice state message.author.voice, most of the things you do in context are shortcuts to Guild/Member object methods. There are some exceptions though.