Inj3ct0r
Inj3ct0r

Reputation: 65

discord.py 1vs1 game - accept invite function

Im making a 1vs1 game that sends invite to user and awaits for accept. Here is my code:

global hasRun
hasRun = False
@client.command()
async def accept(ctx):
    global hasRun
    hasRun = True

@client.command() 
async def fight(ctx, user: discord.Member):
    await ctx.send('sending invite to user')
    await user.send('press `/accept` to start the game')
    await ctx.send('waiting for accept..')
    global hasRun
    if hasRun == True:
      await ctx.send("game started")

Code doesnt drop any error but it just doesnt work. Any idea where the fault lies?

Upvotes: 0

Views: 152

Answers (1)

12944qwerty
12944qwerty

Reputation: 1925

You're not waiting to see if hasRun been true. As soon as you send Waiting for accept... it checks if hasRun is true or not, which is likely False.

Instead of using a separate command and a global variable you can use wait_for()

The check function will check if the user you asked for sends a message to accept the game. You should also include a timeout.

import asyncio # Required for timeout

# ...

@client.command() 
async def fight(ctx, user: discord.Member):
    await ctx.send('sending invite to user')
    await user.send('press `accept` to start the game')
    await ctx.send('waiting for accept..')
    def check(message):
        return message.author == user and message.content in ('accept', '/accept')
    try:
        msg = await client.wait_for('message', check=check, timeout=60.0)
    except asyncio.TimeoutError:
        await ctx.send("User didn't accept game in time")
    # Code can go here

Upvotes: 1

Related Questions