やっぱ初期処理と関連の変数のクラスを分けた

This commit is contained in:
suti7yk5032 2024-07-07 15:24:55 +09:00
parent a16a0424dc
commit 2ef4d639bf

View file

@ -7,8 +7,7 @@ import string
import random import random
import csv import csv
class Dislocker():
class Bot(discord.Client):
def __init__(self): def __init__(self):
self.config_dir_path = "./config/" self.config_dir_path = "./config/"
self.export_dir_path = "./export/" self.export_dir_path = "./export/"
@ -16,7 +15,10 @@ class Bot(discord.Client):
if not os.path.isdir(self.config_dir_path): if not os.path.isdir(self.config_dir_path):
print("config ディレクトリが見つかりません... 作成します。") print("config ディレクトリが見つかりません... 作成します。")
os.mkdir(self.config_dir_path) try:
os.mkdir(self.config_dir_path)
except:
print("config ディレクトリを作成できませんでした。")
if not os.path.isfile(self.server_config_path): if not os.path.isfile(self.server_config_path):
print("config ファイルが見つかりません... 作成します。") print("config ファイルが見つかりません... 作成します。")
@ -35,8 +37,11 @@ class Bot(discord.Client):
} }
} }
with open(self.server_config_path, "w") as w: try:
json.dump(self.server_config, w, indent=4) with open(self.server_config_path, "w") as w:
json.dump(self.server_config, w, indent=4)
except:
print("config ファイルを作成できませんでした。")
elif os.path.isfile(self.server_config_path): elif os.path.isfile(self.server_config_path):
with open(self.server_config_path, "r") as r: with open(self.server_config_path, "r") as r:
@ -44,10 +49,16 @@ class Bot(discord.Client):
if not os.path.isdir(self.export_dir_path): if not os.path.isdir(self.export_dir_path):
print("export ディレクトリが見つかりません... 作成します。") print("export ディレクトリが見つかりません... 作成します。")
os.mkdir(self.export_dir_path) try:
os.mkdir(self.export_dir_path)
except:
print("export ディレクトリを作成できませんでした。")
self.db = psycopg2.connect(f"host={self.server_config['db']['host']} dbname={self.server_config['db']['db_name']} port={self.server_config['db']['port']} user={self.server_config['db']['username']} password={self.server_config['db']['password']}") self.db = psycopg2.connect(f"host={self.server_config['db']['host']} dbname={self.server_config['db']['db_name']} port={self.server_config['db']['port']} user={self.server_config['db']['username']} password={self.server_config['db']['password']}")
class Bot(discord.Client):
def password_generate(self, length): def password_generate(self, length):
numbers = string.digits # (1) numbers = string.digits # (1)
password = ''.join(random.choice(numbers) for _ in range(length)) # (2) password = ''.join(random.choice(numbers) for _ in range(length)) # (2)
@ -58,33 +69,50 @@ class Bot(discord.Client):
return hashed.hexdigest() return hashed.hexdigest()
def register(self, **kwargs): def register(self, **kwargs):
discord_user_id = str(kwargs["user_id"]) try:
pc_number = int(kwargs["pc_number"]) discord_user_id = str(kwargs["user_id"])
device_number = int(kwargs["device_number"]) pc_number = int(kwargs["pc_number"])
if "detail" in kwargs: device_number = int(kwargs["device_number"])
detail = str(kwargs["detail"]) if "detail" in kwargs:
else: detail = str(kwargs["detail"])
detail = None else:
#パスワード生成、ハッシュ化 detail = None
password = self.password_generate(4) #パスワード生成、ハッシュ化
password_hash = self.hash_genarate(password) password = self.password_generate(4)
print("password generated") password_hash = self.hash_genarate(password)
#メンバーリストと送信者を照合 print("password generated")
cursor = self.db.cursor() #メンバーリストと送信者を照合
cursor.execute("SELECT * FROM club_member WHERE discord_userid = %s", (discord_user_id,)) cursor = dislocker.db.cursor()
user_record = cursor.fetchall() cursor.execute("SELECT * FROM club_member WHERE discord_userid = %s", (discord_user_id,))
#ユーザーデータがなかったら(未登録の場合) user_record = cursor.fetchall()
if not user_record: #ユーザーデータがなかったら(未登録の場合)
result = {"result": "user_data_not_found"} if not user_record:
#ユーザーデータが見つかった場合(登録済みの場合) result = {"result": "user_data_not_found"}
else: #ユーザーデータが見つかった場合(登録済みの場合)
print("found user data") else:
cursor.execute("SELECT * FROM pc_usage_history WHERE member_id=%s ORDER BY id DESC LIMIT 1", (user_record[0][0],)) print("found user data")
pc_usage_history_record = cursor.fetchall() cursor.execute("SELECT * FROM pc_usage_history WHERE member_id=%s ORDER BY id DESC LIMIT 1", (user_record[0][0],))
if pc_usage_history_record: pc_usage_history_record = cursor.fetchall()
print("used") if pc_usage_history_record:
if pc_usage_history_record[0][5] == None: print("used")
result = {"result": "pc_already_in_use_by_you", "pc_number": str(pc_usage_history_record[0][2]), "device_number": str(pc_usage_history_record[0][3]), "start_time": str(pc_usage_history_record[0][4]), "detail": str(pc_usage_history_record[0][6])} if pc_usage_history_record[0][5] == None:
result = {"result": "pc_already_in_use_by_you", "pc_number": str(pc_usage_history_record[0][2]), "device_number": str(pc_usage_history_record[0][3]), "start_time": str(pc_usage_history_record[0][4]), "detail": str(pc_usage_history_record[0][6])}
else:
cursor.execute("SELECT * FROM pc_list WHERE pc_number=%s", (pc_number,))
pc_list_record = cursor.fetchall()
if not pc_list_record[0][1] == None:
result = {"result": "pc_already_in_use_by_other"}
else:
if detail == None:
cursor.execute("INSERT INTO pc_usage_history (member_id, pc_number, device_number, start_use_time) VALUES (%s, %s, %s, current_timestamp)", (user_record[0][0], pc_number, device_number))
#使用用途があるとき
else:
cursor.execute("INSERT INTO pc_usage_history (member_id, pc_number, device_number, start_use_time, use_detail) VALUES (%s, %s, %s, current_timestamp, %s)", (user_record[0][0], pc_number, device_number, detail))
cursor.execute("UPDATE pc_list SET using_user_id = %s WHERE pc_number = %s", (user_record[0][0], pc_number))
cursor.execute("UPDATE pc_list SET password_hash = %s WHERE pc_number = %s", (password_hash, pc_number))
dislocker.db.commit()
result = {"result": "ok", "password": str(password), "name": str(user_record[0][1])}
else: else:
cursor.execute("SELECT * FROM pc_list WHERE pc_number=%s", (pc_number,)) cursor.execute("SELECT * FROM pc_list WHERE pc_number=%s", (pc_number,))
pc_list_record = cursor.fetchall() pc_list_record = cursor.fetchall()
@ -99,65 +127,68 @@ class Bot(discord.Client):
cursor.execute("UPDATE pc_list SET using_user_id = %s WHERE pc_number = %s", (user_record[0][0], pc_number)) cursor.execute("UPDATE pc_list SET using_user_id = %s WHERE pc_number = %s", (user_record[0][0], pc_number))
cursor.execute("UPDATE pc_list SET password_hash = %s WHERE pc_number = %s", (password_hash, pc_number)) cursor.execute("UPDATE pc_list SET password_hash = %s WHERE pc_number = %s", (password_hash, pc_number))
self.db.commit() dislocker.db.commit()
result = {"result": "ok", "password": str(password), "name": str(user_record[0][1])} result = {"result": "ok", "password": str(password), "name": str(user_record[0][1])}
else: except:
cursor.execute("SELECT * FROM pc_list WHERE pc_number=%s", (pc_number,)) print("登録処理中にエラーが発生しました。")
pc_list_record = cursor.fetchall() result = {"result": "error"}
if not pc_list_record[0][1] == None:
result = {"result": "pc_already_in_use_by_other"} finally:
else: cursor.close()
if detail == None:
cursor.execute("INSERT INTO pc_usage_history (member_id, pc_number, device_number, start_use_time) VALUES (%s, %s, %s, current_timestamp)", (user_record[0][0], pc_number, device_number))
#使用用途があるとき
else:
cursor.execute("INSERT INTO pc_usage_history (member_id, pc_number, device_number, start_use_time, use_detail) VALUES (%s, %s, %s, current_timestamp, %s)", (user_record[0][0], pc_number, device_number, detail))
cursor.execute("UPDATE pc_list SET using_user_id = %s WHERE pc_number = %s", (user_record[0][0], pc_number))
cursor.execute("UPDATE pc_list SET password_hash = %s WHERE pc_number = %s", (password_hash, pc_number))
self.db.commit()
result = {"result": "ok", "password": str(password), "name": str(user_record[0][1])}
return result return result
def stop(self, **kwargs): def stop(self, **kwargs):
discord_user_id = str(kwargs["user_id"]) try:
cursor = self.db.cursor() discord_user_id = str(kwargs["user_id"])
cursor.execute("SELECT * FROM club_member WHERE discord_userid = %s", (discord_user_id,)) cursor = dislocker.db.cursor()
user_record = cursor.fetchall() cursor.execute("SELECT * FROM club_member WHERE discord_userid = %s", (discord_user_id,))
cursor.execute("SELECT * FROM pc_usage_history WHERE member_id= %s ORDER BY id DESC LIMIT 1", (user_record[0][0],)) user_record = cursor.fetchall()
pc_usage_history_record = cursor.fetchall() cursor.execute("SELECT * FROM pc_usage_history WHERE member_id= %s ORDER BY id DESC LIMIT 1", (user_record[0][0],))
if pc_usage_history_record: pc_usage_history_record = cursor.fetchall()
if not pc_usage_history_record[0][5] == None: if pc_usage_history_record:
result = {"result": "unused"} if not pc_usage_history_record[0][5] == None:
else: result = {"result": "unused"}
cursor.execute("UPDATE pc_usage_history SET end_use_time = current_timestamp WHERE id = %s", (pc_usage_history_record[0][0],)) else:
cursor.execute("UPDATE pc_list SET using_user_id = NULL WHERE pc_number = %s", (pc_usage_history_record[0][2],)) cursor.execute("UPDATE pc_usage_history SET end_use_time = current_timestamp WHERE id = %s", (pc_usage_history_record[0][0],))
cursor.execute("UPDATE pc_list SET password_hash = NULL WHERE pc_number = %s", (pc_usage_history_record[0][2],)) cursor.execute("UPDATE pc_list SET using_user_id = NULL WHERE pc_number = %s", (pc_usage_history_record[0][2],))
self.db.commit() cursor.execute("UPDATE pc_list SET password_hash = NULL WHERE pc_number = %s", (pc_usage_history_record[0][2],))
result = {"result": "ok", "pc_number": str(pc_usage_history_record[0][2]), "name": str(user_record[0][1])} dislocker.db.commit()
result = {"result": "ok", "pc_number": str(pc_usage_history_record[0][2]), "name": str(user_record[0][1])}
except:
print("停止処理にエラーが発生しました。")
result = {"result": "error"}
return result return result
def user_register(self, **kwargs): def user_register(self, **kwargs):
discord_user_id = str(kwargs["discord_user_id"]) try:
discord_user_name = str(kwargs["discord_user_name"]) discord_user_id = str(kwargs["discord_user_id"])
name = str(kwargs["name"]) discord_user_name = str(kwargs["discord_user_name"])
cursor = self.db.cursor() name = str(kwargs["name"])
cursor.execute("SELECT * FROM club_member WHERE discord_userid = %s", (discord_user_id,)) cursor = dislocker.db.cursor()
user_record = cursor.fetchall() cursor.execute("SELECT * FROM club_member WHERE discord_userid = %s", (discord_user_id,))
if not user_record: user_record = cursor.fetchall()
cursor.execute("INSERT INTO club_member (name, discord_username, discord_userid) VALUES (%s, %s, %s)", (name, discord_user_name, discord_user_id)) if not user_record:
self.db.commit() cursor.execute("INSERT INTO club_member (name, discord_username, discord_userid) VALUES (%s, %s, %s)", (name, discord_user_name, discord_user_id))
result = {"result": "ok"} dislocker.db.commit()
else: result = {"result": "ok"}
result = {"result": "already_exists"} else:
result = {"result": "already_exists"}
except:
print("ユーザー登録中にエラーが発生しました。")
result = {"result": "error"}
finally:
cursor.close()
return result return result
def report_export(self, **kwargs): def report_export(self, **kwargs):
try: try:
csv_file_path = self.export_dir_path + "pc_usage_history.csv" csv_file_path = self.export_dir_path + "pc_usage_history.csv"
cursor = self.db.cursor() cursor = dislocker.db.cursor()
# メインテーブルの列情報を取得user_idを除く # メインテーブルの列情報を取得user_idを除く
cur.execute(sql.SQL("SELECT * FROM {} LIMIT 0").format(sql.Identifier(main_table))) cur.execute(sql.SQL("SELECT * FROM {} LIMIT 0").format(sql.Identifier(main_table)))
main_columns = [desc[0] for desc in cur.description if desc[0] != 'member_id'] main_columns = [desc[0] for desc in cur.description if desc[0] != 'member_id']
@ -190,6 +221,7 @@ class Bot(discord.Client):
csvwriter.writerow(formatted_row) csvwriter.writerow(formatted_row)
print(f"テーブル '{main_table}' の内容を '{csv_file_path}' に出力しました。") print(f"テーブル '{main_table}' の内容を '{csv_file_path}' に出力しました。")
result = {"result": "ok", "file_path": csv_file_path}
except (Exception, psycopg2.Error) as error: except (Exception, psycopg2.Error) as error:
print("使用履歴のエクスポート時にエラーが発生しました\nエラー内容\n", error) print("使用履歴のエクスポート時にエラーが発生しました\nエラー内容\n", error)
@ -197,7 +229,6 @@ class Bot(discord.Client):
finally: finally:
cursor.close() cursor.close()
result = {"result": "ok", "file_path": csv_file_path}
return result return result
@ -232,7 +263,7 @@ class Bot(discord.Client):
await message.channel.send(f"使用が開始されました。\nパスワード | {register["password"]}\nPC番号 | {msg_split[1]}\nデバイス番号 | {msg_split[2]}") await message.channel.send(f"使用が開始されました。\nパスワード | {register["password"]}\nPC番号 | {msg_split[1]}\nデバイス番号 | {msg_split[2]}")
elif len(msg_split) == 4: elif len(msg_split) == 4:
await message.channel.send(f"使用が開始されました。\nパスワード | {register["password"]}\nPC番号 | {msg_split[1]}\nデバイス番号 | {msg_split[2]}\n使用目的 | {msg_split[3]}") await message.channel.send(f"使用が開始されました。\nパスワード | {register["password"]}\nPC番号 | {msg_split[1]}\nデバイス番号 | {msg_split[2]}\n使用目的 | {msg_split[3]}")
await self.get_channel(self.server_config["bot"]["log_channel_id"]).send(f'{register["name"]} さんがPC {msg_split[1]} を使用しています') await self.get_channel(dislocker.server.config["bot"]["log_channel_id"]).send(f'{register["name"]} さんがPC {msg_split[1]} を使用しています')
elif register["result"] == "user_data_not_found": elif register["result"] == "user_data_not_found":
await message.channel.send("ユーザーとして登録されていないようです。管理者に問い合わせてください。") await message.channel.send("ユーザーとして登録されていないようです。管理者に問い合わせてください。")
elif register["result"] == "pc_already_in_use_by_you": elif register["result"] == "pc_already_in_use_by_you":
@ -250,9 +281,9 @@ class Bot(discord.Client):
await message.channel.send("使用されていないようです...") await message.channel.send("使用されていないようです...")
elif stop["result"] == "ok": elif stop["result"] == "ok":
await message.channel.send(f"PC番号 {stop["pc_number"]} の使用が終了されました。") await message.channel.send(f"PC番号 {stop["pc_number"]} の使用が終了されました。")
await self.get_channel(self.server_config["bot"]["log_channel_id"]).send(f'{stop["name"]} さんがPC {stop["pc_number"]} の使用を終了しました') await self.get_channel(dislocker.server.config["bot"]["log_channel_id"]).send(f'{stop["name"]} さんがPC {stop["pc_number"]} の使用を終了しました')
elif message.channel.id == self.server_config["bot"]["config_channel_id"]: elif message.channel.id == dislocker.server.config["bot"]["config_channel_id"]:
msg_split = message.content.split() msg_split = message.content.split()
if msg_split[0] == "/register": if msg_split[0] == "/register":
if len(msg_split) <= 3: if len(msg_split) <= 3:
@ -281,5 +312,6 @@ class Bot(discord.Client):
intents = discord.Intents.default() intents = discord.Intents.default()
intents.message_content = True intents.message_content = True
dislocker = Dislocker()
bot = Bot(intents=intents) bot = Bot(intents=intents)
bot.run(bot.server_config['bot']['token']) bot.run(dislocker.server_config['bot']['token'])