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.

572 lines
25 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. <<<<<<< HEAD
  29. #room_history = api.get_private_room_history(room_id)
  30. #print(room_history['messages'][0]['msg'])
  31. # print(myinfo)
  32. rooms = api.get_private_rooms()
  33. print('blubidab oioioi', rooms)
  34. =======
  35. #print(myinfo)
  36. #rooms = api.get_private_rooms()
  37. #print(rooms)
  38. >>>>>>> origin/master
  39. # api.send_message('Ole', room_id)
  40. n = 0
  41. import time
  42. import schedule
  43. #change to False here, if you want to have the update run at server start
  44. already_updated = True
  45. start = True
  46. import datetime
  47. from datetime import timedelta
  48. while True:
  49. time.sleep(2)
  50. #already_updated = True
  51. now = datetime.datetime.now()
  52. current_hour = now.strftime("%H")
  53. #print(current_hour)
  54. # run variable update and creation at start
  55. if start == True:
  56. room_list = []
  57. rooms = os.listdir('rooms')
  58. for room in rooms:
  59. room_file = open('rooms/' + room, 'r')
  60. room_file_raw = room_file.read()
  61. room_file.close()
  62. room_file_list = room_file_raw.split('§%§%')
  63. print(room_list)
  64. print(room)
  65. print(room_file_list)
  66. room_list.append([room[:-4], room_file_list[0], room_file_list[1], room_file_list[2]])
  67. with open(spider_directory + '/spiders/config.yaml' , "r") as stream:
  68. try:
  69. config = yaml.safe_load(stream)
  70. except yaml.YAMLError as exc:
  71. print(exc)
  72. fdb_list = []
  73. #print(config)
  74. for key in config:
  75. fdb_list.append(key)
  76. start = False
  77. if int(current_hour) > 11:
  78. aftersix = True
  79. if int(current_hour) <= 11:
  80. aftersix = False
  81. already_updated = False
  82. if aftersix == True and already_updated == False:
  83. room_list = []
  84. rooms = os.listdir('rooms')
  85. for room in rooms:
  86. room_file = open('rooms/' + room, 'r')
  87. room_file_raw = room_file.read()
  88. room_file.close()
  89. room_file_list = room_file_raw.split('§%§%')
  90. room_list.append([room[:-4], room_file_list[0], room_file_list[1], room_file_list[2]])
  91. with open(spider_directory + '/spiders/config.yaml' , "r") as stream:
  92. try:
  93. config = yaml.safe_load(stream)
  94. except yaml.YAMLError as exc:
  95. print(exc)
  96. fdb_list = []
  97. #print(config)
  98. for key in config:
  99. fdb_list.append(key)
  100. data = dict({})
  101. for room in room_list:
  102. print(room[0])
  103. room_fdbs = room[2]
  104. room_tags = room[3]
  105. #subprocess.run(["python", spider_directory + 'main.py', fdbs])
  106. date = datetime.datetime.now() - timedelta(days=3)
  107. room_history = api.get_room_history(room[0], oldest=date, latest=datetime.datetime.now())
  108. for room_fdb in eval(room_fdbs):
  109. #print('room_fdb',room_fdb, 'fdb_list',fdb_list)
  110. try:
  111. iteration_var_list = config.get(room_fdb).get("entry-list").get("iteration-var-list")
  112. except Exception as e:
  113. print('there was an error with the entry-list parameter in the config regarding the fdb ', room_fdb)
  114. if room_fdb in fdb_list and room_fdb not in [key for key in data]:
  115. iterdict = {}
  116. for i in eval(iteration_var_list):
  117. f = open(spider_directory + "/spiders/output/" + room_fdb + str(i) + "entryList.txt")
  118. text = f.read()
  119. dictionary_entry_list = eval(text)
  120. iterdict[i] = dictionary_entry_list
  121. data[room_fdb] = iterdict
  122. for i in eval(iteration_var_list):
  123. try:
  124. print(room_fdb, i)
  125. for key in data[room_fdb][i]:
  126. contains_tag = False
  127. name_data_lower = [word.lower() for word in data[room_fdb][i][key]["name"].split(' ')]
  128. info_data_lower = [word.lower() for word in data[room_fdb][i][key]["info"].split(' ')]
  129. text_data_lower = [word.lower() for word in data[room_fdb][i][key]["text"].split(' ')]
  130. for tag in eval(room_tags):
  131. if tag.lower() in (name_data_lower or info_data_lower or text_data_lower):
  132. contains_tag = True
  133. if contains_tag == True:
  134. try:
  135. url = data[room_fdb][i][key]["domain"]
  136. except:
  137. url = data[room_fdb][i][key]["link"]
  138. message_was_already_there = False
  139. for message in room_history['messages']:
  140. if name_data_lower.join(' ') in message['msg']:
  141. message_was_already_there = True
  142. if message_was_already_there == False:
  143. entry_message = '<' + url + '|' + data[room_fdb][i][key]["name"]+ '>' + '\n' + data[room_fdb][i][key]["info"]
  144. api.send_message(entry_message, room[0])
  145. except Exception as e:
  146. print("probably i was not there in last page, original error is:", e)
  147. #print('data',data['giz'][2],'data')
  148. already_updated = True
  149. # if datestime.split over etc and updated= true etc
  150. n += 1
  151. print(n)
  152. try:
  153. #print('getting the room history')
  154. date = datetime.datetime.now() - timedelta(days=3)
  155. room_history = api.get_private_room_history(room_id, oldest=date)
  156. except Exception as e:
  157. time.sleep(10)
  158. api = RocketChatAPI(settings={'username': botname, 'password': botpassword, 'domain': server_url})
  159. time.sleep(5)
  160. room_history = api.get_private_room_history(room_id, oldest=date)
  161. print('got a connection error, original message is:',e)
  162. messages_list = []
  163. for message in room_history['messages']:
  164. messages_list.append(message)
  165. if len(messages_list) >= 1:
  166. #print('blub', messages_list)
  167. latest_message_user_id = messages_list[0]['u']['_id']
  168. latest_message_user_username = messages_list[0]['u']['username']
  169. latest_message = messages_list[0]['msg']
  170. latest_message_id = messages_list[0]['_id']
  171. new_message_file = open('new_message_file.txt', 'r')
  172. new_message = new_message_file.read()
  173. new_message_file.close()
  174. new_message_list = new_message.split('§%§%')
  175. #print(latest_message, new_message_list[0])
  176. if new_message_list[0] != latest_message and new_message_list[1] != latest_message_id and latest_message_user_id != bot_user_id:
  177. answer = 'Ich habe kein Kommando erhalten.'
  178. new_message_file = open('new_message_file.txt', 'w')
  179. new_message_file.write(latest_message + '§%§%' + latest_message_id)
  180. new_message_file.close()
  181. user_input = latest_message
  182. user_input_list = user_input.split(' ')
  183. if user_input_list[0] == 'addtags':
  184. try:
  185. room_id_add_tags = user_input_list[1]
  186. except:
  187. room_id_add_tags = 'NONE'
  188. try:
  189. new_tags = user_input_list[2]
  190. except:
  191. new_tags = 'NONE'
  192. try:
  193. thirdarg = user_input_list[3]
  194. except:
  195. thirdarg = 'NONE'
  196. if len(room_id_add_tags) >= 1 and len(new_tags) >= 1 and thirdarg == 'NONE':
  197. try:
  198. room_file_add_tags = open('rooms/' + user_input_list[1] + '.txt', 'r')
  199. room_info_raw = room_file_add_tags.read()
  200. room_file_add_tags.close()
  201. room_info = room_info_raw.split('§%§%')
  202. tag_list = eval(room_info[-1])
  203. for tag in eval(user_input_list[2]):
  204. if tag not in tag_list:
  205. tag_list.append(tag)
  206. room_file_add_tags = open('rooms/' + user_input_list[1] + '.txt', 'w')
  207. room_file_add_tags.write( str(room_info[0]) + '§%§%' + str(room_info[1]) + '§%§%' + str(tag_list))
  208. room_file_add_tags.close()
  209. answer = 'the updated tag list is' + str(tag_list)
  210. except Exception as e:
  211. print('error opening, original error is:', e)
  212. answer = "The room_id to update the tags was not found"
  213. if user_input_list[0] == 'printtags':
  214. try:
  215. room_id_to_print_tags = user_input_list[1]
  216. except:
  217. 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"
  218. room_id_to_print_tags = 'NONE'
  219. if room_id_to_print_tags != 'NONE':
  220. try:
  221. room_file = open('rooms/' + room_id_to_print_tags + '.txt', 'r')
  222. room_info_raw = room_file.read()
  223. room_file.close()
  224. room_info = room_info_raw.split('§%§%')
  225. tag_list = eval(room_info[-1])
  226. answer = tag_list
  227. except Exception as e:
  228. print('error opening, original error is:', e)
  229. answer = "The room_id to get the tags was not found"
  230. if user_input_list[0] == 'printcommands':
  231. answer = """
  232. To print all available rooms and their configuration, use
  233. command : `printrooms`
  234. -----------------------------------------------------------------------------------------
  235. To print all available fdbs, use
  236. command : `printfdbs`
  237. -----------------------------------------------------------------------------------------
  238. To update all rooms use
  239. command : `updaterooms`
  240. -----------------------------------------------------------------------------------------
  241. To update one room use the room_id from the output of printrooms:
  242. command : `updaterooms <room-id>`
  243. example : `updaterooms 6572012bebb39dd248d08320`
  244. -----------------------------------------------------------------------------------------
  245. To create a room use following command, but be sure to not have spaces in your lists,
  246. as a space indicates a new command argument:
  247. command : `createroom <room-name> <list-fdbs> <list-tags>`
  248. example : `createroom room-test-1 ['giz','fdb2'] ['tag1','tag2','tag3']`
  249. -----------------------------------------------------------------------------------------
  250. To delete a room use
  251. command : `deleteroom <room-id>`
  252. example : `deleteroom 6572012bebb39dd248d08320`
  253. -----------------------------------------------------------------------------------------
  254. To print the tags of a room use
  255. command : `printtags <room-id>`
  256. example : `printtags 6572012bebb39dd248d08320`
  257. -----------------------------------------------------------------------------------------
  258. To add tags to the existing tags use
  259. command : `addtags <room-id> <tag-list-without-spaces>`
  260. example : `updaterooms 6572012bebb39dd248d08320 ['tag1','tag2','tag3']`
  261. """
  262. if user_input_list[0] == 'printrooms':
  263. room_was_found = False
  264. # get all the rooms
  265. import os
  266. room_list = []
  267. rooms = os.listdir('rooms')
  268. for room in rooms:
  269. room_file = open('rooms/' + room, 'r')
  270. room_file_raw = room_file.read()
  271. room_file.close()
  272. room_file_list = room_file_raw.split('§%§%')
  273. room_list.append([room[:-4], room_file_list[0], room_file_list[1], room_file_list[2]])
  274. #print(room_list)
  275. answer = str(room_list)
  276. if user_input_list[0] == 'updaterooms':
  277. try:
  278. if len(user_input_list[1]) >= 1:
  279. room_to_update = user_input_list[1]
  280. except Exception as e:
  281. room_to_update = 'NONE'
  282. room_list = []
  283. rooms = os.listdir('rooms')
  284. for room in rooms:
  285. room_file = open('rooms/' + room, 'r')
  286. room_file_raw = room_file.read()
  287. room_file.close()
  288. room_file_list = room_file_raw.split('§%§%')
  289. room_list.append([room[:-4], room_file_list[0], room_file_list[1], room_file_list[2]])
  290. with open(spider_directory + '/spiders/config.yaml' , "r") as stream:
  291. try:
  292. config = yaml.safe_load(stream)
  293. except yaml.YAMLError as exc:
  294. print(exc)
  295. fdb_list = []
  296. #print(config)
  297. for key in config:
  298. fdb_list.append(key)
  299. answer = "Ich update die Rooms auf Basis der Daten von heute morgen um 6 Uhr.."
  300. data = dict({})
  301. for room in room_list:
  302. if room[0] == room_to_update or room_to_update == 'NONE':
  303. room_was_found = True
  304. print(room[0])
  305. room_fdbs = room[2]
  306. room_tags = room[3]
  307. #subprocess.run(["python", spider_directory + 'main.py', fdbs])
  308. #myinfo = api.get_room_info(room[0])
  309. #print(myinfo)
  310. roomid = "'657cbeccebb39dd248d38ec3'"
  311. roomoioioi = api.get_user_info(bot_user_id)
  312. print(roomoioioi)
  313. room_history_updateroom = api.get_private_room_history(room[0])
  314. for room_fdb in eval(room_fdbs):
  315. #print('room_fdb',room_fdb, 'fdb_list',fdb_list)
  316. try:
  317. iteration_var_list = config.get(room_fdb).get("entry-list").get("iteration-var-list")
  318. except Exception as e:
  319. print('there was an error with the entry-list parameter in the config regarding the fdb ', room_fdb)
  320. if room_fdb in fdb_list and room_fdb not in [key for key in data]:
  321. iterdict = {}
  322. for i in eval(iteration_var_list):
  323. f = open(spider_directory + "/spiders/output/" + room_fdb + str(i) + "entryList.txt")
  324. text = f.read()
  325. dictionary_entry_list = eval(text)
  326. iterdict[i] = dictionary_entry_list
  327. data[room_fdb] = iterdict
  328. for i in eval(iteration_var_list):
  329. try:
  330. print(room_fdb, i)
  331. for key in data[room_fdb][i]:
  332. contains_tag = False
  333. name_data_lower = [word.lower() for word in data[room_fdb][i][key]["name"].split(' ')]
  334. info_data_lower = [word.lower() for word in data[room_fdb][i][key]["info"].split(' ')]
  335. text_data_lower = [word.lower() for word in data[room_fdb][i][key]["text"].split(' ')]
  336. for tag in eval(room_tags):
  337. if tag.lower() in (name_data_lower or info_data_lower or text_data_lower):
  338. contains_tag = True
  339. if contains_tag == True:
  340. try:
  341. url = data[room_fdb][i][key]["domain"]
  342. except:
  343. url = data[room_fdb][i][key]["link"]
  344. print('101110001101010010010101000111')
  345. message_was_already_there = False
  346. for message in room_history['messages']:
  347. if name_data_lower.join(' ') in message['msg']:
  348. message_was_already_there = True
  349. if message_was_already_there == False:
  350. entry_message = '<' + url + '|' + data[room_fdb][i][key]["name"]+ '>' + '\n' + data[room_fdb][i][key]["info"]
  351. api.send_message(entry_message, room[0])
  352. except Exception as e:
  353. print("probably i was not there in last page, original error is:", e)
  354. if room_to_update == 'NONE':
  355. answer = 'No room was specified, all rooms will get an update based on the data available'
  356. if room_was_found == False and room_to_update != 'NONE':
  357. answer = 'The room you specified does not exist, or there are no rooms configured, try the command without argument -> updaterooms'
  358. if room_was_found == True and room_to_update != 'NONE':
  359. answer = "I am updating the specified room based on the data in fdb-spider/spiders/output.."
  360. if user_input_list[0] == 'printfdbs':
  361. answer = str(fdb_list)
  362. if len(user_input_list) > 1:
  363. answer = 'Die Syntax zum Ausgeben der konfigurierten Förderdatenbanken hat einen Fehler. Versuche es erneut, mit -> printfdbs'
  364. if user_input_list[0] == 'deleteroom':
  365. try:
  366. room_id_del = user_input_list[1]
  367. except Exception as e:
  368. room_id_del = 'NONE'
  369. print(e)
  370. os.remove("rooms/" + room_id_del + ".txt")
  371. anwer = 'deleting the requested room..'
  372. if len(user_input_list) > 2:
  373. answer = 'Die Syntax zum Löschen eines Raumes hat einen Fehler. Versuche es erneut, nach dem Muster -> deleteroom <room_id>'
  374. if user_input_list[0] == 'createroom':
  375. try:
  376. room_name = user_input_list[1]
  377. except Exception as e:
  378. room_name = 'NONE'
  379. print(e)
  380. try:
  381. databases = user_input_list[2]
  382. except Exception as e:
  383. databases = 'NONE'
  384. print(e)
  385. try:
  386. filters = user_input_list[3]
  387. except Exception as e:
  388. filters = 'NONE'
  389. print(e)
  390. if len(user_input_list) > 3:
  391. 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"]'
  392. if room_name == 'NONE' or databases == 'NONE' or filters == 'NONE':
  393. answer = 'Um einen Raum zu erstellen, in dem neueste Einträge geteilt werden, lautet die Syntax: createroom <Raumname> <Liste-Datenbanken> <Liste-Filtertags>'
  394. else:
  395. try:
  396. new_room = api.create_public_room(room_name,
  397. members=[latest_message_user_username],
  398. read_only=False)
  399. new_room_id = new_room['channel']['_id']
  400. room_file = open('rooms/' + new_room_id + '.txt', 'w')
  401. room_file.write( room_name + '§%§%' + databases + '§%§%' + filters)
  402. room_file.close()
  403. answer = 'Der Command wurde übermittelt'
  404. except Exception as e:
  405. print('it was not able to create the room, the original error message is:', e)
  406. answer = 'There was an error creating the room, look up the logs.. the original error was: ' + str(e)
  407. #print('oi', user_input)
  408. api.send_message('Die Anfrage wird bearbeitet..', room_id)
  409. # here comes the code interacting with the spiders output json
  410. #answer = 'the up to date entries are: oi Oi Oi!'
  411. api.send_message(answer, room_id)
  412. time.sleep(1)
  413. api.send_message('Ich bin wieder bereit für Konfigurationsinput : )', room_id)
  414. time.sleep(1)