Mattermostdriver documentation

See for the github repository.

You interact with this module mainly by using the Driver class. If you want to access information about the logged in user, like the user id, you can access them by using Driver.client.userid.


pip install mattermostdriver


from mattermostdriver import Driver

foo = Driver({
    Required options

    Instead of the login/password, you can also use a personal access token.
    If you have a token, you don't need to pass login/pass.
    It is also possible to use 'auth' to pass a auth header in directly,
    for an example, see:
    'url': '',
    'login_id': '',
    'password': 'verySecret',
    'token': 'YourPersonalAccessToken',

    Optional options

    These options already have useful defaults or are just not needed in every case.
    In most cases, you won't need to modify these, especially the basepath.
    If you can only use a self signed/insecure certificate, you should set
    verify to your CA file or to False. Please double check this if you have any errors while
    using a self signed certificate!
    'scheme': 'https',
    'port': 8065,
    'basepath': '/api/v4',
    'verify': True,  # Or /path/to/file.pem
    'mfa_token': 'YourMFAToken',
    Setting this will pass the your auth header directly to
    the request libraries 'auth' parameter.
    You probably only want that, if token or login/password is not set or
    you want to set a custom auth header.
    'auth': None,
    If for some reasons you get regular timeouts after a while, try to decrease
    this value. The websocket will ping the server in this interval to keep the connection
    If you have access to your server configuration, you can of course increase the timeout
    'timeout': 30,

    This value controls the request timeout.
    for more information.
    The default value is None here, because it is the default in the
    request library, too.
    'request_timeout': None,

    To keep the websocket connection alive even if it gets disconnected for some reason you
    can set the  keepalive option to True. The keepalive_delay defines how long to wait in seconds
    before attempting to reconnect the websocket.
    'keepalive': False,
    'keepalive_delay': 5,

    This option allows you to provide additional keyword arguments when calling websockets.connect()
    By default it is None, meaning we will not add any additional arguments. An example of an
    additional argument you can pass is one used to  disable the client side pings:
    'websocket_kw_args': {"ping_interval": None},
    'websocket_kw_args': None

    Setting debug to True, will activate a very verbose logging.
    This also activates the logging for the requests package,
    so you can see every request you send.

    Be careful. This SHOULD NOT be active in production, because this logs a lot!
    Even the password for your account when doing driver.login()!
    'debug': False,

Most of the requests need you to be logged in, so calling login()
should be the first thing you do after you created your Driver instance.
login() returns the raw response.
If using a personal access token, you still need to run login().
In this case, does not make a login request, but a `get_user('me')`
and sets everything up in the client.

You can make api calls by using calling `Driver.endpointofchoice`.
Using api[''] is deprecated for 5.0.0!

So, for example, if you used `Driver.api['users'].get_user('me')` before,
you now just do `Driver.users.get_user('me')`.
The names of the endpoints and requests are almost identical to
the names on the page.
API calls always return the json the server send as a response.

If the api request needs additional parameters
you can pass them to the function in the following way:
- Path parameters are always simple parameters you pass to the function

# - Query parameters are always passed by passing a `params` dict to the function

# - Request Bodies are always passed by passing an `options` dict or array to the function

# See the mattermost api documentation to see which parameters you need to pass.
    'team_id': 'some_team_id',
    'name': 'awesome-channel',
    'display_name': 'awesome channel',
    'type': 'O'

If you want to make a websocket connection to the mattermost server
you can call the init_websocket method, passing an event_handler.
Every Websocket event send by mattermost will be send to that event_handler.
See the API documentation for which events are available.

# Use `disconnect()` to disconnect the websocket

# To upload a file you will need to pass a `files` dictionary
channel_id = foo.channels.get_channel_by_name_and_team_name('team', 'channel')['id']
file_id = foo.files.upload_file(
    files={'files': (filename, open(filename))}

# track the file id and pass it in `create_post` options, to attach the file
    'channel_id': channel_id,
    'message': 'This is the important file',
    'file_ids': [file_id]})

# If needed, you can make custom requests by calling `make_request`
foo.client.make_request('post', '/endpoint', options=None, params=None, data=None, files=None, basepath=None)

# If you want to call a webhook/execute it use the `call_webhook` method.
# This method does not exist on the mattermost api AFAIK, I added it for ease of use.
foo.webhooks.call_webhook('myHookId', options) # Options are optional


Yuu can either use the normal ways for login, by token and or username, or authenticate using the .netrc file. This passes the credentials to the requests library, where you can also read more about that.

A nice example for authentication with .netrc by @apfeiffer.

# A simple example to retrieve all users for a team while using a _token_ 
# from the .netrc file instead of a password (as requests assumes by default)

import logging 
import requests
import netrc

from mattermostdriver import Driver

logging.basicConfig( format='%(levelname)s - %(name)s - %(asctime)s - %(message)s' )
logger = logging.getLogger( 'MattermostManager' )
logger.setLevel( logging.INFO )

# requests overrides the simple authentication token header if it finds the entry in 
# the ~/.netrc file. Since we want to use ~/.netrc to retrieve the _token_, we need
# to provide our own Authenticator class:

class TokenAuth( requests.auth.AuthBase ) :
    def __call__( self, r ) :
        # Implement my authentication
        mmHost = ''
        (login, account, password) = netrc.netrc().authenticators( mmHost )
        r.headers[ 'Authorization' ] = "Bearer %s" % password
        return r

class MattermostManager( object ) :

    def __init__( self ) :

        # Get the _token_ (as "password") from the ~/.netrc file.
        # the corresponding line in the file should look like:
        # <> foo foo <long-string-of-token>
        # The "login" and "account" (both set to "foo" in the example are ignored)
        mmHost = ''
        (login, account, password) = netrc.netrc().authenticators( mmHost )
        logger.debug( "Going to set up driver for connection to %s " % (mmHost,) )

        self.mmDriver = Driver( options={
            'url'    : mmHost,
            'scheme' : 'https',
            'port'   : 443,
            'auth'   : TokenAuth, # use the new Authenticator class defined above
        } )

        self.mmDriver.users.get_user( user_id='me' )

    def getTeamMembers( self, teamName ) :

        # for restricted teams, we need to get the ID first, and
        # for this, we need to have the "name" (as in the URL), not
        # the "display name", as shown in the GUIs:

        team0 = self.mmDriver.teams.get_team_by_name( teamName )
        logger.debug( 'team by name %s : %s' % (teamName, team0) )
        teamId = team0[ 'id' ]

        team = self.mmDriver.teams.check_team_exists( teamName )
        logger.debug( 'team %s - exists: %s' % (teamName, team[ 'exists' ]) )
        if not team[ 'exists' ] :
            logger.error( 'no team with name %s found' % teamName )

        logger.debug( 'found team %s: %s' % (teamName, self.mmDriver.teams.get_team( teamId )) )

        users = self._getAllUsersForTeam( teamId )
        logger.debug( 'found %s users for team "%s"' % (len( users ), teamName) )

        return users

    def _getAllUsersForTeam( self, teamId ) :

        # get all users for a team
        # with the max of 200 per page, we need to iterate a bit over the pages

        users = [ ]
        pgNo = 0
        teamUsers = self.mmDriver.users.get_users( params={ 'in_team'  : teamId,
                                                            'page'     : str( pgNo ),
                                                            'per_page' : 200,
                                                            } )
        while teamUsers :
            users += teamUsers
            pgNo += 1
            teamUsers = self.mmDriver.users.get_users( params={ 'in_team'  : teamId,
                                                                'per_page' : 200,
                                                                'page'     : str( pgNo ),
                                                                } )
        return users

if __name__ == '__main__' :
    mmM = MattermostManager()
    mmM.getTeamMembers( 'myTeam' )


class mattermostdriver.Driver(options=None, client_cls=<class 'mattermostdriver.client.Client'>)[source]

Contains the client, api and provides you with functions for login, logout and initializing a websocket connection.

default_options = {'auth': None, 'basepath': '/api/v4', 'debug': False, 'keepalive': False, 'keepalive_delay': 5, 'login_id': None, 'mfa_token': None, 'password': None, 'port': 8065, 'request_timeout': None, 'scheme': 'https', 'timeout': 30, 'token': None, 'url': 'localhost', 'verify': True, 'websocket_kw_args': None}
Required options
  • url

  • login_id

  • password

  • scheme (‘https’)

  • port (8065)

  • verify (True)

  • timeout (30)

  • request_timeout (None)

  • mfa_token (None)

  • auth (None)

  • debug (False)

Should not be changed
  • basepath (‘/api/v4’) - unlikely this would do any good

init_websocket(event_handler, websocket_cls=<class 'mattermostdriver.websocket.Websocket'>)[source]

Will initialize the websocket connection to the mattermost server.

This should be run after login(), because the websocket needs to make an authentification.

See for which websocket events mattermost sends.

Example of a really simple event_handler function

async def my_event_handler(message):

event_handler (Function(message)) – The function to handle the websocket events. Takes one argument.


The event loop


Disconnects the driver from the server, stopping the websocket event loop.


Logs the user in.

The log in information is saved in the client
  • userid

  • username

  • cookies


The raw response from the request


Log the user out.


The JSON response from the server

property api

Deprecated since version 4.0.2.

Use the endpoints directly instead.


dictionary containing the endpoints

Return type


property users

Api endpoint for users


Instance of Users

property teams

Api endpoint for teams


Instance of Teams

property channels

Api endpoint for channels


Instance of Channels

property posts

Api endpoint for posts


Instance of Posts

property files

Api endpoint for files


Instance of Files

property preferences

Api endpoint for preferences


Instance of Preferences

property emoji

Api endpoint for emoji


Instance of Emoji

property reactions

Api endpoint for posts’ reactions


Instance of Reactions

property system

Api endpoint for system


Instance of System

property webhooks

Api endpoint for webhooks


Instance of Webhooks

property compliance

Api endpoint for compliance


Instance of Compliance

property cluster

Api endpoint for cluster


Instance of Cluster

property brand

Api endpoint for brand


Instance of Brand

property oauth

Api endpoint for oauth


Instance of OAuth

property saml

Api endpoint for saml


Instance of SAML

property ldap

Api endpoint for ldap


Instance of LDAP

property elasticsearch

Api endpoint for elasticsearch


Instance of Elasticsearch

property data_retention

Api endpoint for data_retention


Instance of DataRetention

property status

Api endpoint for status


Instance of Status

property commands

Api endpoint for commands


Instance of Commands

property roles

Api endpoint for roles


Instance of Roles

property opengraph

Api endpoint for opengraph


Instance of Opengraph

property integration_actions

Api endpoint for integration actions


Instance of IntegrationActions

class mattermostdriver.Client(options)[source]
property userid

The user id of the logged in user

property request_timeout

The configured timeout for the requests

property username

The username of the logged in user. If none, returns an emtpy string.

property cookies

The cookie given on login

property token

The token for the login

Exceptions that api requests can throw

class mattermostdriver.exceptions.InvalidOrMissingParameters(*args, **kwargs)[source]

Raised when mattermost returns a 400 Invalid or missing parameters in URL or request body

class mattermostdriver.exceptions.NoAccessTokenProvided(*args, **kwargs)[source]

Raised when mattermost returns a 401 No access token provided

class mattermostdriver.exceptions.NotEnoughPermissions(*args, **kwargs)[source]

Raised when mattermost returns a 403 Do not have appropriate permissions

class mattermostdriver.exceptions.ResourceNotFound(*args, **kwargs)[source]

Raised when mattermost returns a 404 Resource not found

class mattermostdriver.exceptions.ContentTooLarge(*args, **kwargs)[source]

Raised when mattermost returns a 413 Content too large

class mattermostdriver.exceptions.FeatureDisabled(*args, **kwargs)[source]

Raised when mattermost returns a 501 Feature is disabled

Indices and tables