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.

393 lines
16 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. already_updated = False
  36. import datetime
  37. from datetime import timedelta
  38. while True:
  39. time.sleep(4)
  40. #already_updated = True
  41. now = datetime.datetime.now()
  42. current_hour = now.strftime("%H")
  43. if int(current_hour) > 6:
  44. aftersix = True
  45. if int(current_hour) < 6:
  46. aftersix = False
  47. already_updated == False
  48. if aftersix == True and already_updated == False:
  49. room_list = []
  50. rooms = os.listdir('rooms')
  51. for room in rooms:
  52. room_file = open('rooms/' + room, 'r')
  53. room_file_raw = room_file.read()
  54. room_file.close()
  55. room_file_list = room_file_raw.split('§%§%')
  56. room_list.append([room[:-4], room_file_list[0], room_file_list[1], room_file_list[2]])
  57. with open(spider_directory + '/spiders/config.yaml' , "r") as stream:
  58. try:
  59. config = yaml.safe_load(stream)
  60. except yaml.YAMLError as exc:
  61. print(exc)
  62. fdb_list = []
  63. #print(config)
  64. for key in config:
  65. fdb_list.append(key)
  66. data = dict({})
  67. for room in room_list:
  68. print(room[0])
  69. room_fdbs = room[2]
  70. room_tags = room[3]
  71. #subprocess.run(["python", spider_directory + 'main.py', fdbs])
  72. for room_fdb in eval(room_fdbs):
  73. #print('room_fdb',room_fdb, 'fdb_list',fdb_list)
  74. try:
  75. iteration_var_list = config.get(room_fdb).get("entry-list").get("iteration-var-list")
  76. except Exception as e:
  77. print('there was an error with the entry-list parameter in the config regarding the fdb ', room_fdb)
  78. if room_fdb in fdb_list and room_fdb not in [key for key in data]:
  79. iterdict = {}
  80. for i in eval(iteration_var_list):
  81. f = open(spider_directory + "/spiders/output/" + room_fdb + str(i) + "entryList.txt")
  82. text = f.read()
  83. dictionary_entry_list = eval(text)
  84. iterdict[i] = dictionary_entry_list
  85. data[room_fdb] = iterdict
  86. for i in eval(iteration_var_list):
  87. try:
  88. print(room_fdb, i)
  89. for key in data[room_fdb][i]:
  90. contains_tag = False
  91. for tag in eval(room_tags):
  92. 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(' ')):
  93. contains_tag = True
  94. if contains_tag == True:
  95. try:
  96. url = data[room_fdb][i][key]["domain"]
  97. except:
  98. url = data[room_fdb][i][key]["link"]
  99. entry_message = '<' + url + '|' + data[room_fdb][i][key]["name"]+ '>' + '\n' + data[room_fdb][i][key]["info"]
  100. api.send_message(entry_message, room[0])
  101. except Exception as e:
  102. print("probably i was not there in last page, original error is:", e)
  103. #print('data',data['giz'][2],'data')
  104. already_updated = True
  105. # if datestime.split over etc and updated= true etc
  106. n += 1
  107. print(n)
  108. try:
  109. #print('getting the room history')
  110. date = datetime.datetime.now() - timedelta(days=3)
  111. room_history = api.get_private_room_history(room_id, oldest=date)
  112. except Exception as e:
  113. time.sleep(10)
  114. api = RocketChatAPI(settings={'username': botname, 'password': botpassword, 'domain': server_url})
  115. time.sleep(5)
  116. room_history = api.get_private_room_history(room_id, oldest=date)
  117. print('got a connection error, original message is:',e)
  118. messages_list = []
  119. for message in room_history['messages']:
  120. messages_list.append(message)
  121. if len(messages_list) >= 1:
  122. #print('blub', messages_list)
  123. latest_message_user_id = messages_list[0]['u']['_id']
  124. latest_message_user_username = messages_list[0]['u']['username']
  125. latest_message = messages_list[0]['msg']
  126. latest_message_id = messages_list[0]['_id']
  127. new_message_file = open('new_message_file.txt', 'r')
  128. new_message = new_message_file.read()
  129. new_message_file.close()
  130. new_message_list = new_message.split('§%§%')
  131. #print(latest_message, new_message_list[0])
  132. if new_message_list[0] != latest_message and new_message_list[1] != latest_message_id and latest_message_user_id != bot_user_id:
  133. answer = 'Ich habe kein Kommando erhalten.'
  134. new_message_file = open('new_message_file.txt', 'w')
  135. new_message_file.write(latest_message + '§%§%' + latest_message_id)
  136. new_message_file.close()
  137. user_input = latest_message
  138. user_input_list = user_input.split(' ')
  139. if user_input_list[0] == 'printrooms':
  140. room_was_found = False
  141. # get all the rooms
  142. import os
  143. room_list = []
  144. rooms = os.listdir('rooms')
  145. for room in rooms:
  146. room_file = open('rooms/' + room, 'r')
  147. room_file_raw = room_file.read()
  148. room_file.close()
  149. room_file_list = room_file_raw.split('§%§%')
  150. room_list.append([room[:-4], room_file_list[0], room_file_list[1], room_file_list[2]])
  151. #print(room_list)
  152. answer = str(room_list)
  153. if user_input_list[0] == 'updaterooms':
  154. room_list = []
  155. rooms = os.listdir('rooms')
  156. for room in rooms:
  157. room_file = open('rooms/' + room, 'r')
  158. room_file_raw = room_file.read()
  159. room_file.close()
  160. room_file_list = room_file_raw.split('§%§%')
  161. room_list.append([room[:-4], room_file_list[0], room_file_list[1], room_file_list[2]])
  162. with open(spider_directory + '/spiders/config.yaml' , "r") as stream:
  163. try:
  164. config = yaml.safe_load(stream)
  165. except yaml.YAMLError as exc:
  166. print(exc)
  167. fdb_list = []
  168. #print(config)
  169. for key in config:
  170. fdb_list.append(key)
  171. answer = "Ich update die Rooms auf Basis der Daten von heute morgen um 6 Uhr.."
  172. data = dict({})
  173. for room in room_list:
  174. if room[0] == room_to_update:
  175. room_was_found = True
  176. print(room[0])
  177. room_fdbs = room[2]
  178. room_tags = room[3]
  179. #subprocess.run(["python", spider_directory + 'main.py', fdbs])
  180. for room_fdb in eval(room_fdbs):
  181. #print('room_fdb',room_fdb, 'fdb_list',fdb_list)
  182. try:
  183. iteration_var_list = config.get(room_fdb).get("entry-list").get("iteration-var-list")
  184. except Exception as e:
  185. print('there was an error with the entry-list parameter in the config regarding the fdb ', room_fdb)
  186. if room_fdb in fdb_list and room_fdb not in [key for key in data]:
  187. iterdict = {}
  188. for i in eval(iteration_var_list):
  189. f = open(spider_directory + "/spiders/output/" + room_fdb + str(i) + "entryList.txt")
  190. text = f.read()
  191. dictionary_entry_list = eval(text)
  192. iterdict[i] = dictionary_entry_list
  193. data[room_fdb] = iterdict
  194. for i in eval(iteration_var_list):
  195. try:
  196. print(room_fdb, i)
  197. for key in data[room_fdb][i]:
  198. contains_tag = False
  199. for tag in eval(room_tags):
  200. 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(' ')):
  201. contains_tag = True
  202. if contains_tag == True:
  203. try:
  204. url = data[room_fdb][i][key]["domain"]
  205. except:
  206. url = data[room_fdb][i][key]["link"]
  207. entry_message = '<' + url + '|' + data[room_fdb][i][key]["name"]+ '>' + '\n' + data[room_fdb][i][key]["info"]
  208. api.send_message(entry_message, room[0])
  209. except Exception as e:
  210. print("probably i was not there in last page, original error is:", e)
  211. if room_was_found == False:
  212. answer = 'Den angegebenen Raum gibt es nicht.. Versuche es noch einmal mit -> updaterooms <room-id>'
  213. if room_was_found == True:
  214. answer = "Ich update die Rooms auf Basis der Daten in fdb-spider/spiders/output.."
  215. if user_input_list[0] == 'printfdbs':
  216. answer = str(fdb_list)
  217. if len(user_input_list) > 1:
  218. answer = 'Die Syntax zum Ausgeben der konfigurierten Förderdatenbanken hat einen Fehler. Versuche es erneut, mit -> printfdbs'
  219. if user_input_list[0] == 'deleteroom':
  220. try:
  221. room_id_del = user_input_list[1]
  222. except Exception as e:
  223. room_id_del = 'NONE'
  224. print(e)
  225. os.remove("rooms/" + room_id_del + ".txt")
  226. anwer = 'deleting the requested room..'
  227. if len(user_input_list) > 2:
  228. answer = 'Die Syntax zum Löschen eines Raumes hat einen Fehler. Versuche es erneut, nach dem Muster -> deleteroom <room_id>'
  229. if user_input_list[0] == 'createroom':
  230. try:
  231. room_name = user_input_list[1]
  232. except Exception as e:
  233. room_name = 'NONE'
  234. print(e)
  235. try:
  236. databases = user_input_list[2]
  237. except Exception as e:
  238. databases = 'NONE'
  239. print(e)
  240. try:
  241. filters = user_input_list[3]
  242. except Exception as e:
  243. filters = 'NONE'
  244. print(e)
  245. if len(user_input_list) > 3:
  246. 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"]'
  247. if room_name == 'NONE' or databases == 'NONE' or filters == 'NONE':
  248. answer = 'Um einen Raum zu erstellen, in dem neueste Einträge geteilt werden, lautet die Syntax: createroom <Raumname> <Liste-Datenbanken> <Liste-Filtertags>'
  249. else:
  250. try:
  251. new_room = api.create_public_room(room_name,
  252. members=[latest_message_user_username],
  253. read_only=True)
  254. new_room_id = new_room['channel']['_id']
  255. room_file = open('rooms/' + new_room_id + '.txt', 'w')
  256. room_file.write( room_name + '§%§%' + databases + '§%§%' + filters)
  257. room_file.close()
  258. answer = 'Der Command wurde übermittelt'
  259. except Exception as e:
  260. print('it was not able to create the room, the original error message is:', e)
  261. answer = 'There was an error creating the room, look up the logs.. the original error was: ' + str(e)
  262. #print('oi', user_input)
  263. api.send_message('Die Anfrage wird bearbeitet..', room_id)
  264. # here comes the code interacting with the spiders output json
  265. #answer = 'the up to date entries are: oi Oi Oi!'
  266. api.send_message(answer, room_id)
  267. time.sleep(1)
  268. api.send_message('Ich bin wieder bereit für Konfigurationsinput : )', room_id)
  269. time.sleep(1)