Search code examples
pythondiscord.pybotsmessagepylance

Discord Bots: Detecting a message within another command


On my discord bot (python) I am trying to detect or rather to check a sent message within a command: if someone types the command $start the command should check in a while loop which messages are being sent after the $start command. If the sent message is "join", the user who sent the message should be added to a list. I was trying to detect and save messages in a variable via the on_message() function but it doesnt seem to work and I dont think that my code makes that much sense, but I dont know how to properly implement it.

import discord
from discord.ext import commands
    
client = commands.Bot(command_prefix = "$")

@client.event
async def on_ready():
    print("started")

sentMsg = ""
users = []

@client.event
async def on_message(msg):
    if msg.author == client.user:
        return
    else:
        sentMsg = msg.content
        print(sentMsg)

@client.command()
async def start(ctx):
    print(sentMsg)
    await ctx.send("starting ...")
    users.append(ctx.author)
    while True:
        if sentMsg == "join":
            ctx.send("Joined!")
            sentMsg = ""

client.run(*token*)

I put the sentMsg varibale to the Watch-section in VS-Code and it always says "not available" although it prints the right values. Also when hovering over it in on_message() it says: "sentMsg" is not accessed Pylance. Can anyone improve my code or does anyone have a better idea to implement this?

I'd appreciate anyone's help


Solution

  • instead of using an on_message event, you can make the bot detect messages using client.wait_for!

    for example:

    @client.command()
    async def start(ctx):
        await ctx.send("starting ...")
            try:
                message = await client.wait_for('message', timeout=10, check=lambda m: m.author == ctx.author and m.channel == ctx.channel and ctx.content == "join") # You can set the timeout to 'None' 
                # if you don't want it to timeout (then you can also remove the 'asyncio.TimeoutError' except case 
                # (remember you have to have at least 1 except after a 'try'))
    
                # if you want the bot to cancel this if the message content is not 'join',
                # take the last statement from the check and put it here with an if
                
                # what you want to do after "join" message
    
            except asyncio.TimeoutError:
                await ctx.send('You failed to respond in time!')
                return