hooks.py 11 KB

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