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. # TODO: Make routes for various chat and video links
  8. try:
  9. from names import *
  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. from twython import Twython, TwythonError
  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(log_location, '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. #logging.basicConfig(filename='/var/www/html/webhooks.log', level=logging.DEBUG)
  25. #logging.basicConfig(level=logging.DEBUG)
  26. current_names = [] # Initialize empty list to hold current Twitter and Mastodon names
  27. testing = 0 # Are we testing? 1 for testing. 0 for live.
  28. twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
  29. get_t_info = twitter.verify_credentials() # Get current Twitter name
  30. 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
  31. get_m_info = get_m_info.json() # Jsonify the response
  32. app = Flask(__name__)
  33. def get_now(): # This creates and returns a time stamp
  34. now = str(time.strftime("%Y/%m/%d %H:%M:%S"))
  35. return now
  36. logging.info(f'\n\n\n\n{get_now()} - Webhook called.\n')
  37. def streaming_t_name(): # Change Twitter name to show we're streaming'
  38. get_t_info = twitter.verify_credentials() # Get current Twitter name
  39. current_t_name = f't_name = \'{get_t_info["name"]}\'' # Create Twitter list entry
  40. current_names.append(current_t_name) # Append to list of current names
  41. logging.info(f'{get_now()} - Current Twitter name is \"{get_t_info["name"]}\".')
  42. set_t_name = twitter.update_profile(name=t_streaming_name)
  43. logging.info(f'{get_now()} - Twitter name is now {set_t_name["name"]}.')
  44. def streaming_m_name(): # Change Mastodon name to show we're streaming
  45. 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
  46. get_m_info = get_m_info.json() # Jsonify the response
  47. current_m_name = f'm_name = \'{get_m_info["display_name"]}\'' # Create Mastodon list entry
  48. current_names.append(current_m_name) # Append to list of current names
  49. logging.info(f'{get_now()} - Current Mastodon name is \"{get_m_info["display_name"]}\".')
  50. 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
  51. set_m_name = set_m_name.json() # Jsonify the response
  52. logging.info(f'{get_now()} - Mastodon name is now \"{set_m_name["display_name"]}\".')
  53. def reg_t_name(): # Change Twitter name to regular name
  54. set_t_name = twitter.update_profile(name=t_name)
  55. logging.info(f'{get_now()} - Twitter name is now {set_t_name["name"]}.')
  56. def reg_m_name(): # Change Mastodon name to regular name
  57. 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
  58. set_m_name = set_m_name.json() # Jsonify the response
  59. logging.info(f'{get_now()} - Mastodon name is now \"{set_m_name["display_name"]}\".')
  60. def write_current_names(): # Write current names to names.py
  61. logging.info(f'{get_now()} - Storing {current_names}.')
  62. file = open("names.py", "w")
  63. for name in current_names:
  64. file.write(f'{name}\n')
  65. file.close()
  66. def mc_chat(mc_msg): # Send chat message to Minecraft chat
  67. logging.info(f'{get_now()} - Checking Minecraft server for players.')
  68. mc_server = JavaServer.lookup('mc.deadtom.me:25565')
  69. query = mc_server.query() # Query Minecraft server for players
  70. cur_players = query.players.names
  71. if '_DeadTOm_' in cur_players: # If I'm on the server, send message
  72. logging.info(f'{get_now()} - DeadTOm is on the server, sending message.')
  73. logging.info(f'{get_now()} - Connecting...')
  74. sock_host = 'mc.deadtom.me'
  75. sock_port = 6791
  76. mySocket = socket.socket()
  77. mySocket.connect((sock_host, sock_port))
  78. time.sleep(1)
  79. logging.info(f'{get_now()} - Connected. Sending {mc_msg}...')
  80. mySocket.send(mc_msg.encode())
  81. logging.info(f'{get_now()} - sent.')
  82. mySocket.close()
  83. else: # If I'm not on the server, don't send the message
  84. logging.info(f'{get_now()} - DeadTOm is not on the server, so not sending message.')
  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 Twitter
  110. twitter.update_status(status=msg) # Tweet the message
  111. logging.info(f'{get_now()} - Posted to Twitter.')
  112. # Send to Discord
  113. # for all params, see https://discordapp.com/developers/docs/resources/webhook#execute-webhook
  114. data = {
  115. 'content': discmsg
  116. }
  117. talkback = requests.post(discordwebhookurl, json=data)
  118. if 200 <= talkback.status_code < 300:
  119. logging.info(f'{get_now()} - Discord message sent {talkback.status_code}')
  120. else:
  121. logging.info(
  122. f'{get_now()} - Discord message not sent with {talkback.status_code}, response:\n{talkback.json()}')
  123. @app.route('/stream_started/', methods=["POST"])
  124. def start():
  125. logging.info(f'{get_now()} - stream_started request')
  126. raw_data = request.get_json(force=True) # Get the raw data
  127. event_data = raw_data['eventData']
  128. stream_title = event_data['streamTitle']
  129. hashtags = set_hashtags(stream_title.lower())
  130. msg = f'I\'m streaming on Owncast, at https://owncast.deadtom.me. {stream_title} {hashtags}'
  131. logging.debug(f'{get_now()} - Constructed Mastodon/Twitter message: {msg}')
  132. discmsg = f'DeadTOm is streaming on Owncast, at https://owncast.deadtom.me. {stream_title}'
  133. if testing != 1: # If we're testing, don't actually send out notification
  134. streaming_m_name()
  135. streaming_t_name()
  136. write_current_names()
  137. social_post(msg, discmsg)
  138. else:
  139. logging.info(f'-----------------------\n\n'
  140. f'{get_now()} - Currently running in test mode. We are streaming, but no notifications are being sent to social media.'
  141. f'\n\n---------------------------------')
  142. return jsonify({"Data": raw_data,})
  143. @app.route('/stream_stopped/', methods=["POST"])
  144. def stop():
  145. logging.info(f'{get_now()} - stream_stopped request')
  146. raw_data = request.get_json(force=True) # Get the raw data
  147. event_data = raw_data['eventData']
  148. stream_title = event_data['streamTitle']
  149. hashtags = set_hashtags(stream_title.lower()) # Make title lower case, for comparison with list of tags
  150. msg = f'All done streaming, for now. Maybe catch me next time on Owncast, at https://owncast.deadtom.me.\n\n{hashtags}'
  151. discmsg = f'DeadTOm is done streaming.'
  152. if testing != 1: # If we're testing, don't actually send out notification
  153. reg_m_name()
  154. reg_t_name()
  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}')