This repository has been archived by the owner on Dec 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backup_zendesk_tickets.py
executable file
·75 lines (67 loc) · 2.46 KB
/
backup_zendesk_tickets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import requests
import datetime
import time
import os
import yaml
import logging
import json
from zendesk import Zendesk
import click
@click.command()
@click.option('--config-file', help='Path to the config file', required=True, type=click.Path(exists=True))
@click.option('--days', help='Since how many days ago to backup tickets', default=30, type=int)
def backup(config_file, days):
with open(config_file, 'r') as f:
config = yaml.load(f)
url = config.get('url')
if url is None:
logging.error("No 'url' in config_file: {}".format(config_file))
return
username = config.get('username')
if username is None:
logging.error("No 'username' in config_file: {}".format(config_file))
return
token = config.get('token')
if token is None:
logging.error("No 'token' in config_file: {}".format(config_file))
return
output_path = config.get('output_path')
if output_path is None:
logging.error("No 'output_path' in config_file: {}".format(config_file))
return
now = datetime.datetime.now()
one_month_ago = now - datetime.timedelta(days=days) # get data for the last N days
timestamp = time.mktime(one_month_ago.timetuple())
auth = ('{}/token'.format(username), token)
url = "{}/api/v2/incremental/tickets.json?start_time={}".format(url, timestamp)
logging.info('Retrieving data from {}'.format(url))
try:
r = requests.get(url, auth=auth)
except Exception as e:
logging.error("Cannot retrieve requested data from url: {}".format(url))
logging.error(str(e))
return
tickets = r.json().get('tickets')
filename = "{}.bckp.json".format(now.strftime("%Y-%m-%d_%H-%M"))
output_file = os.path.join(output_path, filename)
logging.info('Recording data to the file {}'.format(output_file))
if not os.path.exists(output_path):
try:
os.makedirs(output_path)
except Exception as e:
logging.error('Cannot create path: {}'.format(output_path))
logging.error(str(e))
return
try:
file = open(output_file, 'w+')
except Exception as e:
logging.error('Cannot open/create file: {}'.format(output_file))
logging.error(str(e))
return
try:
file.write(json.dumps(tickets))
except Exception as e:
logging.error('Cannot write to file: {}'.format(output_file))
logging.error(str(e))
if __name__ == '__main__':
backup()