python-mattermost-driver

repository·master·Indexed 41 days ago

https://github.com/vaelor/python-mattermost-driver

A Python driver for the Mattermost APIv4 providing a high-level interface for interacting with Mattermost servers via HTTP and Websockets. It includes synchronous and asynchronous clients (Client, AsyncClient) and drivers (Driver, AsyncDriver) to manage users, channels, posts, files, and system settings. Supports authentication via Personal Access Tokens, username/password, or .netrc files.

Tokens
9.2K
Snippets
34
Records
48
Agent score
52%

What's inside python-mattermost-driver

  1. Available Mattermost API Endpoints

    master

    The python-mattermost-driver provides access to various Mattermost API endpoints organized by functional modules. These modules allow you to interact with different aspects of the Mattermost ecosystem, including users, channels, posts, files, and system settings.

    Available endpoint modules include:

    • Bots: Manage bot accounts.
    • Brand: Manage Mattermost branding.
    • Channels: Manage channels and channel members.
    • Cluster: Manage cluster information.
    • Commands: Manage slash commands.
    • Compliance: Manage compliance settings.
    • Data_retention: Manage data retention policies.
    • Elasticsearch: Interact with Elasticsearch settings.
    • Emoji: Manage custom emojis.
    • Files: Handle file uploads and management.
    • Integration_actions: Manage integration actions.
    • LDAP: Manage LDAP settings.
    • OAuth: Manage OAuth configurations.
    • Posts: Create, read, and manage posts.
    • Preferences: Manage user preferences.
    • Reactions: Manage post reactions.
    • Roles: Manage system roles.
    • SAML: Manage SAML settings.
    • Scheme: Manage scheme settings.
    • Status: Manage user presence/status.
    • System: Manage system-wide settings.
    • Teams: Manage teams.
    • Users: Manage user accounts.
    • Webhooks: Manage incoming/outgoing webhooks.
  2. Interact with Mattermost using the Driver class

    master

    The primary entry point for the python-mattermost-driver is the Driver class. Most interactions with the Mattermost API are performed through an instance of this class. To access information about the currently authenticated user (such as the userid), use the client attribute on your Driver instance.

    # Example of accessing the logged in user's ID
    # Assuming 'mm' is an instance of Driver
    user_id = mm.client.userid
  3. Authenticate using a .netrc file

    master

    You can authenticate with Mattermost by using a .netrc file. This method allows the underlying requests library to handle credentials automatically, providing a clean way to manage authentication without hardcoding tokens or usernames in your scripts.

    # Example of authentication with .netrc
    # (Refer to mmDriverTokenAuthExample.py for the full implementation)
  4. Initialize a WebSocket connection

    master

    You can listen to real-time events by initializing a websocket connection. This must be done after calling login(), as the websocket requires an authentication token.

    Synchronous (Driver)

    Use init_websocket(event_handler). This method runs the event loop and will not return until the websocket is disconnected.

    Asynchronous (AsyncDriver)

    Use await init_websocket(event_handler). This returns a coroutine that can be awaited; it will not return until shutdown is called.

    Example Event Handler

    async def my_event_handler(message):
        print(message)
    async def my_event_handler(message):
        print(message)
    
    # For AsyncDriver
    await driver.init_websocket(my_event_handler)
    
    # For Driver
    driver.init_websocket(my_event_handler)
    # Note: the sync version runs the loop internally
  5. Configure Driver authentication and connection options

    master

    The Driver constructor accepts several configuration keys:

    KeyTypeDescription
    urlstringRequired. The Mattermost server URL (without scheme/port).
    login_idstringRequired (if not using token). Your Mattermost username.
    passwordstringRequired (if not using token). Your Mattermost password.
    tokenstringRequired (if not using login/pass). Your Personal Access Token.
    authobjectCustom auth header to be passed directly to the requests library.
    schemestringProtocol (e.g., https).
    portintServer port.
    basepathstringAPI base path (defaults to /api/v4).
    verifybool/strSSL verification. Set to False for self-signed certs or provide a path to a .pem file.
    mfa_tokenstringMFA token if required.
    timeoutintWebsocket ping interval to keep connection alive.
    request_timeoutfloat/NoneTimeout for HTTP requests.
    keepaliveboolWhether to attempt to reconnect the websocket if disconnected.
    keepalive_delayintSeconds to wait before attempting websocket reconnection.
    websocket_kw_argsdictAdditional keyword arguments for websockets.connect().
    debugboolEnables verbose logging (includes passwords in logs! Use with caution).
  6. Initialize the Client

    master

    To interact with the Mattermost server, use the Client class for synchronous requests or AsyncClient for asynchronous requests. Both require an options dictionary containing connection details.

    Required keys in options:

    • scheme: The protocol (e.g., 'https').
    • url: The Mattermost server hostname/IP.
    • port: The port number (integer).
    • basepath: The base path for the API (e.g., '/api/v4').
    • auth: An authentication callable or mechanism.
    • debug: Boolean to enable verbose logging.
    • request_timeout: The timeout duration for requests.

    Optional keys:

    • proxy: A proxy URL string.
    • http2: Boolean to enable HTTP/2 support.
    • verify: Boolean to enable/disable SSL verification.
    from mattermostdriver.client import Client
    
    options = {
        'scheme': 'https',
        'url': 'mattermost.example.com',
        'port': 443,
        'basepath': '/api/v4',
        'auth': None, # Or your auth mechanism
        'debug': False,
        'request_timeout': 30,
        'http2': False,
        'verify': True
    }
    
    with Client(options) as client:
        # Use client here
        pass
  7. Use the synchronous Driver

    master

    The Driver class is the primary entrypoint for synchronous interaction with the Mattermost API. It supports context manager usage (with statement) to ensure the client is properly managed.

    To use it, initialize the driver with your configuration, call login() to authenticate, and then access API endpoints via properties like driver.users, driver.posts, or driver.channels.

    from mattermostdriver import Driver
    
    options = {
        "url": "localhost",
        "login_id": "mmuser",
        "password": "mmuser"
    }
    
    with Driver(options=options) as driver:
        driver.login()
        user = driver.users.get_user("me")
        print(user)
        driver.logout()
  8. Use the AsyncDriver

    master

    The AsyncDriver class is designed for asynchronous applications using asyncio. It supports asynchronous context management (async with).

    All authentication methods (login, logout) and websocket initializations are coroutines and must be awaited.

    import asyncio
    from mattermostdriver import AsyncDriver
    
    async def main():
        options = {
            "url": "localhost",
            "token": "your_token"
        }
        
        async with AsyncDriver(options=options) as driver:
            await driver.login()
            user = await driver.users.get_user("me")
            print(user)
            await driver.logout()
    
    asyncio.run(main())
  9. Upload files and attach them to posts

    master

    To upload a file, use foo.files.upload_file with a files dictionary. To attach the uploaded file to a post, capture the file ID and pass it in the file_ids list within the options dictionary of create_post.

    # 1. Get channel ID
    channel_id = foo.channels.get_channel_by_name_and_team_name('team', 'channel')['id']
    
    # 2. Upload file
    file_id = foo.files.upload_file(
        channel_id=channel_id,
        files={'files': ('filename.txt', open('filename.txt', 'rb'))}
    )['file_infos'][0]['id']
    
    # 3. Create post with attachment
    foo.posts.create_post(options={
        'channel_id': channel_id,
        'message': 'This is the important file',
        'file_ids': [file_id]
    })