Source code for saltext.mattermost.modules.mattermost
"""Module for sending messages to Mattermost.. important:: You can optionally :ref:`add a configuration profile <mattermost-setup>` to avoid having to pass `hook` and `api_url` to each invocation."""importloggingfromsalt.exceptionsimportSaltInvocationErrorfromsalt.utilsimportjsonfromsaltext.mattermost.utilsimportmattermostlog=logging.getLogger(__name__)__virtualname__="mattermost"def__virtual__():return__virtualname__def_get_hook():""" Retrieves and return the Mattermost's configured hook :return: String: the hook string """hook=__salt__["config.get"]("mattermost.hook")or__salt__["config.get"]("mattermost:hook")ifnothook:raiseSaltInvocationError("No Mattermost Hook found")returnhookdef_get_api_url():""" Retrieves and return the Mattermost's configured api url :return: String: the api url string """api_url=__salt__["config.get"]("mattermost.api_url")or__salt__["config.get"]("mattermost:api_url")ifnotapi_url:raiseSaltInvocationError("No Mattermost API URL found")returnapi_urldef_get_channel():""" Retrieves the Mattermost's configured channel :return: String: the channel string """channel=__salt__["config.get"]("mattermost.channel")or__salt__["config.get"]("mattermost:channel")returnchanneldef_get_username():""" Retrieves the Mattermost's configured username :return: String: the username string """username=__salt__["config.get"]("mattermost.username")or__salt__["config.get"]("mattermost:username")returnusername
[docs]defpost_message(message,channel=None,username=None,api_url=None,hook=None):""" Send a message to a Mattermost channel. :param channel: The channel name, either will work. :param username: The username of the poster. :param message: The message to send to the Mattermost channel. :param api_url: The Mattermost api url, if not specified in the configuration. :param hook: The Mattermost hook, if not specified in the configuration. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mattermost.post_message message='Build is done' """ifnotapi_url:api_url=_get_api_url()ifnothook:hook=_get_hook()ifnotusername:username=_get_username()ifnotchannel:channel=_get_channel()ifnotmessage:log.error("message is a required option.")parameters={}ifchannel:parameters["channel"]=channelifusername:parameters["username"]=usernameparameters["text"]="```"+message+"```"# pre-formatted, fixed-width textlog.debug("Parameters: %s",parameters)data=f"payload={json.dumps(parameters)}"result=mattermost.query(api_url=api_url,hook=hook,data=data)returnbool(result)