From f79cd98887e71bcc406277e030b36c5a700fdf2d Mon Sep 17 00:00:00 2001 From: Teddy-1024 Date: Mon, 9 Dec 2024 20:24:07 +0000 Subject: [PATCH] Fix: Datastore_Bot_Discord for Oracle Cloud vps. --- datastores/datastore_bot_discord.py | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/datastores/datastore_bot_discord.py b/datastores/datastore_bot_discord.py index e114a3d..d244a1f 100644 --- a/datastores/datastore_bot_discord.py +++ b/datastores/datastore_bot_discord.py @@ -1,4 +1,3 @@ - import discord from discord.ext import commands import asyncio @@ -7,21 +6,38 @@ class DataStore_Bot_Discord: def __init__(self, token): self.token = token self.client = discord.Client(intents=discord.Intents.default()) + self.is_ready = False @self.client.event async def on_ready(): self.is_ready = True - + async def post_message_to_channel(self, message, channel_id): try: - task = asyncio.create_task(self.client.start(self.token)) - await asyncio.sleep(2) + # Use ensure_future instead of create_task for Python 3.6 + task = asyncio.ensure_future(self.client.start(self.token)) + + # Wait for the client to be ready + start_time = asyncio.get_event_loop().time() + while not self.is_ready: + await asyncio.sleep(0.1) + if asyncio.get_event_loop().time() - start_time > 30: # 30 second timeout + raise TimeoutError("Client failed to connect within timeout") + channel = self.client.get_channel(channel_id) if not channel: raise ValueError(f"Could not find channel with ID: {channel_id}") + await channel.send(message) + except Exception as e: print(f"Error sending message: {e}") + raise # Re-raise the exception to handle it in the calling code + finally: - await self.client.close() - task.cancel() \ No newline at end of file + try: + await self.client.close() + if 'task' in locals(): + task.cancel() + except Exception as e: + print(f"Error during cleanup: {e}")