Sends a message to a channel.
POSThttps://slack-gov.com/api/chat.postMessage
application/x-www-form-urlencoded
application/json
token
Authentication token bearing required scopes. Tokens should be passed as an HTTP Authorization header or alternatively, as a POST parameter.
xxxx-xxxxxxxxx-xxxx
An encoded ID that represents a channel, private group, or IM channel to send the message to. See below for more details.
C1234567890
blocks
text
One of these arguments in addition to text
is required to describe the content of the message. When attachments
or blocks
are included, text
will be used as fallback text for notifications only.
A JSON-based array of structured attachments, presented as a URL-encoded string.
[{"pretext": "pre-hello", "text": "text-world"}]
blocks
A JSON-based array of structured blocks, presented as a URL-encoded string.
[{"type": "section", "text": {"type": "plain_text", "text": "Hello world"}}]
How this field works and whether it is required depends on other fields you use in your API call. See below for more detail.
Hello world
(Legacy) Pass true to post the message as the authed user instead of as a bot. Defaults to false. Can only be used by classic apps. See legacy as_user
parameter below.
true
Emoji to use as the icon for this message. Overrides icon_url
.
:chart_with_upwards_trend:
URL to an image to use as the icon for this message.
http://lorempixel.com/48/48
Find and link user groups. No longer supports linking individual users; use syntax shown in Mentioning Users instead.
true
JSON object with event_type and event_payload fields, presented as a URL-encoded string. Metadata you post to Slack is accessible to any app or user who is a member of that workspace.
{"event_type": "task_created", "event_payload": { "id": "11223", "title": "Redesign Homepage"}}
Disable Slack markup parsing by setting to false
. Enabled by default.
true
false
Change how messages are treated. See below.
full
Used in conjunction with thread_ts
and indicates whether reply should be made visible to everyone in the channel or conversation. Defaults to false
.
true
Provide another message's ts
value to make this message a reply. Avoid using a reply's ts
value; use its parent instead.
Pass true to enable unfurling of primarily text-based content.
true
This method posts a message to a public channel, private channel, or direct message (DM, or IM) conversation.
Consider reviewing our message guidelines, especially if you're using attachments or message buttons.
text
, blocks
and attachments
fields The usage of the text
field changes depending on whether you're using blocks
. If you're using blocks
, this is used as a fallback string to display in notifications. If you aren't, this is the main body text of the message. It can be formatted as plain text, or with mrkdwn
.
The text
field is not enforced as required when using blocks
or attachments
. However, we highly recommended that you include text
to provide a fallback when using blocks
, as described above.
It is expected behavior that screen readers will default to the top-level text
field of your post, and will not read the content of any interior blocks
in the underlying structure of the message. Therefore, to make an accessible app, you must either:
text
field of your message, ortext
field if the message has blocks
, and allow Slack attempt to build it for you by appending content from supported blocks
to be read by the screen reader.When POSTing with application/x-www-form-urlencoded
data, the optional attachments
argument should contain a JSON-encoded array of attachments.
As of October 2017, it's possible to send a well-formatted application/json
POST body to chat.postMessage
and other Web API write methods. No need to carefully URL-encode your JSON attachments
and present all other fields as URL encoded key:value pairs; just send JSON instead.
Messages are formatted as described in the formatting spec. The formatting behavior will change depending on the value of parse
.
By default, URLs will be hyperlinked. Set parse
to none
to remove the hyperlinks.
The behavior of parse
is different for text formatted with mrkdwn
. By default, or when parse
is set to none
, mrkdwn
formatting is implemented. To ignore mrkdwn
formatting, set parse
to full
.
By default links to media are unfurled, but links to text content are not. Links found in blocks
will also be unfurled by default.
If you want to suppress link unfurls in messages containing blocks, set unfurl_links
and unfurl_media
to false.
For best results, limit the number of characters in the text
field to 4,000 characters. Ideally, messages should be short and human-readable. Slack will truncate messages containing more than 40,000 characters. If you need to post longer messages, please consider uploading a snippet instead.
If using blocks
, the limit and truncation of characters will be determined by the specific type of block.
Provide a thread_ts
value for the posted message to act as a reply to a parent message. Sparingly, set reply_broadcast
to true
if your reply is important enough for everyone in the channel to receive.
See threading messages for a more in-depth look at message threading.
You must specify a public channel, private channel, or an IM channel with the channel
argument. Each one behaves slightly differently based on the authenticated user's permissions and additional arguments, as discussed in the sections below.
Pass the channel's ID (C123456
) to the channel
parameter and the message will be posted to that channel. The channel's ID can be retrieved through the conversations.list API method.
As long as the authenticated user is a member of the private channel, pass the channel's ID (C123456
) to the channel
parameter and the message will be posted to that channel. The private channel's ID can be retrieved through the conversations.list API method.
As long as the authenticated user is a member of the multi-person direct message (a "private group" or MPIM), you can pass the group's ID (G123456
) and the message will be posted to that group. The private group's ID can be retrieved through the conversations.list API method.
Posting to direct messages (also known as DMs or IMs) can be a little more complex, depending on what you actually want to accomplish.
If you want your app's bot user to start a 1:1 conversation with another user in a workspace, provide the user's ID as the channel
value and a direct message conversation will be opened if it isn't open already. Resultant messages and associated direct message objects will have a direct message ID you can use from that point forward, if you'd rather.
Bot users cannot post to a direct message conversation between two users using chat.postMessage
. If your app was involved in the conversation, then it would be a multi-person direct message instead. Apps can post to direct message conversations between users when a shortcut or slash command belonging to that app is used in the conversation.
You will receive a channel_not_found
error if your app doesn't have permission to enter into a DM with the intended user.
Passing a "username" as a channel
value is deprecated, along with the whole concept of usernames on Slack. Please always use channel-like IDs instead to make sure your message gets to where it's going.
A list of user IDs can be retrieved via the users.list
API method.
Start a conversation with users in your App Home.
With the chat:write
scope enabled, call chat.postMessage
and pass a user's ID (U123456
) as the value of channel
to post to that user's App Home channel. You can use their direct message channel ID (as found with coversations.open
, for instance) instead.
chat.postMessage
has special rate limiting conditions. It will generally allow an app to post 1 message per second to a specific channel. There are limits governing your app's relationship with the entire workspace above that, limiting posting to several hundred messages per minute. Generous burst behavior is also granted.
New Slack apps do not begin life with the ability to post in all public channels.
For your new Slack app to gain the ability to post in all public channels, request the chat:write.public
scope.
Apps can publish messages that appear to have been created by a user in the conversation. The message will be attributed to the user and show their profile photo beside it.
This is a powerful ability and must only be used when the user themselves gives permission to do so. For this reason, this ability is only available when an app has requested and been granted an additional scope — chat:write.customize
.
Your app should only use this feature in response to an inciting user action. It should never be unexpected or surprising to a user that a message was posted on their behalf, and it should be heavily signposted in advance.
To modify the appearance of the app, make calls to chat.postMessage
while providing any of the following parameters:
username
to specify the username for the published message.icon_url
to specify a URL to an image to use as the profile photo alongside the message.icon_emoji
to specify an emoji (using colon shortcodes, eg. :white_check_mark:
) to use as the profile photo alongside the message.If the channel
parameter is set to a User ID (beginning with U
), the message will appear in that user's direct message channel with Slackbot. To post a message to that user's direct message channel with the app, use the DM ID (beginning with D
) instead.
This feature works differently for classic apps, see below for more details.
Information in the section below applies only to classic apps.
Classic apps using the umbrella bot
scope can't request additional scopes to adjust message authorship.
as_user
parameter For classic apps, the best way to control the authorship of a message was to be explicit with the legacy as_user
parameter. If you didn't use the as_user
parameter, chat.postMessage
would guess the most appropriate as_user
interpretation based on the kind of token you were using. If as_user
was not provided at all, the value was inferred based on the scopes granted to the caller: If the caller could post with as_user
passed as false
, then that was how the method behaved; otherwise, the method behaved as if as_user
were passed as true
.
When the as_user
parameter was set to false
, messages were posted as "bot_messages
", with message authorship attributed to the user name and icons associated with the classic app.
Token types provide varying default identity values for username
, icon_url
, and icon_emoji
.
chat:write:user
inherits the icon and username of the token owner.If using icon_url
, icon_emoji
, or username
with chat.postMessage
and a direct message, some special rules apply to ensure the receiver is crystal clear about who is sending the message:
as_user
argument was false:
D123456
) as the value of channel
to post to that DM channel as the app, bot, or user associated with the token. You can change the icon and username that go with the message using the icon_url
and username
parameters. The IM channel's ID can be retrieved through the conversations.list API method.as_user
parameter was true:
D123456
) or a user's ID (U123456
) as the value of channel
to post to that DM channel as the app, bot, or user associated with the token. The IM channel's ID can be retrieved through the conversations.list API method. When as_user
is true, the caller may not manipulate the icon and username on the message.The response includes the "timestamp ID" (ts
) and the channel-like thing where the message was posted. It also includes the complete message object, as parsed by our servers. This may differ from the provided arguments as our servers sanitize links, attachments, and other properties. Your message may mutate.
{
"ok": true,
"channel": "C123ABC456",
"ts": "1503435956.000247",
"message": {
"text": "Here's a message for you",
"username": "ecto1",
"bot_id": "B123ABC456",
"attachments": [
{
"text": "This is an attachment",
"id": 1,
"fallback": "This is an attachment's fallback"
}
],
"type": "message",
"subtype": "bot_message",
"ts": "1503435956.000247"
}
}
Typical error response if too many attachments are included
{
"ok": false,
"error": "too_many_attachments"
}
This table lists the expected errors that this method could return. However, other errors can be returned in the case where the service is down or other unexpected factors affect processing. Callers should always check the value of the ok
params in the response.
Error | Description |
---|---|
as_user_not_supported | The |
channel_not_found | Value passed for |
duplicate_channel_not_found | Channel associated with |
duplicate_message_not_found | No duplicate message exists associated with |
ekm_access_denied | Administrators have suspended the ability to post a message. |
invalid_blocks | Blocks submitted with this message are not valid |
invalid_blocks_format | The |
invalid_metadata_format | Invalid metadata format provided |
invalid_metadata_schema | Invalid metadata schema provided |
is_archived | Channel has been archived. |
message_limit_exceeded | Members on this team are sending too many messages. For more details, see https://slack.com/help/articles/115002422943-Usage-limits-for-free-workspaces |
messages_tab_disabled | Messages tab for the app is disabled. |
metadata_must_be_sent_from_app | Message metadata can only be posted or updated using an app-level token |
metadata_too_large | Metadata exceeds size limit |
msg_blocks_too_long | Blocks submitted with this message are too long. |
no_text | No message text provided |
not_in_channel | Cannot post user messages to a channel they are not in. |
rate_limited | Application has posted too many messages, read the Rate Limit documentation for more information |
restricted_action | A workspace preference prevents the authenticated user from posting. |
restricted_action_non_threadable_channel | Cannot post thread replies into a non_threadable channel. |
restricted_action_read_only_channel | Cannot post any message into a read-only channel. |
restricted_action_thread_locked | Cannot post replies to a thread that has been locked by admins. |
restricted_action_thread_only_channel | Cannot post top-level messages into a thread-only channel. |
slack_connect_canvas_sharing_blocked | Admin has disabled Canvas File sharing in all Slack Connect communications |
slack_connect_file_link_sharing_blocked | Admin has disabled Slack File sharing in all Slack Connect communications |
slack_connect_lists_sharing_blocked | Admin has disabled Lists sharing in all Slack Connect communications |
team_access_not_granted | The token used is not granted the specific workspace access required to complete this request. |
team_not_found | This error occurs if, when using an org-wide token, the |
too_many_attachments | Too many attachments were provided with this message. A maximum of 100 attachments are allowed on a message. |
too_many_contact_cards | Too many contact_cards were provided with this message. A maximum of 10 contact cards are allowed on a message. |
cannot_reply_to_message | This message type cannot have thread replies. |
missing_file_data | Attempted to share a file but some required data was missing. |
attachment_payload_limit_exceeded | Attachment payload size is too long. |
access_denied | Access to a resource specified in the request is denied. |
account_inactive | Authentication token is for a deleted user or workspace when using a |
deprecated_endpoint | The endpoint has been deprecated. |
enterprise_is_restricted | The method cannot be called from an Enterprise. |
invalid_auth | Some aspect of authentication cannot be validated. Either the provided token is invalid or the request originates from an IP address disallowed from making the request. |
method_deprecated | The method has been deprecated. |
missing_scope | The token used is not granted the specific scope permissions required to complete this request. |
not_allowed_token_type | The token type used in this request is not allowed. |
not_authed | No authentication token provided. |
no_permission | The workspace token used in this request does not have the permissions necessary to complete the request. Make sure your app is a member of the conversation it's attempting to post a message to. |
org_login_required | The workspace is undergoing an enterprise migration and will not be available until migration is complete. |
token_expired | Authentication token has expired |
token_revoked | Authentication token is for a deleted user or workspace or the app has been removed when using a |
two_factor_setup_required | Two factor setup is required. |
accesslimited | Access to this method is limited on the current network |
fatal_error | The server could not complete your operation(s) without encountering a catastrophic error. It's possible some aspect of the operation succeeded before the error was raised. |
internal_error | The server could not complete your operation(s) without encountering an error, likely due to a transient issue on our end. It's possible some aspect of the operation succeeded before the error was raised. |
invalid_arg_name | The method was passed an argument whose name falls outside the bounds of accepted or expected values. This includes very long names and names with non-alphanumeric characters other than |
invalid_arguments | The method was either called with invalid arguments or some detail about the arguments passed is invalid, which is more likely when using complex arguments like blocks or attachments. |
invalid_array_arg | The method was passed an array as an argument. Please only input valid strings. |
invalid_charset | The method was called via a |
invalid_form_data | The method was called via a |
invalid_post_type | The method was called via a |
missing_post_type | The method was called via a |
ratelimited | The request has been ratelimited. Refer to the |
request_timeout | The method was called via a |
service_unavailable | The service is temporarily unavailable |
team_added_to_org | The workspace associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete. |
This table lists the expected warnings that this method will return. However, other warnings can be returned in the case where the service is experiencing unexpected trouble.
Warning | Description |
---|---|
message_truncated | The |
missing_charset | The method was called via a |
superfluous_charset | The method was called via a |
import com.slack.api.bolt.App; import com.slack.api.bolt.AppConfig; import com.slack.api.bolt.jetty.SlackAppServer; import com.slack.api.methods.SlackApiException; import java.io.IOException; public class ChatPostMessage { public static void main(String[] args) throws Exception { var config = new AppConfig(); config.setSingleTeamBotToken(System.getenv("SLACK_BOT_TOKEN")); config.setSigningSecret(System.getenv("SLACK_SIGNING_SECRET")); var app = new App(config); // `new App()` does the same app.message("hello", (req, ctx) -> { var logger = ctx.logger; try { var event = req.getEvent(); // Call the chat.postMessage method using the built-in WebClient var result = ctx.client().chatPostMessage(r -> r // The token you used to initialize your app is stored in the `context` object .token(ctx.getBotToken()) // Payload message should be posted in the channel where original message was heard .channel(event.getChannel()) .text("world") ); logger.info("result: {}", result); } catch (IOException | SlackApiException e) { logger.error("error: {}", e.getMessage(), e); } return ctx.ack(); }); var server = new SlackAppServer(app); server.start(); } }
Code to initialize Bolt app// Require the Node Slack SDK package (github.com/slackapi/node-slack-sdk) const { WebClient, LogLevel } = require("@slack/web-api"); // WebClient instantiates a client that can call API methods // When using Bolt, you can use either `app.client` or the `client` passed to listeners. const client = new WebClient("xoxb-your-token", { // LogLevel can be imported and used to make debugging simpler logLevel: LogLevel.DEBUG });
// ID of the channel you want to send the message to const channelId = "C12345"; try { // Call the chat.postMessage method using the WebClient const result = await client.chat.postMessage({ channel: channelId, text: "Hello world" }); console.log(result); } catch (error) { console.error(error); }
Code to initialize Bolt appimport logging import os # Import WebClient from Python SDK (github.com/slackapi/python-slack-sdk) from slack_sdk import WebClient from slack_sdk.errors import SlackApiError # WebClient instantiates a client that can call API methods # When using Bolt, you can use either `app.client` or the `client` passed to listeners. client = WebClient(token=os.environ.get("SLACK_BOT_TOKEN")) logger = logging.getLogger(__name__)
# ID of the channel you want to send the message to channel_id = "C12345" try: # Call the chat.postMessage method using the WebClient result = client.chat_postMessage( channel=channel_id, text="Hello world" ) logger.info(result) except SlackApiError as e: logger.error(f"Error posting message: {e}")