Python Discord.py `time.sleep()` coroutine

Question:

import discord

import os
import random
import time
import math


client = discord.Client()

with open('admins.conf', 'r') as f:
    for line in f.readlines():
        exec(line)
with open('bans.conf', 'r') as f:
    for line in f.readlines():
        exec(line)
with open('coins.conf', 'r') as f:
    for line in f.readlines():
        exec(line)

random.seed(os.urandom(32))
searchusers = []

@client.event
async def on_ready():
    '''Notification on ready.'''
    print('Logged in! Bot running.')
    await client.change_presence(activity=discord.Game(name='/help'))

def getcoins(uid):
    '''Get the amount of coins, if nonexistent set to 0.'''
    try:
        return coins[uid][0]
    except Exception:
        coins[uid] = [0, time.time()+20]
        return 0

def mention_to_uid(mention):
    '''Extract UID from a mention'''
    uid = mention[2:-1]
    if uid[0] == '!':
        uid = uid[1:]
    return uid

def setcoins(uid, value):
    '''Set the amount of coins someone has.'''
    try:
        coins[uid][0] = value
    except Exception:
        coins[uid] = [value, time.time()+20]
    with open('coins.conf','w') as f:
        f.write('coins = '+repr(coins))

@client.event
async def on_message(message):
    '''Main bot code running on message.'''
    if message.author == client.user:
        return
    if message.author.id in bans:
        return
    if message.content.startswith('/') or message.content.startswith('&'):
        user = message.author.id
        text = message.content[1:].strip()
        command = text.split(' ')[0]
        subcommand = text.split(' ')[1:]
        if message.author.id in searchusers:
            await message.channel.send('<@'+str(message.author.id)+'>, you cannot use bot commands while you are searching.')
            return

-------------------- snip --------------------

        if command == 'search':
            await message.channel.send('<@'+str(user)+'>, you have begun searching! It will take 2 minutes.')
            searchusers.append(user)
            time.sleep(59.99)
            await message.channel.send('<@'+str(user)+'>, there is 1 minute left.')
            time.sleep(39.99)
            await message.channel.send('<@'+str(user)+'>, there are 20 seconds left!')
            time.sleep(14.99)
            await message.channel.send('<@'+str(user)+'>, there are 5 seconds left!')
            time.sleep(4.99)
            found = random.randint(50, 120)
            await message.channel.send('<@'+str(user)+'>, you are done searching! You found '+str(found)+' coins!')
            setcoins(user, getcoins(user)+found)
            searchusers.remove(user)

During the time.sleep() events other bot commands do not register until the sleep function has passed. For example doing a command like /help right after doing /search the bot will not respond until after one minute, when it will respond to /help and message there is 1 minute left. I have tried sticking “await” before each one of the sleep functions but it just spit out runtime warnings at me and stopped the execution (It just says you started searching and then nothing happens).

Asked By: Eric Jin

||

Answers:

time.sleep() stops the entire execution of the program. If you just want to delay one async response thread use asyncio.sleep

Example:

import asyncio

async def wait():
    await asyncio.sleep(5)
    print('I waited 5 seconds')
Answered By: chluebi

i tried what you were saying on my bot but it doesn’t sleep "completely". i have it set to respond to any message that comes across, so i want it to pause between responses so it doesn’t spam my server. what i am going for is a ten minute pause between responses. i figured if i had it sleep when it recognizes itself it would suffice but no go. when it responds i want it to wait for ten minutes until it gets cued to respond again.

import discord
import asyncio
from neuralintents import GenericAssistant


chatbot = GenericAssistant('intents.json')
chatbot.train_model()
chatbot.save_model()

print("Bot is done training...")

intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)


channel = client.get_channel(1018756543816155187)

@client.event
async def on_ready():
    print(f'We have logged in as {client.user}')


@client.event
async def on_message(message):
        if message.author == client.user:
            await asyncio.sleep(600)
        if message:
            response = chatbot.request(message.content)
            await message.channel.send(response)

client.run('<my key>')
Answered By: deusopus
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.