简体   繁体   中英

Async - Await Discord.py Function Problem

I wanted to make Discord bot that will do something, wait 1 minute, then do something, after that, loop (while loop) will continue doing the same until i stop the program.

Here is my code:

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)

To make it more clear: I want it to check if the varName (from scraping) isn't equal to None (which means it scraped something) and check if that boolVar is True, because if it's true, it won't send the same message every minute if there is still something on the page. It scrapes the page every 60 seconds, so I can say it's looking for some "changes" on the page. Well, I start the bot, it prints the message... but then this error comes out:

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

Thank you in advance!

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

await asyncio.sleep(60)

If you're talking about making a loop, then discord has something for this. discord.py has a builtin module called tasks which includes looping. You can import it with

from discord.ext import tasks

and then put this before your command definition

@tasks.loop(seconds=some_float)

You can then start the loop by putting this into your on_ready function

function_name.start()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM