ユーザー登録をユーザー自身でもできるように

This commit is contained in:
suti7yk5032 2024-07-20 20:11:11 +09:00
parent 00a4c00fcf
commit 585ddf8cf1

View file

@ -55,6 +55,30 @@ class DL():
self.init_result = "not_int" self.init_result = "not_int"
else: else:
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']}")
cursor = self.db.cursor()
cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'club_member')")
find_club_member_table = cursor.fetchall()
print(find_club_member_table)
if find_club_member_table[0][0] == False:
cursor.execute("CREATE TABLE club_member (id SERIAL NOT NULL, name VARCHAR(30) NOT NULL, discord_username VARCHAR(32) NOT NULL, discord_userid VARCHAR(18) NOT NULL, PRIMARY KEY (id))")
self.db.commit()
cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'pc_list')")
find_pc_list_table = cursor.fetchall()
print(find_pc_list_table)
if find_pc_list_table[0][0] == False:
cursor.execute("CREATE TABLE pc_list (pc_number INTEGER NOT NULL, using_user_id INTEGER, password_hash VARCHAR(32), PRIMARY KEY (pc_number), FOREIGN KEY (using_user_id) REFERENCES club_member(id))")
self.db.commit
cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'pc_usage_history')")
find_pc_usage_history_table = cursor.fetchall()
print(find_pc_usage_history_table)
if find_pc_usage_history_table[0][0] == False:
cursor.execute("CREATE TABLE pc_usage_history (id SERIAL NOT NULL, member_id INTEGER NOT NULL, pc_number INTEGER NOT NULL, device_number INTEGER NOT NULL, start_use_time TIMESTAMP NOT NULL, end_use_time TIMESTAMP, use_detail VARCHAR(30), PRIMARY KEY (id), FOREIGN KEY (member_id) REFERENCES club_member(id), FOREIGN KEY (pc_number) REFERENCES pc_list(pc_number))")
self.db.commit()
cursor.close()
self.init_result = "ok" self.init_result = "ok"
except (Exception) as error: except (Exception) as error:
@ -77,20 +101,25 @@ class Bot(discord.Client):
def register(self, **kwargs): def register(self, **kwargs):
try: try:
discord_user_id = str(kwargs["user_id"]) user_info = {
pc_number = int(kwargs["pc_number"]) "id": str(kwargs["user_id"]),
device_number = int(kwargs["device_number"]) "name": str(kwargs["name"]),
"display_name": str(kwargs["display_name"]),
"pc_number": int(kwargs["pc_number"]),
"device_number": int(kwargs["device_number"]),
"detail": None
}
if "detail" in kwargs: if "detail" in kwargs:
detail = str(kwargs["detail"]) user_info["detail"] = str(kwargs["detail"])
else: else:
detail = None pass
#パスワード生成、ハッシュ化 #パスワード生成、ハッシュ化
password = self.password_generate(4) password = self.password_generate(4)
password_hash = self.hash_genarate(password) password_hash = self.hash_genarate(password)
print("password generated") print("password generated")
#メンバーリストと送信者を照合 #メンバーリストと送信者を照合
cursor = dislocker.db.cursor() cursor = dislocker.db.cursor()
cursor.execute("SELECT * FROM club_member WHERE discord_userid = %s", (discord_user_id,)) cursor.execute("SELECT * FROM club_member WHERE discord_userid = %s", (user_info["id"],))
user_record = cursor.fetchall() user_record = cursor.fetchall()
#ユーザーデータがなかったら(未登録の場合) #ユーザーデータがなかったら(未登録の場合)
if not user_record: if not user_record:
@ -105,39 +134,57 @@ class Bot(discord.Client):
if pc_usage_history_record[0][5] == None: 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])} 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: else:
cursor.execute("SELECT * FROM pc_list WHERE pc_number=%s", (pc_number,)) cursor.execute("SELECT * FROM pc_list WHERE pc_number=%s", (user_info["pc_number"],))
pc_list_record = cursor.fetchall() pc_list_record = cursor.fetchall()
if not pc_list_record[0][1] == None: if not pc_list_record[0][1] == None:
result = {"result": "pc_already_in_use_by_other"} result = {"result": "pc_already_in_use_by_other"}
else: else:
if detail == None: if user_info["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)) 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], user_info["pc_number"], user_info["device_number"]))
#使用用途があるとき #使用用途があるとき
else: 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("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], user_info["pc_number"], user_info["device_number"], user_info["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 using_user_id = %s WHERE pc_number = %s", (user_record[0][0], user_info["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, user_info["pc_number"]))
dislocker.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: else:
cursor.execute("SELECT * FROM pc_list WHERE pc_number=%s", (pc_number,)) print("unused")
cursor.execute("SELECT * FROM pc_list WHERE pc_number=%s", (user_info["pc_number"],))
pc_list_record = cursor.fetchall() pc_list_record = cursor.fetchall()
if not pc_list_record[0][1] == None: if pc_list_record:
result = {"result": "pc_already_in_use_by_other"} if not pc_list_record[0][1] == None:
result = {"result": "pc_already_in_use_by_other"}
else:
if user_info["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], user_info["pc_number"], user_info["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], user_info["pc_number"], user_info["device_number"], user_info["detail"]))
cursor.execute("UPDATE pc_list SET using_user_id = %s WHERE pc_number = %s", (user_record[0][0], user_info["pc_number"]))
cursor.execute("UPDATE pc_list SET password_hash = %s WHERE pc_number = %s", (password_hash, user_info["pc_number"]))
dislocker.db.commit()
result = {"result": "ok", "password": str(password), "name": str(user_record[0][1])}
else: else:
if detail == None: if user_info["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)) 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], user_info["pc_number"], user_info["device_number"]))
#使用用途があるとき #使用用途があるとき
else: 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("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], user_info["pc_number"], user_info["device_number"], user_info["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 using_user_id = %s WHERE pc_number = %s", (user_record[0][0], user_info["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, user_info["pc_number"]))
dislocker.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])}
except:
print("登録処理中にエラーが発生しました。")
except Exception as error:
print("登録処理中にエラーが発生しました。\nエラー内容")
print(str(error.__class__.__name__))
print(str(error.args))
print(str(error))
result = {"result": "error"} result = {"result": "error"}
finally: finally:
@ -184,8 +231,11 @@ class Bot(discord.Client):
else: else:
result = {"result": "already_exists"} result = {"result": "already_exists"}
except: except Exception as error:
print("ユーザー登録中にエラーが発生しました。") print("ユーザー登録中にエラーが発生しました。\nエラー内容")
print(str(error.__class__.__name__))
print(str(error.args))
print(str(error))
result = {"result": "error"} result = {"result": "error"}
finally: finally:
@ -316,9 +366,9 @@ class Bot(discord.Client):
#PC番号が1以上10以下であることを確認 #PC番号が1以上10以下であることを確認
if int(msg_split[1]) <= 10 and int(msg_split[1]) >= 1: if int(msg_split[1]) <= 10 and int(msg_split[1]) >= 1:
if len(msg_split) == 3: if len(msg_split) == 3:
register = self.register(user_id=message.author.id, pc_number=msg_split[1], device_number=msg_split[2]) register = self.register(user_id=message.author.id, name=message.author.name, display_name=message.author.display_name, pc_number=msg_split[1], device_number=msg_split[2])
elif len(msg_split) == 4: elif len(msg_split) == 4:
register = self.register(user_id=message.author.id, pc_number=msg_split[1], device_number=msg_split[2], detail=msg_split[3]) register = self.register(user_id=message.author.id, name=message.author.name, display_name=message.author.display_name, pc_number=msg_split[1], device_number=msg_split[2], detail=msg_split[3])
if register["result"] == "ok": if register["result"] == "ok":
if len(msg_split) == 3: if len(msg_split) == 3:
@ -327,7 +377,7 @@ class Bot(discord.Client):
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(dislocker.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":
await message.channel.send(f"あなたはPCをもう使用されているようです。使用状態を解除するには /stop で使用終了をお知らせください。\nPC番号 | {register["pc_number"]}\nデバイス番号 | {register["device_number"]}\n使用開始時刻 | {register["start_time"]}\n使用目的 | {register["detail"]}") await message.channel.send(f"あなたはPCをもう使用されているようです。使用状態を解除するには /stop で使用終了をお知らせください。\nPC番号 | {register["pc_number"]}\nデバイス番号 | {register["device_number"]}\n使用開始時刻 | {register["start_time"]}\n使用目的 | {register["detail"]}")
elif register["result"] == "pc_already_in_use_by_other": elif register["result"] == "pc_already_in_use_by_other":
@ -348,7 +398,18 @@ class Bot(discord.Client):
elif message.channel.id == dislocker.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: print(len(msg_split))
if len(msg_split) == 1:
register = self.user_register(name=message.author.display_name, discord_user_name=message.author.name, discord_user_id=message.author.id)
print(register)
if register["result"] == "ok":
await message.channel.send(f"ユーザー情報が登録されました。\nユーザー名:{message.author.display_name}")
elif register["result"] == "already_exists":
await message.channel.send("登録できませんでした。もう登録されている可能性があります。")
else:
await message.channel.send("登録できませんでした。内部エラーが発生しています。")
elif len(msg_split) <= 3:
await message.channel.send("名前、Discordのユーザー名、DiscordのユーザーIDのいずれかが入力されていません。") await message.channel.send("名前、Discordのユーザー名、DiscordのユーザーIDのいずれかが入力されていません。")
elif len(msg_split) == 4: elif len(msg_split) == 4:
if msg_split[3].isdigit(): if msg_split[3].isdigit():
@ -387,6 +448,7 @@ class Bot(discord.Client):
dislocker = DL() dislocker = DL()
if dislocker.init_result == "ok": if dislocker.init_result == "ok":
print("Botを起動します...")
intents = discord.Intents.default() intents = discord.Intents.default()
intents.message_content = True intents.message_content = True
bot = Bot(intents=intents) bot = Bot(intents=intents)