MM messages from CLI

How to send a MM message from Linux CLI knowing:

mattermost server
my username (sender)
username of the recipient?

Hi vveckaln and welcome to the Mattermost forums!

You can use the mmctl binary:

# /opt/mattermost/bin/mmctl post create --help
Create a post

  mmctl post create [flags]

  post create myteam:mychannel --message "some text for the post"

Or you can use an incoming webhook after creating one in the “System console” → “Integrations” → “Incoming Webhooks” section:

curl -s -X POST -H "Content-Type: application/json" -d "{\"text\": \"some text for the post\", \"channel\": \"$mychannel\" }"$WEBHOOKID)

And you can also use the API with your Personal Access Token:

1 Like
  1. Can I use the API with a session token?

  2. What to write instead of "channel_id" when I send a direct message?

  3. I try

curl -i -H 'Authorization: Bearer mysessiontoken' -d {"channel_id": "some_channel", "message": "test message"} http://localhost:8065/api/v4/users/me

In this command is the json placed correctly. Is the command composed correctly?

ad 1) Yes, you can also use a session Token, see the API documentation for authentication

ad 2) @username

ad 3) No, this is not correct. The syntax I shared here is for sending messages via a webhook. You do not need to login to send messages via a webhook, the webhook ID is to be kept secret and is the only form of authentication here, as described in my previous posting.
If you want to use the API and not an incoming webhook, you can still use the CreatePost API call from above, but you will have to watch out for the correct usage (as outlined in the documentation).

Replacing a channel_id with username doesn’t seem to work when sending a direct message.

It needs to be @username - the @ character is important.

Like that:
"@username" : "someusername"


"channel_id" : "@someusername"


"username": "@someusername"


What method are we talking about now? mmctl, the API or the webhook? They all use different syntax.

API :heart: :heart: :heart: :heart: :heart: :heart: :heart: :heart: :heart: :heart: :heart: :heart: :heart: :heart: :heart: :heart: :heart: :heart:

Ah, OK - that’s a bit more complicated now.
You need to first create a direct message channel with this specific user. To do that, use the CreateDirectChannel API Call.
The return value of this call will be the channel ID to post to. You can always run the CreateDirectChannel call, if the channel already exists, it will return the ID for you.

Example User ID td6fsn7ow7y9mjc1c6okhpk8ie wants to send to User ID bxsn57fc4inpjg6n89hgxxburw:

curl -H "Authorization: Bearer <yourtoken>" -X POST -d '[ "td6fsn7ow7y9mjc1c6okhpk8ie", "bxsn57fc4inpjg6n89hgxxburw" ]'

The resulting ID nsschcqxajgtdkdymgq55qidto can then be used in the next call to post the message:

curl -H "Authorization: Bearer <yourtoken>" -X POST -d '{ "channel_id": "nsschcqxajgtdkdymgq55qidto", "message": "test" }'