|
| 1 | +"""Discord Connector for Flare AI Kit.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +from typing import Any |
| 5 | + |
| 6 | +from discord import Client, Intents, Message, TextChannel |
| 7 | + |
| 8 | +from flare_ai_kit.config import AppSettings |
| 9 | +from flare_ai_kit.social.connector import SocialConnector |
| 10 | + |
| 11 | + |
| 12 | +class DiscordConnector(SocialConnector): |
| 13 | + """Discord connector implementation.""" |
| 14 | + |
| 15 | + def __init__(self) -> None: |
| 16 | + """Initialize the DiscordConnector with API token and channel ID.""" |
| 17 | + settings = AppSettings().social |
| 18 | + self.token: str = ( |
| 19 | + settings.discord_bot_token.get_secret_value() |
| 20 | + if settings.discord_bot_token |
| 21 | + else "" |
| 22 | + ) |
| 23 | + self.channel_id: int = int( |
| 24 | + settings.discord_channel_id.get_secret_value() |
| 25 | + if settings.discord_channel_id |
| 26 | + else 0 |
| 27 | + ) |
| 28 | + self.client: Client = Client(intents=Intents.default()) |
| 29 | + self._ready_event: asyncio.Event = asyncio.Event() |
| 30 | + self._messages: list[dict[str, Any]] = [] |
| 31 | + |
| 32 | + # Explicitly register event handlers |
| 33 | + self.client.event(self._on_ready) |
| 34 | + self.client.event(self._on_message) |
| 35 | + |
| 36 | + async def _on_ready(self) -> None: |
| 37 | + """Handle bot ready event.""" |
| 38 | + self._ready_event.set() |
| 39 | + |
| 40 | + async def _on_message(self, message: Message) -> None: |
| 41 | + """Handle new messages.""" |
| 42 | + if message.author == self.client.user: |
| 43 | + return |
| 44 | + |
| 45 | + self._messages.append( |
| 46 | + { |
| 47 | + "platform": "discord", |
| 48 | + "content": message.content, |
| 49 | + "author_id": str(message.author.id), |
| 50 | + "timestamp": str(message.created_at), |
| 51 | + } |
| 52 | + ) |
| 53 | + |
| 54 | + @property |
| 55 | + def platform(self) -> str: |
| 56 | + """Return the platform name.""" |
| 57 | + return "discord" |
| 58 | + |
| 59 | + async def _start_if_needed(self) -> None: |
| 60 | + if not self.client.is_ready(): |
| 61 | + self._client_task = asyncio.create_task(self.client.start(self.token)) |
| 62 | + await self._ready_event.wait() |
| 63 | + |
| 64 | + async def fetch_mentions( |
| 65 | + self, query: str = "", limit: int = 10 |
| 66 | + ) -> list[dict[str, Any]]: |
| 67 | + """Fetch messages that mention the query.""" |
| 68 | + await self._start_if_needed() |
| 69 | + await asyncio.sleep(1) # let messages collect |
| 70 | + |
| 71 | + results: list[dict[str, Any]] = [] |
| 72 | + for msg in self._messages: |
| 73 | + if query.lower() in msg["content"].lower(): |
| 74 | + results.append(msg) |
| 75 | + if len(results) >= limit: |
| 76 | + break |
| 77 | + return results |
| 78 | + |
| 79 | + async def post_message(self, content: str) -> dict[str, Any]: |
| 80 | + """Post a message to the Discord channel.""" |
| 81 | + await self._start_if_needed() |
| 82 | + channel = self.client.get_channel(self.channel_id) |
| 83 | + if isinstance(channel, TextChannel): |
| 84 | + message = await channel.send(content) |
| 85 | + return { |
| 86 | + "platform": "discord", |
| 87 | + "message_id": message.id, |
| 88 | + "content": message.content, |
| 89 | + } |
| 90 | + return { |
| 91 | + "platform": "discord", |
| 92 | + "message_id": None, |
| 93 | + "error": "Channel not found or not a text channel.", |
| 94 | + } |
0 commit comments