Mattermost Bots: A Guide to Setup and Integration
How to create Mattermost bots, authenticate with tokens, post messages, and build automation for alerts and standups using REST API and frameworks.
- Mattermost bots are service accounts that automate tasks via REST API: posting alerts, running reminders, and integrating external systems.
- Create a bot account in System Console in under two minutes; it generates a token you use for API authentication.
- Bot accounts offer cleaner permission isolation than personal access tokens and scale better for multiple integrations.
- Real-world use cases include CI/CD alerts, daily standups, GitHub notifications, and ChatOps workflows.
- Use mmpy_bot (Python) or Errbot (multi-platform) for interactive bots, or call the REST API directly for simpler tasks.
Mattermost bots are user accounts that execute automated tasks: sending alerts, posting reminders, and integrating external systems into your team's communication. Unlike webhooks, which push data into channels, bots consume API calls and act like regular users, making them ideal for interactive workflows and persistent services.
Bots handle everything from CI/CD notifications to daily standup reminders. If you run Mattermost in-house or on a managed platform, you'll eventually need them. This guide covers creating and running bots without the technical debt of reinventing the wheel.
What Are Mattermost Bots and When Should You Use Them?
Mattermost bots are service accounts that interact with your Mattermost workspace via REST API. They post messages, create channels, manage users, and respond to triggers. A bot is different from a human user: it never logs in interactively, has a dedicated token for authentication, and runs continuously or on-demand.
You use bots when you need persistent automation. A webhook works fine for one-off notifications, but if you're building a chatbot that handles multiple conversations, assigns tasks, or needs to track state across multiple interactions, a bot is the right tool. Bots can read messages (if granted the permission), which webhooks cannot do. They can post to direct messages without a user creating the conversation first. They run as scheduled tasks or stay listening for events.
The decision between a bot and a webhook depends on direction of traffic and statefulness. Webhooks push data into Mattermost (one-way, stateless). Bots pull, listen, and maintain context. If your integration is "a system alerts Mattermost," use a webhook. If it's "Mattermost orchestrates or queries an external system," use a bot. For most real-world automation, you'll use both: an incoming webhook for rapid-fire alerts and a bot for interactive features.
Bots run on your infrastructure or a third-party service you control. They consume bot tokens, which are cheaper to issue and manage than personal access tokens at scale. A workspace can have dozens of bot accounts without licensing overhead.
Bot Accounts vs. Personal Access Tokens: What's the Difference?
Both bot accounts and personal access tokens authenticate to the Mattermost REST API. They are not interchangeable.
A bot account is a first-class user in Mattermost. It has a display name, a profile picture, and channel membership. When a bot posts, it appears in the channel history with the bot's name and avatar. Admins can see and manage all bots in System Console. Bots can be added to channels, invited to teams, and granted specific roles. A bot is owned by the user who created it; if that user is removed, the bot still functions as long as the workspace admin doesn't delete it.
A personal access token is a credential, not a user. It inherits the permissions of the user who created it. If you generate a token under your admin account, that token has admin privileges. If you create one under a regular user account, it has only that user's permissions. Personal access tokens cannot be members of channels or teams. They are useful for service accounts where you want the API caller to inherit one person's exact access level--typically for tooling or migrations.
For bots, use bot accounts. For integrations that need to act with a specific user's permissions, or for temporary API access by a human tool, use personal access tokens. Bot accounts are cleaner: they separate automation from user identity, scale better, and integrate with Mattermost's audit trail more clearly.
Bot accounts can be granted the bot role, which restricts what they can do. System admins can limit bot capabilities: prevent bots from reading messages, restrict channel creation, or lock down post editing. Personal access tokens inherit the full permission set of their owner, with no granular restrictions. For security-sensitive integrations, bot accounts are preferable.
Step-by-Step: Creating a Bot Account in Mattermost
Creating a bot account takes 90 seconds and requires a workspace admin or system admin.
- Log into Mattermost as an admin. Navigate to System Console > Integrations > Bot Accounts (or, in some versions, System Console > Integrations > Bots).
- Click Create New Bot Account. Mattermost will open a form.
- Enter a Username for the bot. This is what appears in channels. Use descriptive names: "github-notifier," "standup-bot," "alert-service." Mattermost enforces uniqueness; usernames must be 3-63 characters and lowercase.
- (Optional) Add a Display Name and Description. The display name is what humans see in the UI. The description helps admins remember what the bot does.
- (Optional) Upload a Profile Picture. This makes bots easier to spot in message history.
- Choose a Role: either Member or System Admin. Start with Member unless the bot absolutely needs admin privileges (e.g., user management tasks). A Member bot can post to channels it joins and read messages it has access to.
- Click Create Bot Account. Mattermost generates a Personal Access Token specifically for the bot. Copy this token immediately: you can only view it once. Paste it somewhere secure (e.g., a password manager or CI/CD secrets vault).
- Back in System Console, you can now grant the bot additional permissions: disable username editing, disable logout, set an expiration date (optional).
Once created, the bot account appears in the user list and can be invited to channels. You can revoke its token from System Console at any time, which deactivates the bot without deleting the account.
Authenticating and Posting Messages with the REST API
Authentication is straightforward: pass the bot token as a Bearer token in the HTTP Authorization header.
All Mattermost REST API calls follow this pattern:
GET /api/v4/users/me
Authorization: Bearer <bot_token>
The token is the Personal Access Token you copied when creating the bot account. Mattermost validates the token, identifies the bot user, and authorizes the request based on the bot's role and channel membership.
Here is a quick test with curl:
curl -X GET https://<your-mattermost-domain>/api/v4/users/me \
-H "Authorization: Bearer YOUR_BOT_TOKEN"
If the token is valid, you'll see a JSON response with the bot's user details.
To post a message to a channel:
curl -X POST https://<your-mattermost-domain>/api/v4/posts \
-H "Authorization: Bearer YOUR_BOT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"channel_id": "CHANNEL_ID",
"message": "Hello from my bot"
}'
You need the channel ID, not the channel name. Fetch it with:
curl -X GET "https://<your-mattermost-domain>/api/v4/teams/TEAM_ID/channels/name/CHANNEL_NAME" \
-H "Authorization: Bearer YOUR_BOT_TOKEN"
Here is a Python example using the requests library:
import requests
BOT_TOKEN = "your_bot_token"
BASE_URL = "https://<your-mattermost-domain>/api/v4"
headers = {
"Authorization": f"Bearer {BOT_TOKEN}",
"Content-Type": "application/json"
}
# Get bot user info
response = requests.get(f"{BASE_URL}/users/me", headers=headers)
bot_user = response.json()
print(f"Bot user: {bot_user['username']}")
# Post a message
payload = {
"channel_id": "CHANNEL_ID",
"message": "Automated update from bot"
}
response = requests.post(f"{BASE_URL}/posts", json=payload, headers=headers)
print(f"Message posted: {response.json()['id']}")
For Node.js, use fetch or axios:
const fetch = require('node-fetch');
const BOT_TOKEN = 'your_bot_token';
const BASE_URL = 'https://<your-mattermost-domain>/api/v4';
const headers = {
'Authorization': `Bearer ${BOT_TOKEN}`,
'Content-Type': 'application/json'
};
fetch(`${BASE_URL}/posts`, {
method: 'POST',
headers: headers,
body: JSON.stringify({
channel_id: 'CHANNEL_ID',
message: 'Hello from Node.js bot'
})
})
.then(res => res.json())
.then(data => console.log('Posted:', data.id));
Mattermost's API documentation lists all endpoints. Common tasks: creating channels, inviting users to channels, fetching the message history, reacting to messages, and updating posts.
Real-World Use Cases: Alerts, Standups, and Notifications
Alerts are the most common use case. A CI/CD pipeline (GitHub Actions, GitLab CI, Jenkins) runs tests and publishes results. Instead of email, the pipeline calls the bot's endpoint, and the bot posts the result to a channel. Developers see failures in Mattermost in real time.
You can use an incoming webhook for alerts (the pipeline pushes a message), or a bot (the pipeline calls the bot, which posts and optionally reads follow-up reactions). Webhooks are simpler for one-way notifications. Bots add value if you need the bot to react: "If build fails, create a Jira ticket," or "When deployment succeeds, pin the message."
Standup reminders run on a schedule. A bot is triggered daily at 9 AM and posts a reminder in the team channel. This is often a cron job or a scheduled Lambda function that calls the bot API. The bot doesn't need to listen or read; it just posts on a timer. Tools like n8n, Apache Airflow, or your CI/CD platform's scheduler can trigger it.
GitHub notifications work both ways. An incoming webhook sends push events and pull request notifications to Mattermost. If you want the bot to respond (e.g., post a summary of merged PRs or link to an artifact), use the bot API. A scheduled bot can also query GitHub's API, fetch recent activity, and summarize it in Mattermost--useful for a centralized activity log.
Slack-style ChatOps workflows demand a bot. The bot listens for messages in a channel, parses commands, and takes action: "@bot deploy main" triggers a deployment. The bot then posts status updates as the deployment progresses. This requires a WebSocket listener (the bot polls or subscribes to events) and stateful code, which frameworks like mmpy_bot or Errbot handle.
Larger teams use bots to manage access. "@bot request access to customer-data channel" triggers a workflow: the bot notifies the data owner, who replies with approval or denial. The bot then adds or denies the requesting user. This avoids manual Slack messages to admins.
Bots also summarize data. A bot connected to an analytics or logging backend can query Datadog, fetch alerts, and post a daily digest to a channel. This centralizes information flow and reduces tool-switching.
Bot Frameworks and Languages: mmpy_bot, Errbot, and Beyond
You can write a bot in any language using HTTP and the REST API, but frameworks simplify the work. They handle authentication, message parsing, and event listening.
mmpy_bot is a Python framework for Mattermost. It uses the WebSocket API (v4.0.0+) to listen for events in real time. Code is written as decorators: define a function, add a decorator like @listen_to(r'hello'), and the bot reacts when it hears "hello." mmpy_bot handles connection pooling, reconnects if the WebSocket drops, and provides helpers for posting, updating, and deleting messages. The GitHub repository (attzonko/mmpy_bot) contains examples.
Errbot is a multi-platform ChatOps framework. It supports Mattermost, Slack, Telegram, and other backends. Code is backend-agnostic: write a plugin in Python, and it runs on any supported platform. Errbot handles command parsing, regex matching, and role-based access control. The official Mattermost blog includes a detailed Errbot tutorial with examples.
Node.js and Go libraries exist but are less mature. Hubot (once popular for Slack) has limited Mattermost support. Most Node.js bots are hand-written using the axios or fetch library and a simple Express server to listen for webhooks.
Choosing a framework depends on your needs. For a simple alert forwarder, skip the framework: write a few curl commands or a Python script with requests. For ChatOps (interactive commands, state), use mmpy_bot or Errbot. For a multi-platform bot, Errbot avoids lock-in. For rapid prototyping, mmpy_bot's decorator syntax is fast. For enterprise environments where Python is standard, mmpy_bot fits. For teams with Go infrastructure, consider a hand-written bot with the Mattermost Go client library.
Frameworks add dependencies and overhead. A 10-line Python script calling the REST API with requests is simpler than installing mmpy_bot for a one-off cron job. Use frameworks when you have multiple commands, state, or plan to scale.
Permissions, Roles, and Security Best Practices
Bot accounts inherit a role: Member or System Admin. A Member bot can post to channels it joins, read messages in those channels, and update its own profile. A System Admin bot can manage users, teams, and channels. Most bots should be Members; admin privileges are rare and dangerous.
Channels and teams further restrict a bot. If a bot is not a member of a channel, it cannot post there. Admins explicitly add bots to channels, just like users. This prevents a bot from spamming every channel in the workspace.
Permissions in Mattermost are role-based. A Member bot respects channel read/write restrictions. A private channel blocks a Member bot unless the channel owner adds the bot. This is by design: bots respect the same access rules as human users.
Token rotation is critical. Bots should not store tokens in code or hardcoded into scripts. Use environment variables, secrets management systems (HashiCorp Vault, AWS Secrets Manager), or your CI/CD platform's secret store. Rotate tokens periodically (e.g., every 90 days). Mattermost allows admins to revoke a bot's token from System Console without deleting the bot account. If a token is compromised, revoke it immediately and generate a new one.
Audit logging is essential if bots make sensitive changes. Mattermost logs all API activity to the audit log (in Enterprise Edition). Review logs regularly to catch suspicious bot activity. Webhooks and bots can be restricted: some teams disable webhooks entirely and require bots for external integrations, which improves traceability.
Do not use a single shared token across multiple services. Create a separate bot account for each service or component. This isolates blast radius: if one token leaks, one bot is compromised, not the entire system.
Running Bots Reliably: Hosting and Next Steps
Bots run on your infrastructure or a third-party service. For scheduled bots (cron, Lambda), keep your Mattermost instance on reliable hosting: Opsily offers managed Mattermost with high availability, automated backups, and failover. Your bots will connect reliably without managing the server yourself.
For long-running bots that listen via WebSocket, you need a persistent service: an EC2 instance, a Kubernetes pod, or a long-running serverless function. Monitor the bot's health: if the WebSocket disconnects, the bot should reconnect automatically. mmpy_bot handles this; if you write custom code, add exponential backoff and circuit breaker logic.
Environment variables should contain the bot token, the Mattermost URL, and any external API keys. Never hardcode secrets. Use secrets management tools in production.
Start simple. Write a cron job that posts a daily digest. Test it in a staging workspace before promoting to production. Once working, add complexity: message parsing, reactions, state.
Run your Mattermost instance on managed hosting so you can focus on bot development, not server maintenance. Opsily provides dedicated Mattermost environments with automatic updates, scaling, and enterprise support.
Frequently Asked Questions
What is a Mattermost bots list?
There is no official registry of community bots, but GitHub repositories like mksondej/mattermost-bots list examples. Most production bots are custom-built for specific needs. The Mattermost app marketplace does not include a dedicated "bots" category; integrations are mixed. To find examples, search GitHub for "mattermost bot," "mmpy_bot," or "Errbot integration."
Where can I find Mattermost bots on GitHub?
The main source is attzonko/mmpy_bot (the Python framework), which includes examples. Search GitHub for mattermost-bot for repositories tagged with Mattermost. Community repos are scattered, so check a bot's last commit date and issue count: active projects are more reliable.
Can I write a Mattermost bot in Python?
Yes. Use the mmpy_bot framework or write directly against the REST API with the requests library. Python is the most popular choice for Mattermost bots due to mmpy_bot's maturity and simplicity. Errbot, also Python-based, supports Mattermost and multiple other platforms.
How do I use the Mattermost bot API?
Use the REST API v4. Authenticate with a bot token in the Authorization header. POST to /api/v4/posts to send messages, GET /api/v4/channels to list channels, and use other endpoints for user, team, and message management. See the official Mattermost API documentation for the full reference.
What is mmpy_bot?
mmpy_bot is a Python framework for building Mattermost bots. It listens to WebSocket events and dispatches them to decorated functions. Example: @listen_to(r'hello') runs code when someone types "hello." It simplifies event-driven bot logic and is ideal for ChatOps workflows.
What is Welcomebot for Mattermost?
Welcomebot is an example bot that greets new users when they join a channel or team. Implementations vary, but typically, it listens for user_added events and posts a welcome message. The Mattermost docs include a simple Welcomebot example using the REST API.
How does a Mattermost bot differ from a webhook?
Webhooks are one-way: external systems push data into Mattermost. Bots are two-way: they can post, read, and respond. Webhooks are simpler for static notifications. Bots are better for interactive automation, state management, and ChatOps. You often use both: webhooks for alerts, bots for orchestration.
The Bottom Line
Mattermost bots automate your team's workflows without leaving the chat interface. They are user accounts with dedicated tokens, created in minutes, and run on any infrastructure from cron jobs to always-on services.
Start with a simple use case: a daily standup reminder or a build alert. Use the REST API directly or pick a framework (mmpy_bot for Python, Errbot for multi-platform). Keep your bot token secure, restrict its permissions, and monitor its activity.
To scale reliably, host your Mattermost workspace on dedicated, managed infrastructure. Opsily runs Mattermost with zero downtime and automatic failover, so your bots connect consistently. Get started with Opsily's managed Mattermost hosting.