为了账号安全,请及时绑定邮箱和手机立即绑定

Python Discord.py `time.sleep()` 协程

Python Discord.py `time.sleep()` 协程

拉风的咖菲猫 2022-10-05 17:07:19
import discordimport osimport randomimport timeimport mathclient = 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.eventasync 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 0def mention_to_uid(mention):    '''Extract UID from a mention'''    uid = mention[2:-1]    if uid[0] == '!':        uid = uid[1:]    return uiddef 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.eventasync 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在 time.sleep() 事件期间,其他机器人命令在 sleep 函数通过之前不会注册。例如,在执行 /search 后立即执行 /help 之类的命令,机器人将在 1 分钟后才会响应,此时它会响应 /help 并且消息还剩 1 分钟。我尝试在每个睡眠功能之前坚持“等待”,但它只是向我吐出运行时警告并停止执行(它只是说你开始搜索然后什么也没发生)。
查看完整描述

1 回答

?
慕村225694

TA贡献1880条经验 获得超4个赞

time.sleep()停止程序的整个执行。如果您只想延迟一个异步响应线程,请使用asyncio.sleep


例子:


import asyncio


async def wait():

    await asyncio.sleep(5)

    print('I waited 5 seconds')


查看完整回答
反对 回复 2022-10-05
  • 1 回答
  • 0 关注
  • 99 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信