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.

307 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. 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. # get all the rooms
  141. import os
  142. room_list = []
  143. rooms = os.listdir('rooms')
  144. for room in rooms:
  145. room_file = open('rooms/' + room, 'r')
  146. room_file_raw = room_file.read()
  147. room_file.close()
  148. room_file_list = room_file_raw.split('§%§%')
  149. room_list.append([room[:-4], room_file_list[0], room_file_list[1], room_file_list[2]])
  150. #print(room_list)
  151. answer = str(room_list)
  152. if user_input_list[0] == 'printfdbs':
  153. answer = str(fdb_list)
  154. if len(user_input_list) > 1:
  155. answer = 'Die Syntax zum Ausgeben der konfigurierten Förderdatenbanken hat einen Fehler. Versuche es erneut, mit -> printfdbs'
  156. if user_input_list[0] == 'deleteroom':
  157. try:
  158. room_id_del = user_input_list[1]
  159. except Exception as e:
  160. room_id_del = 'NONE'
  161. print(e)
  162. os.remove("rooms/" + room_id_del + ".txt")
  163. anwer = 'deleting the requested room..'
  164. if len(user_input_list) > 2:
  165. answer = 'Die Syntax zum Löschen eines Raumes hat einen Fehler. Versuche es erneut, nach dem Muster -> deleteroom <room_id>'
  166. if user_input_list[0] == 'createroom':
  167. try:
  168. room_name = user_input_list[1]
  169. except Exception as e:
  170. room_name = 'NONE'
  171. print(e)
  172. try:
  173. databases = user_input_list[2]
  174. except Exception as e:
  175. databases = 'NONE'
  176. print(e)
  177. try:
  178. filters = user_input_list[3]
  179. except Exception as e:
  180. filters = 'NONE'
  181. print(e)
  182. if len(user_input_list) > 3:
  183. 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"]'
  184. if room_name == 'NONE' or databases == 'NONE' or filters == 'NONE':
  185. answer = 'Um einen Raum zu erstellen, in dem neueste Einträge geteilt werden, lautet die Syntax: createroom <Raumname> <Liste-Datenbanken> <Liste-Filtertags>'
  186. else:
  187. try:
  188. new_room = api.create_public_room(room_name,
  189. members=[latest_message_user_username],
  190. read_only=True)
  191. new_room_id = new_room['channel']['_id']
  192. room_file = open('rooms/' + new_room_id + '.txt', 'w')
  193. room_file.write( room_name + '§%§%' + databases + '§%§%' + filters)
  194. room_file.close()
  195. answer = 'Der Command wurde übermittelt'
  196. except Exception as e:
  197. print('it was not able to create the room, the original error message is:', e)
  198. answer = 'There was an error creating the room, look up the logs.. the original error was: ' + str(e)
  199. #print('oi', user_input)
  200. api.send_message('Die Anfrage wird bearbeitet..', room_id)
  201. # here comes the code interacting with the spiders output json
  202. #answer = 'the up to date entries are: oi Oi Oi!'
  203. api.send_message(answer, room_id)
  204. time.sleep(1)
  205. api.send_message('Ich bin wieder bereit für Konfigurationsinput : )', room_id)
  206. time.sleep(1)