Compare commits

..

2 commits

Author SHA1 Message Date
07fcc298a9 全部変えた
だいたいの関数で返り値をreturnで直接返すようにした
返り値の辞書の構造変更(resultはだいたいの状況がわかる番号で、aboutに従来のresultであった理由を記載)
データベース構造の変更(キーボード、マウスリスト追加、その他カラム名変更)
PC使用登録時にマウスとキーボードの番号をを別で尋ねるように
PC使用登録時にマウスとキーボードを自前で持ってきている場合のボタンと処理を追加
PC登録の関数内の一部の処理を別の関数に移した
2024-08-22 23:58:31 +09:00
03319676e9 tempディレクトリを除外 2024-08-22 23:53:37 +09:00
2 changed files with 408 additions and 180 deletions

3
.gitignore vendored
View file

@ -164,4 +164,5 @@ config/
db/
test.py
data/
export/
export/
temp/

View file

@ -74,29 +74,51 @@ class DL():
cursor = self.db.cursor()
self.pc_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
self.keyboard_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
self.mouse_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'club_member')")
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(128) NOT NULL, discord_username VARCHAR(128) NOT NULL, discord_userid VARCHAR(18) NOT NULL, PRIMARY KEY (id))")
cursor.execute("CREATE TABLE club_member (member_id SERIAL NOT NULL, name TEXT NOT NULL, discord_user_name TEXT NOT NULL, discord_user_id TEXT 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')")
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))")
for i in range(10):
cursor.execute("CREATE TABLE pc_list (pc_number INTEGER NOT NULL, using_member_id INTEGER, password_hash VARCHAR(32), PRIMARY KEY (pc_number), FOREIGN KEY (using_member_id) REFERENCES club_member(member_id))")
for i in self.pc_list:
print(i)
cursor.execute("INSERT INTO pc_list (pc_number) VALUES (%s)", (i + 1,))
cursor.execute("INSERT INTO pc_list (pc_number) VALUES (%s)", (i,))
self.db.commit()
cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'pc_usage_history')")
cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'keyboard_list')")
find_keyboard_list_table = cursor.fetchall()
print(find_keyboard_list_table)
if find_keyboard_list_table[0][0] == False:
cursor.execute("CREATE TABLE keyboard_list (keyboard_number INTEGER NOT NULL, using_member_id INTEGER, PRIMARY KEY (keyboard_number), FOREIGN KEY (using_member_id) REFERENCES club_member(member_id))")
for i in self.keyboard_list:
print(i)
cursor.execute("INSERT INTO keyboard_list (keyboard_number) VALUES (%s)", (i,))
self.db.commit()
cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'mouse_list')")
find_mouse_list_table = cursor.fetchall()
print(find_mouse_list_table)
if find_mouse_list_table[0][0] == False:
cursor.execute("CREATE TABLE mouse_list (mouse_number INTEGER NOT NULL, using_member_id INTEGER, PRIMARY KEY (mouse_number), FOREIGN KEY (using_member_id) REFERENCES club_member(member_id))")
for i in self.mouse_list:
print(i)
cursor.execute("INSERT INTO mouse_list (mouse_number) VALUES (%s)", (i,))
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(128), bot_about VARCHAR(128), PRIMARY KEY (id), FOREIGN KEY (member_id) REFERENCES club_member(id), FOREIGN KEY (pc_number) REFERENCES pc_list(pc_number))")
cursor.execute("CREATE TABLE pc_usage_history (id SERIAL NOT NULL, member_id INTEGER NOT NULL, pc_number INTEGER NOT NULL, keyboard_number INTEGER, mouse_number INTEGER, start_use_time TIMESTAMP NOT NULL, end_use_time TIMESTAMP, use_detail TEXT, bot_about TEXT, PRIMARY KEY (id), FOREIGN KEY (member_id) REFERENCES club_member(member_id), FOREIGN KEY (pc_number) REFERENCES pc_list(pc_number), FOREIGN KEY (keyboard_number) REFERENCES keyboard_list(keyboard_number), FOREIGN KEY (mouse_number) REFERENCES mouse_list(mouse_number)")
self.db.commit()
cursor.close()
@ -121,6 +143,127 @@ class Bot(discord.Client):
hashed = hashlib.md5(source.encode())
return hashed.hexdigest()
def user_register_check(self, **kwargs):
try:
discord_user_id = str(kwargs["discord_user_id"])
cursor = dislocker.db.cursor()
cursor.execute("SELECT * FROM club_member WHERE discord_user_id = %s", (discord_user_id,))
user_record = cursor.fetchall()
#ユーザーデータが見つかった場合(登録済みの場合)
if user_record:
member_id = user_record[0][0]
name = user_record[0][1]
discord_user_name = user_record[0][2]
return {"result": 0, "about": "exist", "user_info": {"member_id": member_id, "name": name, "discord_user_name": discord_user_name}}
#ユーザーデータがなかったら(未登録の場合)
else:
return {"result": 1, "about": "user_data_not_found"}
except Exception as error:
print("キーボードの使用状況を調査中にエラーが発生しました。\nエラー内容")
print(str(error.__class__.__name__))
print(str(error.args))
print(str(error))
return {"result": 1, "about": "error"}
finally:
cursor.close()
def pc_used_check(self, **kwargs):
try:
if "pc_number" in kwargs:
pc_number = int(kwargs["pc_number"])
else:
pc_number = None
if "discord_user_id" in kwargs:
discord_user_id = str(kwargs["discord_user_id"])
else:
discord_user_id = None
cursor = dislocker.db.cursor()
if discord_user_id == None:
# pc_listから探す
cursor.execute("SELECT * FROM pc_list WHERE pc_number=%s", (pc_number,))
pc_list_record = cursor.fetchall()
if pc_list_record[0][1] == None:
return {"result": 0, "about": "vacent"}
else:
return {"result": 1, "about": "used_by_other"}
else:
#ユーザーIDを指定してPC使用履歴から探す
cursor.execute("SELECT * FROM pc_usage_history WHERE member_id=%s ORDER BY id DESC LIMIT 1", (discord_user_id,))
pc_usage_history_record = cursor.fetchall()
if pc_usage_history_record:
print("used")
if pc_usage_history_record[0][5] == None:
return {"result": 1, "about": "used_by_you", "pc_usage_history": {"pc_number": str(pc_usage_history_record[0][2]), "keyboard_number": str(pc_usage_history_record[0][3]), "mouse_number": str(pc_usage_history_record[0][4]), "start_time": str(pc_usage_history_record[0][5]), "use_detail": str(pc_usage_history_record[0][7])}}
else:
return {"result": 0, "about": "vacent"}
else:
return {"result": 0, "about": "vacent"}
except Exception as error:
print("PCの使用状況を調査中にエラーが発生しました。\nエラー内容")
print(str(error.__class__.__name__))
print(str(error.args))
print(str(error))
return {"result": 1, "about": "error"}
finally:
cursor.close()
def keyboard_used_check(self, **kwargs):
try:
keyboard_number = int(kwargs["keyboard_number"])
cursor = dislocker.db.cursor()
cursor.execute("SELECT * FROM keyboard_list WHERE keyboard_number=%s", (keyboard_number,))
keyboard_list_record = cursor.fetchall()
if keyboard_list_record[0][1] == None:
return {"result": 0, "about": "ok"}
else:
return {"result": 1, "about": "keyboard_already_in_use_by_other"}
except Exception as error:
print("キーボードの使用状況を調査中にエラーが発生しました。\nエラー内容")
print(str(error.__class__.__name__))
print(str(error.args))
print(str(error))
return {"result": 1, "about": "error"}
finally:
cursor.close()
def mouse_used_check(self, **kwargs):
try:
mouse_number = int(kwargs["mouse_number"])
cursor = dislocker.db.cursor()
cursor.execute("SELECT * FROM mouse_list WHERE mouse_number=%s", (mouse_number,))
mouse_list_record = cursor.fetchall()
if mouse_list_record[0][1] == None:
return {"result": 0, "about": "ok"}
else:
return {"result": 1, "about": "mouse_already_in_use_by_other"}
except Exception as error:
print("マウスの使用状況を調査中にエラーが発生しました。\nエラー内容")
print(str(error.__class__.__name__))
print(str(error.args))
print(str(error))
return {"result": 1, "about": "error"}
finally:
cursor.close()
def register(self, **kwargs):
try:
user_info = {
@ -128,90 +271,79 @@ class Bot(discord.Client):
"name": str(kwargs["name"]),
"display_name": str(kwargs["display_name"]),
"pc_number": int(kwargs["pc_number"]),
"device_number": int(kwargs["device_number"]),
"keyboard_number": None,
"mouse_number": None,
"detail": None
}
if "detail" in kwargs:
user_info["detail"] = str(kwargs["detail"])
else:
pass
#パスワード生成、ハッシュ化
password = self.password_generate(4)
password_hash = self.hash_genarate(password)
print("password generated")
#メンバーリストと送信者を照合
cursor = dislocker.db.cursor()
cursor.execute("SELECT * FROM club_member WHERE discord_userid = %s", (user_info["id"],))
user_record = cursor.fetchall()
#ユーザーデータがなかったら(未登録の場合)
if not user_record:
result = {"result": "user_data_not_found"}
#ユーザーデータが見つかった場合(登録済みの場合)
if kwargs["keyboard_number"] == "own":
pass
else:
print("found user data")
cursor.execute("SELECT * FROM pc_usage_history WHERE member_id=%s ORDER BY id DESC LIMIT 1", (user_record[0][0],))
pc_usage_history_record = cursor.fetchall()
if pc_usage_history_record:
print("used")
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", (user_info["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 user_info["detail"] == None:
cursor.execute("INSERT INTO pc_usage_history (member_id, pc_number, device_number, start_use_time) VALUES (%s, %s, %s, clock_timestamp())", (user_record[0][0], user_info["pc_number"], user_info["device_number"]))
#使用用途があるとき
user_info["keyboard_number"] = int(kwargs["keyboard_number"])
if kwargs["mouse_number"] == "own":
pass
else:
user_info["mouse_number"] = int(kwargs["mouse_number"])
cursor = dislocker.db.cursor()
# ユーザー登録されているかの確認
user_register = self.user_register_check(discord_user_id=user_info["id"])
if user_register["result"] == 0:
member_id = user_register["user_info"]["member_id"]
discord_user_name = user_register["user_info"]["discord_user_name"]
# ユーザーがPCを使っているか
pc_check_self = self.pc_used_check(discord_user_id=user_info["id"])
if pc_check_self["result"] == 0:
# 他の人がそのPCを使っているか
pc_check = self.pc_used_check(pc_number=user_info["pc_number"])
if pc_check["result"] == 0:
# キーボードは使われているか
keyboard_check = self.keyboard_used_check(keyboard_number=user_info["keyboard_number"])
if keyboard_check["result"] == 0:
# マウスは使われているか
mouse_check = self.mouse_used_check(mouse_number=user_info["mouse_number"])
if mouse_check["result"] == 0:
# パスワードとハッシュ作成
password = self.password_generate(4)
password_hash = self.hash_genarate(password)
# PC使用履歴のテーブルにレコードを挿入
cursor.execute("INSERT INTO pc_usage_history (member_id, pc_number, keyboard_number, mouse_number, start_use_time, use_detail) VALUES (%s, %s, %s, %s, clock_timestamp(), %s)", (member_id, user_info["pc_number"], user_info["keyboard_number"], user_info["mouse_number"], user_info["detail"]))
# PCリストの該当のレコードを更新
cursor.execute("UPDATE pc_list SET using_member_id = %s, password_hash = %s WHERE pc_number = %s", (member_id, password_hash, user_info["pc_number"]))
# キーボードリストの該当のレコードを自前(None)だったらスキップ、借りていたら更新
if user_info["keyboard_number"] == None:
pass
else:
cursor.execute("UPDATE keyboard_list SET using_member_id = %s WHERE keyboard_number = %s", (member_id, user_info["keyboard_number"]))
# マウスも同様に
if user_info["mouse_number"] == None:
pass
else:
cursor.execute("UPDATE mouse_list SET using_member_id = %s WHERE mouse_number = %s", (member_id, user_info["mouse_number"]))
return {"result": 0, "about": "ok", "output": {"password": str(password), "name": str(discord_user_name)}}
else:
cursor.execute("INSERT INTO pc_usage_history (member_id, pc_number, device_number, start_use_time, use_detail) VALUES (%s, %s, %s, clock_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])}
return {"result": 1, "about": "mouse_already_in_use"}
else:
return {"result": 1, "about": "keyboard_already_in_use"}
else:
return {"result": 1, "about": "pc_already_in_use_by_other"}
else:
print("unused")
cursor.execute("SELECT * FROM pc_list WHERE pc_number=%s", (user_info["pc_number"],))
pc_list_record = cursor.fetchall()
if pc_list_record:
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, clock_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, clock_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:
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, clock_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, clock_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])}
return {"result": 1, "about": "pc_already_in_use_by_you", "pc_usage_history": {"pc_number": pc_check_self["pc_usage_history"]["pc_number"], "keyboard_number": pc_check_self["pc_usage_history"]["keyboard_number"], "mouse_number": pc_check_self["pc_usage_history"]["mouse_number"], "start_time": pc_check_self["pc_usage_history"]["start_time"]}, "use_detail": pc_check_self["pc_usage_history"]["use_detail"]}
else:
return {"result": "user_data_not_found"}
except Exception as error:
print("登録処理中にエラーが発生しました。\nエラー内容")
print(str(error.__class__.__name__))
print(str(error.args))
print(str(error))
result = {"result": "error"}
return {"result": "error"}
finally:
cursor.close()
return result
return {"result": 1, "about": "error"}
def stop(self, **kwargs):
try:
@ -221,34 +353,59 @@ class Bot(discord.Client):
else:
bot_about = None
cursor = dislocker.db.cursor()
cursor.execute("SELECT * FROM club_member WHERE discord_userid = %s", (discord_user_id,))
user_record = cursor.fetchall()
if user_record:
cursor.execute("SELECT * FROM pc_usage_history WHERE member_id= %s ORDER BY id DESC LIMIT 1", (user_record[0][0],))
pc_usage_history_record = cursor.fetchall()
if pc_usage_history_record:
if not pc_usage_history_record[0][5] == None:
result = {"result": "unused"}
else:
if not bot_about == None:
cursor.execute("UPDATE pc_usage_history SET end_use_time = clock_timestamp(), bot_about = %s WHERE id = %s", (bot_about, pc_usage_history_record[0][0]))
else:
cursor.execute("UPDATE pc_usage_history SET end_use_time = clock_timestamp() WHERE id = %s", (pc_usage_history_record[0][0],))
# ユーザーが登録してるかというよりはデータの取得のため
user_register = self.user_register_check(discord_user_id=discord_user_id)
member_id = user_register["user_info"]["member_id"]
name = user_register["user_info"]["name"]
cursor.execute("UPDATE pc_list SET using_user_id = NULL, password_hash = NULL WHERE pc_number = %s", (pc_usage_history_record[0][2],))
if user_register["result"] == 0:
cursor.execute("SELECT * FROM pc_usage_history WHERE member_id= %s ORDER BY id DESC LIMIT 1", (member_id,))
pc_usage_history_record = cursor.fetchall()
if pc_usage_history_record:
usage_id = pc_usage_history_record[0][0]
pc_number = pc_usage_history_record[0][2]
keyboard_number = pc_usage_history_record[0][3]
mouse_number = pc_usage_history_record[0][4]
end_use_time = pc_usage_history_record[0][6]
# 使用中のとき (使用停止時間がNoneのとき)
if end_use_time == None:
# 利用停止の理由の有無を判断
if bot_about == None:
cursor.execute("UPDATE pc_usage_history SET end_use_time = clock_timestamp() WHERE id = %s", (usage_id,))
else:
cursor.execute("UPDATE pc_usage_history SET end_use_time = clock_timestamp(), bot_about = %s WHERE id = %s", (bot_about, usage_id))
# pc_listの使用中ユーザーを消す
cursor.execute("UPDATE pc_list SET using_member_id = NULL, password_hash = NULL WHERE pc_number = %s", (pc_number,))
if keyboard_number == None:
pass
else:
# keyboard_listの使用中ユーザーを消す
cursor.execute("UPDATE keyboard_list SET using_member_id = NULL WHERE keyboard_number = %s", (keyboard_number,))
if mouse_number == None:
pass
else:
# mouse_listの使用中ユーザーを消す
cursor.execute("UPDATE mouse_list SET using_member_id = NULL WHERE keyboard_number = %s", (mouse_number,))
dislocker.db.commit()
result = {"result": "ok", "pc_number": str(pc_usage_history_record[0][2]), "name": str(user_record[0][1])}
return {"result": 0, "about": "ok", "output_dict": {"pc_number": str(pc_number), "name": str(name)}}
else:
return {"result": 1, "about": "unused"}
else:
result = {"result": "unused"}
return {"result": 1, "about": "unused"}
else:
result = {"result": "user_data_not_found"}
except:
print("停止処理にエラーが発生しました。")
result = {"result": "error"}
return {"result": 1, "about": "user_data_not_found"}
except Exception as error:
print("停止処理中にエラーが発生しました。\nエラー内容")
print(str(error.__class__.__name__))
print(str(error.args))
print(str(error))
return {"result": 1, "about": "error"}
finally:
cursor.close()
return result
def user_register(self, **kwargs):
try:
@ -256,25 +413,25 @@ class Bot(discord.Client):
discord_user_name = str(kwargs["discord_user_name"])
name = str(kwargs["name"])
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_user_id = %s", (discord_user_id,))
user_record = cursor.fetchall()
if not user_record:
cursor.execute("INSERT INTO club_member (name, discord_username, discord_userid) VALUES (%s, %s, %s)", (name, discord_user_name, discord_user_id))
cursor.execute("INSERT INTO club_member (name, discord_user_name, discord_user_id) VALUES (%s, %s, %s)", (name, discord_user_name, discord_user_id))
dislocker.db.commit()
result = {"result": "ok"}
return {"result": 0, "about": "ok"}
else:
result = {"result": "already_exists"}
return {"result": 1, "about": "already_exists"}
except Exception as error:
print("ユーザー登録中にエラーが発生しました。\nエラー内容")
print(str(error.__class__.__name__))
print(str(error.args))
print(str(error))
result = {"result": "error"}
return {"result": 1, "about": "error"}
finally:
cursor.close()
return result
def format_datetime(self, value):
if isinstance(value, datetime):
@ -290,20 +447,19 @@ class Bot(discord.Client):
if not pc_list:
cursor.execute("INSERT INTO pc_list (pc_number) VALUES (%s)", (pc_number,))
dislocker.db.commit()
result = {"result": "ok"}
return {"result": 0, "about": "ok"}
else:
result = {"result": "already_exists"}
return {"result": 1, "about": "already_exists"}
except Exception as error:
print("PCの登録中にエラーが発生しました。\nエラー内容")
print(str(error.__class__.__name__))
print(str(error.args))
print(str(error))
result = {"result": "error"}
return {"result": 1, "about": "error"}
finally:
cursor.close()
return result
def report_export(self, **kwargs):
try:
@ -366,50 +522,59 @@ class Bot(discord.Client):
wb.save(excel_file_path)
print(f"テーブル '{main_table}' の内容を '{excel_file_path}' に出力しました。")
result = {"result": "ok", "file_path": excel_file_path}
return {"result": 0, "about": "ok", "file_path": excel_file_path}
except Exception as error:
print("使用履歴のエクスポート中にエラーが発生しました。\nエラー内容")
print(str(error.__class__.__name__))
print(str(error.args))
print(str(error))
return {"result": 1, "about": "error"}
except (Exception, psycopg2.Error) as error:
print("使用履歴のエクスポート時にエラーが発生しました\nエラー内容\n", str(error))
result = {"result": "export_error"}
finally:
cursor.close()
return result
def force_stop(self, **kwargs):
try:
pc_number = kwargs["pc_number"]
cursor = dislocker.db.cursor()
if "bot_about" in kwargs:
bot_about = kwargs["bot_about"]
cursor = dislocker.db.cursor()
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:
cursor.execute("UPDATE pc_list SET using_user_id = NULL WHERE pc_number = %s", (pc_number,))
if not pc_list_record[0][2] == None:
cursor.execute("UPDATE pc_list SET password_hash = NULL WHERE pc_number = %s", (pc_number,))
cursor.execute("SELECT * FROM pc_usage_history WHERE member_id = %s AND pc_number = %s ORDER BY id DESC LIMIT 1", (pc_list_record[0][1], pc_number))
pc_usage_history_record = cursor.fetchall()
cursor.execute("UPDATE pc_usage_history SET end_use_time = clock_timestamp(), bot_about = %s WHERE id = %s", (bot_about, pc_usage_history_record[0][0]))
dislocker.db.commit()
result = {"result": "ok"}
pc_using_member_id = pc_list_record[0][1]
pc_password_hash = pc_list_record[0][2]
if pc_using_member_id == None:
return {"result": 1, "about": "not_used"}
else:
result = {"result": "not_used"}
cursor.execute("UPDATE pc_list SET using_member_id = NULL WHERE pc_number = %s", (pc_number,))
if pc_password_hash == None:
pass
else:
cursor.execute("UPDATE pc_list SET password_hash = NULL WHERE pc_number = %s", (pc_number,))
cursor.execute("SELECT * FROM pc_usage_history WHERE member_id = %s AND pc_number = %s ORDER BY id DESC LIMIT 1", (pc_using_member_id, pc_number))
pc_usage_history_record = cursor.fetchall()
pc_usage_history_record_id = pc_usage_history_record[0][0]
keyboard_id = pc_usage_history_record[0][3]
mouse_id = pc_usage_history_record[0][4]
cursor.execute("UPDATE pc_usage_history SET end_use_time = clock_timestamp(), bot_about = %s WHERE id = %s", (bot_about, pc_usage_history_record_id))
dislocker.db.commit()
return {"result": 0, "about": "ok"}
else:
bot_about = None
result = {"result": "bot_about_not_found"}
return {"result": 1, "about": "bot_about_not_found"}
except Exception as error:
print("fstop中にエラーが発生しました。\nエラー内容")
print(str(error.__class__.__name__))
print(str(error.args))
print(str(error))
return {"result": 1, "about": "error"}
except:
result = {"result": "error"}
finally:
cursor.close()
return result
async def timeout_notify(self, **kwargs):
try:
@ -417,18 +582,15 @@ class Bot(discord.Client):
discord_display_name = kwargs["discord_display_name"]
await self.get_channel(dislocker.server_config["bot"]["log_channel_id"]).send(f':negative_squared_cross_mark: {discord_display_name} さんのPC {pc_number} の使用登録はタイムアウトにより解除されました。')
result = {"result": "ok"}
return {"result": 0, "result": "ok"}
except Exception as error:
print("自動停止処理中にエラーが発生しました。\nエラー内容")
print(str(error.__class__.__name__))
print(str(error.args))
print(str(error))
result = {"result": "error"}
return {"result": 1, "about": "error"}
finally:
return result
async def on_ready(self):
print("DiscordのBotが起動しました。")
@ -452,6 +614,7 @@ class Bot(discord.Client):
pass
elif isinstance(message.channel, discord.DMChannel):
"""
msg_split = message.content.split()
if msg_split[0] == "/password" or msg_split[0] == "/start":
#メッセージの要素が2つ以下の場合は拒否
@ -492,6 +655,8 @@ class Bot(discord.Client):
elif stop["result"] == "ok":
await message.channel.send(f":white_check_mark: PC番号 {stop["pc_number"]} の使用が終了されました。")
await self.get_channel(dislocker.server_config["bot"]["log_channel_id"]).send(f':negative_squared_cross_mark: {stop["name"]} さんがPC {stop["pc_number"]} の使用を終了しました。')
"""
await message.channel.send("# :warning: DMでの応答は、現在無効化されています。")
elif message.channel.id == dislocker.server_config["bot"]["config_channel_id"]:
msg_split = message.content.split()
@ -500,9 +665,9 @@ class Bot(discord.Client):
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":
if register["about"] == "ok":
await message.channel.send(f"# :white_check_mark: ユーザー情報が登録されました。\n>>> ユーザー名:{message.author.display_name}")
elif register["result"] == "already_exists":
elif register["about"] == "already_exists":
await message.channel.send("# :no_entry: 登録できませんでした。\nもう登録されている可能性があります。")
else:
await message.channel.send("# :no_entry: 登録できませんでした。\n内部エラーが発生しています。")
@ -512,9 +677,9 @@ class Bot(discord.Client):
elif len(msg_split) == 4:
if msg_split[3].isdigit():
register = self.user_register(name=msg_split[1], discord_user_name=msg_split[2], discord_user_id=msg_split[3])
if register["result"] == "ok":
if register["about"] == "ok":
await message.channel.send(f"# :white_check_mark: 登録が完了しました。\n>>> # 名前 | {msg_split[1]}\n# Discordのユーザー名 | {msg_split[2]}\n# DiscordのユーザーID | {msg_split[3]}")
elif register["result"] == "already_exists":
elif register["about"] == "already_exists":
await message.channel.send("# :skull_crossbones: 登録できませんでした。\nそのDiscordアカウントはすでに登録されています。")
else:
await message.channel.send("# :skull_crossbones: 登録できませんでした。\nDiscordのユーザーIDが不正です。")
@ -523,10 +688,10 @@ class Bot(discord.Client):
elif msg_split[0] == "/export":
export = self.report_export()
if export["result"] == "ok":
if export["about"] == "ok":
await message.channel.send("# :page_facing_up: 使用履歴のレポートです。", file=discord.File(export["file_path"]))
pass
elif export["result"] == "export_error":
elif export["about"] == "export_error":
await message.channel.send("# :volcano: エクスポートに失敗しました。")
elif msg_split[0] == "/fstop":
@ -535,9 +700,9 @@ class Bot(discord.Client):
elif len(msg_split) == 2:
if msg_split[1].isdigit():
fstop = self.force_stop(pc_number=msg_split[1], bot_about="管理者による強制停止。")
if fstop["result"] == "ok":
if fstop["about"] == "ok":
await message.channel.send(f"# :white_check_mark: PC番号 {msg_split[1]} の使用登録を解除しました。")
elif fstop["result"] == "not_used":
elif fstop["about"] == "not_used":
await message.channel.send("# :exploding_head: 登録を解除できませんでした。\nPCは使用されていないようです...")
else:
await message.channel.send("# :x: 登録を解除できませんでした。\n内部エラーが発生しています。")
@ -552,9 +717,9 @@ class Bot(discord.Client):
elif len(msg_split) == 2:
if msg_split[1].isdigit():
pc_register = self.pc_register(pc_number=msg_split[1])
if pc_register["result"] == "ok":
if pc_register["about"] == "ok":
await message.channel.send(f"# :white_check_mark: PCを登録しました。\n>>> # PC番号 | {msg_split[1]}")
elif pc_register["result"] == "already_exists":
elif pc_register["about"] == "already_exists":
await message.channel.send(f":x: PCを登録できませんでした。\nその番号のPCは既に存在します。")
else:
await message.channel.send("# :x: PCを登録できませんでした。\n内部エラーが発生しています。")
@ -563,10 +728,30 @@ class Bot(discord.Client):
else:
await message.channel.send("# :warning: PCを登録できませんでした。\n構文が間違っています。\n-# /pcregister PC番号")
elif msg_split[0] == "/init":
user_register_button_view = View(timeout=None)
user_register_button = discord.ui.Button(style=discord.ButtonStyle.green, label="ユーザー登録", custom_id="user_register")
user_register_button_view.add_item(user_register_button)
await self.get_channel(dislocker.server_config["bot"]["config_public_channel_id"]).send(f'# :index_pointing_at_the_viewer: ユーザー登録はお済ですか?', view=user_register_button_view)
stop_button_view = View(timeout=None)
stop_button = discord.ui.Button(style=discord.ButtonStyle.danger, label="PCの使用を停止", custom_id="stop")
stop_button_view.add_item(stop_button)
await self.get_channel(dislocker.server_config["bot"]["config_public_channel_id"]).send(f'# :index_pointing_at_the_viewer: 使用を停止しますか?', view=stop_button_view)
pc_button_view = View(timeout=None)
for i in dislocker.pc_list:
pc_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{str(i)}", custom_id=f"pcregister_{str(i)}")
pc_button_view.add_item(pc_register_button)
await self.get_channel(dislocker.server_config["bot"]["config_public_channel_id"]).send(f'# :index_pointing_at_the_viewer: 使いたいPCの番号を選んでください', view=pc_button_view)
elif msg_split[0] == "/registerbutton":
pc_button_view = View(timeout=None)
for i in range(1, 11):
pc_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{i}", custom_id=f"pcregister_{i}")
for i in dislocker.pc_list:
pc_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{str(i)}", custom_id=f"pcregister_{str(i)}")
pc_button_view.add_item(pc_register_button)
await self.get_channel(dislocker.server_config["bot"]["config_public_channel_id"]).send(f'# :index_pointing_at_the_viewer: 使いたいPCの番号を選んでください', view=pc_button_view)
@ -585,7 +770,6 @@ class Bot(discord.Client):
await self.get_channel(dislocker.server_config["bot"]["config_public_channel_id"]).send(f'# :index_pointing_at_the_viewer: ユーザー登録はお済ですか?', view=user_register_button_view)
elif message.channel.id == dislocker.server_config["bot"]["config_public_channel_id"]:
msg_split = message.content.split()
@ -594,9 +778,9 @@ class Bot(discord.Client):
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":
if register["about"] == "ok":
await message.channel.send(f"# :white_check_mark: ユーザー情報が登録されました。\nユーザー名:{message.author.display_name}")
elif register["result"] == "already_exists":
elif register["about"] == "already_exists":
await message.channel.send("# :skull_crossbones: 登録できませんでした。\nそのDiscordアカウントはすでに登録されています。")
else:
await message.channel.send("# :skull_crossbones: 登録できませんでした。\n内部エラーが発生しています。")
@ -609,23 +793,51 @@ class Bot(discord.Client):
print(custom_id, custom_id_split[0])
if custom_id_split[0] == "pcregister":
device_register_view = View(timeout=15)
keyboard_register_view = View(timeout=15)
pc_number = custom_id_split[1]
print(custom_id_split)
for i in range(1, 11):
device_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{i}", custom_id=f"deviceregister_{str(pc_number)}_{i}")
device_register_view.add_item(device_register_button)
for i in dislocker.keyboard_list:
keyboard_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{str(i)}", custom_id=f"keyboardregister_{str(pc_number)}_{str(i)}")
keyboard_register_view.add_item(keyboard_register_button)
keyboard_not_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label="キーボードは自前", custom_id=f"keyboardregister_{str(pc_number)}_own")
keyboard_register_view.add_item(keyboard_not_register_button)
await interaction.response.send_message(f"# :keyboard: デバイス番号を選んでください!\n>>> # PC番号 | {str(pc_number)}", view=device_register_view, ephemeral=True)
await interaction.response.send_message(f"# :keyboard: キーボードのデバイス番号を選んでください!\n>>> # PC番号 | {str(pc_number)}", view=keyboard_register_view, ephemeral=True)
elif custom_id_split[0] == "deviceregister":
elif custom_id_split[0] == "keyboardregister":
mouse_register_view = View(timeout=15)
pc_number = custom_id_split[1]
device_number = custom_id_split[2]
keyboard_number = custom_id_split[2]
if keyboard_number == "own":
keyboard_number_show = "自前"
else:
keyboard_number_show = keyboard_number
print(custom_id_split)
for i in dislocker.mouse_list:
mouse_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{str(i)}", custom_id=f"mouseregister_{str(pc_number)}_{str(keyboard_number)}_{str(i)}")
mouse_register_view.add_item(mouse_register_button)
mouse_not_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label="マウスは自前", custom_id=f"mouseregister_{str(pc_number)}_{str(keyboard_number)}_own")
mouse_register_view.add_item(mouse_not_register_button)
await interaction.response.send_message(f"# :mouse_three_button: マウスのデバイス番号を選んでください!\n>>> # PC番号 | {str(pc_number)}\n# キーボード番号 | {str(keyboard_number_show)}", view=keyboard_register_view, ephemeral=True)
elif custom_id_split[0] == "mouseregister":
pc_number = custom_id_split[1]
keyboard_number = custom_id_split[2]
if keyboard_number == "own":
keyboard_number_show = "自前"
else:
keyboard_number_show = keyboard_number
mouse_number = custom_id_split[3]
if mouse_number == "own":
mouse_number_show = "自前"
else:
mouse_number_show = mouse_number
reason_register_view = View(timeout=15)
reason_button = discord.ui.Button(style=discord.ButtonStyle.primary, label="使用目的を入力する", custom_id=f"reasonregister_{str(pc_number)}_{str(device_number)}")
reason_button = discord.ui.Button(style=discord.ButtonStyle.primary, label="使用目的を入力する", custom_id=f"reasonregister_{str(pc_number)}_{str(keyboard_number)}_{str(mouse_number)}")
reason_register_view.add_item(reason_button)
await interaction.response.send_message(f"# :regional_indicator_q: 使用目的を書いてください!\n>>> # PC番号 | {str(pc_number)}\n# デバイス番号 | {str(device_number)}", view=reason_register_view, ephemeral=True)
await interaction.response.send_message(f"# :regional_indicator_q: 使用目的を書いてください!\n>>> # PC番号 | {str(pc_number)}\n# キーボード番号 | {str(keyboard_number_show)}\n# マウス番号 | {str(mouse_number_show)}", view=reason_register_view, ephemeral=True)
elif custom_id_split[0] == "reasonregister":
pc_number = custom_id_split[1]
@ -638,22 +850,22 @@ class Bot(discord.Client):
pc_stop = self.stop(user_id=interaction.user.id)
print(pc_stop)
stop_view = View(timeout=15)
if pc_stop["result"] == "unused":
if pc_stop["about"] == "unused":
await interaction.response.send_message("# :shaking_face: 使用されていないようです...", ephemeral=True)
elif pc_stop["result"] == "user_data_not_found":
elif pc_stop["about"] == "user_data_not_found":
await interaction.response.send_message("# :dizzy_face: ユーザーとして登録されていないようです。\n最初にサーバーで登録を行ってください。", ephemeral=True)
elif pc_stop["result"] == "ok":
await interaction.response.send_message(f":white_check_mark: PC番号 {pc_stop["pc_number"]} の使用が終了されました。", ephemeral=True)
await self.get_channel(dislocker.server_config["bot"]["log_channel_id"]).send(f':negative_squared_cross_mark: {pc_stop["name"]} さんがPC {pc_stop["pc_number"]} の使用を終了しました。')
elif pc_stop["about"] == "ok":
await interaction.response.send_message(f":white_check_mark: PC番号 {pc_stop["output_dict"]["pc_number"]} の使用が終了されました。", ephemeral=True)
await self.get_channel(dislocker.server_config["bot"]["log_channel_id"]).send(f':negative_squared_cross_mark: {pc_stop["output_dict"]["name"]} さんがPC {pc_stop["output_dict"]["pc_number"]} の使用を終了しました。')
else:
await interaction.response.send_message("# :skull_crossbones: 停止できませんでした。\n内部エラーが発生しています。", ephemeral=True)
elif custom_id_split[0] == "user" and custom_id_split[1] == "register":
print("User Register RUnning")
user_register = self.user_register(name=interaction.user.display_name, discord_user_name=interaction.user.name, discord_user_id=interaction.user.id)
if user_register["result"] == "ok":
if user_register["about"] == "ok":
await interaction.response.send_message(f"# :white_check_mark: ユーザー情報が登録されました。\n>>> ユーザー名:{interaction.user.display_name}", ephemeral=True)
elif user_register["result"] == "already_exists":
elif user_register["about"] == "already_exists":
await interaction.response.send_message("# :no_entry: 登録できませんでした。\nもう登録されている可能性があります。", ephemeral=True)
else:
await interaction.response.send_message("# :no_entry: 登録できませんでした。\n内部エラーが発生しています。", ephemeral=True)
@ -770,18 +982,33 @@ class Reason(Modal):
print(custom_id)
custom_id_split = custom_id.split("_")
pc_number = custom_id_split[1]
device_number = custom_id_split[2]
register = bot.register(user_id=interaction.user.id, name=interaction.user.name, display_name=interaction.user.display_name, pc_number=pc_number, device_number=device_number, detail=self.reason_input_form.value)
print(register["result"])
keyboard_number = custom_id_split[2]
if keyboard_number == "own":
keyboard_number_show = "自前"
else:
keyboard_number_show = keyboard_number
mouse_number = custom_id_split[3]
if mouse_number == "own":
mouse_number_show = "自前"
else:
mouse_number_show = mouse_number
if register["result"] == "ok":
await interaction.response.send_message(f":white_check_mark: 使用が開始されました。\n>>> # パスワード | {register["password"]}\n## PC番号 | {pc_number}\n## デバイス番号 | {device_number}\n## 使用目的 | {self.reason_input_form.value}", ephemeral=True)
await bot.get_channel(dislocker.server_config["bot"]["log_channel_id"]).send(f':white_check_mark: {register["name"]} さんがPC {pc_number} の使用を開始しました。')
elif register["result"] == "pc_already_in_use_by_you":
await interaction.response.send_message(f"# :exploding_head: あなたはPCをもう使用されているようです。\n使用状態を解除するには 終了ボタン で使用終了をお知らせください。\n>>> # PC番号 | {register["pc_number"]}\n# デバイス番号 | {register["device_number"]}\n# 使用開始時刻 | {register["start_time"]}\n# 使用目的 | {register["detail"]}", ephemeral=True)
elif register["result"] == "pc_already_in_use_by_other":
register = bot.register(user_id=interaction.user.id, name=interaction.user.name, display_name=interaction.user.display_name, pc_number=pc_number, keyboard_number=keyboard_number, mouse_number=mouse_number, detail=self.reason_input_form.value)
print(register)
if register["about"] == "ok":
await interaction.response.send_message(f":white_check_mark: 使用が開始されました。\n>>> # パスワード | {register["password"]}\n## PC番号 | {pc_number}\n## キーボード番号 | {keyboard_number_show}\n## マウス番号 | {mouse_number_show}\n## 使用目的 | {self.reason_input_form.value}", ephemeral=True)
await bot.get_channel(dislocker.server_config["bot"]["log_channel_id"]).send(f':white_check_mark: {register["name"]} さんがPC {pc_number} の使用を開始しました。\n>>> ## キーボード番号 | {keyboard_number_show}\n## マウス番号 | {mouse_number_show}\n## 使用目的 | {self.reason_input_form.value}')
elif register["about"] == "pc_already_in_use_by_you":
pc_usage_history = register["pc_usage_history"]
await interaction.response.send_message(f"# :exploding_head: あなたはPCをもう使用されているようです。\n使用状態を解除するには 終了ボタン で使用終了をお知らせください。\n>>> # PC番号 | {pc_usage_history["pc_number"]}\n# キーボード番号 | {pc_usage_history["keyboard_number"]}\n# マウス番号 | {pc_usage_history["mouse_number"]}\n# 使用開始時刻 | {pc_usage_history["start_time"]}\n# 使用目的 | {pc_usage_history["use_detail"]}", ephemeral=True)
elif register["about"] == "pc_already_in_use_by_other":
await interaction.response.send_message(f"# :man_gesturing_no: そのPCは他のメンバーによって使用されています。\n別のPC番号を指定して、再度お試しください。", ephemeral=True)
elif register["result"] == "user_data_not_found":
elif register["about"] == "keyboard_already_in_use":
await interaction.response.send_message(f"# :man_gesturing_no: そのキーボードは他のメンバーによって使用されています。\n別のキーボードのデバイス番号を指定して、再度お試しください。", ephemeral=True)
elif register["about"] == "mouse_already_in_use":
await interaction.response.send_message(f"# :man_gesturing_no: そのマウスは他のメンバーによって使用されています。\n別のマウスのデバイス番号を指定して、再度お試しください。", ephemeral=True)
elif register["about"] == "user_data_not_found":
await interaction.response.send_message("# :dizzy_face: ユーザーとして登録されていないようです。\n最初にサーバーで登録を行ってください。", ephemeral=True)
else:
await interaction.response.send_message("# :skull_crossbones: 登録できませんでした。\n内部エラーが発生しています。", ephemeral=True)