Fix: Datastore_Bot_Discord for Oracle Cloud vps.

This commit is contained in:
2024-12-09 20:24:07 +00:00
parent 9746421550
commit f79cd98887

View File

@@ -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()
try:
await self.client.close()
if 'task' in locals():
task.cancel()
except Exception as e:
print(f"Error during cleanup: {e}")