gpt4 book ai didi

Python discord bot - 从未等待过协程

转载 作者:行者123 更新时间:2023-12-04 16:08:02 25 4
gpt4 key购买 nike

好吧,我正在使用 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")

有人可以帮我弄这个吗?

最佳答案

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

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

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

还有 不要使用 time.sleep() 使用 discord.py 时,改为使用 await asyncio.sleep(seconds)
您会希望尽可能避免阻塞,因为它会导致您的机器人卡住。您可以在 "FAQ" section of the discord.py docs 阅读更多相关信息。 .

关于Python discord bot - 从未等待过协程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47954196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com