Skip to content

DiscordSendTool

autogen.tools.experimental.DiscordSendTool #

DiscordSendTool(*, bot_token, channel_name, guild_name)

Bases: Tool

Sends a message to a Discord channel.

Initialize the DiscordSendTool.

PARAMETER DESCRIPTION
bot_token

The bot token to use for sending messages.

TYPE: str

channel_name

The name of the channel to send messages to.

TYPE: str

guild_name

The name of the guild for the channel.

TYPE: str

Source code in autogen/tools/experimental/messageplatform/discord/discord.py
def __init__(self, *, bot_token: str, channel_name: str, guild_name: str) -> None:
    """
    Initialize the DiscordSendTool.

    Args:
        bot_token: The bot token to use for sending messages.
        channel_name: The name of the channel to send messages to.
        guild_name: The name of the guild for the channel.
    """

    # Function that sends the message, uses dependency injection for bot token / channel / guild
    async def discord_send_message(
        message: Annotated[str, "Message to send to the channel."],
        bot_token: Annotated[str, Depends(on(bot_token))],
        guild_name: Annotated[str, Depends(on(guild_name))],
        channel_name: Annotated[str, Depends(on(channel_name))],
    ) -> Any:
        """
        Sends a message to a Discord channel.

        Args:
            message: The message to send to the channel.
            bot_token: The bot token to use for Discord. (uses dependency injection)
            guild_name: The name of the server. (uses dependency injection)
            channel_name: The name of the channel. (uses dependency injection)
        """
        intents = Intents.default()
        intents.message_content = True
        intents.guilds = True
        intents.guild_messages = True

        client = Client(intents=intents)
        result_future: asyncio.Future[str] = asyncio.Future()  # Stores the result of the send

        # When the client is ready, we'll send the message
        @client.event  # type: ignore[misc]
        async def on_ready() -> None:
            try:
                # Server
                guild = utils.get(client.guilds, name=guild_name)
                if guild:
                    # Channel
                    channel = utils.get(guild.text_channels, name=channel_name)
                    if channel:
                        # Send the message
                        if len(message) > MAX_MESSAGE_LENGTH:
                            chunks = [
                                message[i : i + (MAX_MESSAGE_LENGTH - 1)]
                                for i in range(0, len(message), (MAX_MESSAGE_LENGTH - 1))
                            ]
                            for i, chunk in enumerate(chunks):
                                sent = await channel.send(chunk)

                                # Store ID for the first chunk
                                if i == 0:
                                    sent_message_id = str(sent.id)

                            result_future.set_result(
                                f"Message sent successfully ({len(chunks)} chunks, first ID: {sent_message_id}):\n{message}"
                            )
                        else:
                            sent = await channel.send(message)
                            result_future.set_result(f"Message sent successfully (ID: {sent.id}):\n{message}")
                    else:
                        result_future.set_result(f"Message send failed, could not find channel: {channel_name}")
                else:
                    result_future.set_result(f"Message send failed, could not find guild: {guild_name}")

            except Exception as e:
                result_future.set_exception(e)
            finally:
                try:
                    await client.close()
                except Exception as e:
                    raise Exception(f"Unable to close Discord client: {e}")

        # Start the client and when it's ready it'll send the message in on_ready
        try:
            await client.start(bot_token)

            # Capture the result of the send
            return await result_future
        except Exception as e:
            raise Exception(f"Failed to start Discord client: {e}")

    super().__init__(
        name="discord_send",
        description="Sends a message to a Discord channel.",
        func_or_tool=discord_send_message,
    )

name property #

name

description property #

description

func property #

func

tool_schema property #

tool_schema

Get the schema for the tool.

This is the preferred way of handling function calls with OpeaAI and compatible frameworks.

function_schema property #

function_schema

Get the schema for the function.

This is the old way of handling function calls with OpenAI and compatible frameworks. It is provided for backward compatibility.

realtime_tool_schema property #

realtime_tool_schema

Get the schema for the tool.

This is the preferred way of handling function calls with OpeaAI and compatible frameworks.

register_for_llm #

register_for_llm(agent)

Registers the tool for use with a ConversableAgent's language model (LLM).

This method registers the tool so that it can be invoked by the agent during interactions with the language model.

PARAMETER DESCRIPTION
agent

The agent to which the tool will be registered.

TYPE: ConversableAgent

Source code in autogen/tools/tool.py
def register_for_llm(self, agent: "ConversableAgent") -> None:
    """Registers the tool for use with a ConversableAgent's language model (LLM).

    This method registers the tool so that it can be invoked by the agent during
    interactions with the language model.

    Args:
        agent (ConversableAgent): The agent to which the tool will be registered.
    """
    agent.register_for_llm()(self)

register_for_execution #

register_for_execution(agent)

Registers the tool for direct execution by a ConversableAgent.

This method registers the tool so that it can be executed by the agent, typically outside of the context of an LLM interaction.

PARAMETER DESCRIPTION
agent

The agent to which the tool will be registered.

TYPE: ConversableAgent

Source code in autogen/tools/tool.py
def register_for_execution(self, agent: "ConversableAgent") -> None:
    """Registers the tool for direct execution by a ConversableAgent.

    This method registers the tool so that it can be executed by the agent,
    typically outside of the context of an LLM interaction.

    Args:
        agent (ConversableAgent): The agent to which the tool will be registered.
    """
    agent.register_for_execution()(self)

register_tool #

register_tool(agent)

Register a tool to be both proposed and executed by an agent.

Equivalent to calling both register_for_llm and register_for_execution with the same agent.

Note: This will not make the agent recommend and execute the call in the one step. If the agent recommends the tool, it will need to be the next agent to speak in order to execute the tool.

PARAMETER DESCRIPTION
agent

The agent to which the tool will be registered.

TYPE: ConversableAgent

Source code in autogen/tools/tool.py
def register_tool(self, agent: "ConversableAgent") -> None:
    """Register a tool to be both proposed and executed by an agent.

    Equivalent to calling both `register_for_llm` and `register_for_execution` with the same agent.

    Note: This will not make the agent recommend and execute the call in the one step. If the agent
    recommends the tool, it will need to be the next agent to speak in order to execute the tool.

    Args:
        agent (ConversableAgent): The agent to which the tool will be registered.
    """
    self.register_for_llm(agent)
    self.register_for_execution(agent)