'Python discord bot - coroutine was never awaited
I'm working on a Discord bot and it works to some degree but it keeps crashing every couple minutes. It gives me an error like
Task was detroyed but it's pending
I came across the information that I had to get rid of my response = request.get(url)
and replace it with async with aiohttp.get(url) as response
.
Now when I have it like this, it gives me
coroutine 'availability' was never awaited"
To solve this I think I have to use some sort of loop, but how exactly do I need to do this?
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")
Solution 1:[1]
I'm not one hundred percent certain about this however, after some research and as according to the code I viewed on this stackoverflow thread it might be because you are not awaiting response.text.
Try adding the await keyword in front of response.text:
soup = BeautifulSoup(await response.text(), "lxml")
Also don't use time.sleep() when using discord.py, instead use await asyncio.sleep(seconds)
You'll want to avoid blocking whenever possible as it can cause your bot to freeze. You can read more about it at the "FAQ" section of the discord.py docs.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Milan Donhowe |