This repository was archived by the owner on Jul 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrun.py
More file actions
135 lines (109 loc) · 5.12 KB
/
run.py
File metadata and controls
135 lines (109 loc) · 5.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import asyncio
import logging
import os
import pytz
import json
from copy import deepcopy
from datetime import datetime
from shutil import copyfile
import discord
from discord.ext import commands
svgebot = commands.Bot(command_prefix="placeholder")
@svgebot.event
async def on_ready():
logger.info("SVGEBot ready")
@svgebot.event
async def on_message(message):
if message.author.bot:
return
try:
if message.content.startswith(svgebot.bot_config["cmd_prefix"]):
async with message.channel.typing():
if message.channel != message.author.dm_channel:
await message.delete()
logger.info(f"Command: '{message.content}' from: '{message.author}'")
await svgebot.process_commands(message)
except commands.errors.CheckFailure as check_fail:
logger.info("User {0} sent the command {1}, which failed "
"command checks with: \n{2}".format(message.author,
message.content,
check_fail))
await message.channel.send("You do not have the permissions "
"required for this command",
delete_after=svgebot.delete_msg_after)
except commands.errors.CommandNotFound as cmd_not_found:
logger.debug(f"Command Not Found Error: \n{cmd_not_found}.")
await message.author.send(f'Command "{message.content}" does not exist.',
delete_after=svgebot.delete_msg_after)
except commands.errors.MissingRequiredArgument as missing_required_arg:
logger.debug(f"Command Not Found Error: \n{missing_required_arg}.")
await message.author.send(f'Command "{message.content}" was missing a '
f'required argument:\n\n```{missing_required_arg}```')
if __name__ == "__main__":
# Logging configuration
dt_now_formatted = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
if not os.path.exists("./logs/"):
os.mkdir("./logs/")
print("Created ./logs/ folder for persistent logging")
logger = logging.getLogger("SVGEBot")
logger.setLevel(logging.INFO)
if not os.path.exists("./config/temp_config.json"):
copyfile("./config/temp_config_default.json", "./config/temp_config.json")
logger.warning("Config was missing, copied config template")
with open("./config/temp_config.json", "r") as config_file:
temp_config_json = json.load(config_file)
formatter = logging.Formatter('[{asctime}] [{levelname:}] {name}: {message}',
'%Y-%m-%d %H:%M:%S', style='{')
file_log = logging.FileHandler(f"./logs/svgebot_log_{dt_now_formatted}.log",
encoding="utf-8", mode="w")
console_log = logging.StreamHandler()
file_log.setFormatter(formatter)
console_log.setFormatter(formatter)
logger.addHandler(file_log)
logger.addHandler(console_log)
logger.debug("Logging ready")
possible_logging_levels = {
"DEBUG": logging.DEBUG,
"INFO": logging.INFO,
"WARN": logging.WARN,
"WARNING": logging.WARNING,
"ERROR": logging.ERROR
}
try:
logger.setLevel(possible_logging_levels[temp_config_json["logging_level"]])
except KeyError:
logger.exception("Selected logging level not supported")
input()
exit(1)
if temp_config_json["bot"]["delete_msg_after"] == -1:
temp_config_json["bot"]["delete_msg_after"] = None
logger.debug("Loaded config variables")
svgebot.command_prefix = temp_config_json["bot"]["cmd_prefix"]
logger.info(f"Set command prefix to: {temp_config_json['bot']['cmd_prefix']}")
config_for_bot_dist = deepcopy(temp_config_json)
# Remove the token from the data that's distributed to cogs
del config_for_bot_dist["bot"]["token"]
svgebot.bot_config = config_for_bot_dist["bot"]
svgebot.delete_msg_after = config_for_bot_dist["bot"]["delete_msg_after"]
cogs_loaded_counter = 0
for cog_to_load in os.listdir("./extensions/"):
if cog_to_load.endswith(".py"):
logger.debug(f"Found {cog_to_load[:-3]}")
if f"extensions.{cog_to_load[:-3]}" in temp_config_json["autoload extensions"]:
try:
svgebot.load_extension(f"extensions.{cog_to_load[:-3]}")
cogs_loaded_counter += 1
except Exception as e:
logger.warning(f"Failed to load extension: {cog_to_load[:-3]}\n\n"
f"{e}")
if cogs_loaded_counter != 0:
logger.debug(f"Auto-loaded {cogs_loaded_counter} extension(s)")
else:
logger.warning("Autoloaded no extensions in ./extensions/, this will cause "
"major losses in bot functionality")
logger.debug("Bot process starting")
try:
svgebot.run(temp_config_json["bot"]["token"], reconnect=True)
except discord.LoginFailure as login_failure_e:
logger.exception(f"Bot login was not completed:\n{login_failure_e}")
input()