Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2017
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.64 KB | None | 0 0
  1. # Prereq:
  2. # PIP3 packages for app server
  3. # apt-get install python3-pip
  4. # pip3 install uwsgi flask requests py-zabbix
  5.  
  6. # Nginx config locations
  7. # location /bot/endpoint {
  8. #    proxy_pass http://127.0.0.1:9000;
  9. # }
  10. #
  11. # location /bot/status {
  12. #    proxy_pass http://127.0.0.1:9000;
  13. # }
  14. #
  15. # location /bot/zabbix {
  16. #    proxy_pass http://127.0.0.1:9000;
  17. # }
  18.  
  19. # -*- coding: utf-8 -*-
  20. import time
  21. import requests
  22. import json
  23. from pyzabbix import ZabbixAPI
  24. from flask import request, Flask
  25.  
  26. # Flask apps
  27. bot = Flask(__name__)
  28.  
  29.  
  30. class SkypeBot:
  31.     def __init__(self, api_url, api_user, api_password, app_id, app_password, session_token):
  32.         self._z_connect = ZabbixAPI(url=str(api_url), user=str(api_user), password=str(api_password))
  33.         self._app_id = app_id
  34.         self._app_password = app_password
  35.         self._session_token = session_token
  36.         self._log = ""
  37.  
  38.     def _get_ms_token(self):
  39.         payload = {'grant_type': 'client_credentials',
  40.                    'client_id': self._app_id,
  41.                    'client_secret': self._app_password,
  42.                    'scope': 'https://api.botframework.com/.default',
  43.                    }
  44.         self._token = requests.post('https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token', data=payload).content
  45.         self._session_token = json.loads(str(self._token)[2:-1])
  46.         self._log += "Session token: %s \n" % (self._session_token)
  47.         return json.loads(str(self._token)[2:-1])
  48.  
  49.     def _send_ms_token_to_connector(self, token):
  50.         url = 'https://groupme.botframework.com/v3/conversations'
  51.         headers = {'Authorization': 'Bearer ' + token}
  52.         print(headers)
  53.         ms_auth_response = requests.post(url, headers=headers)
  54.         print(ms_auth_response)
  55.         self._log += "Response auth request: %s \n" % (ms_auth_response)
  56.         return ms_auth_response
  57.  
  58.     def get_and_verify_ms_token(self):
  59.         while True:
  60.             token = self._get_ms_token()
  61.             self._send_ms_token_to_connector(token['access_token'])
  62.             time.sleep(token['expires_in']*0.9)
  63.  
  64.     def send_message_user(self, text):
  65.         token = self._get_ms_token()
  66.         data = request.get_json()
  67.         self._log += "Data from send function: %s \n" % data
  68.         talk_id = data['conversation']['id']
  69.         self._log += "Talk ID: %s" % talk_id
  70.         msg = {
  71.             "type": "message",
  72.             "from": {
  73.                 "id": self._app_id,
  74.                 "name": "zabbix-cuboid"
  75.             },
  76.             "conversation": {
  77.                 "id": talk_id,
  78.             },
  79.             "text": text,
  80.         }
  81.         url = data['serviceUrl'] + '/v3/conversations/{}/activities/'.format(data['conversation']['id'])
  82.         self._log += "URL for conversation: %s" % url
  83.         headers = {'Authorization': 'Bearer ' + token['access_token'],
  84.                    'content-type': 'application/json; charset=utf8'}
  85.         requests.post(url, headers=headers, data=json.dumps(msg))
  86.  
  87.     def _handle_user_command(self):
  88.         data = request.get_json()
  89.         self._log += "Data from handle decorator: \n %s" % data
  90.         if data['text'] != "!status":
  91.             status = "Supported command list: !status"
  92.             self.send_message_user(status)
  93.         else:
  94.             # Request to ZabbixAPI
  95.             alerts = self._z_connect.do_request('trigger.get',
  96.                                                 {
  97.                                                     "filter": {"value": "1"},
  98.                                                     'output': 'extend',
  99.                                                     'selectHosts': 'extend',
  100.                                                     'sortfield': 'lastchange',
  101.                                                     'monitored': 'true',
  102.                                                     'only_true': 'true',
  103.                                                     'maintenance': 'false'
  104.                                                 })
  105.             alerts_json = json.dumps(alerts)
  106.             item_dict = json.loads(alerts_json)
  107.             counter_alerts = len(item_dict['result'])
  108.             self._log += "Count alerts number: %s \n" % counter_alerts
  109.             start_count = 0
  110.             while start_count < counter_alerts:
  111.                 self._log += "Start cycle send messages to user: \n"
  112.                 status = str(alerts.get("result")[(start_count)].get("description") + ' - FAIL')
  113.                 self._log += "Alert: %s \n" % status
  114.                 self.send_message_user(status)
  115.                 start_count = start_count + 1
  116.         return 'success'
  117.  
  118.     def _listen_zabbix(self):
  119.         data = request.get_json()
  120.         self._log += "Data from Zabbix listen decorator: \n %s" % data
  121.         message = "%s1 %s2" % (data['description'], data['status'])
  122.  
  123.  
  124. # Static variables
  125. # Zabbix API
  126. zabbix_api_url = "https://zabbix.contora.com/zabbix"
  127. zabbix_api_user = "user"
  128. zabbix_api_password = "xxxxxxxxxx"
  129.  
  130. # MS Bot Framework
  131. ms_app_id = 'xxxxxxxxxxxxxxx'
  132. ms_app_password = 'xxxxxxxxxxx'
  133. ms_session_token = {}
  134.  
  135. # Init class
  136. isb = SkypeBot(zabbix_api_url, zabbix_api_user, zabbix_api_password, ms_app_id, ms_app_password, ms_session_token)
  137.  
  138.  
  139. # Decorators
  140. @bot.route('/bot/status', methods=['GET'])
  141. def version():
  142.     return "ACTIVE"
  143.  
  144.  
  145. @bot.route('/bot/endpoint', methods=['GET', 'POST'])
  146. def handle_endpoint():
  147.     result = isb._handle_user_command()
  148.     return result
  149.  
  150.  
  151. @bot.route('/bot/zabbix', methods=['GET', 'POST'])
  152. def listen_zabbix_events():
  153.     return "Zabbix listener"
  154.  
  155.  
  156. if __name__ == '__main__':
  157.     bot.run(host='0.0.0.0', port=9000, ssl_context=None)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement