Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Prereq:
- # PIP3 packages for app server
- # apt-get install python3-pip
- # pip3 install uwsgi flask requests py-zabbix
- # Nginx config locations
- # location /bot/endpoint {
- # proxy_pass http://127.0.0.1:9000;
- # }
- #
- # location /bot/status {
- # proxy_pass http://127.0.0.1:9000;
- # }
- #
- # location /bot/zabbix {
- # proxy_pass http://127.0.0.1:9000;
- # }
- # -*- coding: utf-8 -*-
- import time
- import requests
- import json
- from pyzabbix import ZabbixAPI
- from flask import request, Flask
- # Flask apps
- bot = Flask(__name__)
- class SkypeBot:
- def __init__(self, api_url, api_user, api_password, app_id, app_password, session_token):
- self._z_connect = ZabbixAPI(url=str(api_url), user=str(api_user), password=str(api_password))
- self._app_id = app_id
- self._app_password = app_password
- self._session_token = session_token
- self._log = ""
- def _get_ms_token(self):
- payload = {'grant_type': 'client_credentials',
- 'client_id': self._app_id,
- 'client_secret': self._app_password,
- 'scope': 'https://api.botframework.com/.default',
- }
- self._token = requests.post('https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token', data=payload).content
- self._session_token = json.loads(str(self._token)[2:-1])
- self._log += "Session token: %s \n" % (self._session_token)
- return json.loads(str(self._token)[2:-1])
- def _send_ms_token_to_connector(self, token):
- url = 'https://groupme.botframework.com/v3/conversations'
- headers = {'Authorization': 'Bearer ' + token}
- print(headers)
- ms_auth_response = requests.post(url, headers=headers)
- print(ms_auth_response)
- self._log += "Response auth request: %s \n" % (ms_auth_response)
- return ms_auth_response
- def get_and_verify_ms_token(self):
- while True:
- token = self._get_ms_token()
- self._send_ms_token_to_connector(token['access_token'])
- time.sleep(token['expires_in']*0.9)
- def send_message_user(self, text):
- token = self._get_ms_token()
- data = request.get_json()
- self._log += "Data from send function: %s \n" % data
- talk_id = data['conversation']['id']
- self._log += "Talk ID: %s" % talk_id
- msg = {
- "type": "message",
- "from": {
- "id": self._app_id,
- "name": "zabbix-cuboid"
- },
- "conversation": {
- "id": talk_id,
- },
- "text": text,
- }
- url = data['serviceUrl'] + '/v3/conversations/{}/activities/'.format(data['conversation']['id'])
- self._log += "URL for conversation: %s" % url
- headers = {'Authorization': 'Bearer ' + token['access_token'],
- 'content-type': 'application/json; charset=utf8'}
- requests.post(url, headers=headers, data=json.dumps(msg))
- def _handle_user_command(self):
- data = request.get_json()
- self._log += "Data from handle decorator: \n %s" % data
- if data['text'] != "!status":
- status = "Supported command list: !status"
- self.send_message_user(status)
- else:
- # Request to ZabbixAPI
- alerts = self._z_connect.do_request('trigger.get',
- {
- "filter": {"value": "1"},
- 'output': 'extend',
- 'selectHosts': 'extend',
- 'sortfield': 'lastchange',
- 'monitored': 'true',
- 'only_true': 'true',
- 'maintenance': 'false'
- })
- alerts_json = json.dumps(alerts)
- item_dict = json.loads(alerts_json)
- counter_alerts = len(item_dict['result'])
- self._log += "Count alerts number: %s \n" % counter_alerts
- start_count = 0
- while start_count < counter_alerts:
- self._log += "Start cycle send messages to user: \n"
- status = str(alerts.get("result")[(start_count)].get("description") + ' - FAIL')
- self._log += "Alert: %s \n" % status
- self.send_message_user(status)
- start_count = start_count + 1
- return 'success'
- def _listen_zabbix(self):
- data = request.get_json()
- self._log += "Data from Zabbix listen decorator: \n %s" % data
- message = "%s1 %s2" % (data['description'], data['status'])
- # Static variables
- # Zabbix API
- zabbix_api_url = "https://zabbix.contora.com/zabbix"
- zabbix_api_user = "user"
- zabbix_api_password = "xxxxxxxxxx"
- # MS Bot Framework
- ms_app_id = 'xxxxxxxxxxxxxxx'
- ms_app_password = 'xxxxxxxxxxx'
- ms_session_token = {}
- # Init class
- isb = SkypeBot(zabbix_api_url, zabbix_api_user, zabbix_api_password, ms_app_id, ms_app_password, ms_session_token)
- # Decorators
- @bot.route('/bot/status', methods=['GET'])
- def version():
- return "ACTIVE"
- @bot.route('/bot/endpoint', methods=['GET', 'POST'])
- def handle_endpoint():
- result = isb._handle_user_command()
- return result
- @bot.route('/bot/zabbix', methods=['GET', 'POST'])
- def listen_zabbix_events():
- return "Zabbix listener"
- if __name__ == '__main__':
- bot.run(host='0.0.0.0', port=9000, ssl_context=None)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement