Package: matterapi
MatterApiA python client library for the Mattermost API with sync/async support.FeaturesEndpoints generated from theAPI documentationHowever: if the description is wrong, this library will be wrongBased onhttpxand supports sync and async operationResponse parsing into models withpydanticTyping supportWebsocket handling to connect to the Mattermost event stream.Getting StartedThe client has synch and async support. Depending on your workflow you will want to choose between
theSyncClientandAsyncClient.SyncClientFirst, let's look at an example on how to use the SyncClient:frommatterapiimportSyncClientfrommatterapi.client.exceptionsimportApiError,InvalidOrMissingParametersfrommatterapi.modelsimport(CreateChannelJsonBody,CreatePostJsonBody,CreateTeamJsonBody,CreateUserJsonBody,)# set the options for the clientoptions={'url':'http://localhost:8095','auth':{'token':'<yourtokenhere>'}}# Create a sync clientsd=SyncClient(options=options)# Use the client""" You can use the client directly. This will create a new httpx.Client for eachrequest (an potentially run the login flow again, if you use username/password authentication)."""## Get your own user objectsd.users.get_user("me")## Get channelschannels=sd.channels.get_all_channels(per_page=20)print(channels[0])## Get posts for channelpost_list=sd.posts.get_posts_for_channel("<channel_id>")forpostinpost_list.posts:print(post,post_list.posts[post].id)""" Or you can open a session, which will reuse a single httpx client instancefor the requests, thereby reusing connections ( the login flow is then only run once).The returned object can be used exactly the same as the SyncClient.Most often you will want to use this as it requires fewer connections to the server"""withsd.session()asapi_session:# Get the current useruser=api_session.users.get_user("me")print("User id:",user.id)# Get a list of pluginsplugins_avail=api_session.plugins.get_plugins()print("Number of active plugins:",len(plugins_avail.active))print("Name of first active plugin:",plugins_avail.active[0].name)# Create a new Team or get existingnew_team=CreateTeamJsonBody(name="rebels",display_name="Rebels",type="I")try:team=api_session.teams.create_team(json_body=new_team)print("New Team created with id:",team.id)exceptInvalidOrMissingParametersase:print("> Exception:",e)team=api_session.teams.get_team_by_name(name=new_team.name)print("Got existing Team with id:",team.id)# Create a channel or get existingnew_channel=CreateChannelJsonBody(team_id=team.id,name="newchannelname",display_name="New Channel",type="O")try:channel=api_session.channels.create_channel(json_body=new_channel)print(f"New Channel with id:",channel.id)exceptInvalidOrMissingParametersase:print("> Exception:",e)channel=api_session.channels.get_channel_by_name(team_id=team.id,channel_name=new_channel.name)print(f"Got existing Channel with id:",channel.id)# Upload files to be used in a channelfile_info=api_session.files.upload_file(channel_id=channel.id,multipart_data={"files":{"upload1.png":open("testfile1.png","rb"),"upload2.png":open("testfile2.png","rb"),},},)print("File id for second file:",file_info.file_infos[1].id)# Create a post including the uploaded filesnew_post=CreatePostJsonBody(channel_id=channel.id,message="A wild message appears",file_ids=[info.idforinfoinfile_info.file_infos],)post=api_session.posts.create_post(json_body=new_post)print("Creation time for new post:",post.create_at)AsyncClientAnd this is how you can use the AsyncClientimportasynciofrommatterapiimportAsyncClient# set the options for the clientoptions={'url':'https://localhost:8095',# User username and password authentication'auth':{'login_id':'hansolo','password':'lea1234'},# Disable TLS verification for the client# httpx_client_options are passed to the underlying httpx.Client'httpx_client_options':{'verify':False}}# Create a async clientad=AsyncClient(options=options)asyncdefdo_something():# Use the clientusers=awaitad.users.get_users()print(users)# To upload files, you could for example use the following requestdata={"files":{"test1.png":open("testfile1.png","rb"),"test2.png":open("testfile2.png","rb"),}}file_infos=awaitad.files.upload_file(channel_id="7bzsijaqopfczygxm1qc3r63do",multipart_data=data)print(file_info)asyncio.run(do_something())The AsyncClient supports sessions as well, same as the SyncClient.Websocket connectionYou can also listen for event data from Mattermostdefhandler(message):print(message)# either use the sync versionsd.start_ws_sync(handler)# or the async version withasyncdefwrapper():awaitad.start_ws(handler)ContributingThe actual endpoints in Matterapi are autogenerated with a fork ofopenapi-python-client. If anything there needs changing, please refer to the generator project.Some endpoints might return wrong results or miss parameters. Currently, I can image the following reasons:The generator is broken and/or does not support the required feature set.Create an issue in thematterapi-generatorrepositoryIf you know how to fix it, consider to do a pull requestThemattermost api documentation, which this client is generated from, is not correctSometimes entries in the documentation might not be completely correctConsider fixing the API documentation/do a pull request/post an issue thereThis will help everybody who is using the documentationThe API documentation changed or included new endpoints, but the library was not updated.Currently creation of the api client is not automated, so you have two options:Help with the automation so that this proejct is automatically updated with changesCreate a new issue here that the client is out of syncClone the generator repo, update the mattermost api with the generator and do a pull request here. (This is currently the only save way to get changes into the matterapi folder)CreditsCredits where credits are due:This library is autogenerated from the Mattermost API documentation using a fork ofopenapi-python-client.It's heavily inspired by (but not a 1:1 drop-in replacement for)mattermostdriver, which I used for several years already. This is still your go-to if you look for something stable that has been in use for years by lot's of people.