Source code for saltext.telegram.beacons.telegram_bot_msg
"""Beacon to emit Telegram messages.Configuration example---------------------Include the following in the minion configuration:.. code-block:: yaml beacons: telegram_bot_msg: - token: "<bot access token>" - accept_from: - "<valid username>" - interval: 10"""importloggingimportsalt.utils.beaconstry:importtelegramlogging.getLogger("telegram").setLevel(logging.CRITICAL)HAS_TELEGRAM=TrueexceptImportError:HAS_TELEGRAM=Falselog=logging.getLogger(__name__)__virtualname__="telegram_bot_msg"def__virtual__():ifHAS_TELEGRAM:return__virtualname__err_msg="telegram library is missing."log.error("Unable to load %s beacon: %s",__virtualname__,err_msg)returnFalse,err_msg
[docs]defvalidate(config):""" Validate the beacon configuration """ifnotisinstance(config,list):returnFalse,"Configuration for telegram_bot_msg beacon must be a list."config=salt.utils.beacons.list_to_dict(config)ifnotall(config.get(required_config)forrequired_configin["token","accept_from"]):return(False,"Not all required configuration for telegram_bot_msg are set.",)ifnotisinstance(config.get("accept_from"),list):return(False,"Configuration for telegram_bot_msg, accept_from must be a list of usernames.",)returnTrue,"Valid beacon configuration."
[docs]defbeacon(config):""" Emit a dict with a key "msgs" whose value is a list of messages sent to the configured bot by one of the allowed usernames. """config=salt.utils.beacons.list_to_dict(config)log.debug("telegram_bot_msg beacon starting")ret=[]output={}output["msgs"]=[]bot=telegram.Bot(config["token"])updates=bot.get_updates(limit=100,timeout=0)log.debug("Num updates: %d",len(updates))ifnotupdates:log.debug("Telegram Bot beacon has no new messages")returnretlatest_update_id=0forupdateinupdates:message=update.messagelatest_update_id=max(update.update_id,latest_update_id)ifmessage.chat.usernameinconfig["accept_from"]:output["msgs"].append(message.to_dict())# mark in the server that previous messages are processedbot.get_updates(offset=latest_update_id+1)log.debug("Emitting %d messages.",len(output["msgs"]))ifoutput["msgs"]:ret.append(output)returnret