You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何通过Slash Commands修改Slack Bot名称/头像?API设置用户名无效

Why isn't the username parameter working in my Slack Slash Command response?

Great question—you’re right to notice this key difference! When using Slack Slash Commands, the username parameter in your direct JSON response is actually ignored, which sets it apart from sending messages via the standard Bot API. Let me break down why this happens and how to fix it.

The Root Cause

Slash Command responses have a constrained identity model. When you return a JSON payload directly from your Slash Command endpoint, Slack sends that message as your app’s default identity (the name you set in your app’s settings) or, in some cases, as the user who ran the command. The username field in this direct response doesn’t override that—Slack only respects this parameter when messages are sent via the chat.postMessage API using a valid Bot OAuth token.

How to Set a Custom Username for Slash Command Responses

To get the username parameter working, you need to switch from returning a direct response to calling Slack’s chat.postMessage API instead. Here’s how to adjust your code:

  1. Get a Bot OAuth Token

    • Go to your Slack app’s settings → OAuth & Permissions
    • Add the chat:write scope under Bot Token Scopes
    • Reinstall the app to your workspace to generate a Bot User OAuth Token (looks like xoxb-...)
  2. Modify Your Code to Call the API
    Replace your current direct response with an API call using the token. Here’s an updated version of your code using requests:

from bottle import run, post, request
import requests

@post('/hello')
def hello():
    # Extract the channel ID from the Slash Command request
    channel_id = request.forms.get('channel_id')
    # Replace with your actual Bot OAuth Token
    bot_token = "xoxb-your-bot-token-here"
    
    # Build the payload for chat.postMessage
    message_payload = {
        "channel": channel_id,
        "username": "test",
        "text": "Greetings!",
        "response_type": "in_channel"
    }
    
    # Send the message via Slack API
    requests.post(
        "https://slack.com/api/chat.postMessage",
        json=message_payload,
        headers={"Authorization": f"Bearer {bot_token}"}
    )
    
    # Return an empty response to Slack to avoid duplicate messages
    return {}

Key Notes

  • Make sure your Bot Token has the chat:write permission—without it, the API call will fail.
  • You can also add icon_url or icon_emoji to the payload to customize the avatar, just like with regular Bot messages.
  • When you return an empty response, Slack won’t send an extra message from the Slash Command itself—all communication happens via the API call.

内容的提问来源于stack exchange,提问作者user230250

火山引擎 最新活动