Skip to content

Conversation

Copilot
Copy link
Contributor

@Copilot Copilot AI commented Oct 2, 2025

Problem

The SendDiscordMessageBlock only accepted channel names, while other Discord blocks like SendDiscordFileBlock and SendDiscordEmbedBlock accept both channel IDs and channel names. This inconsistency made it difficult to use channel IDs with the message sending block, which is often more reliable and direct than name-based lookup.

Solution

Updated SendDiscordMessageBlock to accept both channel IDs and channel names through the channel_name field, matching the implementation pattern used in other Discord blocks.

Changes Made

  1. Enhanced channel resolution logic to try parsing the input as a channel ID first, then fall back to name-based search:

    # Try to parse as channel ID first
    try:
        channel_id = int(channel_name)
        channel = client.get_channel(channel_id)
    except ValueError:
        # Not an ID, treat as channel name
        # ... search guilds for matching channel name
  2. Updated field descriptions to clarify the dual functionality:

    • channel_name: Now describes that it accepts "Channel ID or channel name"
    • server_name: Clarified as "only needed if using channel name"
  3. Added type checking to ensure the resolved channel can send messages before attempting to send

  4. Updated documentation to reflect the new capability

Backward Compatibility

Fully backward compatible: The field name remains channel_name (not renamed), and all existing workflows using channel names will continue to work exactly as before.

New capability: Users can now also provide channel IDs (e.g., "123456789012345678") for more direct channel targeting.

Testing

  • All existing tests pass, including SendDiscordMessageBlock and all other Discord block tests
  • Implementation verified to match the pattern used in SendDiscordFileBlock and SendDiscordEmbedBlock
  • Code passes all linting, formatting, and type checking

Fixes #10909

Original prompt

Issue Title: SendDiscordMessage needs to take a channel id as an option under channelname the same as the other discord blocks
Issue Description: with how we can process the other discord blocks we should do the same here with the identifiers being allowed to be a channel name or id. we can't rename the field though or that will break backwards compatibility
Fixes https://linear.app/autogpt/issue/OPEN-2701/senddiscordmessage-needs-to-take-a-channel-id-as-an-option-under

Comment by User :
This thread is for an agent session with githubcopilotcodingagent.

Comment by User :
This thread is for an agent session with githubcopilotcodingagent.

Comment by User 055a3053-5ab6-449a-bcfa-990768594185:
the ones with boxes around them need confirmed for lables but yeah its related but not dupe

Comment by User 264d7bf4-db2a-46fa-a880-7d67b58679e6:
this might be a duplicate since there is a related ticket but not sure

Comment by User :
This comment thread is synced to a corresponding GitHub issue. All replies are displayed in both locations.


💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.

Summary by CodeRabbit

  • New Features

    • Send Discord Message block now accepts a channel ID in addition to channel name.
    • Server name is only required when using a channel name.
    • Improved channel detection and validation with clearer errors if the channel isn’t found.
  • Documentation

    • Updated block documentation to reflect support for channel ID or name and clarify when server name is needed.

Copy link

coderabbitai bot commented Oct 2, 2025

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

Updated Discord Send message block to accept either channel ID or channel name, with optional server_name only needed for name-based lookup. Implemented hybrid lookup in on_ready: try ID via get_channel, otherwise search guilds (optionally filtered by server_name), validate channel is sendable, chunk and send message, or set status to "Channel not found." Updated docs accordingly.

Changes

Cohort / File(s) Summary
Discord block logic and inputs
autogpt_platform/backend/backend/blocks/discord/bot_blocks.py
Input descriptions updated: channel_name now accepts ID or name; server_name clarified as optional for name lookups. on_ready control flow changed to attempt channel ID first via get_channel; fallback to guild search by name (optionally filtered by server_name); validate channel type; chunk and send; explicit "Channel not found" handling.
Docs update
docs/content/platform/blocks/discord.md
Documentation adjusted to state Channel Name field accepts a channel ID or name for Send Discord Message block.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant Block as SendDiscordMessageBlock
  participant Discord as Discord Client/API

  User->>Block: Provide token, channel_name (ID or name), server_name (optional), message
  Block->>Discord: Login and on_ready
  rect rgb(235, 245, 255)
    note over Block: Resolve channel
    Block->>Block: Is channel_name numeric?
    alt ID-based lookup
      Block->>Discord: get_channel(channel_id)
      Discord-->>Block: Channel or null
    else Name-based lookup
      Block->>Discord: List guilds (filter by server_name if provided)
      Block->>Discord: Find text channel by name
      Discord-->>Block: Channel or null
    end
  end

  alt Channel found and sendable
    loop Chunk message
      Block->>Discord: channel.send(chunk)
      Discord-->>Block: ack
    end
    Block-->>User: Status: sent
  else Channel not found or not text
    Block-->>User: Status: Channel not found
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

I twitch my whiskers at IDs and names,
Hop through guilds in lookup games.
If numbers shine, I bound straight through—
If names, I sniff for matching hue.
Found a text perch? I drop the note.
Else, ears droop softly—no channel to quote. 🐇📨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run `@coderabbitai generate docstrings` to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit's high-level summary is enabled.
Title Check ✅ Passed The title concisely and accurately summarizes the main change by indicating that channel ID support has been added to the SendDiscordMessageBlock and follows the conventional commit format.
Linked Issues Check ✅ Passed The PR implements numeric channel ID parsing with fallback to name lookup, updates field descriptions accordingly, retains the existing channel_name field for backward compatibility, and updates documentation, fully addressing issues #10909 and OPEN-2701.
Out of Scope Changes Check ✅ Passed All code and documentation changes focus exclusively on extending SendDiscordMessageBlock to support channel IDs and do not include any unrelated functionality or modifications outside the scope of the linked issues.

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

netlify bot commented Oct 2, 2025

Deploy Preview for auto-gpt-docs canceled.

Name Link
🔨 Latest commit 714365c
🔍 Latest deploy log https://app.netlify.com/projects/auto-gpt-docs/deploys/68dfe909352e3f0008b566b0

Copy link

deepsource-io bot commented Oct 2, 2025

Here's the code health analysis summary for commits 0fc6a44..714365c. View details on DeepSource ↗.

Analysis Summary

AnalyzerStatusSummaryLink
DeepSource JavaScript LogoJavaScript✅ SuccessView Check ↗
DeepSource Python LogoPython✅ SuccessView Check ↗

💡 If you’re a repository administrator, you can configure the quality gates from the settings.

@AutoGPT-Agent
Copy link

This PR is marked as Work in Progress and doesn't contain any code changes yet. Please update the PR once you have implemented the requested changes - allowing SendDiscordMessage to accept a channel ID under the channelname parameter similar to other Discord blocks. When submitting your changes, please ensure you:

  • Update the PR title to follow the conventional commit format (e.g., 'fix(blocks): Allow SendDiscordMessage to accept channel ID')
  • Complete the PR description template with relevant information
  • Fill out the checklist in the PR description
  • Include proper tests for your changes

Looking forward to reviewing your implementation once it's ready!

@AutoGPT-Agent
Copy link

Thank you for creating this PR to address the SendDiscordMessageBlock enhancement. I can see this is marked as Work In Progress (WIP), and there are no code changes submitted yet. Here's some feedback to help you prepare for when you're ready to submit the actual changes:

  1. Please update the PR title to follow our conventional commit format, such as fix: platform/blocks support channel IDs in SendDiscordMessageBlock

  2. Your checklist of tasks is clear and helpful. Once you've completed the implementation, please check off these items.

  3. When you're ready for review, please complete the standard PR template checklist (test plan, etc.) in addition to your current task list.

  4. Don't forget to remove the [WIP] prefix from the title when the PR is ready for review.

This looks like a straightforward enhancement that will improve consistency across our Discord blocks. Looking forward to reviewing the implementation when it's ready!

@AutoGPT-Agent
Copy link

Thanks for making these changes to improve the SendDiscordMessageBlock! The implementation looks good and follows the pattern from the other Discord blocks.

Before this can be merged, please update the PR title to follow our conventional commit format. The title should use one of these types: feat, fix, refactor, ci, dx - followed by an appropriate scope.

For example, a good title might be:
fix(blocks): Allow SendDiscordMessageBlock to accept channel IDs

Also, I notice the PR is marked as [WIP] (Work in Progress). Once you're ready for review and merge, please remove that prefix from the title.

The code changes themselves look great and match the requirements described in the linked issue.

@AutoGPT-Agent
Copy link

Thank you for submitting this PR that enhances the SendDiscordMessageBlock to accept both channel IDs and channel names. The implementation looks solid and follows the pattern from other Discord blocks.

Before we can merge this PR:

  1. The PR title needs to be updated to follow our conventional commit format. Since this is enhancing existing functionality, it should be something like feat(blocks): allow channel IDs in SendDiscordMessageBlock

  2. The "[WIP]" tag suggests this is still a work in progress. Once you've completed the work, please remove this tag from the title.

Otherwise, your implementation looks good - you've maintained backward compatibility while adding the ability to use channel IDs, added appropriate error handling, and updated both the code and documentation. Nice work!

@AutoGPT-Agent
Copy link

Thank you for this PR enhancing the SendDiscordMessageBlock functionality!

Your implementation looks good - I can see you've followed the pattern from other Discord blocks to make the channel_name field accept both IDs and channel names. The code changes look appropriate with proper error handling and type checking.

Before this can be merged, please update the PR title to follow our conventional commit format. Since this is enhancing an existing feature, a title like:

feat: platform/blocks - allow SendDiscordMessageBlock to accept channel IDs

would be appropriate.

Also, you might want to remove the [WIP] tag when you're ready for final review. Everything else looks good to go!

@Copilot Copilot AI changed the title [WIP] Copilot Request fix(backend): Add channel ID support to SendDiscordMessageBlock for consistency with other Discord blocks Oct 2, 2025
@Copilot Copilot AI requested a review from ntindle October 2, 2025 21:07
Copilot finished work on behalf of ntindle October 2, 2025 21:07
@github-actions github-actions bot added documentation Improvements or additions to documentation platform/blocks size/m labels Oct 2, 2025
@ntindle ntindle changed the base branch from master to dev October 2, 2025 21:20
@ntindle
Copy link
Member

ntindle commented Oct 2, 2025

@coderabbitai review

Copy link

coderabbitai bot commented Oct 2, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@ntindle
Copy link
Member

ntindle commented Oct 2, 2025

@claude review this follows our block best practices

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 0fc6a44 and 0298bc4.

📒 Files selected for processing (2)
  • autogpt_platform/backend/backend/blocks/discord/bot_blocks.py (2 hunks)
  • docs/content/platform/blocks/discord.md (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: test (3.11)
  • GitHub Check: Check PR Status
  • GitHub Check: Check PR Status
🔇 Additional comments (1)
docs/content/platform/blocks/discord.md (1)

46-46: Docs change looks good.

Updated wording accurately reflects the new flexibility in the backend.

Comment on lines 233 to 250
print(f"Logged in as {client.user}")
for guild in client.guilds:
if server_name and guild.name != server_name:
continue
for channel in guild.text_channels:
if channel.name == channel_name:
# Split message into chunks if it exceeds 2000 characters
chunks = self.chunk_message(message_content)
last_message = None
for chunk in chunks:
last_message = await channel.send(chunk)
result["status"] = "Message sent"
result["message_id"] = (
str(last_message.id) if last_message else ""
)
result["channel_id"] = str(channel.id)
await client.close()
return

result["status"] = "Channel not found"
channel = None

# Try to parse as channel ID first
try:
channel_id = int(channel_name)
channel = client.get_channel(channel_id)
except ValueError:
# Not an ID, treat as channel name
for guild in client.guilds:
if server_name and guild.name != server_name:
continue
for ch in guild.text_channels:
if ch.name == channel_name:
channel = ch
break
if channel:
break
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Fallback to name lookup when ID cache miss occurs.

If channel_name is something numeric like "12345", int(channel_name) succeeds but client.get_channel() returns None, so we never drop into the name-based search. Those channels worked before and now always hit “Channel not found,” which is a regression. Make the name-search fallback run whenever the ID lookup fails to resolve a channel, not only when int() raises.

             channel = None

             # Try to parse as channel ID first
-            try:
-                channel_id = int(channel_name)
-                channel = client.get_channel(channel_id)
-            except ValueError:
-                # Not an ID, treat as channel name
-                for guild in client.guilds:
-                    if server_name and guild.name != server_name:
-                        continue
-                    for ch in guild.text_channels:
-                        if ch.name == channel_name:
-                            channel = ch
-                            break
-                    if channel:
-                        break
+            try:
+                channel_id = int(channel_name)
+                channel = client.get_channel(channel_id)
+            except ValueError:
+                channel = None
+
+            if not channel:
+                # Treat as channel name
+                for guild in client.guilds:
+                    if server_name and guild.name != server_name:
+                        continue
+                    for ch in guild.text_channels:
+                        if ch.name == channel_name:
+                            channel = ch
+                            break
+                    if channel:
+                        break
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
print(f"Logged in as {client.user}")
for guild in client.guilds:
if server_name and guild.name != server_name:
continue
for channel in guild.text_channels:
if channel.name == channel_name:
# Split message into chunks if it exceeds 2000 characters
chunks = self.chunk_message(message_content)
last_message = None
for chunk in chunks:
last_message = await channel.send(chunk)
result["status"] = "Message sent"
result["message_id"] = (
str(last_message.id) if last_message else ""
)
result["channel_id"] = str(channel.id)
await client.close()
return
result["status"] = "Channel not found"
channel = None
# Try to parse as channel ID first
try:
channel_id = int(channel_name)
channel = client.get_channel(channel_id)
except ValueError:
# Not an ID, treat as channel name
for guild in client.guilds:
if server_name and guild.name != server_name:
continue
for ch in guild.text_channels:
if ch.name == channel_name:
channel = ch
break
if channel:
break
print(f"Logged in as {client.user}")
channel = None
# Try to parse as channel ID first
try:
channel_id = int(channel_name)
channel = client.get_channel(channel_id)
except ValueError:
channel = None
if not channel:
# Treat as channel name
for guild in client.guilds:
if server_name and guild.name != server_name:
continue
for ch in guild.text_channels:
if ch.name == channel_name:
channel = ch
break
if channel:
break
🤖 Prompt for AI Agents
In autogpt_platform/backend/backend/blocks/discord/bot_blocks.py around lines
233–250, the code currently only performs the name-based guild/channel search
when int(channel_name) raises; change the logic so that after attempting to
parse channel_name as an int and calling client.get_channel(channel_id), if that
returns None you still fall back to the name-based search (and likewise if
parsing raises ValueError). Implement a single fallback path that runs the
existing guild/text_channel name loop whenever the ID lookup yields None or
parsing fails.

Copy link
Contributor

claude bot commented Oct 2, 2025

Claude finished @ntindle's task —— View job


Code Review: SendDiscordMessageBlock Channel ID Support

I've reviewed the PR against your block best practices. Here's my analysis:

Strengths

  1. Pattern Consistency: The implementation correctly follows the same pattern used in other Discord blocks (SendDiscordFileBlock and SendDiscordEmbedBlock) for channel resolution (lines 484-498 and 659-673 in those blocks).

  2. Backward Compatibility: Field name channel_name is preserved, ensuring existing workflows won't break.

  3. Documentation Updates: The docs correctly reflect the dual functionality.

  4. Error Handling: Includes type checking to ensure the resolved channel can send messages (line 258).

⚠️ Critical Issue Found

Channel ID Fallback Logic Bug

The current implementation has a bug that breaks backward compatibility. When a numeric string like "12345" is provided:

  • int(channel_name) succeeds
  • client.get_channel() returns None (channel not in cache)
  • The code never falls back to name-based search
  • Results in "Channel not found" error for previously working channel names

Location: autogpt_platform/backend/backend/blocks/discord/bot_blocks.py:236-250

Impact: This breaks existing workflows where channel names happen to be numeric strings.

📋 Recommendations

1. Fix the Fallback Logic (REQUIRED)

# Try to parse as channel ID first
channel = None
try:
    channel_id = int(channel_name)
    channel = client.get_channel(channel_id)
except ValueError:
    pass  # Not a valid ID, will try name lookup

# If not found by ID (or not an ID), try name lookup
if not channel:
    for guild in client.guilds:
        if server_name and guild.name != server_name:
            continue
        for ch in guild.text_channels:
            if ch.name == channel_name:
                channel = ch
                break
        if channel:
            break

2. Consider Field Description Enhancement

The current description "Channel ID or channel name to send the message to" is good, but could be clearer:

channel_name: str = SchemaField(
    description="Channel ID (e.g., '123456789012345678') or channel name to send the message to"
)

3. Testing Recommendation

Add test cases for:

  • Numeric channel names that aren't valid IDs
  • Valid channel IDs that aren't in the bot's cache
  • Ensure the fallback mechanism works properly

🔍 Block Best Practices Compliance

Follows AsyncIO pattern - Uses async/await correctly
Schema definitions - Input/Output schemas properly defined
Error handling - Appropriate ValueError exceptions
Consistent field patterns - Matches other Discord blocks
Test structure - Has test_input, test_output, test_mock
⚠️ Channel resolution - Needs the fallback fix mentioned above

📝 Summary

This PR implements a valuable enhancement that improves consistency across Discord blocks. The main implementation is solid, but the channel resolution logic needs to be fixed to ensure backward compatibility isn't broken for numeric channel names. Once that critical issue is addressed, this will be a great addition to the platform.

CodeRabbit also identified this same issue in their review, so addressing it is essential before merging.

@ntindle ntindle requested a review from Bentlybro October 3, 2025 15:09
@ntindle
Copy link
Member

ntindle commented Oct 3, 2025

@claude fix that issue you found

Copy link
Contributor

claude bot commented Oct 3, 2025

Claude finished @ntindle's task —— View job


✅ Fixed the channel ID fallback logic

Completed Tasks

  • Read the current implementation to understand the code structure
  • Fix the fallback logic in SendDiscordMessageBlock
  • Commit and push the changes

Summary

The issue has been fixed! The channel resolution logic now properly falls back to name-based search when:

  • The channel_name cannot be parsed as an integer (ValueError)
  • The channel_name is a valid integer but get_channel() returns None (channel not in cache)

This ensures backward compatibility for numeric channel names like "12345" that previously worked as channel names. They will now correctly fall back to name-based search if not found as an ID.

The fix is simple but critical: the name-based search now runs whenever channel is None after the ID lookup attempt, not only when the integer parsing fails.


View job |

When a numeric string was provided as channel_name, the code would try to parse
it as an ID, but if get_channel() returned None (channel not in cache), it would
never fall back to name-based search. This broke backward compatibility for
channel names that happened to be numeric strings.

The fix ensures that name-based search runs whenever ID lookup yields None,
not only when int() raises ValueError.

Co-authored-by: Nicholas Tindle <[email protected]>
Copy link

netlify bot commented Oct 3, 2025

Deploy Preview for auto-gpt-docs-dev ready!

Name Link
🔨 Latest commit 714365c
🔍 Latest deploy log https://app.netlify.com/projects/auto-gpt-docs-dev/deploys/68dfe90987e4f70008014c6c
😎 Deploy Preview https://deploy-preview-11055--auto-gpt-docs-dev.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation platform/blocks size/m
Projects
Status: 🆕 Needs initial review
Development

Successfully merging this pull request may close these issues.

SendDiscordMessage needs to take a channel id as an option under channelname the same as the other discord blocks
3 participants