From 5a50b2ac989c25f9c174ee88fc32f8a9b8ae6f28 Mon Sep 17 00:00:00 2001 From: beacon Date: Sun, 21 Aug 2022 20:59:53 +0300 Subject: [PATCH] edditing code --- cogs/audio.py | 95 ++++++++++++++++++++++++++++++++++++++--------- cogs/general.py | 36 +++++++++++------- cogs/info.py | 16 +++++--- lib.py | 98 ++++++++++++++++++++++++++++++++++++------------- test.py | 1 + 5 files changed, 182 insertions(+), 64 deletions(-) diff --git a/cogs/audio.py b/cogs/audio.py index 4042efb..9e5a28c 100644 --- a/cogs/audio.py +++ b/cogs/audio.py @@ -1,11 +1,28 @@ import logging -from os import path, makedirs, rename, remove +import tempfile +from os import path, makedirs, rename, remove, walk +from random import random +import disnake +import inter as inter +from disnake import FFmpegPCMAudio +from enum import Enum from disnake.ext import commands import lib +# Files = commands.option_enum(lib.Commands.list_files(inter.id)) +def Files(str, fold, Enum) -> None: + fl = [] + for filenames in walk(fold): + fl.extend(filenames) + break + files = {} + for x in fl[2]: + files[x] = x + + class Audio(commands.Cog): def __init__(self, bot): self.bot = bot # defining bot as global var in class @@ -14,17 +31,59 @@ class Audio(commands.Cog): async def on_ready(self): logging.info(f'Cog {__name__.split(".")[1]} is ready!.') + @commands.Cog.listener() + async def on_voice_state_update(self, member, before, after): + role = await lib.Commands.read_json(member.guild.id, 'tigger_role') + audio = await lib.DB.read_db(member.guild.id, member.id, 'usertracks') + audio_files = await lib.Commands.list_files(f'audio/{member.id}') + logging.info(f'Func check audio state:\n' + f'\t\t\t\t\tUser: {member}\n' + f'\t\t\t\t\tTrigger role: {role}\n' + f'\t\t\t\t\tAudio list: {audio}\n' + f'\t\t\t\t\tAudio file list: {audio_files}\n' + f'\t\t\t\t\t-----------------') + if before.channel is None and role in member.roles: + pass + # track = random.randint(0, len(f) - 1) + # audio_source = FFmpegPCMAudio(f'audio/{f[track]}') + # logging.error(f'{track}\t\t{f[track]}') + # if not bot.voice_clients: + # await sleep(1) + # _channel = after.channel + # vc = await after.channel.connect() + # if not vc.is_playing(): + # vc.play(audio_source, after=None) + # while vc.is_playing(): + # await sleep(0.5) + # await sleep(1) + # await vc.disconnect() + # if before.channel is None and member.id == _memb: + # track = random.randint(0, len(f) - 1) + # audio_source = FFmpegPCMAudio(f'audio/{_memb}/bear2_enemy_scav3.wav') + # logging.error(f'{track}\t\t\t{f[track]}') + # if not bot.voice_clients: + # await sleep(1) + # _channel = after.channel + # vc = await after.channel.connect() + # if not vc.is_playing(): + # vc.play(audio_source, after=None) + # while vc.is_playing(): + # await sleep(0.5) + # await sleep(1) + # await vc.disconnect() + + # @commands.slash_command(name="select_audio") + # async def select_audio(self, inter: disnake.ApplicationCommandInteraction, + # files: Files): + # pass + @commands.command(name="upload_audio") async def upload_audio(self, ctx, user=None): user = user or ctx.author + print(tempfile.tempdir) if ctx.author.guild_permissions.administrator or user is ctx.author: if ctx.message.attachments: from os import error - if not path.isdir(f'tmp/{user.id}'): - try: - makedirs(f'tmp/{user.id}') - except error as _error: - logging.info(f"Failed to create dir", _error) if not path.isdir(f'audio/{user.id}'): try: makedirs(f'audio/{user.id}') @@ -33,28 +92,28 @@ class Audio(commands.Cog): for at in ctx.message.attachments: import mimetypes - await at.save(f'tmp/{user.id}/{at.filename}') - guess = mimetypes.guess_type(f'tmp/{user.id}/{at.filename}') - await ctx.reply(f'it`s {guess}') + await at.save(f'{tempfile.tempdir}/{tempfile.mkdtemp(dir=f"tmp/{user.id}")}/{at.filename}') + guess = mimetypes.guess_type(f'{tempfile.tempdir}/{user.id}/{at.filename}') if guess[0].split('/')[0] == 'audio': from pymediainfo import MediaInfo - file = f'tmp/{user.id}/{at.filename}' + file = f'{tempfile.tempdir}/{user.id}/{at.filename}' duration = round(MediaInfo.parse(file).tracks[0].duration / 1000) if duration > 15: await ctx.reply(f'Audio duration is {duration}, but max is 15') - remove(f'tmp/{user.id}/{at.filename}') + remove(f'{tempfile.tempdir}/{user.id}/{at.filename}') else: - a = lib.DB.read_db(ctx.guild.id, user.id) - if a is None: - audiolist = f'{user.id}/{at.filename}' + a = await lib.DB.read_db(ctx.guild.id, user.id, 'usertracks') + if a: + audiolist = a + ", " + f'{at.filename}' else: - audiolist = lib.DB.read_db(ctx.guild.id, user.id) + ", " + f'{user.id}/{at.filename}' + audiolist = f'{at.filename}' - lib.DB.add_audio(ctx.guild.id, user.id, audiolist) - rename(f'tmp/{user.id}/{at.filename}', f'audio/{user.id}/{at.filename}') + await lib.DB.check_exist_audio(ctx, ctx.guild.id, user.id, 'usertracks', at.filename) + await lib.DB.add_audio(ctx.guild.id, user.id, audiolist) + rename(f'{tempfile.tempdir}/{user.id}/{at.filename}', f'audio/{user.id}/{at.filename}') elif guess[0].split('/')[0] != 'audio': await ctx.reply(f'It not audio {at.filename}\n it`s {guess[0]}') - remove(f'tmp/{user.id}/{at.filename}') + remove(f'{tempfile.tempdir}/{user.id}/{at.filename}') else: await ctx.reply("Has no Attachment") else: diff --git a/cogs/general.py b/cogs/general.py index c5521ae..0e984fe 100644 --- a/cogs/general.py +++ b/cogs/general.py @@ -1,7 +1,7 @@ import logging import disnake -from disnake import Option, OptionType +from disnake import Option, OptionType, Colour from disnake.ext import commands import lib @@ -14,20 +14,20 @@ class General(commands.Cog): @commands.Cog.listener() # this is a decorator for events/listeners async def on_ready(self): for g in self.bot.get_all_members(): - lib.DB.prepare_db(g.guild.id) + await lib.DB.prepare_db(g.guild.id) for g in self.bot.get_all_members(): - lib.DB.fill_bd(g.name, g.id, g.bot, g.nick, g.guild.id) + await lib.DB.fill_bd(g.name, g.id, g.bot, g.nick, g.guild.id) logging.info(f'Cog {__name__.split(".")[1]} is ready!.') @commands.Cog.listener() async def on_guild_join(self, guild): for g in guild.members: - lib.DB.fill_bd(g.name, g.id, g.bot, g.nick, guild.id) + await lib.DB.fill_bd(g.name, g.id, g.bot, g.nick, guild.id) @commands.Cog.listener() async def on_member_join(self, member): - lib.DB.fill_bd(member.name, member.id, member.bot, member.nick, member.guild.id) + await lib.DB.fill_bd(member.name, member.id, member.bot, member.nick, member.guild.id) bot_role = lib.Commands.read_json(member.guild.id, 'bot_role') # Get bot role guest_role = lib.Commands.read_json(member.guild.id, 'guest_role') # Get guest role @@ -44,7 +44,7 @@ class General(commands.Cog): async def on_member_update(self, before: disnake.Member, after: disnake.Member): sql_update_query = f"""UPDATE "{after.guild.id}" set nick = ? where userid = ?""" data_tuple = (after.nick, before.id) - lib.DB.work_with_db(sql_update_query, data_tuple) + await lib.DB.work_with_db(sql_update_query, data_tuple) @commands.slash_command( name="info", @@ -55,28 +55,36 @@ class General(commands.Cog): ) async def info(self, inter, user=None): user = user or inter.author - audio = lib.DB.read_db(inter.guild.id, user.id) + user_audio = await lib.DB.read_db(inter.guild.id, user.id, column='usertracks') + default_audio = await lib.DB.read_db(inter.guild.id, user.id, column='defaulttracks') rolelist = [r.mention for r in user.roles if r != inter.guild.default_role] if rolelist: roles = "\n".join(rolelist) else: roles = "Not added any role" - if audio is None: - audios = "Not selected audio" + if user_audio: + audios = "• " + "\n• ".join(sorted(user_audio.split(", "))) else: - audios = "• " + "\n• ".join(sorted(audio.split(", "))) + audios = "Not selected audio" + + if default_audio: + audios2 = "• " + "\n• ".join(sorted(default_audio.split(", "))) + else: + audios2 = "Not selected audio" emb = disnake.Embed( title=f"General information", - description=f"General information on server about {user}" + description=f"General information on server about {user}", + color=Colour.random() ) - emb.set_thumbnail(url=user.avatar.url) + emb.set_thumbnail(url=user.display_avatar) 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="User audio list", value=f"{audios}", inline=True) + emb.add_field(name="Default audio list", value=f"{audios2}", inline=True) emb.add_field(name="Roles list", value=f"{roles}", inline=True) emb.set_footer(text="Information requested by: {}".format(inter.author.display_name)) @@ -126,7 +134,7 @@ class General(commands.Cog): @commands.has_permissions(administrator=True) async def set_trigger_role(self, inter, role): await lib.Commands.write_json(inter.guild.id, "tigger_role", role.id) - await inter.responce.send(f"Role to trigger set to : `{role.name}`", ephemeral=True) + await inter.response.send_message(f"Role to trigger set to : `{role.name}`", ephemeral=True) @commands.slash_command( name="set_bot_role", diff --git a/cogs/info.py b/cogs/info.py index d3142de..fc0858e 100644 --- a/cogs/info.py +++ b/cogs/info.py @@ -1,11 +1,14 @@ import logging +import os + +import psutil import disnake from disnake.ext import commands class Bot_info(commands.Cog, name='Bot Info'): - def __init__(self, bot: object) -> object: + def __init__(self, bot): self.bot = bot # defining bot as global var in class @commands.Cog.listener() # this is a decorator for events/listeners @@ -14,20 +17,21 @@ class Bot_info(commands.Cog, name='Bot Info'): @commands.slash_command(name="info_bot") # this is for making a command async def info_bot(self, inter): - # await ctx.send(f'Pong! {round(self.bot.latency * 1000)}') + _pid = os.getpid() + _process = psutil.Process(_pid) emb = disnake.Embed( title=f"General information", description=f"General information on about bot", ) - # emb.set_thumbnail(self.bot.avatar.url) + # emb.set_thumbnail(self.bot.display_avatar) emb.add_field(name="Bot ping", value=f'Bot ping: {round(self.bot.latency * 1000)}', inline=True) + emb.add_field(name="Memory Usage", value=f"{_process.memory_info()[0]/2**20} Mb", inline=True) + emb.add_field(name="CPU Usage", value=f"{_process.cpu_percent()}%", inline=True) + emb.add_field(name="Bot owner", value=f"<@{self.bot.owner_id}>") emb.set_footer(text="Information requested by: {}".format(inter.author.display_name)) await inter.response.send_message(embed=emb, ephemeral=True) - - - def setup(bot): # an extension must have a setup function bot.add_cog(Bot_info(bot)) # adding a cog diff --git a/lib.py b/lib.py index 3cca471..90b6553 100644 --- a/lib.py +++ b/lib.py @@ -2,13 +2,12 @@ import json import logging import sqlite3 from os import walk, listdir, path - -DEFAULT_PREFIX = "$" # The prefix you want everyone to have if you don't define your own +from enum import Enum class DB: @staticmethod - def prepare_db(guild: int): + async def prepare_db(guild: int): try: connect = sqlite3.connect('user.db') cursor = connect.cursor() @@ -21,7 +20,7 @@ class DB: logging.error("failed to connect db", _error) @staticmethod - def work_with_db(db_func: str, data_turple: tuple): + async def work_with_db(db_func: str, data_turple: tuple): """ Writing to db per server userinfo :param db_func: @@ -38,32 +37,81 @@ class DB: logging.error("failed to connect db", _error) @staticmethod - def fill_bd(name: str, userid: int, isbot: bool, nick: str, guild: int): + async def fill_bd(name: str, userid: int, isbot: bool, nick: str, guild: int): sqlite_insert_with_param = (f"""INSERT OR IGNORE INTO "{guild}" (username, userid, nick, isbot) VALUES (?, ?, ?, ?)""") data_tuple: tuple[str, int, str, bool] = (name, userid, nick, isbot) - DB.work_with_db(sqlite_insert_with_param, data_tuple) + await DB.work_with_db(sqlite_insert_with_param, data_tuple) @staticmethod - def add_audio(guild: int, user: int, audio: str): - sql_update_query = f"""UPDATE "{guild}" set track = ? where userid = ?""" + async def add_audio(guild: int, user: int, audio: str, track: str = 'usertracks'): + """ + Adding audio into folder and DB + + :param guild: Guild id + :param user: + :param audio: + :param track: usertracks or defaulttracks + """ + # audio = f'{DB.read_db(guild, user, track)}, {audio}' + + logging.error(f"Guild id is: {guild}\n" + f"\t\t\t\t\tUser id is: {user}\n" + f"\t\t\t\t\taudio is: {audio}\n" + f"\t\t\t\t\tcolumn is {track}\n" + f"\t\t\t\t\t---------------") + sql_update_query = f"""UPDATE "{guild}" set {track} = ? where userid = ?""" data_tuple = (audio, user) - DB.work_with_db(sql_update_query, data_tuple) + logging.info(f'Func add_audio:\n' + f'\t\t\t\t\tQuery: {sql_update_query}\n' + f'\t\t\t\t\tTurple: {data_tuple}\n' + f'\t\t\t\t\tAudio: {audio}\n' + f'\t\t\t\t\t-----------------') + await DB.work_with_db(sql_update_query, data_tuple) @staticmethod - def read_db(guild: int, user: int): + async def read_db(guild: int, user: int, column: str): + _col_dict = {'userid': 0, + 'username': 1, + 'nick': 2, + 'isbot': 3, + 'defaulttracks': 4, + 'usertracks': 5} try: sql_con = sqlite3.connect("user.db") cursor = sql_con.cursor() sql_read = f"""SELECT * FROM "{guild}" where userid = {user}""" cursor.execute(sql_read) record = cursor.fetchone() - return record[4] + + logging.info(f'Func read_db:\n' + f'\t\t\t\t\tTrack: {column}\n' + f'\t\t\t\t\tRecord: {record}\n' + f'\t\t\t\t\t-----------------') + + return record[_col_dict[column]] except sqlite3.Error as _error: logging.error("Failed to read sqlite table", _error) + @staticmethod + async def check_exist_audio(ctx, guild: int, user: int, column: str, audio: str): + _list_str = await DB.read_db(guild, user, column) + print(type(_list_str)) + if _list_str is not None: + _list = _list_str.split(',') + if audio in _list: + await ctx.reply("File in list") + logging.info(f'File {audio} in list') + else: + logging.info(f'File {audio} is not in list') + else: + _list = 'None' + logging.info(f'check_exist_audio\n' + f'\t\t\t\t\t{_list}' + f'\t\t\t\t\t{audio}') + class CogsPrepare: """ @@ -79,7 +127,7 @@ class CogsPrepare: return cogs_list @staticmethod - def cogs_dict(): + async def cogs_dict(): cog_dict = {} for _cog in CogsPrepare.cog_list(): cog_dict.update({f'{_cog}': f'{_cog}'}) @@ -109,7 +157,7 @@ class Commands: await Commands.write_json(inter.guild.id, "prefix", prefix) @staticmethod - def list_files(fold: str): + async def list_files(fold: str): fl = [] for filenames in walk(fold): fl.extend(filenames) @@ -142,9 +190,9 @@ class Commands: @staticmethod async def write_json(guild: int, param_name: str, param: str or int): - with open('prefix.json', 'r', encoding='utf-8') as _f: + with open('prefix.json', 'r', encoding='utf-8') as f: try: - _json = json.load(_f) + _json = json.load(f) except json.decoder.JSONDecodeError: _json = {} try: @@ -154,15 +202,15 @@ class Commands: _guild = _json[f'{guild}'] _guild.update({f'{param_name}': f'{param}'}) - with open('prefix.json', 'w', encoding='utf-8') as _f: - json.dump(_json, _f, indent=4) + with open('prefix.json', 'w', encoding='utf-8') as f: + json.dump(_json, f, indent=4) @staticmethod - def determine_prefix(bot, msg): + async def determine_prefix(bot, msg): """ Determite perserver bot prefix - :param bot: - :param msg: + :param bot: Disnake Bot object + :param msg: Disnake msg object :return: prefix """ with open('prefix.json', 'r', encoding='utf-8') as fp: # Open the JSON @@ -173,11 +221,9 @@ class Commands: except: _json = {} - if msg.guild: # If the guild exists - try: - parameter = _json[f"{msg.guild.id}"]["prefix"] # Read prefix from json if is setted up - except: - parameter = DEFAULT_PREFIX + try: + parameter = _json[f"{msg.guild.id}"]["prefix"] # Read prefix from json if is setted up + except: + parameter = '$' - print(parameter) return parameter diff --git a/test.py b/test.py index 989c12f..df5b889 100644 --- a/test.py +++ b/test.py @@ -12,6 +12,7 @@ bot_owner = 386629192743256065 lib.Commands.check_json() intents = disnake.Intents(messages=True, guilds=True, message_content=True) intents.members = True +intents.voice_states = True bot = commands.Bot(command_prefix=lib.Commands.determine_prefix, intents=intents,