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.

304 lines
11 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. if room_fdb in fdb_list and room_fdb not in [key for key in data]:
  75. try:
  76. iteration_var_list = config.get(room_fdb).get("entry-list").get("iteration-var-list")
  77. except Exception as e:
  78. print('there was an error with the entry-list parameter in the config regarding the fdb ', room_fdb)
  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. for key in data[room_fdb][i]:
  88. contains_tag = False
  89. for tag in eval(room_tags):
  90. 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(' ')):
  91. contains_tag = True
  92. if contains_tag == True:
  93. try:
  94. url = data[room_fdb][i][key]["domain"]
  95. except:
  96. url = data[room_fdb][i][key]["link"]
  97. entry_message = '[' + url + ']' + data[room_fdb][i][key]["name"] + '\n' + data[room_fdb][i][key]["info"]
  98. api.send_message(entry_message, room[0])
  99. #print('data',data['giz'][2],'data')
  100. already_updated = True
  101. # if datestime.split over etc and updated= true etc
  102. n += 1
  103. print(n)
  104. try:
  105. #print('getting the room history')
  106. date = datetime.datetime.now() - timedelta(days=3)
  107. room_history = api.get_private_room_history(room_id, oldest=date)
  108. except Exception as e:
  109. time.sleep(10)
  110. api = RocketChatAPI(settings={'username': botname, 'password': botpassword, 'domain': server_url})
  111. time.sleep(5)
  112. room_history = api.get_private_room_history(room_id, oldest=date)
  113. print('got a connection error, original message is:',e)
  114. messages_list = []
  115. for message in room_history['messages']:
  116. messages_list.append(message)
  117. if len(messages_list) >= 1:
  118. #print('blub', messages_list)
  119. latest_message_user_id = messages_list[0]['u']['_id']
  120. latest_message_user_username = messages_list[0]['u']['username']
  121. latest_message = messages_list[0]['msg']
  122. latest_message_id = messages_list[0]['_id']
  123. new_message_file = open('new_message_file.txt', 'r')
  124. new_message = new_message_file.read()
  125. new_message_file.close()
  126. new_message_list = new_message.split('§%§%')
  127. #print(latest_message, new_message_list[0])
  128. if new_message_list[0] != latest_message and new_message_list[1] != latest_message_id and latest_message_user_id != bot_user_id:
  129. answer = 'Ich habe kein Kommando erhalten.'
  130. new_message_file = open('new_message_file.txt', 'w')
  131. new_message_file.write(latest_message + '§%§%' + latest_message_id)
  132. new_message_file.close()
  133. user_input = latest_message
  134. user_input_list = user_input.split(' ')
  135. if user_input_list[0] == 'printrooms':
  136. # get all the rooms
  137. import os
  138. room_list = []
  139. rooms = os.listdir('rooms')
  140. for room in rooms:
  141. room_file = open('rooms/' + room, 'r')
  142. room_file_raw = room_file.read()
  143. room_file.close()
  144. room_file_list = room_file_raw.split('§%§%')
  145. room_list.append([room[:-4], room_file_list[0], room_file_list[1], room_file_list[2]])
  146. #print(room_list)
  147. answer = str(room_list)
  148. if user_input_list[0] == 'printfdbs':
  149. answer = str(fdb_list)
  150. if len(user_input_list) > 1:
  151. answer = 'Die Syntax zum Ausgeben der konfigurierten Förderdatenbanken hat einen Fehler. Versuche es erneut, mit -> printfdbs'
  152. if user_input_list[0] == 'deleteroom':
  153. try:
  154. room_id_del = user_input_list[1]
  155. except Exception as e:
  156. room_id_del = 'NONE'
  157. print(e)
  158. os.remove("rooms/" + room_id_del + ".txt")
  159. anwer = 'deleting the requested room..'
  160. if len(user_input_list) > 2:
  161. answer = 'Die Syntax zum Löschen eines Raumes hat einen Fehler. Versuche es erneut, nach dem Muster -> deleteroom <room_id>'
  162. if user_input_list[0] == 'createroom':
  163. try:
  164. room_name = user_input_list[1]
  165. except Exception as e:
  166. room_name = 'NONE'
  167. print(e)
  168. try:
  169. databases = user_input_list[2]
  170. except Exception as e:
  171. databases = 'NONE'
  172. print(e)
  173. try:
  174. filters = user_input_list[3]
  175. except Exception as e:
  176. filters = 'NONE'
  177. print(e)
  178. if len(user_input_list) > 3:
  179. 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"]'
  180. if room_name == 'NONE' or databases == 'NONE' or filters == 'NONE':
  181. answer = 'Um einen Raum zu erstellen, in dem neueste Einträge geteilt werden, lautet die Syntax: createroom <Raumname> <Liste-Datenbanken> <Liste-Filtertags>'
  182. else:
  183. try:
  184. new_room = api.create_public_room(room_name,
  185. members=[latest_message_user_username],
  186. read_only=True)
  187. new_room_id = new_room['channel']['_id']
  188. room_file = open('rooms/' + new_room_id + '.txt', 'w')
  189. room_file.write( room_name + '§%§%' + databases + '§%§%' + filters)
  190. room_file.close()
  191. answer = 'Der Command wurde übermittelt'
  192. except Exception as e:
  193. print('it was not able to create the room, the original error message is:', e)
  194. answer = 'There was an error creating the room, look up the logs.. the original error was: ' + str(e)
  195. #print('oi', user_input)
  196. api.send_message('Die Anfrage wird bearbeitet..', room_id)
  197. # here comes the code interacting with the spiders output json
  198. #answer = 'the up to date entries are: oi Oi Oi!'
  199. api.send_message(answer, room_id)
  200. time.sleep(1)
  201. api.send_message('Ich bin wieder bereit für Konfigurationsinput : )', room_id)
  202. time.sleep(1)