Issue
I have written a small api wrapper and i wanted to try to put it in a discord bot using discord.py. I tried using requests, grequests and aiohttp for the requests, but that didn't work. The code that is throwing the error is the following:
async def _get(url):
return await requests.get(url)
def getUser(name):
url = 'some url'
resp = asyncio.run(_get(url))
and the error is:
/usr/lib/python3.8/asyncio/events.py:81: RuntimeWarning: coroutine '_get' was never awaited
self._context.run(self._callback, *self._args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
this seems to be an issue just when using discord py, as the actual code works fine in python
Solution
requests.get()
is synchronous, so awaiting it is useless, however _get
is. Since requests
is synchronous, you'll have to use aiohttp
:
# Set json to True if the response uses json format
async def _get(link, headers=None, json=False):
async with ClientSession() as s:
async with s.get(link, headers=headers) as resp:
return await resp.json() if json else await resp.text()
async def getUser(name):
url = 'some url'
resp = await _get(url)
If you don't want getUser
to be asynchronous, you can use asyncio.run_coroutine_threadsafe
:
from asyncio import run_coroutine_threadsafe
def getUser(name):
url = 'some url'
resp = run_coroutine_threadsafe(_get(url), bot.loop) #or client.loop
Answered By - MrSpaar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.