异步 - 等待Discord.py函数问题

我想制作能做某事的Discord机器人,等待1分钟,然后做一些事情,之后,循环(while循环)将继续这样做,直到我停止程序 .

这是我的代码:

import discord
from discord.ext import commands
import requests
from bs4 import BeautifulSoup
import time

TOKEN = "MyToken!"
bot = commands.Bot(command_prefix='!')

@bot.event
async def on_ready():
    print("Started!")

@bot.command(pass_context=True)
async def start_bot():
    isAlreadyLive = False
    print("Let's get it started! :D")
    url = 'someLink'
    while True:
        soup = BeautifulSoup(requests.get(url).content, 'html.parser')
        varName = soup.find('span', {'class': 'firstClass secondClass'})
        if varName != None and boolVarName == False:
            await bot.say("SAY THIS! :D ")
            boolVarName = True
        if varName == None:
            await bot.say("SAY THIS #2! :D")
            boolVarName = False
        await time.sleep(60)
        print("Refreshed")

bot.run(TOKEN)

为了使它更清楚:我希望它检查varName(来自scraping)是否不等于None(这意味着它刮了一些东西)并检查boolVar是否为True,因为如果它是真的,它将不会发送如果页面上还有某些内容,则每分钟都会显示相同的消息 . 它每60秒擦除一次页面,所以我可以说它正在寻找页面上的一些“更改” . 好吧,我启动机器人,它打印消息......但然后出现这个错误:

Ignoring exception in command start_bot
Traceback (most recent call last):
  File "C:\Users\WiMAX\PycharmProjects\KockarBot\venv\lib\site-packages\discord\ext\commands\core.py", line 50, in wrapped
    ret = yield from coro(*args, **kwargs)
  File "LiveBot.py", line 27, in start_bot
    await time.sleep(60)
TypeError: object NoneType can't be used in 'await' expression

先感谢您!

回答(1)

2 years ago

要使用异步睡眠,请执行以下操作:

await asyncio.sleep(60)