v0.0.6\nplay_audio fixes
This commit is contained in:
114
lib/CogsPrep.py
114
lib/CogsPrep.py
@@ -1,57 +1,57 @@
|
||||
"""
|
||||
lib.CogsPrepare
|
||||
~~~~~~~~~~~~~
|
||||
Loads, unloads Cogs files
|
||||
cog_list: return list of cog filenames
|
||||
work_with_cogs: loads, reloads and unloads cogs files
|
||||
|
||||
"""
|
||||
import os
|
||||
import traceback
|
||||
from os import listdir
|
||||
from typing import List
|
||||
|
||||
from disnake.ext import commands
|
||||
from .Logger import logger
|
||||
|
||||
|
||||
async def cog_list(fold='./cogs') -> List[str]:
|
||||
cogs_list = []
|
||||
for _filename in listdir(fold):
|
||||
if _filename.endswith('.py'):
|
||||
cogs_list.append(_filename[:-3])
|
||||
return cogs_list
|
||||
|
||||
|
||||
async def work_with_cogs(what_do, bot, cog):
|
||||
if isinstance(cog, str):
|
||||
cog = cog.split()
|
||||
for _filename in cog:
|
||||
if what_do == "load":
|
||||
try:
|
||||
bot.load_extension(f'cogs.{_filename}')
|
||||
logger.info(f'Loaded cog {_filename}')
|
||||
|
||||
except commands.ExtensionNotFound:
|
||||
logger.error(f"Error: {_filename} couldn't be find to load.")
|
||||
|
||||
except commands.ExtensionFailed as error:
|
||||
logger.error(f'Error: {_filename} failed to load properly.\n\t{error}\n\n{traceback.format_exc()}')
|
||||
|
||||
except commands.ExtensionError:
|
||||
logger.error(f'Error: unknown error with {_filename}')
|
||||
|
||||
elif what_do == 'unload':
|
||||
bot.unload_extension(f'cogs.{_filename}')
|
||||
logger.info(f'Cog {_filename} unloaded')
|
||||
elif what_do == 'reload':
|
||||
bot.reload_extension(f'cogs.{_filename}')
|
||||
logger.info(f'Cog {_filename} reloaded')
|
||||
elif what_do == 'disable':
|
||||
bot.unload_extension(f'cogs.{_filename}')
|
||||
os.rename(f'cogs/{_filename}.py', f'cogs/disabled/{_filename}.py')
|
||||
logger.info(f'Cog {_filename} stopped and disabled')
|
||||
elif what_do == 'enable':
|
||||
os.rename(f'cogs/disabled/{_filename}.py', f'cogs/{_filename}.py')
|
||||
bot.load_extension(f'cogs.{_filename}')
|
||||
logger.info(f'Cog {_filename} started and enabled')
|
||||
"""
|
||||
lib.CogsPrepare
|
||||
~~~~~~~~~~~~~
|
||||
Loads, unloads Cogs files
|
||||
cog_list: return list of cog filenames
|
||||
work_with_cogs: loads, reloads and unloads cogs files
|
||||
|
||||
"""
|
||||
import os
|
||||
import traceback
|
||||
from os import listdir
|
||||
from typing import List
|
||||
|
||||
from disnake.ext import commands
|
||||
from .Logger import logger
|
||||
|
||||
|
||||
async def cog_list(fold='./cogs') -> List[str]:
|
||||
cogs_list = []
|
||||
for _filename in listdir(fold):
|
||||
if _filename.endswith('.py'):
|
||||
cogs_list.append(_filename[:-3])
|
||||
return cogs_list
|
||||
|
||||
|
||||
async def work_with_cogs(what_do, bot, cog):
|
||||
if isinstance(cog, str):
|
||||
cog = cog.split()
|
||||
for _filename in cog:
|
||||
if what_do == "load":
|
||||
try:
|
||||
bot.load_extension(f'cogs.{_filename}')
|
||||
logger.info(f'Loaded cog {_filename}')
|
||||
|
||||
except commands.ExtensionNotFound:
|
||||
logger.error(f"Error: {_filename} couldn't be find to load.")
|
||||
|
||||
except commands.ExtensionFailed as error:
|
||||
logger.error(f'Error: {_filename} failed to load properly.\n\t{error}\n\n{traceback.format_exc()}')
|
||||
|
||||
except commands.ExtensionError:
|
||||
logger.error(f'Error: unknown error with {_filename}')
|
||||
|
||||
elif what_do == 'unload':
|
||||
bot.unload_extension(f'cogs.{_filename}')
|
||||
logger.info(f'Cog {_filename} unloaded')
|
||||
elif what_do == 'reload':
|
||||
bot.reload_extension(f'cogs.{_filename}')
|
||||
logger.info(f'Cog {_filename} reloaded')
|
||||
elif what_do == 'disable':
|
||||
bot.unload_extension(f'cogs.{_filename}')
|
||||
os.rename(f'cogs/{_filename}.py', f'cogs/disabled/{_filename}.py')
|
||||
logger.info(f'Cog {_filename} stopped and disabled')
|
||||
elif what_do == 'enable':
|
||||
os.rename(f'cogs/disabled/{_filename}.py', f'cogs/{_filename}.py')
|
||||
bot.load_extension(f'cogs.{_filename}')
|
||||
logger.info(f'Cog {_filename} started and enabled')
|
||||
|
||||
226
lib/Comands.py
226
lib/Comands.py
@@ -1,113 +1,113 @@
|
||||
"""
|
||||
lib.Commands
|
||||
~~~~~~~~~~~~~~
|
||||
Some prepare for commands
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import dotenv
|
||||
|
||||
|
||||
def preload_checks():
|
||||
dotenv.load_dotenv()
|
||||
if not os.path.isfile('.env') or not os.getenv('CONF_FILE'):
|
||||
with open('.env', 'a', encoding='utf-8') as f:
|
||||
f.write("CONF_FILE='config.json'\n")
|
||||
dotenv.load_dotenv()
|
||||
if not os.path.isfile(os.getenv('CONF_FILE')):
|
||||
with open(os.getenv('CONF_FILE'), 'a', encoding='utf-8') as f:
|
||||
f.write("")
|
||||
|
||||
|
||||
async def list_files(fold: str = 'audio'):
|
||||
if fold != 'audio': fold = f'audio/{fold}'
|
||||
fl = []
|
||||
for filenames in os.walk(fold):
|
||||
fl.extend(filenames)
|
||||
break
|
||||
files = {}
|
||||
for x in fl[2]:
|
||||
files[x] = x
|
||||
return fl[2]
|
||||
|
||||
|
||||
async def read_json(guild: int, _param: str):
|
||||
"""
|
||||
Reads Json file to determite config strings
|
||||
:param guild: ID of Guild
|
||||
:param _param: Parameter in json file
|
||||
:return: value of parameter.
|
||||
"""
|
||||
parameter = None
|
||||
with open(os.getenv('CONF_FILE'), 'r', encoding='utf-8') as f: # Open the JSON
|
||||
try:
|
||||
_json = json.load(f) # Load the custom prefixes
|
||||
except json.decoder.JSONDecodeError:
|
||||
_json = {}
|
||||
if guild: # If the guild exists
|
||||
try:
|
||||
guild_conf = _json[f"{guild}"]
|
||||
try:
|
||||
parameter = guild_conf[f"{_param}"]
|
||||
except KeyError:
|
||||
pass
|
||||
except KeyError:
|
||||
pass
|
||||
return parameter
|
||||
|
||||
|
||||
async def write_json(guild: int, param_name: str, param: str or int):
|
||||
with open(os.getenv('CONF_FILE'), 'r', encoding='utf-8') as f:
|
||||
try:
|
||||
_json = json.load(f)
|
||||
except json.decoder.JSONDecodeError:
|
||||
_json = {}
|
||||
try:
|
||||
_guild = _json[f'{guild}']
|
||||
except KeyError:
|
||||
_json.update({f'{guild}': {}})
|
||||
_guild = _json[f'{guild}']
|
||||
_guild.update({f'{param_name}': f'{param}'})
|
||||
with open(os.getenv('CONF_FILE'), 'w', encoding='utf-8') as f:
|
||||
json.dump(_json, f, indent=4)
|
||||
|
||||
|
||||
def determine_prefix(bot, msg):
|
||||
"""
|
||||
Determite per-server bot prefix
|
||||
:param bot: Disnake Bot object
|
||||
:param msg: Disnake msg object
|
||||
:return: prefix for server, default is $
|
||||
"""
|
||||
parameter = '$'
|
||||
with open(os.getenv('CONF_FILE'), 'r', encoding='utf-8') as f: # Open the JSON
|
||||
try:
|
||||
_json = json.load(f) # Load the custom prefixes
|
||||
except json.JSONDecodeError:
|
||||
_json = {}
|
||||
try:
|
||||
parameter = _json[f"{msg.guild.id}"]["prefix"] # Read prefix from json if is setted up
|
||||
|
||||
except KeyError:
|
||||
pass
|
||||
return parameter
|
||||
|
||||
|
||||
def determine_time(msg):
|
||||
"""
|
||||
Determite per-server bot prefix
|
||||
:param msg: Disnake msg object
|
||||
:return: prefix for server, default is $
|
||||
"""
|
||||
parameter = 15
|
||||
with open(os.getenv('CONF_FILE'), 'r', encoding='utf-8') as f: # Open the JSON
|
||||
try:
|
||||
_json = json.load(f) # Load the custom prefixes
|
||||
except json.JSONDecodeError:
|
||||
_json = {}
|
||||
try:
|
||||
parameter = _json[f"{msg.guild.id}"]["seconds"] # Read prefix from json if is setted up
|
||||
|
||||
except KeyError:
|
||||
pass
|
||||
return parameter
|
||||
"""
|
||||
lib.Commands
|
||||
~~~~~~~~~~~~~~
|
||||
Some prepare for commands
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import dotenv
|
||||
|
||||
|
||||
def preload_checks():
|
||||
dotenv.load_dotenv()
|
||||
if not os.path.isfile('.env') or not os.getenv('CONF_FILE'):
|
||||
with open('.env', 'a', encoding='utf-8') as f:
|
||||
f.write("CONF_FILE='config.json'\n")
|
||||
dotenv.load_dotenv()
|
||||
if not os.path.isfile(os.getenv('CONF_FILE')):
|
||||
with open(os.getenv('CONF_FILE'), 'a', encoding='utf-8') as f:
|
||||
f.write("")
|
||||
|
||||
|
||||
async def list_files(fold: str = 'audio'):
|
||||
if fold != 'audio': fold = f'audio/{fold}'
|
||||
fl = []
|
||||
for filenames in os.walk(fold):
|
||||
fl.extend(filenames)
|
||||
break
|
||||
files = {}
|
||||
for x in fl[2]:
|
||||
files[x] = x
|
||||
return fl[2]
|
||||
|
||||
|
||||
async def read_json(guild: int, _param: str):
|
||||
"""
|
||||
Reads Json file to determite config strings
|
||||
:param guild: ID of Guild
|
||||
:param _param: Parameter in json file
|
||||
:return: value of parameter.
|
||||
"""
|
||||
parameter = None
|
||||
with open(os.getenv('CONF_FILE'), 'r', encoding='utf-8') as f: # Open the JSON
|
||||
try:
|
||||
_json = json.load(f) # Load the custom prefixes
|
||||
except json.decoder.JSONDecodeError:
|
||||
_json = {}
|
||||
if guild: # If the guild exists
|
||||
try:
|
||||
guild_conf = _json[f"{guild}"]
|
||||
try:
|
||||
parameter = guild_conf[f"{_param}"]
|
||||
except KeyError:
|
||||
pass
|
||||
except KeyError:
|
||||
pass
|
||||
return parameter
|
||||
|
||||
|
||||
async def write_json(guild: int, param_name: str, param: str or int):
|
||||
with open(os.getenv('CONF_FILE'), 'r', encoding='utf-8') as f:
|
||||
try:
|
||||
_json = json.load(f)
|
||||
except json.decoder.JSONDecodeError:
|
||||
_json = {}
|
||||
try:
|
||||
_guild = _json[f'{guild}']
|
||||
except KeyError:
|
||||
_json.update({f'{guild}': {}})
|
||||
_guild = _json[f'{guild}']
|
||||
_guild.update({f'{param_name}': f'{param}'})
|
||||
with open(os.getenv('CONF_FILE'), 'w', encoding='utf-8') as f:
|
||||
json.dump(_json, f, indent=4)
|
||||
|
||||
|
||||
def determine_prefix(bot, msg):
|
||||
"""
|
||||
Determite per-server bot prefix
|
||||
:param bot: Disnake Bot object
|
||||
:param msg: Disnake msg object
|
||||
:return: prefix for server, default is $
|
||||
"""
|
||||
parameter = '$'
|
||||
with open(os.getenv('CONF_FILE'), 'r', encoding='utf-8') as f: # Open the JSON
|
||||
try:
|
||||
_json = json.load(f) # Load the custom prefixes
|
||||
except json.JSONDecodeError:
|
||||
_json = {}
|
||||
try:
|
||||
parameter = _json[f"{msg.guild.id}"]["prefix"] # Read prefix from json if is setted up
|
||||
|
||||
except KeyError:
|
||||
pass
|
||||
return parameter
|
||||
|
||||
|
||||
def determine_time(msg):
|
||||
"""
|
||||
Determite per-server bot prefix
|
||||
:param msg: Disnake msg object
|
||||
:return: prefix for server, default is $
|
||||
"""
|
||||
parameter = 15
|
||||
with open(os.getenv('CONF_FILE'), 'r', encoding='utf-8') as f: # Open the JSON
|
||||
try:
|
||||
_json = json.load(f) # Load the custom prefixes
|
||||
except json.JSONDecodeError:
|
||||
_json = {}
|
||||
try:
|
||||
parameter = _json[f"{msg.guild.id}"]["seconds"] # Read prefix from json if is setted up
|
||||
|
||||
except KeyError:
|
||||
pass
|
||||
return parameter
|
||||
|
||||
330
lib/DB_Worker.py
330
lib/DB_Worker.py
@@ -1,165 +1,165 @@
|
||||
import sqlite3
|
||||
|
||||
|
||||
from lib import logger
|
||||
|
||||
|
||||
class DB_Reader:
|
||||
|
||||
def __init__(self, guildid: int = None):
|
||||
self._guildid = guildid
|
||||
self.list = self._read_db(self._guildid)
|
||||
self._current_index = 0
|
||||
|
||||
def __str__(self) -> str:
|
||||
return str(self._guildid)
|
||||
|
||||
@classmethod
|
||||
def _read_db(cls, guildid: int) -> list:
|
||||
try:
|
||||
sql_con = sqlite3.connect("user.db")
|
||||
cursor = sql_con.cursor()
|
||||
cursor.execute(f"""SELECT * FROM "{guildid}" """)
|
||||
record = cursor.fetchall()
|
||||
return record
|
||||
except sqlite3.Error as _e:
|
||||
logger.info(f'Error reading DB\n{_e}')
|
||||
|
||||
def __iter__(self):
|
||||
return _ListGenerationIter(self)
|
||||
|
||||
|
||||
class _DBAttrs:
|
||||
def __init__(self,
|
||||
userid: int,
|
||||
username: str,
|
||||
nick: str,
|
||||
isbot: bool,
|
||||
defaulttracks: None or list,
|
||||
usertracks: None or list):
|
||||
self.userid = userid
|
||||
self.username = username
|
||||
self.nick = nick
|
||||
self.isbot = isbot
|
||||
self.defaulttracks = defaulttracks
|
||||
self.usertracks = usertracks
|
||||
|
||||
def __str__(self):
|
||||
return self.username
|
||||
|
||||
def __repr__(self):
|
||||
return f'<File attrs userid={self.userid} username={self.username} nick={self.nick} ' \
|
||||
f'isbot={self.isbot} defaulttracks={self.defaulttracks} usertracks={self.usertracks}>'
|
||||
|
||||
|
||||
class _ListGenerationIter:
|
||||
def __init__(self, user_class):
|
||||
self._current_index = 0
|
||||
self._list = user_class.list
|
||||
|
||||
self._size = len(self._list)
|
||||
|
||||
def __iter__(self):
|
||||
return self
|
||||
|
||||
def __next__(self):
|
||||
if self._current_index < self._size:
|
||||
_userid = self._list[self._current_index][0]
|
||||
_username = self._list[self._current_index][1]
|
||||
_nick = self._list[self._current_index][2]
|
||||
_isbot = bool(self._list[self._current_index][3])
|
||||
_defaulttracks = self._list[self._current_index][4]
|
||||
_usertracks = self._list[self._current_index][5]
|
||||
|
||||
self._current_index += 1
|
||||
memb = _DBAttrs(_userid,
|
||||
_username,
|
||||
_nick,
|
||||
_isbot,
|
||||
_defaulttracks,
|
||||
_usertracks)
|
||||
return memb
|
||||
raise StopIteration
|
||||
|
||||
|
||||
async def prepare_db(guild: int):
|
||||
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, [defaulttracks] TEXT, [usertracks] TEXT) ''')
|
||||
cursor.execute(create_table)
|
||||
cursor.close()
|
||||
except sqlite3.Error as _error:
|
||||
pass
|
||||
|
||||
|
||||
async def work_with_db(db_func: str, data_turple: tuple):
|
||||
"""
|
||||
Writing to db per server userinfo
|
||||
:param db_func:
|
||||
:param 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:
|
||||
pass
|
||||
|
||||
|
||||
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)
|
||||
await work_with_db(sqlite_insert_with_param, data_tuple)
|
||||
|
||||
|
||||
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}'
|
||||
sql_update_query = f"""UPDATE "{guild}" set {track} = ? where userid = ?"""
|
||||
data_tuple = (audio, user)
|
||||
await work_with_db(sql_update_query, data_tuple)
|
||||
|
||||
|
||||
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[_col_dict[column]]
|
||||
except sqlite3.Error as _error:
|
||||
pass
|
||||
|
||||
|
||||
async def check_exist_audio(ctx, guild: int, user: int, column: str, audio: str):
|
||||
_list_str = await 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")
|
||||
|
||||
else:
|
||||
pass
|
||||
|
||||
else:
|
||||
_list = 'None'
|
||||
import sqlite3
|
||||
|
||||
|
||||
from lib import logger
|
||||
|
||||
|
||||
class DBReader:
|
||||
|
||||
def __init__(self, guildid: int = None):
|
||||
self._guildid = guildid
|
||||
self.list = self._read_db(self._guildid)
|
||||
self._current_index = 0
|
||||
|
||||
def __str__(self) -> str:
|
||||
return str(self._guildid)
|
||||
|
||||
@classmethod
|
||||
def _read_db(cls, guildid: int) -> list:
|
||||
try:
|
||||
sql_con = sqlite3.connect("user.db")
|
||||
cursor = sql_con.cursor()
|
||||
cursor.execute(f"""SELECT * FROM "{guildid}" """)
|
||||
record = cursor.fetchall()
|
||||
return record
|
||||
except sqlite3.Error as _e:
|
||||
logger.info(f'Error reading DB\n{_e}')
|
||||
|
||||
def __iter__(self):
|
||||
return _ListGenerationIter(self)
|
||||
|
||||
|
||||
class _DBAttrs:
|
||||
def __init__(self,
|
||||
userid: int,
|
||||
username: str,
|
||||
nick: str,
|
||||
isbot: bool,
|
||||
defaulttracks: None or list,
|
||||
usertracks: None or list):
|
||||
self.userid = userid
|
||||
self.username = username
|
||||
self.nick = nick
|
||||
self.isbot = isbot
|
||||
self.defaulttracks = defaulttracks
|
||||
self.usertracks = usertracks
|
||||
|
||||
def __str__(self):
|
||||
return self.username
|
||||
|
||||
def __repr__(self):
|
||||
return f'<File attrs userid={self.userid} username={self.username} nick={self.nick} ' \
|
||||
f'isbot={self.isbot} defaulttracks={self.defaulttracks} usertracks={self.usertracks}>'
|
||||
|
||||
|
||||
class _ListGenerationIter:
|
||||
def __init__(self, user_class):
|
||||
self._current_index = 0
|
||||
self._list = user_class.list
|
||||
|
||||
self._size = len(self._list)
|
||||
|
||||
def __iter__(self):
|
||||
return self
|
||||
|
||||
def __next__(self):
|
||||
if self._current_index < self._size:
|
||||
_userid = self._list[self._current_index][0]
|
||||
_username = self._list[self._current_index][1]
|
||||
_nick = self._list[self._current_index][2]
|
||||
_isbot = bool(self._list[self._current_index][3])
|
||||
_defaulttracks = self._list[self._current_index][4]
|
||||
_usertracks = self._list[self._current_index][5]
|
||||
|
||||
self._current_index += 1
|
||||
memb = _DBAttrs(_userid,
|
||||
_username,
|
||||
_nick,
|
||||
_isbot,
|
||||
_defaulttracks,
|
||||
_usertracks)
|
||||
return memb
|
||||
raise StopIteration
|
||||
|
||||
|
||||
async def prepare_db(guild: int):
|
||||
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, [defaulttracks] TEXT, [usertracks] TEXT) ''')
|
||||
cursor.execute(create_table)
|
||||
cursor.close()
|
||||
except sqlite3.Error as _error:
|
||||
pass
|
||||
|
||||
|
||||
async def work_with_db(db_func: str, data_turple: tuple):
|
||||
"""
|
||||
Writing to db per server userinfo
|
||||
:param db_func:
|
||||
:param 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:
|
||||
pass
|
||||
|
||||
|
||||
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)
|
||||
await work_with_db(sqlite_insert_with_param, data_tuple)
|
||||
|
||||
|
||||
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}'
|
||||
sql_update_query = f"""UPDATE "{guild}" set {track} = ? where userid = ?"""
|
||||
data_tuple = (audio, user)
|
||||
await work_with_db(sql_update_query, data_tuple)
|
||||
|
||||
|
||||
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[_col_dict[column]]
|
||||
except sqlite3.Error as _error:
|
||||
pass
|
||||
|
||||
|
||||
async def check_exist_audio(ctx, guild: int, user: int, column: str, audio: str):
|
||||
_list_str = await 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")
|
||||
|
||||
else:
|
||||
pass
|
||||
|
||||
else:
|
||||
_list = 'None'
|
||||
|
||||
@@ -1,87 +1,86 @@
|
||||
import mimetypes
|
||||
import os
|
||||
from typing import Tuple, Optional
|
||||
|
||||
|
||||
class ListGenerator:
|
||||
def __init__(self, path: str = None):
|
||||
self.path = path
|
||||
self.list: list = self._lister(self.path)
|
||||
try:
|
||||
self._size = len(self.list)
|
||||
except TypeError:
|
||||
pass
|
||||
self._current_index = 0
|
||||
|
||||
def __str__(self) -> str:
|
||||
return 'Audio iter generator'
|
||||
|
||||
@classmethod
|
||||
def _lister(cls, path) -> list:
|
||||
_list: list = []
|
||||
try:
|
||||
for f in os.walk(path):
|
||||
_list.extend(f)
|
||||
break
|
||||
return sorted(_list[2])
|
||||
except TypeError:
|
||||
pass
|
||||
|
||||
def __iter__(self):
|
||||
return _ListGenerationIter(self)
|
||||
|
||||
def __next__(self):
|
||||
if self._current_index < self._size:
|
||||
self._current_index += 1
|
||||
|
||||
|
||||
class _FileAttrs:
|
||||
def __init__(self, name, path, type, exc):
|
||||
self.name = name
|
||||
self.path = path
|
||||
self.mimetype = type
|
||||
self.exc = exc
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
def __repr__(self):
|
||||
return f'<File attrs name={self.name} path={self.path} exc={self.exc} type=<{self.mimetype}> >'
|
||||
|
||||
|
||||
class _ListGenerationIter:
|
||||
|
||||
def __init__(self, list_class):
|
||||
self._current_index = 0
|
||||
self._list = list_class.list
|
||||
self._name = self._list[self._current_index]
|
||||
self._path = list_class.path
|
||||
|
||||
self._size = len(self._list)
|
||||
|
||||
def __iter__(self):
|
||||
return self
|
||||
|
||||
@property
|
||||
def type(self) -> tuple[Optional[str], Optional[str]]:
|
||||
guess = mimetypes.guess_type(f'{self._path}/{self._list[self._current_index]}')[0]
|
||||
return guess
|
||||
|
||||
@property
|
||||
def _exc(self) -> str:
|
||||
try:
|
||||
_ret = self._list[self._current_index].split('.')[-1]
|
||||
except AttributeError:
|
||||
_ret = None
|
||||
return _ret
|
||||
|
||||
def __next__(self):
|
||||
if self._current_index < self._size:
|
||||
_name = self._list[self._current_index]
|
||||
_path = self._path
|
||||
_type = self.type
|
||||
_exc = self._exc
|
||||
self._current_index += 1
|
||||
memb = _FileAttrs(_name, _path, _type, _exc)
|
||||
return memb
|
||||
raise StopIteration
|
||||
import mimetypes
|
||||
import os
|
||||
|
||||
|
||||
class ListGenerator:
|
||||
def __init__(self, path: str = None):
|
||||
self.path = path
|
||||
self.list: list = self._lister(self.path)
|
||||
try:
|
||||
self._size = len(self.list)
|
||||
except TypeError:
|
||||
pass
|
||||
self._current_index = 0
|
||||
|
||||
def __str__(self) -> str:
|
||||
return 'Audio iter generator'
|
||||
|
||||
@classmethod
|
||||
def _lister(cls, path) -> list:
|
||||
_list: list = []
|
||||
try:
|
||||
for f in os.walk(path):
|
||||
_list.extend(f)
|
||||
break
|
||||
return sorted(_list[2])
|
||||
except TypeError:
|
||||
pass
|
||||
|
||||
def __iter__(self):
|
||||
return _ListGenerationIter(self)
|
||||
|
||||
def __next__(self):
|
||||
if self._current_index < self._size:
|
||||
self._current_index += 1
|
||||
|
||||
|
||||
class _FileAttrs:
|
||||
def __init__(self, name, path, mimetype, exc):
|
||||
self.name = name
|
||||
self.path = path
|
||||
self.mimetype = mimetype
|
||||
self.exc = exc
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
def __repr__(self):
|
||||
return f'<File attrs name={self.name} path={self.path} exc={self.exc} type=<{self.mimetype}> >'
|
||||
|
||||
|
||||
class _ListGenerationIter:
|
||||
|
||||
def __init__(self, list_class):
|
||||
self._current_index = 0
|
||||
self._list = list_class.list
|
||||
self._name = self._list[self._current_index]
|
||||
self._path = list_class.path
|
||||
|
||||
self._size = len(self._list)
|
||||
|
||||
def __iter__(self):
|
||||
return self
|
||||
|
||||
@property
|
||||
def type(self) -> str:
|
||||
guess = mimetypes.guess_type(f'{self._path}/{self._list[self._current_index]}')[0]
|
||||
return guess
|
||||
|
||||
@property
|
||||
def _exc(self) -> str:
|
||||
try:
|
||||
_ret = self._list[self._current_index].split('.')[-1]
|
||||
except AttributeError:
|
||||
_ret = None
|
||||
return _ret
|
||||
|
||||
def __next__(self):
|
||||
if self._current_index < self._size:
|
||||
_name = self._list[self._current_index]
|
||||
_path = self._path
|
||||
_type = self.type
|
||||
_exc = self._exc
|
||||
self._current_index += 1
|
||||
_memb = _FileAttrs(_name, _path, _type, _exc)
|
||||
return _memb
|
||||
raise StopIteration
|
||||
|
||||
104
lib/Logger.py
104
lib/Logger.py
@@ -1,52 +1,52 @@
|
||||
import logging
|
||||
|
||||
|
||||
class _CustomFormatter(logging.Formatter):
|
||||
grey = "\x1b[38;20m"
|
||||
yellow = "\x1b[33;20m"
|
||||
red = "\x1b[31;20m"
|
||||
bold_red = "\x1b[31;1m"
|
||||
reset = "\x1b[0m"
|
||||
format = f"%(asctime)s - [%(levelname)s] -%(module)s- %(message)s"
|
||||
|
||||
FORMATS = {
|
||||
logging.DEBUG: grey + format + reset,
|
||||
logging.INFO: grey + format + reset,
|
||||
logging.WARNING: yellow + format + reset,
|
||||
logging.ERROR: red + format + reset,
|
||||
logging.CRITICAL: bold_red + format + reset
|
||||
}
|
||||
|
||||
old_factory = logging.getLogRecordFactory()
|
||||
|
||||
def _record_factory(*args, **kwargs):
|
||||
record = _CustomFormatter.old_factory(*args, **kwargs)
|
||||
_module = record.module
|
||||
_levelname = record.levelname
|
||||
if len(_module) % 2 == 0 and len(_module) < 12:
|
||||
_module = ' ' * ((12 - len(_module)) // 2) + _module + ' ' * ((12 - len(_module)) // 2)
|
||||
elif len(_module) % 2 == 1 and len(_module) < 12:
|
||||
_module = ' ' * ((12 - len(_module)) // 2) + record.module + ' ' * ((12 - len(_module)) // 2 + 1)
|
||||
if len(_levelname) % 2 == 0 and len(_levelname) < 8:
|
||||
_levelname = ' ' * ((8 - len(_levelname)) // 2) + _levelname + ' ' * ((8 - len(_levelname)) // 2)
|
||||
elif len(record.levelname) % 2 == 1 and len(record.module) < 8:
|
||||
_levelname = ' ' * ((8 - len(_levelname)) // 2) + _levelname + ' ' * ((8 - len(_levelname)) // 2 + 1)
|
||||
record.module = _module
|
||||
record.levelname = _levelname
|
||||
return record
|
||||
|
||||
logging.setLogRecordFactory(_record_factory)
|
||||
|
||||
def format(self, record):
|
||||
log_fmt = self.FORMATS.get(record.levelno)
|
||||
formatter = logging.Formatter(log_fmt, "%d-%m-%Y %H:%M:%S")
|
||||
return formatter.format(record)
|
||||
|
||||
|
||||
logger = logging.getLogger('Pisya_Bot')
|
||||
logger.setLevel(logging.DEBUG)
|
||||
|
||||
ch = logging.StreamHandler()
|
||||
ch.setLevel(logging.DEBUG)
|
||||
ch.setFormatter(_CustomFormatter())
|
||||
logger.addHandler(ch)
|
||||
import logging
|
||||
|
||||
|
||||
class _CustomFormatter(logging.Formatter):
|
||||
grey = "\x1b[38;20m"
|
||||
yellow = "\x1b[33;20m"
|
||||
red = "\x1b[31;20m"
|
||||
bold_red = "\x1b[31;1m"
|
||||
reset = "\x1b[0m"
|
||||
format = f"%(asctime)s - [%(levelname)s] -%(module)s- %(message)s"
|
||||
|
||||
FORMATS = {
|
||||
logging.DEBUG: grey + format + reset,
|
||||
logging.INFO: grey + format + reset,
|
||||
logging.WARNING: yellow + format + reset,
|
||||
logging.ERROR: red + format + reset,
|
||||
logging.CRITICAL: bold_red + format + reset
|
||||
}
|
||||
|
||||
old_factory = logging.getLogRecordFactory()
|
||||
|
||||
def _record_factory(*args, **kwargs):
|
||||
record = _CustomFormatter.old_factory(*args, **kwargs)
|
||||
_module = record.module
|
||||
_levelname = record.levelname
|
||||
if len(_module) % 2 == 0 and len(_module) < 12:
|
||||
_module = ' ' * ((12 - len(_module)) // 2) + _module + ' ' * ((12 - len(_module)) // 2)
|
||||
elif len(_module) % 2 == 1 and len(_module) < 12:
|
||||
_module = ' ' * ((12 - len(_module)) // 2) + record.module + ' ' * ((12 - len(_module)) // 2 + 1)
|
||||
if len(_levelname) % 2 == 0 and len(_levelname) < 8:
|
||||
_levelname = ' ' * ((8 - len(_levelname)) // 2) + _levelname + ' ' * ((8 - len(_levelname)) // 2)
|
||||
elif len(record.levelname) % 2 == 1 and len(record.module) < 8:
|
||||
_levelname = ' ' * ((8 - len(_levelname)) // 2) + _levelname + ' ' * ((8 - len(_levelname)) // 2 + 1)
|
||||
record.module = _module
|
||||
record.levelname = _levelname
|
||||
return record
|
||||
|
||||
logging.setLogRecordFactory(_record_factory)
|
||||
|
||||
def format(self, record):
|
||||
log_fmt = self.FORMATS.get(record.levelno)
|
||||
formatter = logging.Formatter(log_fmt, "%d-%m-%Y %H:%M:%S")
|
||||
return formatter.format(record)
|
||||
|
||||
|
||||
logger = logging.getLogger('Pisya_Bot')
|
||||
logger.setLevel(logging.DEBUG)
|
||||
|
||||
ch = logging.StreamHandler()
|
||||
ch.setLevel(logging.DEBUG)
|
||||
ch.setFormatter(_CustomFormatter())
|
||||
logger.addHandler(ch)
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
from .Logger import logger
|
||||
from asyncio import sleep
|
||||
from disnake import FFmpegPCMAudio
|
||||
|
||||
|
||||
async def play_audio(audio, bot, vc):
|
||||
if not bot.voice_clients:
|
||||
logger.info(audio)
|
||||
logger.error(f'Playing: {audio}')
|
||||
await sleep(1)
|
||||
vp = await vc.connect()
|
||||
if not vp.is_playing():
|
||||
vp.play(FFmpegPCMAudio(f'{audio}'), after=None)
|
||||
while vp.is_playing():
|
||||
await sleep(0.5)
|
||||
await sleep(1)
|
||||
await vp.disconnect()
|
||||
from .Logger import logger
|
||||
from asyncio import sleep
|
||||
from disnake import FFmpegOpusAudio, opus
|
||||
|
||||
|
||||
async def play_audio(audio, bot, vc):
|
||||
if not bot.voice_clients:
|
||||
# logger.info(audio)
|
||||
logger.error(f'Playing: {audio}')
|
||||
await sleep(1)
|
||||
vp = await vc.connect()
|
||||
if not vp.is_playing():
|
||||
vp.play(FFmpegOpusAudio(f'{audio}', executable='ffmpeg'), after=lambda e: print('done', e))
|
||||
while vp.is_playing():
|
||||
await sleep(0.5)
|
||||
await sleep(1)
|
||||
await vp.disconnect()
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
"""
|
||||
lib
|
||||
~~~~~~~~~~~~~
|
||||
Some libs for the bot whitch help him
|
||||
"""
|
||||
from .ListGenerator import *
|
||||
from .Logger import *
|
||||
from .Comands import *
|
||||
from .Player import *
|
||||
from .DB_Worker import *
|
||||
from .CogsPrep import *
|
||||
"""
|
||||
lib
|
||||
~~~~~~~~~~~~~
|
||||
Some libs for the bot whitch help him
|
||||
"""
|
||||
from .ListGenerator import *
|
||||
from .Logger import *
|
||||
from .Comands import *
|
||||
from .Player import *
|
||||
from .DB_Worker import *
|
||||
from .CogsPrep import *
|
||||
|
||||
Reference in New Issue
Block a user