简体   繁体   English

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

[英]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.我想让 Discord bot 做一些事情,等待 1 分钟,然后做一些事情,之后,循环(while 循环)将继续做同样的事情,直到我停止程序。

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.为了更清楚:我希望它检查 varName(来自刮取)是否不等于 None(这意味着它刮取了一些东西)并检查 boolVar 是否为 True,因为如果为真,它不会发送如果页面上仍有内容,则每分钟都会显示相同的消息。 It scrapes the page every 60 seconds, so I can say it's looking for some "changes" on the page.它每 60 秒刮一次页面,所以我可以说它正在页面上寻找一些“更改”。 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 对此有一些帮助。 discord.py has a builtin module called tasks which includes looping. discord.py 有一个名为 tasks 的内置模块,其中包括循环。 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然后,您可以通过将其放入 on_ready 函数来启动循环

function_name.start()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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