hooks.py 11 KB

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