From 51acb6e60cca1df79dc48a524c833137fde226a8 Mon Sep 17 00:00:00 2001 From: Slava Date: Sun, 26 Jun 2022 08:10:16 +0300 Subject: [PATCH] up db test --- test.py | 198 +++++++++++++++++++++++++++++++++++++------------------- user.db | Bin 28672 -> 16384 bytes 2 files changed, 131 insertions(+), 67 deletions(-) diff --git a/test.py b/test.py index 07844d5..2c5ecd4 100644 --- a/test.py +++ b/test.py @@ -4,65 +4,62 @@ import logging import discord import sqlite3 +from os import walk from discord.ext import commands from dislash import InteractionClient, Option, OptionType -def insert_varible_into_table(name, userid, isbot, nick, guild): - try: - sqlite_connection = sqlite3.connect('user.db') - cursor = sqlite_connection.cursor() - cursor.execute(f'''CREATE TABLE IF NOT EXISTS "{str(guild)}" - ([userid] INTEGER PRIMARY KEY, [username] TEXT, [nick] TEXT, [isbot] BOOL, [track] TEXT) - ''') +class DB: + def _prepare_db(guild): + try: + connect = sqlite3.connect('user.db') + cursor = connect.cursor() + create_table = (f'''CREATE TABLE IF NOT EXISTS "{guild}" + ([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)}" - (username, userid, nick, isbot) - VALUES (?, ?, ?, ?)""") + 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) + VALUES (?, ?, ?, ?)""") data_tuple = (name, userid, nick, isbot) - cursor.execute(sqlite_insert_with_param, data_tuple) - sqlite_connection.commit() + DB._work_with_db(sqlite_insert_with_param, data_tuple) - 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: - logging.error("Failed to insert Python variable into sqlite table", error) + def _read_db(guildid, user): + try: + sql_con = sqlite3.connect("user.db") + cursor = sql_con.cursor() + sql_read = f"""SELECT * FROM "{guildid}" where userid = {user}""" + cursor.execute(sql_read) + record = cursor.fetchone() + print(record[4]) + if record[4] is None: + return "None" + else: + return record[4] - -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: - sql_con = sqlite3.connect("user.db") - cursor = sql_con.cursor() - print(user) - sql_read = f"""SELECT * FROM "{guildid}" where userid = {user}""" - cursor.execute(sql_read) - record = cursor.fetchone() - if record[4] is None: - return "None" - else: - return record[4] - - except sqlite3.Error as error: - logging.error("Failed to read sqlite table", error) - finally: - if sql_con: - sql_con.close() + except sqlite3.Error as error: + logging.error("Failed to read sqlite table", error) threading.current_thread().name = "main" @@ -75,46 +72,113 @@ bot = commands.Bot(command_prefix='$', guild_subscriptions=True, intents=intents 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 async def on_ready(): 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('We have logged in as {0.user}'.format(bot)) @bot.event async def on_guild_join(guild): + DB._prepare_db(guild.id) 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 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() -async def add_audio(ctx, user, audio): - _add_audio(ctx.guild.id, user, audio) +# @bot.command() +# async def add_audio(ctx, 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() 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( - name="read-audio", - description="Shows user's profile", - options=[ - Option("user", "Specify any user", OptionType.USER), - ] -) -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.event +async def on_member_update(before: discord.Member, after: discord.Member): + sql_update_query = f"""UPDATE "{after.guild.id}" set nick = ? where userid = ?""" + data_tuple = (after.nick, before.id) + DB._work_with_db(sql_update_query, data_tuple) bot.run('OTQ3OTUzOTAxNzgzNjIxNjYy.GTXbMv.KrztaTO7-ivsPEAVjsyikSQ-GP-ANwULmDraig') diff --git a/user.db b/user.db index c5329d2ba46cf67347f924fa61d60399dca4d7bb..b46cc6f727a9eac140ae2e42c798776f9e8248df 100644 GIT binary patch delta 432 zcmZp8z}V2hI6+#_gMop81&CpQd7_T7um^*le=RRih?(~o1HThr3-7Vbf(jwLT#eSu z?Ba%oj7^G@w{vSw=Hla<{El0G@*@5?pcE5KDxXJ_k$Lh=9v!FzBTPb_S95X=Ki}jy zUXY$VKi=2eOSt>^n)&{4UE)jR-N3Vz=L|P1-)tT;u0?$6eEj^IxVZT*^UCrI@xSC{ zICy<8^0rrlh4^p zPk!!WG5M9egupolR(@v&erNtz{*C-C{11S>G30j?X#8+)?x&`f1_m|;MFvg=m&Ckm z1>e-%)FRoY>zgjm+uG8=$i^To%Ax8~l%AJVlxJpWWNf6DTVSlCU7?c?}#Y<9)OEUA)6_WBxj6r(9!OFjdfqx7CIsT`c1r3(* Q%i(qiFVG>AFU9Kt0Mh<`*8l(j delta 922 zcmaiyUr19?9LLX{^G@%%=lm42n}6npK3S&s&+c`rKs2QnwWtyKP_VU&1i8W7ET~}W zkRC$R``|-hVMz~Rq(e#SF{EM)aYV01ge@|9@TH!*cTGq%J8)jUzw`N>-}!J72_~_@ zOw^PQAcP#|-dXHqlTtN+n$O-LX2jxo1ZU_tc~6|Yj^`JKRm=^mtV56_W~9I4**SJ~QL65>BhapRxa2#@kCEsC+T*g%p#@pmRe+2sQ0RIWE&~5G#-%GL!!}Fyn zT>Yk~rhM$}&mUj5k`L=x)PPD+OdpJ03-`N&kytA0e9ah(u5&bp><~f_f;2pUWU5^B z!^y)V9~QGSOUVSoq8e1<>Wub>gVAtcFcb(i-v|sH(AY?}^tgq;U{rvuPhx`%f*fSb zTOPsWgzKOQjZB+x#e$A;7;z2!5_b=8Q9pi(=jb=kxg32*t4JMDaV^;S9&UwB(3|`w zhe-(;gInAziO^H9K~}K{uXs%Dd<#6mNz#qipu;q!^J&YJfvcwlGWs+#y8P^J0_ER} z+T*cEXQV$hTU}u@rd=0O%e5bEWyGAm;A#Pq@Hy|w{SQ~Ms2