Search code examples
pythondiscorddiscord.pybots

Discord.py wait_for() not working when using Cogs-- API docs useless


I'm trying to create a basic command that, after a user types /'command_name', the bot waits for the user to send another message (it would be nice if there was an option for a little text field) and then does something with the message they send.


class Test(commands.Cog, name="test"):
    def __init__(self,bot):
        self.bot = bot

   @commands.hybrid_command(name='create_response', with_app_command=True)
    async def create_response(self, ctx):
        def check(msg):
            return msg.author == ctx.author
        msg = await self.bot.wait_for('message', check=check)
        await ctx.send(msg)

This code does nothing and sometimes(?) errors out.

The expected output would be something like:

User: /create_response

Bot reply: [______]  (this would be a text box after they type the /create_response command

User: "Hello"

Bot reply: "Hello"

Solution

  • To get the contents of messages and use the on_message event (this is what your bot is waiting for) you need to enable Intents.message_content:

    from discord import Intents
    from discord.ext import commands
    
    
    # This factory method that creates a Intents with everything enabled
    # Except the privileged gateway intents (presences, members, and message_content);
    # You also need to authorize privileged intents in the developer portal;
    # For greater control of the bot's cache
    # I recommend using Intents(<option>=True) to select only what you need
    intents = Intents.default()
    
    # Enabling the message content intent
    intents.message_content = True
    
    bot = commands.Bot(command_prefix="!", intents=intents)
    

    You can also receive the text as a command parameter:

    @commands.hybrid_command(name='create_response')
    async def create_response(self, ctx: commands.Context, *, text: str):
        """This command creates a response
    
        Args:
            text: type the text you want to send
        """
        await ctx.reply(text)
    
    • I'm using docstrings to describe the function of the command and arguments. These descriptions will automatically be used by the application commands;
    • I recommend reading this article on how to develop slash commands using the discord.ext.commands framework.