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.

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