【问题标题】:Python discord bot - coroutine was never awaitedPython discord bot - 从未等待协程
【发布时间】:2018-06-05 20:33:27
【问题描述】:

嗯,我正在使用 Python3 开发一个 Discord 机器人,它在某种程度上可以工作,但每隔几分钟就会崩溃一次。它给了我一个错误,例如“任务已被破坏,但它正在等待处理”。现在,我搜索了问题并发现了我必须摆脱我的 response = request.get(url) 并将其替换为“async with aiohttp.get(url) as response”的信息。现在,当我拥有它时,它给了我“从未等待过协程'可用性'”。为了解决这个问题,我认为我必须使用某种循环,但我对异步的东西还很陌生,所以我一无所知。

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")

有人可以帮我解决这个问题吗?

【问题讨论】:

  • 您需要使用await availability()

标签: python python-3.x python-asyncio discord discord.py


【解决方案1】:

不过,我对此不是百分百确定,根据我在this stackoverflow thread 上查看的代码,经过一些研究,这可能是因为您没有等待 response.text。

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

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

另外在使用 discord.py 时不要使用 time.sleep(),而是使用 await asyncio.sleep(seconds)

您需要尽可能避免阻塞,因为它可能会导致您的机器人冻结。你可以在"FAQ" section of the discord.py docs阅读更多关于它的信息。

【讨论】:

    猜你喜欢
    • 2021-03-31
    • 2020-07-03
    • 2020-10-10
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 2021-02-23
    相关资源
    最近更新 更多