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.

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