首页 文章

Python discord bot - coroutine从未等待过

提问于
浏览
2

好吧,我正在使用Python3制作一个Discord机器人,它在某种程度上起作用但它每隔几分钟就会崩溃 . 它给了我一个错误,如“任务被摧毁但它正在等待” . 现在,我搜索了问题并遇到了我必须摆脱我的响应= request.get(url)的信息,并将其替换为“async with aiohttp.get(url)as response” . 现在,当我拥有它时,它给了我“coroutine'可用性'从未等待过” . 为了解决这个问题,我想我必须使用某种循环,但我对异步的东西相当新,所以我没有任何线索 .

import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time

import requests
from bs4 import BeautifulSoup
import smtplib
import aiohttp
import async_timeout


async def availability():
    url = "some url"
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
    async with aiohttp.ClientSession().get(url, headers=headers) as response:
        soup = BeautifulSoup(response.text, "lxml")
        print(soup)
        return soup


Client = discord.Client()
bot_prefix= "?"
client = commands.Bot(command_prefix=bot_prefix)


availible = True


@client.event
async def on_ready():
    print("Bot Online!")
    print("Name: {}".format(client.user.name))
    print("ID: {}".format(client.user.id))

    bessie = 0
    waittime = 0

    while True:
        time.sleep(1)
        if wachttijd == 0:
            if ("0 available") not in str(availability()):
                bessie = bessie + 1
                if bessie == 3:
                    await client.send_message(discord.Object(id='some id'),
                                              '<@&some channel>some text!')
                    print("available")
                    bessie = 0
                    waittime = 10
            else:
                bessie = 0
        else:
            wachttijd = wachttijd - 1



client.run("token")

有人可以帮我弄这个吗?

1 回答

  • 0

    然而,经过一些研究并根据我在this stackoverflow thread上看到的代码,我可能并不是百分之百肯定这一点,这可能是因为你没有等待response.text .

    尝试在response.text前面添加await关键字:

    soup = BeautifulSoup(await response.text(), "lxml")
    

    使用discord.py时也是 don't use time.sleep() ,而是使用 await asyncio.sleep(seconds)

    您可能希望尽可能避免阻塞,因为它可能导致僵尸程序冻结 . 您可以在"FAQ" section of the discord.py docs阅读更多相关信息 .

相关问题