Upload 0.0.5

This commit is contained in:
norohind 2021-08-10 17:33:21 +03:00 committed by GitHub
parent 23d5ec14e6
commit 9eedde8450
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

227
load.py
View File

@ -1,48 +1,37 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import os, requests, threading, json, logging import os
import requests
import threading
import json
import logging
from config import appname from config import appname
''' # GPLv3, wrote by a31 aka norohind aka CMDR Aleksey31
#GPLv3, wrote by a31 aka norohind aka CMDR Aleksey31 # contact: a31#6403 (discord)
Patch note:
Add support for carrier name change event
Add possibility to disable sending any type of events (checkout class Plugin_settings from 35 line)
Add support for beta
Change way to build message for discord
Add body to jump message if we have it
'''
VERSION="0.0.4"
force_beta=False VERSION = "0.0.5"
''' force_beta = False # override Plugin_settings.SEND_IN_BETA
for use you must set an url
url can be str or list of strs
for example, single hook:
url="https://discord.com/api/webhooks/1"
or we can use multiple hooks like:
url1="https://discord.com/api/webhooks/1"
url2="https://discord.com/api/webhooks/2"
url= [ url1, url2 ]
and also we can do it in one line
url = ["https://discord.com/api/webhooks/1", "https://discord.com/api/webhooks/2"]
'''
url="" #set your url(s)
plugin_name = os.path.basename(os.path.dirname(__file__)) plugin_name = os.path.basename(os.path.dirname(__file__))
logger = logging.getLogger(f'{appname}.{plugin_name}') logger = logging.getLogger(f'{appname}.{plugin_name}')
#some settings
class Plugin_settings(): class Plugin_settings():
SEND_IN_BETA = False #do send messages when play in beta? SEND_IN_BETA = False # do send messages when play in beta?
SEND_JUMP_REQUESTS = True SEND_JUMP_REQUESTS = True
SEND_JUMPS = True SEND_JUMPS = True
SEND_JUMP_CANCELING = True SEND_JUMP_CANCELING = True
SEND_CHANGES_DOCKING_PERMISSIONS = True SEND_CHANGES_DOCKING_PERMISSIONS = True
SEND_CHANGES_NAME = True SEND_CHANGES_NAME = True
SEND_JUMPS_NOT_MY_OWN_CARRIER = True
class Messages(): class Messages():
"""Class that contains all using messages text"""
#take color in HEX and turn it into decimal # take color in HEX and turn it into decimal
COLOR_JUMP_REQUEST = "1127128" COLOR_JUMP_REQUEST = "1127128"
COLOR_JUMP_CANCELLED = "14177041" COLOR_JUMP_CANCELLED = "14177041"
COLOR_JUMP = "130816" COLOR_JUMP = "130816"
@ -53,14 +42,15 @@ class Messages():
TITLE_JUMP = "Прыжок совершён" TITLE_JUMP = "Прыжок совершён"
TITLE_JUMP_CANCELLED = "Прыжок отменён" TITLE_JUMP_CANCELLED = "Прыжок отменён"
TITLE_CHANGE_DOCKING_PERMISSION = "Изменение разрешения на стыковку" TITLE_CHANGE_DOCKING_PERMISSION = "Изменение разрешения на стыковку"
TITLE_IN_BETA= "Бета версия игры" TITLE_IN_BETA = "Бета версия игры"
TITLE_CHANGE_NAME = "Изменение имени носителя" TITLE_CHANGE_NAME = "Изменение имени носителя"
TEXT_JUMP_REQUEST_BODY_DIFF = " к телу {body}" TEXT_JUMP_REQUEST_BODY_DIFF = " к телу {body}"
TEXT_JUMP_REQUEST = "Запланирован прыжок носителя {name} в систему {system}" TEXT_JUMP_REQUEST = "Запланирован прыжок носителя {name} в систему {system}"
TEXT_JUMP = "Носитель {name} совершил прыжок в систему {system}" TEXT_JUMP = "Носитель {name} совершил прыжок в систему {system}"
TEXT_JUMP_CANCELLED = "Прыжок носителя {name} отменён" TEXT_JUMP_CANCELLED = "Прыжок носителя {name} отменён"
TEXT_PERMISSION_CHANGE = "Носитель {name} сменил разрешение на стыковку с {old_permission} на {new_permission}\nСтыковка для преступников была {old_doc_for_crime}, сейчас {new_doc_for_crime}" TEXT_PERMISSION_CHANGE = """Носитель {name} сменил разрешение на стыковку с {old_permission} на {new_permission}
Стыковка для преступников была {old_doc_for_crime}, сейчас {new_doc_for_crime}"""
TEXT_IN_BETA = "Внимание, данное сообщение относится только к бета версии игры!" TEXT_IN_BETA = "Внимание, данное сообщение относится только к бета версии игры!"
TEXT_CHANGE_NAME = "Имя носителя изменилось с {old_name} на {new_name}" TEXT_CHANGE_NAME = "Имя носителя изменилось с {old_name} на {new_name}"
@ -72,37 +62,65 @@ class Messages():
DOC_PERMISSION_ALLOW_NOTORIUS = "Разрешена" DOC_PERMISSION_ALLOW_NOTORIUS = "Разрешена"
DOC_PERMISSION_DISALLOW_NOTORIUS = "Запрещена" DOC_PERMISSION_DISALLOW_NOTORIUS = "Запрещена"
class Carrier(): class Carrier():
def __init__(self): def __init__(self):
self.name = None self.name = None
self.current_location = None self.callsign = None
self.cID = None #CarrierID (aka MarketID) self.location = None
self.cID = None # CarrierID (aka MarketID)
self.docking_permission = None self.docking_permission = None
self.allow_notorius = None self.allow_notorius = None
self.owner = None
self.store_key = None
class embed():
class Embed():
"""Building completed and ready for send embed message for discord. Requeries json lib""" """Building completed and ready for send embed message for discord. Requeries json lib"""
def __init__(self, **kwargs): # color, title, description, postponed def __init__(self, **kwargs): # color, title, description, username
self.items = list() self.items = list()
if len(kwargs) == 0: #we can create new object without creating an item of list, just do not pass anything to constructor
if kwargs.get('username') is not None: # we can pass only username
self.username = kwargs.get('username')
kwargs.pop('username')
else:
self.username = None
if len(kwargs) == 0: # we can create new object without creating an item, just do not pass anything (exception is 'username') to constructor
return return
self.add_item(**kwargs) self.add_item(**kwargs)
def add_item(self, **kwargs): def add_item(self, **kwargs):
color = str(kwargs.get('color')) color = kwargs.get('color')
title = str(kwargs.get('title')) title = kwargs.get('title')
description = str(kwargs.get('description')) description = kwargs.get('description')
self.items.append(dict(title=title, color=color, description=description)) self.items.append(dict(title=title, color=color, description=description))
return len(self.items) - 1 # index of added item
def get_message(self): def get_message(self):
"""Get full and ready for sending message"""
if self.username is not None:
return json.dumps(dict(username=self.username, embeds=self.items))
else:
return json.dumps(dict(embeds=self.items)) return json.dumps(dict(embeds=self.items))
def __str__(self): def __str__(self):
return str(self.get_message()) return str(self.get_message())
def update_item(self, item, key, new_value): #item number, key, new value def update_item(self, item, key, new_value):
"""Replace value under 'key' in 'item'"""
self.items[item][key] = new_value self.items[item][key] = new_value
def concatenate_item(self, item, key, new_value):
"""Add to existing value new part"""
self.items[item][key] = self.items[item][key] + new_value
def set_username(self, username):
"""Will override current webhook username, for reset call this func with None"""
self.username = username
class Messages_sender(threading.Thread): class Messages_sender(threading.Thread):
"""Sending message to discord asynchronously, support embeds and content= ways""" """Sending message to discord asynchronously, support embeds and content= ways"""
@ -111,14 +129,15 @@ class Messages_sender(threading.Thread):
self.message = message self.message = message
self.url = url self.url = url
self.embeds = embeds self.embeds = embeds
self.start()
def run(self): def run(self):
self.message = str(self.message)
if not self.embeds: if not self.embeds:
self.message=f"content={self.message}" self.message = f"content={self.message}"
self.headers={'Content-Type':'application/x-www-form-urlencoded'} self.headers = {'Content-Type': 'application/x-www-form-urlencoded'}
else: else:
self.headers={'Content-Type':'application/json'} self.headers = {'Content-Type': 'application/json'}
if isinstance(self.url, str): if isinstance(self.url, str):
self.single_url = self.url self.single_url = self.url
@ -136,45 +155,57 @@ class Messages_sender(threading.Thread):
logger.error(f"Status code: {r.status_code}!") logger.error(f"Status code: {r.status_code}!")
logger.error(r.text) logger.error(r.text)
def docking_permission2text(permission): def docking_permission2text(permission):
"""Convert one of all/none/friends/squadron/squadronfriends to user friendly message""" """Convert one of all/none/friends/squadron/squadronfriends to user friendly message"""
if permission == "all": options = {
return Messages.DOC_PERMISSION_ALL "all": Messages.DOC_PERMISSION_ALL,
elif permission == "none": "none": Messages.DOC_PERMISSION_NONE,
return Messages.DOC_PERMISSION_NONE "friends": Messages.DOC_PERMISSION_FRIENDS,
elif permission == "friends": "squadron": Messages.DOC_PERMISSION_SQUADRON,
return Messages.DOC_PERMISSION_FRIENDS "squadronfriends": Messages.DOC_PERMISSION_FRIENDS_SQUADRON
elif permission == "squadron": }
return Messages.DOC_PERMISSION_SQUADRON
elif permission == "squadronfriends": return options.get(permission) # if key isn't valid then return None
return Messages.DOC_PERMISSION_FRIENDS_SQUADRON
def docking_permission4notorius2text(notorius): def docking_permission4notorius2text(notorius):
"""As docking_permission2text() but for notorius (crime persons)""" """As docking_permission2text() but for notorius (crime persons)"""
if notorius == True: # in python True = 1, False = 0. So in our case False = docking disallow, True = docking allow
return Messages.DOC_PERMISSION_ALLOW_NOTORIUS return (Messages.DOC_PERMISSION_DISALLOW_NOTORIUS, Messages.DOC_PERMISSION_ALLOW_NOTORIUS)[notorius]
elif notorius == False:
return Messages.DOC_PERMISSION_DISALLOW_NOTORIUS
def plugin_start3(plugin_dir): def plugin_start3(plugin_dir):
logger.info(f"Plugin version: {VERSION}") logger.info(f"Plugin version: {VERSION}")
return 'FC dispatcher' return 'FC dispatcher'
def journal_entry(cmdr, is_beta, system, station, entry, state): def journal_entry(cmdr, is_beta, system, station, entry, state):
if is_beta and not Plugin_settings.SEND_IN_BETA: if is_beta and not Plugin_settings.SEND_IN_BETA:
return return
if state["Role"] is not None: # we don't work while you are multicrew passenger
logger.debug(f"returning because multicrew, role: {state['Role']}")
return
event = entry["event"] event = entry["event"]
if event == "CarrierStats": if event == "CarrierStats" and carrier.name is None:
carrier.name = entry["Name"] carrier.name = entry["Name"]
carrier.cID = entry["CarrierID"] carrier.cID = entry["CarrierID"]
carrier.docking_permission = entry["DockingAccess"] carrier.docking_permission = entry["DockingAccess"]
carrier.allow_notorius = entry["AllowNotorious"] carrier.allow_notorius = entry["AllowNotorious"]
carrier.callsign = entry["Callsign"]
return return
if event in ["CarrierJumpRequest", "CarrierJumpCancelled", "CarrierJump", "CarrierDockingPermission", "CarrierNameChanged"]: if event in [
message = embed() "CarrierJumpRequest",
"CarrierJumpCancelled",
"CarrierJump",
"CarrierDockingPermission",
"CarrierNameChange"]:
message = Embed()
if event == "CarrierJumpRequest" and Plugin_settings.SEND_JUMP_REQUESTS: if event == "CarrierJumpRequest" and Plugin_settings.SEND_JUMP_REQUESTS:
destination_system = entry["SystemName"] destination_system = entry["SystemName"]
@ -182,45 +213,93 @@ def journal_entry(cmdr, is_beta, system, station, entry, state):
try: try:
destination_body = entry["Body"] destination_body = entry["Body"]
message.update_item(item=0, key="description", new_value=Messages.TEXT_JUMP_REQUEST.format(name=carrier.name, system=destination_system) + Messages.TEXT_JUMP_REQUEST_BODY_DIFF.format(body=destination_body)) message.update_item(
item=0,
key="description",
new_value=Messages.TEXT_JUMP_REQUEST.format(
name=carrier.name,
system=destination_system) + Messages.TEXT_JUMP_REQUEST_BODY_DIFF.format(body=destination_body))
except KeyError: except KeyError:
message.update_item(item=0, key="description", new_value=TEXT_JUMP_REQUEST.format(name=carrier.name, system=destination_system)) message.update_item(
item=0,
key="description",
new_value=Messages.TEXT_JUMP_REQUEST.format(
name=carrier.name,
system=destination_system))
if event == "CarrierJumpCancelled" and Plugin_settings.SEND_JUMP_CANCELING: if event == "CarrierJumpCancelled" and Plugin_settings.SEND_JUMP_CANCELING:
message.add_item(color=Messages.COLOR_JUMP_CANCELLED, title=Messages.TITLE_JUMP_CANCELLED, description=Messages.TEXT_JUMP_CANCELLED.format(name=carrier.name)) message.add_item(
color=Messages.COLOR_JUMP_CANCELLED,
title=Messages.TITLE_JUMP_CANCELLED,
description=Messages.TEXT_JUMP_CANCELLED.format(name=carrier.name))
if event == "CarrierJump" and Plugin_settings.SEND_JUMPS: if event == "CarrierJump" and Plugin_settings.SEND_JUMPS:
# jump on not your own carrier case
if carrier.callsign != station:
# for case when you have your own carrier but now jumping on another one
if Plugin_settings.SEND_JUMPS_NOT_MY_OWN_CARRIER:
remember_carrier_name = carrier.name
carrier.name = station
else:
return
destination_system = entry["StarSystem"] destination_system = entry["StarSystem"]
message.add_item(color=Messages.COLOR_JUMP, title=Messages.TITLE_JUMP) message.add_item(color=Messages.COLOR_JUMP, title=Messages.TITLE_JUMP)
try: try:
destination_body = entry["Body"] destination_body = entry["Body"]
message.update_item(item=0, key="description", new_value=Messages.TEXT_JUMP.format(system=destination_system, name=carrier.name) + Messages.TEXT_JUMP_REQUEST_BODY_DIFF.format(body=destination_body)) message.update_item(
except KeyError: item=0,
message.update_item(item=0, key="description", new_value=Messages.TEXT_JUMP.format(system=destination_system, name=carrier.name)) key="description",
new_value=Messages.TEXT_JUMP.format(
system=destination_system,
name=carrier.name) + Messages.TEXT_JUMP_REQUEST_BODY_DIFF.format(body=destination_body))
except KeyError:
message.update_item(
item=0,
key="description",
new_value=Messages.TEXT_JUMP.format(
system=destination_system,
name=carrier.name))
if Plugin_settings.SEND_JUMPS_NOT_MY_OWN_CARRIER and carrier.callsign != station:
carrier.name = remember_carrier_name
if event == "CarrierDockingPermission" and Plugin_settings.SEND_CHANGES_DOCKING_PERMISSIONS: if event == "CarrierDockingPermission" and Plugin_settings.SEND_CHANGES_DOCKING_PERMISSIONS:
new_permission = entry["DockingAccess"] new_permission = entry["DockingAccess"]
new_doc_for_crime = entry["AllowNotorious"] new_doc_for_crime = entry["AllowNotorious"]
message.add_item(title=Messages.TITLE_CHANGE_DOCKING_PERMISSION, color=Messages.COLOR_PERMISSION_CHANGE, description=Messages.TEXT_PERMISSION_CHANGE.format( message.add_item(
name=carrier.name, old_permission=docking_permission2text(carrier.docking_permission), new_permission=docking_permission2text(new_permission), title=Messages.TITLE_CHANGE_DOCKING_PERMISSION,
old_doc_for_crime=docking_permission4notorius2text(carrier.allow_notorius), new_doc_for_crime=docking_permission4notorius2text(new_doc_for_crime))) color=Messages.COLOR_PERMISSION_CHANGE,
description=Messages.TEXT_PERMISSION_CHANGE.format(
name=carrier.name,
old_permission=docking_permission2text(carrier.docking_permission),
new_permission=docking_permission2text(new_permission),
old_doc_for_crime=docking_permission4notorius2text(carrier.allow_notorius),
new_doc_for_crime=docking_permission4notorius2text(new_doc_for_crime)))
carrier.docking_permission = new_permission carrier.docking_permission = new_permission
carrier.allow_notorius = new_doc_for_crime carrier.allow_notorius = new_doc_for_crime
if event == "CarrierNameChanged" and Plugin_settings.SEND_CHANGES_NAME: if event == "CarrierNameChange" and Plugin_settings.SEND_CHANGES_NAME:
new_name = entry["Name"] new_name = entry["Name"]
message.add_item(title=Messages.TITLE_CHANGE_NAME, description=Messages.TEXT_CHANGE_NAME.format(old_name=carrier.name, new_name=new_name), color=COLOR_CHANGE_NAME) message.add_item(
title=Messages.TITLE_CHANGE_NAME,
description=Messages.TEXT_CHANGE_NAME.format(
old_name=carrier.name,
new_name=new_name),
color=Messages.COLOR_CHANGE_NAME)
carrier.name = new_name carrier.name = new_name
if is_beta or force_beta: if is_beta or force_beta:
message.add_item(title=Messages.TITLE_IN_BETA, description=Messages.TEXT_IN_BETA) message.add_item(title=Messages.TITLE_IN_BETA, description=Messages.TEXT_IN_BETA)
Messages_sender(message.get_message(), url).start() #one Messages_sender instance per message Messages_sender(message.get_message(), url) #one Messages_sender instance per message
carrier = Carrier() carrier = Carrier()