"""Module for sending messages via Telegram."""importloggingfromsalt.exceptionsimportSaltInvocationErrortry:importrequestsHAS_REQUESTS=TrueexceptImportError:HAS_REQUESTS=Falselog=logging.getLogger(__name__)__virtualname__="telegram"def__virtual__():ifnotHAS_REQUESTS:return(False,"Missing dependency requests")return__virtualname__def_get_chat_id():""" Retrieve and return the Telegram's configured chat id :return: String: the chat id string """chat_id=__salt__["config.get"]("telegram:chat_id")or__salt__["config.get"]("telegram.chat_id")ifnotchat_id:raiseSaltInvocationError("No Telegram chat id found")returnchat_iddef_get_token():""" Retrieve and return the Telegram's configured token :return: String: the token string """token=__salt__["config.get"]("telegram:token")or__salt__["config.get"]("telegram.token")ifnottoken:raiseSaltInvocationError("No Telegram token found")returntoken
[docs]defpost_message(message,chat_id=None,token=None):""" Send a message to a Telegram chat. :param message: The message to send to the Telegram chat. :param chat_id: (optional) The Telegram chat id. :param token: (optional) The Telegram API token. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' telegram.post_message message="Hello Telegram!" """ifnotchat_id:chat_id=_get_chat_id()ifnottoken:token=_get_token()ifnotmessage:log.error("message is a required option.")return_post_message(message=message,chat_id=chat_id,token=token)
def_post_message(message,chat_id,token):""" Send a message to a Telegram chat. :param chat_id: The chat id. :param message: The message to send to the Telegram chat. :param token: The Telegram API token. :return: Boolean if message was sent successfully. """url=f"https://api.telegram.org/bot{token}/sendMessage"parameters={}ifchat_id:parameters["chat_id"]=chat_idifmessage:parameters["text"]=messagetry:response=requests.post(url,data=parameters,timeout=120)result=response.json()log.debug("Raw response of the telegram request is %s",response)exceptException:# pylint: disable=broad-exceptlog.exception("Sending telegram api request failed")returnFalse# Check if the Telegram Bot API returned successfully.ifnotresult.get("ok",False):log.debug("Sending telegram api request failed due to error %s (%s)",result.get("error_code"),result.get("description"),)returnFalsereturnTrue