up db test

This commit is contained in:
2022-06-26 08:10:16 +03:00
parent 8563b50aa3
commit 51acb6e60c
2 changed files with 131 additions and 67 deletions

166
test.py
View File

@@ -4,55 +4,55 @@ import logging
import discord import discord
import sqlite3 import sqlite3
from os import walk
from discord.ext import commands from discord.ext import commands
from dislash import InteractionClient, Option, OptionType from dislash import InteractionClient, Option, OptionType
def insert_varible_into_table(name, userid, isbot, nick, guild): class DB:
def _prepare_db(guild):
try: try:
sqlite_connection = sqlite3.connect('user.db') connect = sqlite3.connect('user.db')
cursor = sqlite_connection.cursor() cursor = connect.cursor()
cursor.execute(f'''CREATE TABLE IF NOT EXISTS "{str(guild)}" create_table = (f'''CREATE TABLE IF NOT EXISTS "{guild}"
([userid] INTEGER PRIMARY KEY, [username] TEXT, [nick] TEXT, [isbot] BOOL, [track] TEXT) ([userid] INTEGER PRIMARY KEY, [username] TEXT, [nick] TEXT, [isbot] BOOL, [track] TEXT)
''') ''')
cursor.execute(create_table)
cursor.close()
except sqlite3.Error as error:
logging.error("failed to connecct db", error)
sqlite_insert_with_param = (f"""INSERT OR IGNORE INTO "{str(guild)}" def _work_with_db(db_func, data_turple):
try:
connect = sqlite3.connect('user.db')
cursor = connect.cursor()
cursor.execute(db_func, data_turple)
connect.commit()
cursor.close()
except sqlite3.Error as error:
logging.error("failed to connecct db", error)
def _fill_bd(name, userid, isbot, nick, guild):
sqlite_insert_with_param = (f"""INSERT OR IGNORE INTO "{guild}"
(username, userid, nick, isbot) (username, userid, nick, isbot)
VALUES (?, ?, ?, ?)""") VALUES (?, ?, ?, ?)""")
data_tuple = (name, userid, nick, isbot) data_tuple = (name, userid, nick, isbot)
cursor.execute(sqlite_insert_with_param, data_tuple) DB._work_with_db(sqlite_insert_with_param, data_tuple)
sqlite_connection.commit()
cursor.close() def _add_audio(guildid, user, audio):
sql_update_query = f"""UPDATE "{guildid}" set track = ? where userid = ?"""
data_tuple = (audio, user)
DB._work_with_db(sql_update_query, data_tuple)
except sqlite3.Error as error: def _read_db(guildid, user):
logging.error("Failed to insert Python variable into sqlite table", error)
def _add_audio(guildid, user, audio):
try:
sql_conn = sqlite3.connect('user.db')
cursor = sql_conn.cursor()
sql_update_query = f"""UPDATE "{str(guildid)}" set track = ? where userid = ?"""
data_tuple = (audio, user.removesuffix('>').removeprefix('<@'))
cursor.execute(sql_update_query, data_tuple)
sql_conn.commit()
cursor.close()
except sqlite3.Error as error:
logging.error("Failed to insert Python variable into sqlite table", error)
def _read_db(guildid, user):
try: try:
sql_con = sqlite3.connect("user.db") sql_con = sqlite3.connect("user.db")
cursor = sql_con.cursor() cursor = sql_con.cursor()
print(user)
sql_read = f"""SELECT * FROM "{guildid}" where userid = {user}""" sql_read = f"""SELECT * FROM "{guildid}" where userid = {user}"""
cursor.execute(sql_read) cursor.execute(sql_read)
record = cursor.fetchone() record = cursor.fetchone()
print(record[4])
if record[4] is None: if record[4] is None:
return "None" return "None"
else: else:
@@ -60,9 +60,6 @@ def _read_db(guildid, user):
except sqlite3.Error as error: except sqlite3.Error as error:
logging.error("Failed to read sqlite table", error) logging.error("Failed to read sqlite table", error)
finally:
if sql_con:
sql_con.close()
threading.current_thread().name = "main" threading.current_thread().name = "main"
@@ -75,46 +72,113 @@ bot = commands.Bot(command_prefix='$', guild_subscriptions=True, intents=intents
inter_client = InteractionClient(bot) inter_client = InteractionClient(bot)
class Arg:
f = []
for filenames in walk('audio'):
f.extend(filenames)
break
f = f[2]
dict = {}
keys = range(len(f))
for i in keys:
for x in f:
dict[x] = x
@bot.event @bot.event
async def on_ready(): async def on_ready():
for g in bot.get_all_members(): for g in bot.get_all_members():
insert_varible_into_table(g.name, g.id, g.bot, g.nick, g.guild.id) DB._prepare_db(g.guild.id)
for g in bot.get_all_members():
DB._fill_bd(g.name, g.id, g.bot, g.nick, g.guild.id)
logging.info(f'Bot started') logging.info(f'Bot started')
logging.info('We have logged in as {0.user}'.format(bot)) logging.info('We have logged in as {0.user}'.format(bot))
@bot.event @bot.event
async def on_guild_join(guild): async def on_guild_join(guild):
DB._prepare_db(guild.id)
for g in guild.members: for g in guild.members:
insert_varible_into_table(g.name, g.id, g.bot, g.nick, guild.id) DB._fill_bd(g.name, g.id, g.bot, g.nick, guild.id)
@bot.event @bot.event
async def on_member_join(member): async def on_member_join(member):
insert_varible_into_table(member.name, member.id, member.bot, member.nick, member.guild.id) DB._fill_bd(member.name, member.id, member.bot, member.nick, member.guild.id)
@bot.command() # @bot.command()
async def add_audio(ctx, user, audio): # async def add_audio(ctx, user, audio):
_add_audio(ctx.guild.id, user, audio) # DB._add_audio(ctx.guild.id, user.removesuffix('>').removeprefix('<@'), audio)
@inter_client.slash_command(
name="add-audio",
description="Add audio track to user",
options=[
Option("audio", "Specify audio name", OptionType.STRING, required=True),
Option("user", "Specify any user", OptionType.USER)
]
)
async def add_audio(ctx, audio, user=None):
user = user or ctx.author
a = DB._read_db(ctx.guild.id, user.id)
if a == "None":
audiolist = audio
else:
audiolist = DB._read_db(ctx.guild.id, user.id) + ", " + audio
DB._add_audio(ctx.guild.id, user.id, audiolist)
emb = discord.Embed(
title=f"Sucseed added {audio} to {user}",
color=discord.Color.blue()
)
emb.set_thumbnail(url=user.avatar_url)
await ctx.reply(embed=emb)
@inter_client.slash_command(
name="info",
description="Read list of tracks for user",
options=[
Option("user", "Specify any user", OptionType.USER),
]
)
async def info(ctx, user=None):
user = user or ctx.author
audio = DB._read_db(ctx.guild.id, user.id)
rolelist = [r.mention for r in user.roles if r != ctx.guild.default_role]
audiolist = audio.split(", ")
roles = "\n".join(rolelist)
audios = "\n".join(audiolist)
emb = discord.Embed(
title=f"General information",
description=f"General information on server about {user}",
icon=user.avatar_url
)
emb.set_thumbnail(url=user.avatar_url)
emb.add_field(name="General info",
value=f"Username: {user}\n"
f"Nickname: {user.nick}\n"
f"Joined at: {user.joined_at.strftime('%A, %B %d %Y @ %H:%M:%S')}", inline=False)
emb.add_field(name="Audio list", value=f"{audios}", inline=True)
emb.add_field(name="Roles list", value=f"{roles}", inline=True)
emb.set_footer(text="Information requested by: {}".format(ctx.author.display_name))
await ctx.reply(embed=emb)
@bot.command() @bot.command()
async def test(ctx, user): async def test(ctx, user):
await ctx.send(_read_db(ctx.guild.id, user)) await ctx.send(DB._read_db(ctx.guild.id, user))
@inter_client.slash_command( @bot.event
name="read-audio", async def on_member_update(before: discord.Member, after: discord.Member):
description="Shows user's profile", sql_update_query = f"""UPDATE "{after.guild.id}" set nick = ? where userid = ?"""
options=[ data_tuple = (after.nick, before.id)
Option("user", "Specify any user", OptionType.USER), DB._work_with_db(sql_update_query, data_tuple)
]
)
async def hello(ctx, user):
await ctx.send(_read_db(ctx.guild.id, user.id))
# await ctx.send(_read_db(ctx.guild.id, user))
bot.run('OTQ3OTUzOTAxNzgzNjIxNjYy.GTXbMv.KrztaTO7-ivsPEAVjsyikSQ-GP-ANwULmDraig') bot.run('OTQ3OTUzOTAxNzgzNjIxNjYy.GTXbMv.KrztaTO7-ivsPEAVjsyikSQ-GP-ANwULmDraig')

BIN
user.db

Binary file not shown.