1 | #!/usr/bin/env python |
---|
2 | # -*- coding: utf-8 -*- |
---|
3 | # |
---|
4 | # Post error tickets to slack on a 5 minute schedule. |
---|
5 | # |
---|
6 | # Proper use depends on having created a web-hook through Slack, and having set |
---|
7 | # that value in your app's model as the value of global_settings.slack_hook. |
---|
8 | # Details on creating web-hooks can be found at https://slack.com/integrations |
---|
9 | # |
---|
10 | # requires the Requests module for posting to slack, other requirements are |
---|
11 | # standard or provided by web2py |
---|
12 | # |
---|
13 | # Usage (on Unices), replace myapp with the name of your application and run: |
---|
14 | # nohup python web2py.py -S myapp -M -R scripts/tickets2slack.py & |
---|
15 | |
---|
16 | import sys |
---|
17 | import os |
---|
18 | import time |
---|
19 | import pickle |
---|
20 | import json |
---|
21 | |
---|
22 | try: |
---|
23 | import requests |
---|
24 | except ImportError as e: |
---|
25 | print("missing module 'Requests', aborting.") |
---|
26 | sys.exit(1) |
---|
27 | |
---|
28 | from gluon import URL |
---|
29 | from gluon.utils import md5_hash |
---|
30 | from gluon.restricted import RestrictedError |
---|
31 | from gluon.settings import global_settings |
---|
32 | |
---|
33 | |
---|
34 | path = os.path.join(request.folder, 'errors') |
---|
35 | sent_errors_file = os.path.join(path, 'slack_errors.pickle') |
---|
36 | hashes = {} |
---|
37 | if os.path.exists(sent_errors_file): |
---|
38 | try: |
---|
39 | with open(sent_errors_file, 'rb') as f: |
---|
40 | hashes = pickle.load(f) |
---|
41 | except Exception as _: |
---|
42 | pass |
---|
43 | |
---|
44 | # ## CONFIGURE HERE |
---|
45 | SLEEP_MINUTES = 5 |
---|
46 | ALLOW_DUPLICATES = False |
---|
47 | global_settings.slack_hook = global_settings.slack_hook or \ |
---|
48 | 'https://hooks.slack.com/services/your_service' |
---|
49 | # ## END CONFIGURATION |
---|
50 | |
---|
51 | while 1: |
---|
52 | for file_name in os.listdir(path): |
---|
53 | if file_name == 'slack_errors.pickle': |
---|
54 | continue |
---|
55 | |
---|
56 | if not ALLOW_DUPLICATES: |
---|
57 | key = md5_hash(file_name) |
---|
58 | if key in hashes: |
---|
59 | continue |
---|
60 | hashes[key] = 1 |
---|
61 | |
---|
62 | error = RestrictedError() |
---|
63 | |
---|
64 | try: |
---|
65 | error.load(request, request.application, file_name) |
---|
66 | except Exception as _: |
---|
67 | continue # not an exception file? |
---|
68 | |
---|
69 | url = URL(a='admin', f='ticket', args=[request.application, file], |
---|
70 | scheme=True) |
---|
71 | payload = json.dumps(dict(text="Error in %(app)s.\n%(url)s" % |
---|
72 | dict(app=request.application, url=url))) |
---|
73 | |
---|
74 | requests.post(global_settings.slack_hook, data=dict(payload=payload)) |
---|
75 | |
---|
76 | with open(sent_errors_file, 'wb') as f: |
---|
77 | pickle.dump(hashes, f) |
---|
78 | time.sleep(SLEEP_MINUTES * 60) |
---|