The Interface of the fdb-spider, based on rocketchat
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

722 lines
35 KiB

  1. import os
  2. from rocketchat.api import RocketChatAPI
  3. import configparser
  4. import json
  5. import requests
  6. import yaml
  7. import subprocess
  8. config = configparser.ConfigParser()
  9. config.read('config.ini')
  10. botname = config['Chat']['username']
  11. botpassword = config['Chat']['password']
  12. server_url = config['Chat']['URL']
  13. room_id = config['Chat']['room_id']
  14. bot_user_id = config['Chat']['bot_user_id']
  15. spider_directory = config['Spider']['spider_directory']
  16. # here comes the functions to talk to gpt
  17. # For local streaming, the websockets are hosted without ssl - http://
  18. HOST = 'localhost:5000'
  19. URI = f'http://{HOST}/api/v1/chat'
  20. #URI = f'http://{HOST}/api'
  21. # http://192.168.9.197:5000/api/v1/chat
  22. # For reverse-proxied streaming, the remote will likely host with ssl - https://
  23. # URI = 'https://your-uri-here.trycloudflare.com/api/v1/chat'
  24. if __name__ == '__main__':
  25. api = RocketChatAPI(settings={'username': botname, 'password': botpassword, 'domain': server_url})
  26. # api.send_message('Ciao, I am the fdb-spider', room_id)
  27. #myinfo = api.get_my_info()
  28. #room_history = api.get_private_room_history(room_id)
  29. #print(room_history['messages'][0]['msg'])
  30. # print(myinfo)
  31. rooms = api.get_private_rooms()
  32. print('blubidab oioioi', rooms)
  33. # api.send_message('Ole', room_id)
  34. n = 0
  35. import time
  36. import schedule
  37. #change to False here, if you want to have the update run at server start
  38. already_updated = True
  39. start = True
  40. import datetime
  41. from datetime import timedelta
  42. while True:
  43. time.sleep(2)
  44. #already_updated = True
  45. now = datetime.datetime.now()
  46. current_hour = now.strftime("%H")
  47. #print(current_hour)
  48. # run variable update and creation at start
  49. if start == True:
  50. room_list = []
  51. rooms = os.listdir('rooms')
  52. for room in rooms:
  53. room_file = open('rooms/' + room, 'r')
  54. room_file_raw = room_file.read()
  55. room_file.close()
  56. room_file_list = room_file_raw.split('§%§%')
  57. print(room_list)
  58. print(room)
  59. print(room_file_list)
  60. room_list.append([room[:-4], room_file_list[0], room_file_list[1], room_file_list[2]])
  61. with open(spider_directory + '/spiders/config.yaml' , "r") as stream:
  62. try:
  63. config = yaml.safe_load(stream)
  64. except yaml.YAMLError as exc:
  65. print(exc)
  66. fdb_list = []
  67. #print(config)
  68. for key in config:
  69. fdb_list.append(key)
  70. start = False
  71. if int(current_hour) > 11:
  72. aftersix = True
  73. if int(current_hour) <= 11:
  74. aftersix = False
  75. already_updated = False
  76. if aftersix == True and already_updated == False and aftersix == False:
  77. room_list = []
  78. rooms = os.listdir('rooms')
  79. for room in rooms:
  80. room_file = open('rooms/' + room, 'r')
  81. room_file_raw = room_file.read()
  82. room_file.close()
  83. room_file_list = room_file_raw.split('§%§%')
  84. room_list.append([room[:-4], room_file_list[0], room_file_list[1], room_file_list[2]])
  85. with open(spider_directory + '/spiders/config.yaml' , "r") as stream:
  86. try:
  87. config = yaml.safe_load(stream)
  88. except yaml.YAMLError as exc:
  89. print(exc)
  90. fdb_list = []
  91. #print(config)
  92. for key in config:
  93. fdb_list.append(key)
  94. data = dict({})
  95. for room in room_list:
  96. print(room[0])
  97. room_fdbs = room[2]
  98. room_tags = room[3]
  99. #subprocess.run(["python", spider_directory + 'main.py', fdbs])
  100. room_history_list = []
  101. try:
  102. room_history_file = open('roomhistories/' + room[0] + '.txt', 'x')
  103. room_history_file.close()
  104. except:
  105. print('reading from roomhistory')
  106. with open('roomhistories/' + room[0] + '.txt') as room_history_file:
  107. lines = room_history_file.readlines()
  108. for line in lines:
  109. room_history_list.append(line)
  110. #date = datetime.datetime.now() - timedelta(days=3)
  111. #room_history = api.get_room_history(room[0], oldest=date, latest=datetime.datetime.now())
  112. for room_fdb in eval(room_fdbs):
  113. #print('room_fdb',room_fdb, 'fdb_list',fdb_list)
  114. try:
  115. iteration_var_list = config.get(room_fdb).get("entry-list").get("iteration-var-list")
  116. except Exception as e:
  117. print('there was an error with the entry-list parameter in the config regarding the fdb ', room_fdb)
  118. if room_fdb in fdb_list and room_fdb not in [key for key in data]:
  119. iterdict = {}
  120. for i in eval(iteration_var_list):
  121. f = open(spider_directory + "/spiders/output/" + room_fdb + str(i) + "entryList.txt")
  122. text = f.read()
  123. dictionary_entry_list = eval(text)
  124. iterdict[i] = dictionary_entry_list
  125. data[room_fdb] = iterdict
  126. for i in eval(iteration_var_list):
  127. try:
  128. print(room_fdb, i)
  129. for key in data[room_fdb][i]:
  130. contains_tag = False
  131. name_data_lower = [word.lower() for word in data[room_fdb][i][key]["name"].split(' ')]
  132. info_data_lower = [word.lower() for word in data[room_fdb][i][key]["info"].split(' ')]
  133. text_data_lower = [word.lower() for word in data[room_fdb][i][key]["text"].split(' ')]
  134. tag_list = []
  135. for tag in eval(room_tags):
  136. if '_' in tag:
  137. ntags = tag.split('_')
  138. ntags_length = len(ntags)
  139. ntag_count = 0
  140. for nword in name_data_lower:
  141. for ntag in ntags:
  142. if ntag.lower() in nword:
  143. ntag_count += 1
  144. if ntag_count == ntags_length:
  145. contains_tag = True
  146. tag_list.append(tag + ' in name')
  147. ntag_count = 0
  148. for iword in info_data_lower:
  149. for ntag in ntags:
  150. if ntag.lower() in iword:
  151. ntag_count += 1
  152. if ntag_count == ntags_length:
  153. contains_tag = True
  154. tag_list.append(tag + ' in info')
  155. ntag_count = 0
  156. for tword in text_data_lower:
  157. ntag_count = 0
  158. for ntag in ntags:
  159. if ntag.lower() in tword:
  160. ntag_count += 1
  161. if ntag_count == ntags_length:
  162. contains_tag = True
  163. tag_list.append(tag + ' in text')
  164. else:
  165. for nword in name_data_lower:
  166. if tag.lower() in nword:
  167. contains_tag = True
  168. tag_list.append(tag + ' in name')
  169. for iword in info_data_lower:
  170. if tag.lower() in iword:
  171. contains_tag = True
  172. tag_list.append(tag + ' in info')
  173. for tword in text_data_lower:
  174. if tag.lower() in tword:
  175. contains_tag = True
  176. tag_list.append(tag + ' in text')
  177. if contains_tag == True:
  178. try:
  179. url = data[room_fdb][i][key]["domain"]
  180. except:
  181. url = data[room_fdb][i][key]["link"]
  182. entry_message = '<' + url + '|' + data[room_fdb][i][key]["name"]+ '>' + '\n' + data[room_fdb][i][key]["info"] + '\n' + str(tag_list)
  183. entry_message_identifier = '<' + url + '|' + data[room_fdb][i][key]["name"]+ '>'
  184. message_was_already_there = False
  185. for message in room_history_list:
  186. print('message that gets checked with identifier ', message[:-1])
  187. print('the entry message identifier is:', entry_message_identifier)
  188. if url in message[:-1] or data[room_fdb][i][key]["name"] in message:
  189. message_was_already_there = True
  190. if message_was_already_there == False:
  191. print('went into already there false')
  192. api.send_message(entry_message, room[0])
  193. print('before writing')
  194. try:
  195. room_file = open('roomhistories/' + room[0] + '.txt', 'x')
  196. room_file.close()
  197. except:
  198. print('appending to roomhistory')
  199. room_file = open('roomhistories/' + room[0] + '.txt', 'a')
  200. room_file.write(entry_message_identifier + '\n')
  201. room_file.close()
  202. print('after writing')
  203. except Exception as e:
  204. print("probably i was not there in last page, original error is:", e)
  205. #print('data',data['giz'][2],'data')
  206. already_updated = True
  207. # if datestime.split over etc and updated= true etc
  208. n += 1
  209. if n%100 == 0:
  210. print(n)
  211. try:
  212. #print('getting the room history')
  213. date = datetime.datetime.now() - timedelta(days=3)
  214. room_history = api.get_private_room_history(room_id, oldest=date)
  215. except Exception as e:
  216. time.sleep(10)
  217. api = RocketChatAPI(settings={'username': botname, 'password': botpassword, 'domain': server_url})
  218. time.sleep(5)
  219. room_history = api.get_private_room_history(room_id, oldest=date)
  220. print('got a connection error, original message is:',e)
  221. messages_list = []
  222. for message in room_history['messages']:
  223. messages_list.append(message)
  224. if len(messages_list) >= 1:
  225. #print('blub', messages_list)
  226. latest_message_user_id = messages_list[0]['u']['_id']
  227. latest_message_user_username = messages_list[0]['u']['username']
  228. latest_message = messages_list[0]['msg']
  229. latest_message_id = messages_list[0]['_id']
  230. new_message_file = open('new_message_file.txt', 'r')
  231. new_message = new_message_file.read()
  232. new_message_file.close()
  233. new_message_list = new_message.split('§%§%')
  234. #print(latest_message, new_message_list[0])
  235. if new_message_list[0] != latest_message and new_message_list[1] != latest_message_id and latest_message_user_id != bot_user_id:
  236. answer = 'Ich habe kein Kommando erhalten.'
  237. new_message_file = open('new_message_file.txt', 'w')
  238. new_message_file.write(latest_message + '§%§%' + latest_message_id)
  239. new_message_file.close()
  240. user_input = latest_message
  241. user_input_list = user_input.split(' ')
  242. if user_input_list[0] == 'addtags':
  243. try:
  244. room_id_add_tags = user_input_list[1]
  245. except:
  246. room_id_add_tags = 'NONE'
  247. try:
  248. new_tags = user_input_list[2]
  249. except:
  250. new_tags = 'NONE'
  251. try:
  252. thirdarg = user_input_list[3]
  253. except:
  254. thirdarg = 'NONE'
  255. if len(room_id_add_tags) >= 1 and len(new_tags) >= 1 and thirdarg == 'NONE':
  256. try:
  257. room_file_add_tags = open('rooms/' + user_input_list[1] + '.txt', 'r')
  258. room_info_raw = room_file_add_tags.read()
  259. room_file_add_tags.close()
  260. room_info = room_info_raw.split('§%§%')
  261. tag_list = eval(room_info[-1])
  262. for tag in eval(user_input_list[2]):
  263. if tag not in tag_list:
  264. tag_list.append(tag)
  265. room_file_add_tags = open('rooms/' + user_input_list[1] + '.txt', 'w')
  266. room_file_add_tags.write( str(room_info[0]) + '§%§%' + str(room_info[1]) + '§%§%' + str(tag_list))
  267. room_file_add_tags.close()
  268. answer = 'the updated tag list is' + str(tag_list)
  269. except Exception as e:
  270. print('error opening, original error is:', e)
  271. answer = "The room_id to update the tags was not found"
  272. if user_input_list[0] == 'printtags':
  273. try:
  274. room_id_to_print_tags = user_input_list[1]
  275. except:
  276. answer = "after the command printtags, the second argument has to be the room id.. use printrooms and look up the id of the room you want to print the tags"
  277. room_id_to_print_tags = 'NONE'
  278. if room_id_to_print_tags != 'NONE':
  279. try:
  280. room_file = open('rooms/' + room_id_to_print_tags + '.txt', 'r')
  281. room_info_raw = room_file.read()
  282. room_file.close()
  283. room_info = room_info_raw.split('§%§%')
  284. tag_list = eval(room_info[-1])
  285. answer = tag_list
  286. except Exception as e:
  287. print('error opening, original error is:', e)
  288. answer = "The room_id to get the tags was not found"
  289. if user_input_list[0] == 'printcommands':
  290. answer = """
  291. To print all available rooms and their configuration, use
  292. command : `printrooms`
  293. -----------------------------------------------------------------------------------------
  294. To print all available fdbs, use
  295. command : `printfdbs`
  296. -----------------------------------------------------------------------------------------
  297. To update all rooms use
  298. command : `updaterooms`
  299. -----------------------------------------------------------------------------------------
  300. To update one room use the room_id from the output of printrooms:
  301. command : `updaterooms <room-id>`
  302. example : `updaterooms 6572012bebb39dd248d08320`
  303. -----------------------------------------------------------------------------------------
  304. To create a room use following command, but be sure to not have spaces in your lists,
  305. as a space indicates a new command argument:
  306. command : `createroom <room-name> <list-fdbs> <list-tags>`
  307. example : `createroom room-test-1 ['giz','fdb2'] ['tag1','tag2','tag3']`
  308. -----------------------------------------------------------------------------------------
  309. To delete a room use
  310. command : `deleteroom <room-id>`
  311. example : `deleteroom 6572012bebb39dd248d08320`
  312. -----------------------------------------------------------------------------------------
  313. To print the tags of a room use
  314. command : `printtags <room-id>`
  315. example : `printtags 6572012bebb39dd248d08320`
  316. -----------------------------------------------------------------------------------------
  317. To add tags to the existing tags use
  318. command : `addtags <room-id> <tag-list-without-spaces>`
  319. example : `addtags 6572012bebb39dd248d08320 ['tag1','tag2','tag3']`
  320. """
  321. if user_input_list[0] == 'printrooms':
  322. room_was_found = False
  323. # get all the rooms
  324. import os
  325. room_list = []
  326. rooms = os.listdir('rooms')
  327. for room in rooms:
  328. room_file = open('rooms/' + room, 'r')
  329. room_file_raw = room_file.read()
  330. room_file.close()
  331. room_file_list = room_file_raw.split('§%§%')
  332. room_list.append([room[:-4], room_file_list[0], room_file_list[1], room_file_list[2]])
  333. #print(room_list)
  334. answer = str(room_list)
  335. if user_input_list[0] == 'updaterooms':
  336. try:
  337. if len(user_input_list[1]) >= 1:
  338. room_to_update = user_input_list[1]
  339. except Exception as e:
  340. room_to_update = 'NONE'
  341. room_list = []
  342. rooms = os.listdir('rooms')
  343. for room in rooms:
  344. room_file = open('rooms/' + room, 'r')
  345. room_file_raw = room_file.read()
  346. room_file.close()
  347. room_file_list = room_file_raw.split('§%§%')
  348. room_list.append([room[:-4], room_file_list[0], room_file_list[1], room_file_list[2]])
  349. with open(spider_directory + '/spiders/config.yaml' , "r") as stream:
  350. try:
  351. config = yaml.safe_load(stream)
  352. except yaml.YAMLError as exc:
  353. print(exc)
  354. fdb_list = []
  355. #print(config)
  356. for key in config:
  357. fdb_list.append(key)
  358. answer = "Ich update die Rooms auf Basis der Daten von heute morgen um 6 Uhr.."
  359. data = dict({})
  360. for room in room_list:
  361. if room[0] == room_to_update or room_to_update == 'NONE':
  362. room_was_found = True
  363. print(room[0])
  364. room_fdbs = room[2]
  365. room_tags = room[3]
  366. # not running get_rooms because disfunctional
  367. #subprocess.run(["python", spider_directory + 'main.py', fdbs])
  368. #myinfo = api.get_room_info(room[0])
  369. #print(myinfo)
  370. #roomid = "'657cbeccebb39dd248d38ec3'"
  371. #roomoioioi = api.get_user_info(bot_user_id)
  372. #print(roomoioioi)
  373. #room_history_updateroom = api.get_private_room_history(room[0])
  374. # reading from txt state history instead
  375. try:
  376. room_history_file = open('roomhistories/' + room[0] + '.txt', 'x')
  377. room_history_file.close()
  378. except:
  379. print('reading from roomhistory which is already there')
  380. room_history_list = []
  381. with open('roomhistories/' + room[0] + '.txt') as room_history_file:
  382. lines = room_history_file.readlines()
  383. for line in lines:
  384. room_history_list.append(line)
  385. #
  386. #for message in room_history_raw:
  387. # print(message)
  388. for room_fdb in eval(room_fdbs):
  389. #print('room_fdb',room_fdb, 'fdb_list',fdb_list)
  390. try:
  391. iteration_var_list = config.get(room_fdb).get("entry-list").get("iteration-var-list")
  392. except Exception as e:
  393. print('there was an error with the entry-list parameter in the config regarding the fdb ', room_fdb)
  394. if room_fdb in fdb_list and room_fdb not in [key for key in data]:
  395. iterdict = {}
  396. for i in eval(iteration_var_list):
  397. f = open(spider_directory + "/spiders/output/" + room_fdb + str(i) + "entryList.txt")
  398. text = f.read()
  399. dictionary_entry_list = eval(text)
  400. iterdict[i] = dictionary_entry_list
  401. data[room_fdb] = iterdict
  402. for i in eval(iteration_var_list):
  403. try:
  404. print(room_fdb, i)
  405. for key in data[room_fdb][i]:
  406. contains_tag = False
  407. name_data_lower = [word.lower() for word in data[room_fdb][i][key]["name"].split(' ')]
  408. info_data_lower = [word.lower() for word in data[room_fdb][i][key]["info"].split(' ')]
  409. text_data_lower = [word.lower() for word in data[room_fdb][i][key]["text"].split(' ')]
  410. tag_list = []
  411. for tag in eval(room_tags):
  412. if '_' in tag:
  413. ntags = tag.split('_')
  414. ntags_length = len(ntags)
  415. ntag_count = 0
  416. for nword in name_data_lower:
  417. for ntag in ntags:
  418. if ntag.lower() in nword and nword != '':
  419. ntag_count += 1
  420. if ntag_count == ntags_length:
  421. contains_tag = True
  422. tag_list.append(ntags.join('_') + ' in name')
  423. ntag_count = 0
  424. for iword in info_data_lower:
  425. for ntag in ntags:
  426. if ntag.lower() in iword and iword != '':
  427. ntag_count += 1
  428. if ntag_count == ntags_length:
  429. contains_tag = True
  430. tag_list.append(ntags.join('_') + ' in info')
  431. ntag_count = 0
  432. for tword in text_data_lower:
  433. ntag_count = 0
  434. for ntag in ntags:
  435. if ntag.lower() in tword and tword != '':
  436. ntag_count += 1
  437. if ntag_count == ntags_length:
  438. contains_tag = True
  439. tag_list.append(ntags.join('_') + ' in text')
  440. else:
  441. #print('------------------')
  442. #print(name_data_lower, info_data_lower, text_data_lower, room[0], room_tags)
  443. for nword in name_data_lower:
  444. if tag.lower() in nword and nword != '':
  445. contains_tag = True
  446. if contains_tag == True:
  447. tag_list.append(tag + ' in name')
  448. for iword in info_data_lower:
  449. if tag.lower() in iword and iword != '':
  450. contains_tag = True
  451. if contains_tag == True:
  452. tag_list.append(tag + ' in info')
  453. for tword in text_data_lower::
  454. if tag.lower() in tword and tword != '':
  455. contains_tag = True
  456. if contains_tag == True:
  457. tag_list.append(tag + ' in text')
  458. if contains_tag == True:
  459. print('------------------')
  460. print(name_data_lower, info_data_lower, text_data_lower)
  461. try:
  462. url = data[room_fdb][i][key]["domain"]
  463. except:
  464. url = data[room_fdb][i][key]["link"]
  465. print('101110001101010010010101000111')
  466. entry_message = '<' + url + '|' + data[room_fdb][i][key]["name"]+ '>' + '\n' + data[room_fdb][i][key]["info"] + '\n' + str(tag_list)
  467. entry_message_identifier = '<' + url + '|' + data[room_fdb][i][key]["name"]+ '>'
  468. message_was_already_there = False
  469. for message in room_history_list:
  470. print('message', message[:-1], 'identifier', entry_message_identifier)
  471. if url in message[:-1] or data[room_fdb][i][key]["name"] in message:
  472. message_was_already_there = True
  473. if message_was_already_there == False:
  474. api.send_message(entry_message, room[0])
  475. try:
  476. room_file = open('roomhistories/' + room[0] + '.txt', 'x')
  477. room_file.close()
  478. except:
  479. print('appending to roomhistory')
  480. room_file = open('roomhistories/' + room[0] + '.txt', 'a')
  481. room_file.write(entry_message_identifier + '\n')
  482. room_file.close()
  483. except Exception as e:
  484. print("probably i was not there in last page, original error is:", e)
  485. if room_to_update == 'NONE':
  486. answer = 'No room was specified, all rooms will get an update based on the data available'
  487. if room_was_found == False and room_to_update != 'NONE':
  488. answer = 'The room you specified does not exist, or there are no rooms configured, try the command without argument -> updaterooms'
  489. if room_was_found == True and room_to_update != 'NONE':
  490. answer = "I am updating the specified room based on the data in fdb-spider/spiders/output.."
  491. if user_input_list[0] == 'printfdbs':
  492. answer = str(fdb_list)
  493. if len(user_input_list) > 1:
  494. answer = 'Die Syntax zum Ausgeben der konfigurierten Förderdatenbanken hat einen Fehler. Versuche es erneut, mit -> printfdbs'
  495. if user_input_list[0] == 'deleteroom':
  496. try:
  497. room_id_del = user_input_list[1]
  498. except Exception as e:
  499. room_id_del = 'NONE'
  500. print(e)
  501. os.remove("rooms/" + room_id_del + ".txt")
  502. anwer = 'deleting the requested room..'
  503. if len(user_input_list) > 2:
  504. answer = 'Die Syntax zum Löschen eines Raumes hat einen Fehler. Versuche es erneut, nach dem Muster -> deleteroom <room_id>'
  505. if user_input_list[0] == 'createroom':
  506. try:
  507. room_name = user_input_list[1]
  508. except Exception as e:
  509. room_name = 'NONE'
  510. print(e)
  511. try:
  512. databases = user_input_list[2]
  513. except Exception as e:
  514. databases = 'NONE'
  515. print(e)
  516. try:
  517. filters = user_input_list[3]
  518. except Exception as e:
  519. filters = 'NONE'
  520. print(e)
  521. if len(user_input_list) > 3:
  522. answer = 'Die Syntax hat einen Fehler. Wahrscheinlich sind Leerzeichen in den Listen. Leerzeichen definieren die Syntax. Versuche es erneut, nach dem Muster -> createroom room1 ["fdb1","fdb2"] ["tag1","tag2"]'
  523. if room_name == 'NONE' or databases == 'NONE' or filters == 'NONE':
  524. answer = 'Um einen Raum zu erstellen, in dem neueste Einträge geteilt werden, lautet die Syntax: createroom <Raumname> <Liste-Datenbanken> <Liste-Filtertags>'
  525. else:
  526. try:
  527. new_room = api.create_public_room(room_name,
  528. members=[latest_message_user_username],
  529. read_only=False)
  530. new_room_id = new_room['channel']['_id']
  531. room_file = open('rooms/' + new_room_id + '.txt', 'w')
  532. room_file.write( room_name + '§%§%' + databases + '§%§%' + filters)
  533. room_file.close()
  534. answer = 'Der Command wurde übermittelt'
  535. except Exception as e:
  536. print('it was not able to create the room, the original error message is:', e)
  537. answer = 'There was an error creating the room, look up the logs.. the original error was: ' + str(e)
  538. #print('oi', user_input)
  539. api.send_message('Die Anfrage wird bearbeitet..', room_id)
  540. # here comes the code interacting with the spiders output json
  541. #answer = 'the up to date entries are: oi Oi Oi!'
  542. api.send_message(answer, room_id)
  543. time.sleep(1)
  544. api.send_message('Ich bin wieder bereit für Konfigurationsinput : )', room_id)
  545. time.sleep(1)