Skip to content

Commit

Permalink
style: formatted the code with black
Browse files Browse the repository at this point in the history
- Formatted the code with black to look better
- Added dev-requirements.txt
- Added some missing screenshot
  • Loading branch information
moonburnt committed Jul 29, 2021
1 parent 196f9e4 commit 98fff57
Show file tree
Hide file tree
Showing 8 changed files with 620 additions and 430 deletions.
1 change: 1 addition & 0 deletions dev-requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
black>=21.7b0
4 changes: 2 additions & 2 deletions notashark/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
BOT_NAME = "notashark"
BOT_PREFIX = "!"
SERVERLIST_UPDATE_TIME = 30
#updating settings file each 5 minutes
# updating settings file each 5 minutes
SETTINGS_AUTOSAVE_TIME = 300
SETTINGS_FILE = join('.', 'settings.json')
SETTINGS_FILE = join(".", "settings.json")
LOG_FILE = f"{BOT_NAME}.log"
321 changes: 181 additions & 140 deletions notashark/data_fetcher.py

Large diffs are not rendered by default.

287 changes: 181 additions & 106 deletions notashark/discord_bot.py

Large diffs are not rendered by default.

253 changes: 141 additions & 112 deletions notashark/embeds_processor.py

Large diffs are not rendered by default.

43 changes: 26 additions & 17 deletions notashark/settings_fetcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,51 +26,60 @@
SETTINGS_FILE = configuration.SETTINGS_FILE
SETTINGS_AUTOSAVE_TIME = configuration.SETTINGS_AUTOSAVE_TIME


def settings_loader():
'''Loads settings from SETTINGS_FILE, if available'''
with open(SETTINGS_FILE, 'r') as j:
"""Loads settings from SETTINGS_FILE, if available"""
with open(SETTINGS_FILE, "r") as j:
data = json.load(j)
log.debug(f"Got following data: {data}")
return data


try:
SETTINGS_DICTIONARY = settings_loader()
except Exception as e:
log.error("An unfortunate exception has occured while "
f"trying to load {SETTINGS_FILE}: {e}")
log.error(
"An unfortunate exception has occured while "
f"trying to load {SETTINGS_FILE}: {e}"
)
SETTINGS_DICTIONARY = {}


def settings_saver():
'''Converts SETTINGS_DICTIONARY to json and saves to SETTINGS_FILE'''
"""Converts SETTINGS_DICTIONARY to json and saves to SETTINGS_FILE"""
jdata = json.dumps(SETTINGS_DICTIONARY)
with open(SETTINGS_FILE, 'w') as f:
with open(SETTINGS_FILE, "w") as f:
f.write(jdata)
log.debug(f"Successfully wrote data to {SETTINGS_FILE}")


def settings_checker(guild_id):
'''Receive str(guild_id). If guild doesnt exist - add it to list'''
#I have no idea if this should be there at all, lol
"""Receive str(guild_id). If guild doesnt exist - add it to list"""
# I have no idea if this should be there at all, lol
guild_id = str(guild_id)
global SETTINGS_DICTIONARY
if not guild_id in SETTINGS_DICTIONARY:
log.debug(f"Couldnt find {guild_id} in SETTINGS_DICTIONARY, adding")
x = {}
x['serverlist_channel_id'] = None #id of serverlist channel
x['serverlist_message_id'] = None #id of message that should be edited
#idk if this needs more settings
x["serverlist_channel_id"] = None # id of serverlist channel
x["serverlist_message_id"] = None # id of message that should be edited
# idk if this needs more settings
SETTINGS_DICTIONARY[guild_id] = x
#Im not sure if this may go into race condition situation
#if called for multiple servers at once. Hopefully not
# Im not sure if this may go into race condition situation
# if called for multiple servers at once. Hopefully not
log.debug(f"Now settings list looks like: {SETTINGS_DICTIONARY}")
else:
log.debug(f"Found {guild_id} on SETTINGS_DICTIONARY, no need to add manually")


def _settings_autosaver():
'''Autosaves settings to SETTINGS_FILE each SETTINGS_AUTOSAVE_TIME seconds.
Intended to be ran in separate thread on application's launch'''
"""Autosaves settings to SETTINGS_FILE each SETTINGS_AUTOSAVE_TIME seconds.
Intended to be ran in separate thread on application's launch"""
while True:
log.debug(f"Waiting {SETTINGS_AUTOSAVE_TIME} seconds "
f"to save settings to {SETTINGS_FILE}")
log.debug(
f"Waiting {SETTINGS_AUTOSAVE_TIME} seconds "
f"to save settings to {SETTINGS_FILE}"
)
sleep(SETTINGS_AUTOSAVE_TIME)
try:
settings_saver()
Expand Down
141 changes: 88 additions & 53 deletions run_notashark
Original file line number Diff line number Diff line change
Expand Up @@ -28,49 +28,72 @@ BOT_NAME = notashark.configuration.BOT_NAME
DEFAULT_SERVERLIST_UPDATE_TIME = notashark.configuration.SERVERLIST_UPDATE_TIME
DEFAULT_SETTINGS_AUTOSAVE_TIME = notashark.configuration.SETTINGS_AUTOSAVE_TIME

#log = logging.getLogger('notashark')
# log = logging.getLogger('notashark')
log = logging.getLogger()
#looks like overriding logger's own level isnt the best idea, since it also make
#logs below its level unaccessible to handlers, regardless of their settings.
#Correct approach is to set logger itself to some sane level and then toggle
#things on per-handler basis
#log.setLevel(logging.WARNING)
# looks like overriding logger's own level isnt the best idea, since it also make
# logs below its level unaccessible to handlers, regardless of their settings.
# Correct approach is to set logger itself to some sane level and then toggle
# things on per-handler basis
# log.setLevel(logging.WARNING)
log.setLevel(logging.INFO)

#Formatter for both handlers
# Formatter for both handlers
formatter = logging.Formatter(
fmt = '[%(asctime)s][%(name)s][%(levelname)s] %(message)s',
datefmt = '%d.%m.%y %H:%M:%S',
)

#this is a rotating handler that automatically ensures that log wont grow beyond
#certain size and make backups of older logs. Really cool thing, may tweak it l8r
file_handler = RotatingFileHandler(notashark.configuration.LOG_FILE, mode='a',
maxBytes=(10*1024*1024),
backupCount=2, encoding=None, delay=0)
#file_handler = logging.FileHandler(LOG_FILE)
fmt="[%(asctime)s][%(name)s][%(levelname)s] %(message)s",
datefmt="%d.%m.%y %H:%M:%S",
)

# this is a rotating handler that automatically ensures that log wont grow beyond
# certain size and make backups of older logs. Really cool thing, may tweak it l8r
file_handler = RotatingFileHandler(
notashark.configuration.LOG_FILE,
mode="a",
maxBytes=(10 * 1024 * 1024),
backupCount=2,
encoding=None,
delay=0,
)
# file_handler = logging.FileHandler(LOG_FILE)
file_handler.setFormatter(formatter)
#file_handler.setLevel(logging.WARNING)
# file_handler.setLevel(logging.WARNING)
log.addHandler(file_handler)

ap = argparse.ArgumentParser()
ap.add_argument("--token", help = ("Use this to supply your token to bot, "
"in case envars arent an option"))
ap.add_argument("--debug", action = "store_true",
help = f"Add debug messages to {BOT_NAME}'s output")
ap.add_argument("--serverlist-update-time", type = int,
help = ("Custom lengh (in seconds) of pause between requests to api in order "
"to get fresh info about active servers with players on them. Also "
"used to autoupdate related embed. Could not be less than default "
f"value, which is {DEFAULT_SERVERLIST_UPDATE_TIME} seconds"))
ap.add_argument("--settings-autosave-time", type = int,
help = ("Custom lengh (in seconds) of pause between autosaving per-server "
"settings on disk. Could not be less than default value, which is "
f"{DEFAULT_SETTINGS_AUTOSAVE_TIME} seconds"))
ap.add_argument("--show-logs", action = "store_true",
help = ("Enable showcase of logs in terminal. Else these will be "
f"only seen in {notashark.configuration.LOG_FILE} file"))
#TODO: maybe add arg to override log file location/name?
ap.add_argument(
"--token",
help=("Use this to supply your token to bot, " "in case envars arent an option"),
)
ap.add_argument(
"--debug", action="store_true", help=f"Add debug messages to {BOT_NAME}'s output"
)
ap.add_argument(
"--serverlist-update-time",
type=int,
help=(
"Custom lengh (in seconds) of pause between requests to api in order "
"to get fresh info about active servers with players on them. Also "
"used to autoupdate related embed. Could not be less than default "
f"value, which is {DEFAULT_SERVERLIST_UPDATE_TIME} seconds"
),
)
ap.add_argument(
"--settings-autosave-time",
type=int,
help=(
"Custom lengh (in seconds) of pause between autosaving per-server "
"settings on disk. Could not be less than default value, which is "
f"{DEFAULT_SETTINGS_AUTOSAVE_TIME} seconds"
),
)
ap.add_argument(
"--show-logs",
action="store_true",
help=(
"Enable showcase of logs in terminal. Else these will be "
f"only seen in {notashark.configuration.LOG_FILE} file"
),
)
# TODO: maybe add arg to override log file location/name?

args = ap.parse_args()

Expand All @@ -80,31 +103,41 @@ if args.debug:
if args.show_logs:
terminal_handler = logging.StreamHandler()
terminal_handler.setFormatter(formatter)
#terminal_handler.setLevel(logging.ERROR)
# terminal_handler.setLevel(logging.ERROR)
log.addHandler(terminal_handler)

BOT_TOKEN = args.token or environ.get('NOTASHARK_DISCORD_KEY', None)
BOT_TOKEN = args.token or environ.get("NOTASHARK_DISCORD_KEY", None)
if not BOT_TOKEN:
log.critical("You didnt specify your discord bot's token! Please, either "
"set NOTASHARK_DISCORD_KEY environment variable, or pass it "
"via --token launch argument!\nAbort")
log.critical(
"You didnt specify your discord bot's token! Please, either "
"set NOTASHARK_DISCORD_KEY environment variable, or pass it "
"via --token launch argument!\nAbort"
)
exit(1)

if (args.serverlist_update_time and
(args.serverlist_update_time > DEFAULT_SERVERLIST_UPDATE_TIME)):
if args.serverlist_update_time and (
args.serverlist_update_time > DEFAULT_SERVERLIST_UPDATE_TIME
):
notashark.configuration.SERVERLIST_UPDATE_TIME = args.serverlist_update_time
log.info("Serverlist update time has been set to "
f"{notashark.configuration.SERVERLIST_UPDATE_TIME} seconds")

if (args.settings_autosave_time and
(args.settings_autosave_time > DEFAULT_SETTINGS_AUTOSAVE_TIME)):
log.info(
"Serverlist update time has been set to "
f"{notashark.configuration.SERVERLIST_UPDATE_TIME} seconds"
)

if args.settings_autosave_time and (
args.settings_autosave_time > DEFAULT_SETTINGS_AUTOSAVE_TIME
):
notashark.configuration.SETTINGS_AUTOSAVE_TIME = args.settings_autosave_time
log.info("Settings autosave time has been set to "
f"{notashark.configuration.SETTINGS_AUTOSAVE_TIME} seconds")
log.info(
"Settings autosave time has been set to "
f"{notashark.configuration.SETTINGS_AUTOSAVE_TIME} seconds"
)

log.debug(f"Launching data fetcher")
#daemon=True allows to shutdown this thing in case of emergency right away
dft = threading.Thread(target=notashark.data_fetcher._serverlist_autoupdater, daemon=True)
# daemon=True allows to shutdown this thing in case of emergency right away
dft = threading.Thread(
target=notashark.data_fetcher._serverlist_autoupdater, daemon=True
)
dft.start()

log.debug(f"Launching settings autosaver")
Expand All @@ -115,6 +148,8 @@ log.debug(f"Launching {BOT_NAME}")
try:
notashark.discord_bot.bot.run(BOT_TOKEN)
except discord.errors.LoginFailure:
log.critical("Invalid token error: double-check the value of "
"NOTASHARK_DISCORD_KEY environment variable.\nAbort")
log.critical(
"Invalid token error: double-check the value of "
"NOTASHARK_DISCORD_KEY environment variable.\nAbort"
)
exit(1)
Binary file added screenshots/self_updating_status.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 98fff57

Please sign in to comment.