Compare commits
3 commits
5de39f92a4
...
a16a0424dc
Author | SHA1 | Date | |
---|---|---|---|
a16a0424dc | |||
41e85cb6bc | |||
dde933fc14 |
3 changed files with 159 additions and 95 deletions
108
dislocker.py
108
dislocker.py
|
@ -5,16 +5,19 @@ import psycopg2
|
||||||
import hashlib
|
import hashlib
|
||||||
import string
|
import string
|
||||||
import random
|
import random
|
||||||
|
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.server_config_path = self.config_dir_path + "server.json"
|
self.server_config_path = self.config_dir_path + "server.json"
|
||||||
|
|
||||||
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)
|
os.mkdir(self.config_dir_path)
|
||||||
|
|
||||||
if not os.path.isfile(self.server_config_path):
|
if not os.path.isfile(self.server_config_path):
|
||||||
print("config ファイルが見つかりません... 作成します。")
|
print("config ファイルが見つかりません... 作成します。")
|
||||||
self.server_config = {
|
self.server_config = {
|
||||||
|
@ -39,12 +42,11 @@ class Dislocker():
|
||||||
with open(self.server_config_path, "r") as r:
|
with open(self.server_config_path, "r") as r:
|
||||||
self.server_config = json.load(r)
|
self.server_config = json.load(r)
|
||||||
|
|
||||||
|
if not os.path.isdir(self.export_dir_path):
|
||||||
|
print("export ディレクトリが見つかりません... 作成します。")
|
||||||
|
os.mkdir(self.export_dir_path)
|
||||||
|
|
||||||
|
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 db_connect(self, host, db, port, user, password):
|
|
||||||
self.db = psycopg2.connect(f"host={host} dbname={db} port={port} user={user} password={password}")
|
|
||||||
|
|
||||||
def password_generate(self, length):
|
def password_generate(self, length):
|
||||||
numbers = string.digits # (1)
|
numbers = string.digits # (1)
|
||||||
|
@ -55,12 +57,12 @@ class Bot(discord.Client):
|
||||||
hashed = hashlib.md5(source.encode())
|
hashed = hashlib.md5(source.encode())
|
||||||
return hashed.hexdigest()
|
return hashed.hexdigest()
|
||||||
|
|
||||||
def register(self, **kwrags):
|
def register(self, **kwargs):
|
||||||
discord_user_id = str(kwrags["user_id"])
|
discord_user_id = str(kwargs["user_id"])
|
||||||
pc_number = int(kwrags["pc_number"])
|
pc_number = int(kwargs["pc_number"])
|
||||||
device_number = int(kwrags["device_number"])
|
device_number = int(kwargs["device_number"])
|
||||||
if "detail" in kwrags:
|
if "detail" in kwargs:
|
||||||
detail = str(kwrags["detail"])
|
detail = str(kwargs["detail"])
|
||||||
else:
|
else:
|
||||||
detail = None
|
detail = None
|
||||||
#パスワード生成、ハッシュ化
|
#パスワード生成、ハッシュ化
|
||||||
|
@ -118,8 +120,8 @@ class Bot(discord.Client):
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
def stop(self, **kwrags):
|
def stop(self, **kwargs):
|
||||||
discord_user_id = str(kwrags["user_id"])
|
discord_user_id = str(kwargs["user_id"])
|
||||||
cursor = self.db.cursor()
|
cursor = self.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", (discord_user_id,))
|
||||||
user_record = cursor.fetchall()
|
user_record = cursor.fetchall()
|
||||||
|
@ -137,10 +139,10 @@ class Bot(discord.Client):
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
def user_register(self, **kwrags):
|
def user_register(self, **kwargs):
|
||||||
discord_user_id = str(kwrags["discord_user_id"])
|
discord_user_id = str(kwargs["discord_user_id"])
|
||||||
discord_user_name = str(kwrags["discord_user_name"])
|
discord_user_name = str(kwargs["discord_user_name"])
|
||||||
name = str(kwrags["name"])
|
name = str(kwargs["name"])
|
||||||
cursor = self.db.cursor()
|
cursor = self.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", (discord_user_id,))
|
||||||
user_record = cursor.fetchall()
|
user_record = cursor.fetchall()
|
||||||
|
@ -150,9 +152,57 @@ class Bot(discord.Client):
|
||||||
result = {"result": "ok"}
|
result = {"result": "ok"}
|
||||||
else:
|
else:
|
||||||
result = {"result": "already_exists"}
|
result = {"result": "already_exists"}
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
def report_export(self, **kwargs):
|
||||||
|
try:
|
||||||
|
csv_file_path = self.export_dir_path + "pc_usage_history.csv"
|
||||||
|
cursor = self.db.cursor()
|
||||||
|
# メインテーブルの列情報を取得(user_idを除く)
|
||||||
|
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']
|
||||||
|
|
||||||
|
# クエリを作成(列名を明確に指定)
|
||||||
|
query = sql.SQL("""
|
||||||
|
SELECT {main_columns}, {related_table}.name
|
||||||
|
FROM {main_table}
|
||||||
|
LEFT JOIN {related_table} ON {main_table}.member_id = {related_table}.id
|
||||||
|
""").format(
|
||||||
|
main_columns=sql.SQL(', ').join([sql.SQL("{}.{}").format(sql.Identifier(main_table), sql.Identifier(col)) for col in main_columns]),
|
||||||
|
main_table=sql.Identifier(main_table),
|
||||||
|
related_table=sql.Identifier(related_table)
|
||||||
|
)
|
||||||
|
|
||||||
|
cur.execute(query)
|
||||||
|
|
||||||
|
# 列名を再構成(nameを2番目に配置)
|
||||||
|
column_names = [main_columns[0], 'name'] + main_columns[1:]
|
||||||
|
|
||||||
|
rows = cur.fetchall()
|
||||||
|
|
||||||
|
with open(csv_file_path, 'w', newline='', encoding='utf-8-sig') as csvfile:
|
||||||
|
csvwriter = csv.writer(csvfile)
|
||||||
|
csvwriter.writerow(column_names)
|
||||||
|
|
||||||
|
for row in rows:
|
||||||
|
# nameを2番目に移動
|
||||||
|
formatted_row = [format_datetime(row[0])] + [row[-1]] + [format_datetime(field) if field is not None else '' for field in row[1:-1]]
|
||||||
|
csvwriter.writerow(formatted_row)
|
||||||
|
|
||||||
|
print(f"テーブル '{main_table}' の内容を '{csv_file_path}' に出力しました。")
|
||||||
|
|
||||||
|
except (Exception, psycopg2.Error) as error:
|
||||||
|
print("使用履歴のエクスポート時にエラーが発生しました\nエラー内容\n", error)
|
||||||
|
result = {"result": "export_error"}
|
||||||
|
|
||||||
|
finally:
|
||||||
|
cursor.close()
|
||||||
|
result = {"result": "ok", "file_path": csv_file_path}
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
async def on_ready(self):
|
async def on_ready(self):
|
||||||
print("ログイン成功")
|
print("ログイン成功")
|
||||||
|
|
||||||
|
@ -182,7 +232,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(dislocker.server_config["bot"]["log_channel_id"]).send(f'{register["name"]} さんがPC {msg_split[1]} を使用しています')
|
await self.get_channel(self.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":
|
||||||
|
@ -200,9 +250,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(dislocker.server_config["bot"]["log_channel_id"]).send(f'{stop["name"]} さんがPC {stop["pc_number"]} の使用を終了しました')
|
await self.get_channel(self.server_config["bot"]["log_channel_id"]).send(f'{stop["name"]} さんがPC {stop["pc_number"]} の使用を終了しました')
|
||||||
|
|
||||||
elif message.channel.id == dislocker.server_config["bot"]["config_channel_id"]:
|
elif message.channel.id == self.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:
|
||||||
|
@ -219,11 +269,17 @@ class Bot(discord.Client):
|
||||||
else:
|
else:
|
||||||
await message.channel.send("なんでかわからんけど不正です。")
|
await message.channel.send("なんでかわからんけど不正です。")
|
||||||
|
|
||||||
|
elif msg_split[0] == "/export":
|
||||||
|
export = self.report_export()
|
||||||
|
if export["result"] == "ok":
|
||||||
|
await message.channel.send("使用履歴のレポートです。", file=discord.file(export["file_path"]))
|
||||||
|
pass
|
||||||
|
elif export["result"] == "export_error":
|
||||||
|
await message.channel.send("エクスポートに失敗しました。")
|
||||||
|
|
||||||
|
|
||||||
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.db_connect(dislocker.server_config["db"]["host"], dislocker.server_config["db"]["db_name"], dislocker.server_config["db"]["port"], dislocker.server_config["db"]["username"], dislocker.server_config["db"]["password"])
|
bot.run(bot.server_config['bot']['token'])
|
||||||
bot.run(dislocker.server_config["bot"]["token"])
|
|
||||||
|
|
69
temp/csv.py
69
temp/csv.py
|
@ -1,69 +0,0 @@
|
||||||
import psycopg2
|
|
||||||
import csv
|
|
||||||
from psycopg2 import sql
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
def format_datetime(value):
|
|
||||||
if isinstance(value, datetime):
|
|
||||||
return value.strftime('%Y-%m-%d %H:%M:%S')
|
|
||||||
return value
|
|
||||||
|
|
||||||
def export_table_to_csv(host, port, database, user, password, table_name, csv_file_path):
|
|
||||||
try:
|
|
||||||
# データベースに接続
|
|
||||||
conn = psycopg2.connect(
|
|
||||||
host=host,
|
|
||||||
port=port,
|
|
||||||
database=database,
|
|
||||||
user=user,
|
|
||||||
password=password
|
|
||||||
)
|
|
||||||
|
|
||||||
# カーソルを作成
|
|
||||||
cur = conn.cursor()
|
|
||||||
|
|
||||||
# テーブルの全データを取得
|
|
||||||
cur.execute(sql.SQL("SELECT * FROM {}").format(sql.Identifier(table_name)))
|
|
||||||
|
|
||||||
# 列名を取得
|
|
||||||
column_names = [desc[0] for desc in cur.description]
|
|
||||||
|
|
||||||
# 結果を取得
|
|
||||||
rows = cur.fetchall()
|
|
||||||
|
|
||||||
# CSVファイルに書き込み
|
|
||||||
with open(csv_file_path, 'w', newline='', encoding='utf-8-sig') as csvfile:
|
|
||||||
csvwriter = csv.writer(csvfile)
|
|
||||||
|
|
||||||
# 列名を書き込み
|
|
||||||
csvwriter.writerow(column_names)
|
|
||||||
|
|
||||||
# データを書き込み
|
|
||||||
for row in rows:
|
|
||||||
# 各フィールドを適切にフォーマット
|
|
||||||
formatted_row = [format_datetime(field) if field is not None else '' for field in row]
|
|
||||||
csvwriter.writerow(formatted_row)
|
|
||||||
|
|
||||||
print(f"テーブル '{table_name}' の内容を '{csv_file_path}' に出力しました。")
|
|
||||||
|
|
||||||
except (Exception, psycopg2.Error) as error:
|
|
||||||
print("エラーが発生しました:", error)
|
|
||||||
|
|
||||||
finally:
|
|
||||||
# データベース接続を閉じる
|
|
||||||
if conn:
|
|
||||||
cur.close()
|
|
||||||
conn.close()
|
|
||||||
print("データベース接続を閉じました。")
|
|
||||||
|
|
||||||
# 使用例
|
|
||||||
# 使用例
|
|
||||||
host = "192.168.1.220"
|
|
||||||
port = "12245"
|
|
||||||
database = "dislocker"
|
|
||||||
user = "suti7"
|
|
||||||
password = "Testing1234"
|
|
||||||
table_name = "pc_usage_history"
|
|
||||||
csv_file_path = "./output.csv"
|
|
||||||
|
|
||||||
export_table_to_csv(host, port, database, user, password, table_name, csv_file_path)
|
|
77
temp/csv_test.py
Normal file
77
temp/csv_test.py
Normal file
|
@ -0,0 +1,77 @@
|
||||||
|
import psycopg2
|
||||||
|
import csv
|
||||||
|
from psycopg2 import sql
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
def format_datetime(value):
|
||||||
|
if isinstance(value, datetime):
|
||||||
|
return value.strftime('%Y-%m-%d %H:%M:%S')
|
||||||
|
return value
|
||||||
|
|
||||||
|
def export_table_to_csv(host, port, database, user, password, main_table, related_table, related_column, csv_file_path):
|
||||||
|
try:
|
||||||
|
# データベースに接続
|
||||||
|
conn = psycopg2.connect(
|
||||||
|
host=host,
|
||||||
|
port=port,
|
||||||
|
database=database,
|
||||||
|
user=user,
|
||||||
|
password=password
|
||||||
|
)
|
||||||
|
|
||||||
|
cur = conn.cursor()
|
||||||
|
|
||||||
|
# メインテーブルの列情報を取得(user_idを除く)
|
||||||
|
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']
|
||||||
|
|
||||||
|
# クエリを作成(列名を明確に指定)
|
||||||
|
query = sql.SQL("""
|
||||||
|
SELECT {main_columns}, {related_table}.name
|
||||||
|
FROM {main_table}
|
||||||
|
LEFT JOIN {related_table} ON {main_table}.member_id = {related_table}.id
|
||||||
|
""").format(
|
||||||
|
main_columns=sql.SQL(', ').join([sql.SQL("{}.{}").format(sql.Identifier(main_table), sql.Identifier(col)) for col in main_columns]),
|
||||||
|
main_table=sql.Identifier(main_table),
|
||||||
|
related_table=sql.Identifier(related_table)
|
||||||
|
)
|
||||||
|
|
||||||
|
cur.execute(query)
|
||||||
|
|
||||||
|
# 列名を再構成(nameを2番目に配置)
|
||||||
|
column_names = [main_columns[0], 'name'] + main_columns[1:]
|
||||||
|
|
||||||
|
rows = cur.fetchall()
|
||||||
|
|
||||||
|
with open(csv_file_path, 'w', newline='', encoding='utf-8-sig') as csvfile:
|
||||||
|
csvwriter = csv.writer(csvfile)
|
||||||
|
csvwriter.writerow(column_names)
|
||||||
|
|
||||||
|
for row in rows:
|
||||||
|
# nameを2番目に移動
|
||||||
|
formatted_row = [format_datetime(row[0])] + [row[-1]] + [format_datetime(field) if field is not None else '' for field in row[1:-1]]
|
||||||
|
csvwriter.writerow(formatted_row)
|
||||||
|
|
||||||
|
print(f"テーブル '{main_table}' の内容を '{csv_file_path}' に出力しました。")
|
||||||
|
|
||||||
|
except (Exception, psycopg2.Error) as error:
|
||||||
|
print("エラーが発生しました:", error)
|
||||||
|
|
||||||
|
finally:
|
||||||
|
if conn:
|
||||||
|
cur.close()
|
||||||
|
conn.close()
|
||||||
|
print("データベース接続を閉じました。")
|
||||||
|
|
||||||
|
# 使用例
|
||||||
|
host = "192.168.1.220"
|
||||||
|
port = "12245"
|
||||||
|
database = "dislocker"
|
||||||
|
user = "suti7"
|
||||||
|
password = "Testing1234"
|
||||||
|
main_table = "pc_usage_history"
|
||||||
|
related_table = "club_member"
|
||||||
|
related_column = "name" # 例: 登録者の名前を表示したい場合
|
||||||
|
csv_file_path = "output.csv"
|
||||||
|
|
||||||
|
export_table_to_csv(host, port, database, user, password, main_table, related_table, related_column, csv_file_path)
|
Loading…
Reference in a new issue