coollsd commited on
Commit
114843b
·
verified ·
1 Parent(s): 79f8fbd

Update database.py

Browse files
Files changed (1) hide show
  1. database.py +28 -11
database.py CHANGED
@@ -1,25 +1,42 @@
1
  import discord
2
  from discord import app_commands
3
- import json
4
  from cash import user_cash
 
5
 
6
- @app_commands.command(name="database", description="database")
7
  @app_commands.describe(action="'save' or 'load'")
8
  async def database(interaction: discord.Interaction, action: str):
9
  if action.lower() == "save":
10
  with open("database.txt", "w") as f:
11
- json.dump(user_cash, f)
12
- await interaction.response.send_message("Database saved to database.txt")
 
 
13
  elif action.lower() == "load":
14
  try:
15
  with open("database.txt", "r") as f:
16
- loaded_data = json.load(f)
 
 
17
  user_cash.clear()
18
- user_cash.update({int(k): v for k, v in loaded_data.items()})
19
- await interaction.response.send_message("Database")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  except FileNotFoundError:
21
- await interaction.response.send_message(". '/database save' first to create a database.")
22
- except json.JSONDecodeError:
23
- await interaction.response.send_message("ERRRERERER")
24
  else:
25
- await interaction.response.send_message(" Use 'save' or 'load'.")
 
1
  import discord
2
  from discord import app_commands
 
3
  from cash import user_cash
4
+ import io
5
 
6
+ @app_commands.command(name="database", description="Save or load ")
7
  @app_commands.describe(action="'save' or 'load'")
8
  async def database(interaction: discord.Interaction, action: str):
9
  if action.lower() == "save":
10
  with open("database.txt", "w") as f:
11
+ for user_id, cash in user_cash.items():
12
+ f.write(f"{user_id} cash ({cash})\n")
13
+ await interaction.response.send_message("Database saved")
14
+
15
  elif action.lower() == "load":
16
  try:
17
  with open("database.txt", "r") as f:
18
+ content = f.read()
19
+
20
+ if content:
21
  user_cash.clear()
22
+ for line in content.split('\n'):
23
+ if line:
24
+ user_id, cash_info = line.split(' cash ')
25
+ cash = int(cash_info.strip('()'))
26
+ user_cash[int(user_id)] = cash
27
+
28
+ # Create a text file with the current database content
29
+ buffer = io.StringIO()
30
+ for user_id, cash in user_cash.items():
31
+ buffer.write(f"{user_id} cash ({cash})\n")
32
+ buffer.seek(0)
33
+
34
+ # Send the file
35
+ file = discord.File(fp=buffer, filename="current_database.txt")
36
+ await interaction.response.send_message("Current database :", file=file)
37
+ else:
38
+ await interaction.response.send_message("The database is empty.")
39
  except FileNotFoundError:
40
+ await interaction.response.send_message("errer")
 
 
41
  else:
42
+ await interaction.response.send_message("'save' or 'load'.")