Search code examples
pythonpython-3.xpython-asyncioaiohttp

I had made a bot but it sometimes fails to answer


This bot is made for chatting like a human where it uses a endpoint it works good but sometimes.

I tried my best to solve it but it still gives error.

My unmodified code

import aiohttp
import asyncio

async def get_response(query):
    async with aiohttp.ClientSession() as ses:
        async with ses.get(
            f'https://some-random-api.ml/chatbot?message={query}'
        ) as resp:
            return (await resp.json())['response']
async def main():
    print(await get_response('world'))

But it gives error

rep = await get_response(query)

File "/app/chatbot/plugins/response.py", line 9, in get_response

 return (await resp.json())['response']

KeyError: 'response'

Solution

  • You should use asycio.gather to gather the task wich will make your code resiliant to spam. gather lets you fire off a bunch of coroutines simultaneously, and the current context will resume once all of the coroutines have completed.

    here is how to fix it:

    import aiohttp
    import asyncio
    
    
    async def get_response(query):
        async with aiohttp.ClientSession() as ses:
            async with ses.get(
                f'https://some-random-api.ml/chatbot?message={query}'
            ) as resp:
                return (await resp.json()),['response']
        
    #using an event loop
    loop = asyncio.get_event_loop()
    Task = asyncio.gather(*[get_response('world') for _ in range(500)])
    
    try:
        loop.run_until_complete(Task)
    finally:
        loop.close()