1

I'm trying to implement a discord bot connection to a web app running on Quart. I tried using one of the solutions posted here, which works for a while, but after about 24 hours the app breaks returning asyncio.exceptions.TimeoutError

     data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
   File "/path/to/my/venv/lib/python3.9/site-packages/discord/http.py", line 185, in request
     async with self.__session.request(method, url, **kwargs) as r:
   File "/path/to/my/venv/lib/python3.9/site-packages/aiohttp/client.py", line 1117, in __aenter__
     self._resp = await self._coro
   File "/path/to/my/venv/lib/python3.9/site-packages/aiohttp/client.py", line 619, in _request
     break
   File "/path/to/my/venv/lib/python3.9/site-packages/aiohttp/helpers.py", line 656, in __exit__
     raise asyncio.TimeoutError from None
 asyncio.exceptions.TimeoutError

relevant code:

import discord
import asyncio
from quart import Quart, request, Response

app = Quart(__name__)
client = discord.Client()

@app.before_serving
async def before_serving():
    loop = asyncio.get_event_loop()
    await client.login(os.getenv('TOKEN'))
    loop.create_task(client.connect())

@app.route('/webhook', methods=['POST'])
async def webhook():
    ...
    await channel.send(content, embed=embed)
    ...

How could I keep the client loop alive for more than one day? Is there a way to prevent the client session from disconnecting or should I reconnect it periodically?

TheV
  • 63
  • 7

1 Answers1

0

I cought the asyncio.TimeoutError and managed to restart the session:

async def discord_post(channel, message, embed):
    try:
        await channel.send(message, embed=embed)
    except asyncio.TimeoutError:
        await connect_client()
        await channel.send(message, embed=embed)
    
@app.before_serving
async def connect_client():
    loop = asyncio.get_event_loop()
    await client.login(os.getenv('DISCORD_TOKEN'))
    loop.create_task(client.connect())

@app.route('/webhook', methods=['POST'])
async def webhook():
    ...
    await discord_post(channel, text, embed)
    ...

but processing the restart takes close to 300 seconds after which all requests get processed at once and nginx keeps returning a 499 even though the code exectues correctly now, but I guess it's another issue entirely

TheV
  • 63
  • 7