import discord
from discord.ext import commands
import asyncio

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