3 Script for running a simple bot.
7 from urllib.parse import urljoin
8 from urllib.request import Request, urlopen
12 def __init__(self, base_url, token):
13 self.base_url = base_url
16 def request(self, url, method='GET', data=None):
17 url = urljoin(self.base_url, url)
19 data = json.dumps(data).encode('utf-8')
24 "Content-type": "application/json",
27 headers['Authorization'] = 'Token ' + self.token
29 req = Request(url, data=data, method=method, headers=headers)
32 except Exception as e:
34 print(e.read().decode('utf-8'))
37 return json.load(resp)
40 me = self.request('me/')['id']
41 return self.request('documents/chunks/?user={}'.format(me))
44 def process_chunk(chunk, api, executable):
47 text = api.request(head)['text']
48 text = text.encode('utf-8')
57 except subprocess.CalledProcessError as e:
58 print('Ditching the update. Bot exited with error code {} and output:'.format(e.returncode))
59 print(e.stderr.decode('utf-8'))
61 result_text = p.stdout.decode('utf-8')
62 stderr_text = p.stderr.decode('utf-8')
63 api.request(chunk['revisions'], 'POST', {
65 "description": stderr_text or 'Automatic update.',
68 # Remove the user assignment.
69 api.request(chunk['id'], 'PUT', {
74 if __name__ == '__main__':
76 parser = argparse.ArgumentParser(
77 description='Runs a bot for Redakcja. '
78 'You need to provide an executable which will take current revision '
79 'of text as stdin, and output the new version on stdout. '
80 'Any output given on stderr will be used as revision description. '
81 'If bot exits with non-zero return code, the update will be ditched.'
84 'token', metavar='TOKEN', help='A Redakcja API token.'
87 'executable', metavar='EXECUTABLE', help='An executable to run as bot.'
90 '--api', metavar='API', help='A base URL for the API.',
91 default='https://redakcja.wolnelektury.pl/api/',
93 args = parser.parse_args()
96 api = API(args.api, args.token)
98 chunks = api.my_chunks()
100 for chunk in api.my_chunks():
101 process_chunk(chunk, api, args.executable)
103 print('No assigned chunks found.')