-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatrix_bot_logic_redmine.py_requests
executable file
·234 lines (204 loc) · 7.13 KB
/
matrix_bot_logic_redmine.py_requests
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# A simple chat client for matrix.
# This sample will allow you to connect to a room, and send/recieve messages.
# Args: host:port username password room
# Error Codes:
# 1 - Unknown problem has occured
# 2 - Could not find the server.
# 3 - Bad URL Format.
# 4 - Bad username/password.
# 11 - Wrong room format.
# 12 - Couldn't find room.
import sys
import logging
import time
import datetime
import json
import os
import re
import requests
import traceback
import matrix_bot_api as mba
import matrix_bot_logic as mbl
import config as conf
from matrix_client.api import MatrixRequestError
from pyzabbix import ZabbixAPI
def ra_attach_file_to_issue(log,issue_id,filename,file_data):
# скачиваем список проектов:
data = post_redmine_api_file(log,filename, file_data)
token=None
if "upload" in data:
if "token" in data["upload"]:
token=data["upload"]["token"]
return data
def ra_get_users(log):
# скачиваем список проектов:
data = get_redmine_api(log,"users")
return data
def ra_get_projects(log):
# скачиваем список проектов:
data = get_redmine_api(log,"projects")
return data
def ra_create_user(log, data):
# создаём "пользователя" в redmine:
ret = post_redmine_api(log,"users",{"user":data})
if ret == None:
log.error("post_redmine_api('users')")
return None
if "errors" in ret:
log.warning("error create user: %s"%str(ret["errors"]))
return None
else:
return ret["user"]["id"]
def ra_create_issue(log, data):
# создаём "ошибку" в redmine:
ret = post_redmine_api(log,"issues",{"issue":data})
if ret == None:
log.error("post_redmine_api('issues')")
return None
if "errors" in ret:
log.warning("error create issue: %s"%str(ret["errors"]))
return None
else:
return ret["issue"]["id"]
def redmine_test(log):
# скачиваем список проектов:
#all_issues = get_redmine_api(log,"projects")
# log.debug("%s"%(json.dumps(all_issues, indent=4, sort_keys=True,ensure_ascii=False)))
# return True
# скачиваем список ошибок:
# all_users = ra_get_users(log)
# log.debug("%s"%(json.dumps(all_users, indent=4, sort_keys=True,ensure_ascii=False)))
#return True
user={}
user["login"]="svc_odsa_340-00"
user["firstname"]="svc_ODSA_340-00"
user["lastname"]="неизвестно"
user["mail"]="[email protected]"
user["auth_source_id"]=1
user_id=ra_create_user(log,user)
if user_id == None:
log.error("ra_create_user()")
return False
else:
log.info("создал пользователя: http://redmine.prim.drsk.ru/users/%d"%user_id)
return True
# скачиваем список ошибок:
all_issues = get_redmine_api(log,"issues")
log.debug("%s"%(json.dumps(all_issues, indent=4, sort_keys=True,ensure_ascii=False)))
return True
# all_projects = ra_get_projects(log)
# log.debug("%s"%(json.dumps(all_projects, indent=4, sort_keys=True,ensure_ascii=False)))
issue={}
issue["project_id"]=1
issue["subject"]="тестовая задача от бота"
issue["description"]="создана через питон"
issue_id=ra_create_issue(log,issue)
if issue_id == None:
log.error("ra_create_issue()")
return False
else:
log.info("создал ошибку: http://redmine.prim.drsk.ru/issues/%d"%issue_id)
return True
def get_redmine_api(log,request_name):
# request_name: projects, users, issues и т.п. (см. https://www.redmine.org/projects/redmine/wiki/Rest_api )
try:
url="%(redmine_server)s/%(request_name)s.json?key=%(redmine_api_access_key)s"%{\
"redmine_server":conf.redmine_server,\
"request_name":request_name,\
"redmine_api_access_key":conf.redmine_api_access_key}
data = get_url_json(log,url)
except Exception as e:
log.error(get_exception_traceback_descr(e))
return None
return data
def post_redmine_api_file(log,filename,file_data):
# request_name: projects, users, issues и т.п. (см. https://www.redmine.org/projects/redmine/wiki/Rest_api )
request_name="uploads"
try:
url="%(redmine_server)s/%(request_name)s.json?key=%(redmine_api_access_key)s&filename=%(filename)s"%{\
"redmine_server":conf.redmine_server,\
"request_name":request_name,\
"filename":filename,\
"redmine_api_access_key":conf.redmine_api_access_key}
data = post_url_binary_data(log,url,data)
except Exception as e:
log.error(get_exception_traceback_descr(e))
return None
return data
def post_redmine_api(log,request_name,json_data):
# request_name: projects, users, issues и т.п. (см. https://www.redmine.org/projects/redmine/wiki/Rest_api )
try:
url="%(redmine_server)s/%(request_name)s.json?key=%(redmine_api_access_key)s"%{\
"redmine_server":conf.redmine_server,\
"request_name":request_name,\
"redmine_api_access_key":conf.redmine_api_access_key}
data = post_url_json(log,url,json_data)
except Exception as e:
log.error(get_exception_traceback_descr(e))
return None
return data
def get_url_json(log,url):
data = get_url_data(log,url)
if data == None:
log.error("get_url_json: get_url_data() return None")
return None
try:
json_data = json.loads(data.decode('utf8'))
except Exception as e:
log.error("get_url_json: parse json with error: '%s' from url: %s"%(e,url))
return None
return json_data
def get_url_data(log,url):
try:
response = requests.get(url, stream=True)
data = response.content # a `bytes` object
except Exception as e:
log.error("get_url_data: requests.get(%s) exception: %s"%(url,e))
return None
return data
def post_url_binary_data(log,url,data):
try:
files = {'upload_file': data}
response = requests.post(url, files=files)
except Exception as e:
log.error("post_url_binary_data: requests.post(%s,data) exception: %s"%(url,e))
return None
return response.json()
def post_url_json(log,url,data):
try:
response = requests.post(url, json=data)
except Exception as e:
log.error("post_url_json: requests.post(%s,data) exception: %s"%(url,e))
return None
return response.json()
def get_exception_traceback_descr(e):
tb_str = traceback.format_exception(etype=type(e), value=e, tb=e.__traceback__)
result=""
for msg in tb_str:
result+=msg
return result
if __name__ == '__main__':
log=logging.getLogger("matrix_bot_logic_zabbix")
if conf.debug:
log.setLevel(logging.DEBUG)
else:
log.setLevel(logging.INFO)
# create the logging file handler
fh = logging.FileHandler(conf.log_path_bot)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(filename)s:%(lineno)d - %(funcName)s() %(levelname)s - %(message)s')
fh.setFormatter(formatter)
if conf.debug:
# логирование в консоль:
#stdout = logging.FileHandler("/dev/stdout")
stdout = logging.StreamHandler(sys.stdout)
stdout.setFormatter(formatter)
log.addHandler(stdout)
# add handler to logger object
log.addHandler(fh)
log.info("Program started")
if redmine_test(log) == False:
log.error("error redmine_test()")
sys.exit(1)
log.info("Program exit!")