hooks.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. #!/var/www/html/webhooks/.venv/bin/python
  2. # File name: Hooks.py
  3. # Date created: 09/16/2022
  4. # Date last modified: 10/15/2022
  5. # Python Version: 3.9.2
  6. # Copyright © 2022 DeadTOm
  7. # TODO: Make routes for various chat and video links
  8. try:
  9. from names import m_name
  10. from config import *
  11. from auth import *
  12. from DTChatbot import *
  13. from flask import Flask, jsonify, current_app, request
  14. import requests
  15. import logging
  16. import time
  17. import socket
  18. from mcstatus import JavaServer
  19. except Exception as import_error: # Log any errors loading modules, and try to keep running
  20. fail_log = open('/var/www/html/webhooks.log', 'a')
  21. fail_log.write(f'------{import_error}------\n')
  22. fail_log.close()
  23. logging.basicConfig(filename='/var/www/html/webhooks.log', level=logging.INFO)
  24. current_names = [] # Initialize empty list to hold current names
  25. testing = 0 # Are we testing? 1 for testing. 0 for live.
  26. get_m_info = requests.get('https://fosstodon.org/api/v1/accounts/verify_credentials', headers={'Authorization': m_api_key, 'Accept': 'application/json'}) # Get Mastodon account information
  27. get_m_info = get_m_info.json() # Jsonify the response
  28. app = Flask(__name__)
  29. def get_now(): # This creates and returns a time stamp
  30. now = str(time.strftime("%Y/%m/%d %H:%M:%S"))
  31. return now
  32. logging.info(f'\n\n\n\n{get_now()} - Webhook called.\n')
  33. def streaming_m_name(): # Change Mastodon name to show we're streaming
  34. get_m_info = requests.get('https://fosstodon.org/api/v1/accounts/verify_credentials', headers={'Authorization': m_api_key, 'Accept': 'application/json'}) # Get Mastodon account information
  35. get_m_info = get_m_info.json() # Jsonify the response
  36. current_m_name = f'm_name = \'{get_m_info["display_name"]}\'' # Create Mastodon list entry
  37. current_names.append(current_m_name) # Append to list of current names
  38. logging.info(f'{get_now()} - Current Mastodon name is \"{get_m_info["display_name"]}\".')
  39. set_m_name = requests.patch('https://fosstodon.org/api/v1/accounts/update_credentials', params={'display_name': m_streaming_name}, headers={'Authorization': m_api_key, 'Accept': 'application/json'}) # Set Mastodon display name
  40. set_m_name = set_m_name.json() # Jsonify the response
  41. logging.info(f'{get_now()} - Mastodon name is now \"{set_m_name["display_name"]}\".')
  42. def reg_m_name(): # Change Mastodon name to regular name
  43. set_m_name = requests.patch('https://fosstodon.org/api/v1/accounts/update_credentials', params={'display_name': m_name}, headers={'Authorization': m_api_key, 'Accept': 'application/json'}) # Set Mastodon display name
  44. set_m_name = set_m_name.json() # Jsonify the response
  45. logging.info(f'{get_now()} - Mastodon name is now \"{set_m_name["display_name"]}\".')
  46. def write_current_names(): # Write current names to names.py
  47. logging.info(f'{get_now()} - Storing {current_names}.')
  48. try:
  49. file = open("/var/www/html/webhooks/names.py", "w")
  50. for name in current_names:
  51. file.write(f'{name}\n')
  52. file.close()
  53. except Exception as write_error:
  54. logging.info(f'{get_now()} - {write_error}')
  55. def mc_chat(mc_msg): # Send chat message to Minecraft chat
  56. logging.info(f'{get_now()} - Checking Minecraft server for players.')
  57. mc_server = JavaServer.lookup('mc.deadtom.me:25565')
  58. query = mc_server.query() # Query Minecraft server for players
  59. cur_players = query.players.names
  60. if '_DeadTOm_' in cur_players: # If I'm on the server, send message
  61. logging.info(f'{get_now()} - DeadTOm is on the server, sending message.')
  62. logging.info(f'{get_now()} - Connecting...')
  63. sock_host = 'mc.deadtom.me'
  64. sock_port = 6791
  65. try:
  66. mySocket = socket.socket()
  67. mySocket.connect((sock_host, sock_port))
  68. time.sleep(1)
  69. logging.info(f'{get_now()} - Connected. Sending {mc_msg}...')
  70. mySocket.send(mc_msg.encode())
  71. logging.info(f'{get_now()} - sent.')
  72. mySocket.close()
  73. except ConnectionRefusedError as error:
  74. logging.info(f'{get_now()} - Unable to contact {sock_host} - {error}.')
  75. mySocket.close()
  76. except TimeoutError as error:
  77. logging.info(f'{get_now()} - Unable to contact {sock_host} - {error}.')
  78. mySocket.close()
  79. except OSError as error:
  80. logging.info(f'{get_now()} - Unable to contact {sock_host} - {error}.')
  81. mySocket.close()
  82. else: # If I'm not on the server, don't send the message
  83. logging.info(f'{get_now()} - DeadTOm is not on the server, so not sending message.')
  84. def set_hashtags(title): # Sets up hash tags to be appended to social media
  85. logging.info(f'{get_now()} - Examining stream title \"{title}\" to apply hashtags.')
  86. check_title = title.lower()
  87. default_tags = '#Owncast '
  88. tags = ''
  89. # tag_dict located in config.py
  90. for tag in tag_dict.keys(): # Iterate through each dict entry, and check for hashtag triggers
  91. if tag in check_title:
  92. print(f'Found {tag}, adding {tag_dict[tag]} to hashtags.')
  93. tags = f'{tags}{tag_dict[tag]} '
  94. tags = f'{tags}#Owncast #NSFW' # Adding NSFW tag, just for good measure
  95. logging.info(f'{get_now()} - Adding {tags} to title.')
  96. return tags
  97. def social_post(msg, discmsg): # Post to Mastodon
  98. # Send to Mastodon
  99. logging.info(f'{get_now()} - Posting to Mastodon.')
  100. response = requests.post(m_api_url,
  101. params={'status': msg},
  102. headers={'Authorization': m_api_key,
  103. 'visibility': 'public',
  104. 'Accept': 'application/json'})
  105. json_response = response.json()
  106. for line in json_response:
  107. logging.debug(f'{get_now()} - API returned: {line}: {json_response[line]}')
  108. # Send to Discord
  109. # for all params, see https://discordapp.com/developers/docs/resources/webhook#execute-webhook
  110. data = {
  111. 'content': discmsg
  112. }
  113. talkback = requests.post(discordwebhookurl, json=data)
  114. if 200 <= talkback.status_code < 300:
  115. logging.info(f'{get_now()} - Discord message sent {talkback.status_code}')
  116. else:
  117. logging.info(
  118. f'{get_now()} - Discord message not sent with {talkback.status_code}, response:\n{talkback.json()}')
  119. @app.route('/stream_started/', methods=["POST"])
  120. def start():
  121. logging.info(f'{get_now()} - stream_started request')
  122. raw_data = request.get_json(force=True) # Get the raw data
  123. event_data = raw_data['eventData']
  124. stream_title = event_data['streamTitle']
  125. hashtags = set_hashtags(stream_title.lower())
  126. msg = f'I\'m streaming on Owncast, at https://owncast.deadtom.me. {stream_title} {hashtags}'
  127. logging.debug(f'{get_now()} - Constructed Mastodon/Twitter message: {msg}')
  128. discmsg = f'DeadTOm is streaming on Owncast, at https://owncast.deadtom.me. {stream_title}'
  129. if testing != 1: # If we're testing, don't actually send out notification
  130. streaming_m_name()
  131. social_post(msg, discmsg)
  132. else:
  133. logging.info(f'-----------------------\n\n'
  134. f'{get_now()} - Currently running in test mode. We are streaming, but no notifications are being sent to social media.'
  135. f'\n\n---------------------------------')
  136. return jsonify({"Data": raw_data, })
  137. @app.route('/stream_stopped/', methods=["POST"])
  138. def stop():
  139. logging.info(f'{get_now()} - stream_stopped request')
  140. raw_data = request.get_json(force=True) # Get the raw data
  141. event_data = raw_data['eventData']
  142. stream_title = event_data['streamTitle']
  143. hashtags = set_hashtags(stream_title.lower()) # Make title lower case, for comparison with list of tags
  144. msg = f'All done streaming, for now. Maybe catch me next time on Owncast, at https://owncast.deadtom.me.\n\n{hashtags}'
  145. discmsg = f'DeadTOm is done streaming.'
  146. if testing != 1: # If we're testing, don't actually send out notification
  147. reg_m_name()
  148. social_post(msg, discmsg)
  149. return jsonify({"Data": raw_data, })
  150. @app.route('/user_joined/', methods=["POST"])
  151. def joined():
  152. logging.info(f'{get_now()} - user_joined request')
  153. raw_data = request.get_json(force=True) # Get the raw data
  154. event_data = raw_data['eventData']
  155. chatter_name = event_data['user']['displayName']
  156. ownchat_msg = f'{chatter_name} joined the chat.'
  157. logging.info(f'{get_now()} - {ownchat_msg}')
  158. mc_chat(ownchat_msg)
  159. logging.info(f'{get_now()} - Sent to Minecraft server.')
  160. return jsonify({"Data": raw_data, })
  161. @app.route('/name_changed/', methods=["POST"])
  162. def changed():
  163. logging.info(f'{get_now()} - name_changed request')
  164. raw_data = request.get_json(force=True) # Get the raw data
  165. event_data = raw_data['eventData']
  166. chatter_old_name = event_data['user']['previousNames']
  167. chatter_new_name = event_data['user']['displayName']
  168. last_name = len(chatter_old_name) - 1 # Get last name in previousNames list
  169. chatter_old_name = event_data['user']['previousNames'][last_name]
  170. ownchat_msg = f'{chatter_old_name} changed their name to {chatter_new_name}'
  171. logging.debug(f'{get_now()} - {type}\n{raw_data}')
  172. logging.info(f'{get_now()} - {ownchat_msg}')
  173. mc_chat(ownchat_msg)
  174. logging.info(f'{get_now()} - Sent to Minecraft server.')
  175. return jsonify({"Data": raw_data, })
  176. @app.route('/message_sent/', methods=["POST"])
  177. def sent():
  178. logging.info(f'{get_now()} - message_sent request')
  179. raw_data = request.get_json(force=True) # Get the raw data
  180. event_data = raw_data['eventData']
  181. chatter_name = event_data['user']['displayName']
  182. chat_msg = event_data['rawBody']
  183. ownchat_msg = f'{chatter_name} on Owncast says: {chat_msg}'
  184. logging.info(f'{get_now()} - Chat message: \"{ownchat_msg}\".')
  185. mc_chat(ownchat_msg)
  186. logging.info(f'{get_now()} - Sent to Minecraft server.')
  187. return jsonify({"Data": raw_data, })
  188. @app.route('/chatbot/', methods=["POST"])
  189. def send_chatbot():
  190. logging.info(f'{get_now()} - message_sent request')
  191. raw_data = request.get_json(force=True) # Get the raw data
  192. event_data = raw_data['eventData']
  193. chatter_name = event_data['user']['displayName']
  194. chat_msg = event_data['rawBody']
  195. bot_msg = f'{chatter_name}, {chat_msg}'
  196. DTChatbot.chat_bot(bot_msg)
  197. logging.info(f'{get_now()} - Sent to chat bot.')
  198. return jsonify({"Data": raw_data, })
  199. if __name__ == '__main__':
  200. try:
  201. app.run()
  202. except Exception as main_error:
  203. logging.info(f'{get_now()} - {main_error}')