Advertisement
NaroxEG

Discord+SQL Tutorial

Aug 29th, 2023
1,150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. import discord
  2. from discord.ext import commands
  3. from discord import app_commands
  4. import mysql.connector
  5.  
  6. intents = discord.Intents.default()
  7. client = commands.Bot(command_prefix="-", intents=intents)
  8. tree = client.tree
  9.  
  10. @client.event
  11. async def on_ready():
  12.     synced = await tree.sync()
  13.     print(f"Synced {len(synced)} Command(s)")
  14.  
  15. db = mysql.connector.connect(
  16.     host="localhost",
  17.     user="root",
  18.     password="",
  19.     database="test"
  20. )
  21. cursor = db.cursor(dictionary=True)
  22.  
  23. @tree.command(name="set", description="sets user balance")
  24. @app_commands.describe(balance="amount of money")
  25. async def set(interaction: discord.Interaction, balance: int):
  26.     sql = "INSERT INTO users (ID, BALANCE) VALUES (%s, %s)"
  27.     val = (interaction.user.id, balance)
  28.  
  29.     cursor.execute(sql, val)
  30.     db.commit()
  31.  
  32.     await interaction.response.send_message("Done")
  33.  
  34. @tree.command(name="update", description="updates user balance")
  35. @app_commands.describe(balance="amount of money")
  36. async def update(interaction: discord.Interaction, balance: int):
  37.     sql = "UPDATE users SET BALANCE=%s WHERE ID=%s"
  38.     val = (balance, interaction.user.id)
  39.     cursor.execute(sql, val)
  40.     db.commit()
  41.     await interaction.response.send_message("Done")
  42.  
  43.  
  44. @tree.command(name="check", description="checks user balance")
  45. async def check(interaction:discord.Interaction):
  46.     sql = f"SELECT BALANCE FROM users WHERE ID={interaction.user.id}"
  47.     cursor.execute(sql)
  48.  
  49.     rows = cursor.fetchall()
  50.     # [{'BALANCE': '150'}]
  51.     for row in rows:
  52.         balance = row["BALANCE"]
  53.         await interaction.response.send_message(balance)
  54.  
  55.  
  56.  
  57.  
  58.  
  59. client.run("TOKEN")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement