executable_cerb 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. #! /usr/bin/env cached-nix-shell
  2. #! nix-shell -i python3 -p "with import (builtins.fetchTarball {url = "https://github.com/nixos/nixpkgs/archive/8686922e68dfce2786722acad9593ad392297188.tar.gz";}) {overlays = [(self: super: {cerb = (with super; python3.pkgs.buildPythonPackage rec {pname = \"cerbapi\"; version = \"1.0.9\"; src = python3.pkgs.fetchPypi {inherit pname version; sha256 = \"1c5xahjfb60vrwn7hj0n4s66dyzsx81gai7af564n8pkbdylcz37\";}; doCheck = false;});})];}; python3.withPackages (ps: with ps; [ cerb pydbus notify2 pymysql pyopenssl slackclient ])"
  3. from cerbapi import Cerb
  4. import notify2
  5. import time
  6. import os
  7. import argparse
  8. # _context: cerberusweb.contexts.ticket
  9. # _label: [#JD-43166-193] Запрос из панели AC_225134 (Тема запроса: Перестал работать сайт)
  10. # closed_at: 1587110403
  11. # closed: 1587110403
  12. # created: 1587109927
  13. # elapsed_response_first: 476
  14. # elapsed_resolution_first: 476
  15. # id: 12079330
  16. # importance: 0
  17. # mask: JD-43166-193
  18. # num_messages: 3
  19. # org_id: 0
  20. # reopen_date: 0
  21. # spam_score: 0.0001
  22. # spam_training: N
  23. # status_id: 0
  24. # subject: Запрос из панели AC_225134 (Тема запроса: Перестал работать сайт)
  25. # updated: 1587112328
  26. # status: open
  27. # url: https://cerberus.intr/index.php/profiles/ticket/JD-43166-193
  28. # group_id: 31
  29. # bucket_id: 27
  30. # initial_message_id: 14812768
  31. # initial_response_message_id: 14812861
  32. # latest_message_id: 14812903
  33. # owner_id: 0
  34. class Cerberus:
  35. def __init__(self):
  36. try:
  37. self.cerberus_key = os.environ['CERBERUS_KEY']
  38. self.cerberus_secret = os.environ['CERBERUS_SECRET']
  39. except KeyError:
  40. print("Check system environment variables CERBERUS_KEY and CERBERUS_SECRET")
  41. exit(1)
  42. self.api = Cerb(access_key=self.cerberus_key, secret=self.cerberus_secret,
  43. base="https://cerberus.intr/index.php/rest/")
  44. self.group_list = {}
  45. self._load_groups()
  46. def get_tickets(self, groups, status, count=100):
  47. groups_string = ""
  48. for i, group in enumerate(groups):
  49. if i == 0:
  50. groups_string = "("
  51. groups_string = groups_string + group
  52. if i < len(groups)-1:
  53. groups_string = groups_string + " OR "
  54. else:
  55. groups_string = groups_string + ")"
  56. result = self.api.search_records('ticket', query='group:{} status:{}'.format(groups_string, status), limit=count)
  57. return result
  58. def _load_groups(self):
  59. self.group_list = self.api.search_records('group')
  60. def get_group_by_id(self, id):
  61. for group in self.group_list['results']:
  62. if group['id'] == id:
  63. return group['name']
  64. return "Undefined"
  65. def is_valid_group(self, name):
  66. for group in self.group_list['results']:
  67. if group['name'] == name:
  68. return True
  69. return False
  70. def main():
  71. cerb = Cerberus()
  72. known_tickets = []
  73. parser = argparse.ArgumentParser(description="Cerberus notifications")
  74. parser.add_argument('-i', default=10, help='Update interval in seconds', type=int)
  75. parser.add_argument('-g', default='support@majordomo.ru,admin@majordomo.ru', help='Watching groups')
  76. args = parser.parse_args()
  77. interval_time = args.i
  78. watching_groups = args.g.split(",")
  79. for group in watching_groups:
  80. if not cerb.is_valid_group(group):
  81. print("Invalid group name: {}".format(group))
  82. exit(1)
  83. while(True):
  84. tickets = cerb.get_tickets(watching_groups, 'open')
  85. status = tickets['__status']
  86. if status != 'success':
  87. print("Error: {}".format(tickets))
  88. continue
  89. count = tickets['count']
  90. print("Ticket count: {}".format(count))
  91. result = tickets['results']
  92. actual_tickets = []
  93. for ticket in result:
  94. actual_tickets.append(ticket['id'])
  95. if ticket['id'] in known_tickets:
  96. continue
  97. notify2.init("New Tiket")
  98. n = notify2.Notification("New tiket in group {}: {}\n{}".format(
  99. cerb.get_group_by_id(ticket['group_id']),
  100. ticket['subject'],
  101. ticket['url']))
  102. n.set_urgency(notify2.URGENCY_CRITICAL) # For red notification in dunst case
  103. n.set_timeout(30000)
  104. n.show()
  105. known_tickets = actual_tickets
  106. print("Known tickets: {}".format(known_tickets))
  107. time.sleep(interval_time)
  108. if __name__ == '__main__':
  109. main()