some code changes
This commit is contained in:
@@ -6,11 +6,10 @@ cog_list: return list of cog filenames
|
||||
work_with_cogs: loads, reloads and unloads cogs files
|
||||
|
||||
"""
|
||||
import logging
|
||||
import traceback
|
||||
from os import listdir
|
||||
|
||||
from disnake.ext import commands
|
||||
|
||||
from .Logger import logger
|
||||
|
||||
|
||||
def cog_list():
|
||||
@@ -26,16 +25,16 @@ async def work_with_cogs(what_do, bot):
|
||||
if what_do == "load":
|
||||
try:
|
||||
bot.load_extension(f'cogs.{_filename}')
|
||||
logging.info(f'Loaded cog {_filename}')
|
||||
logger.info(f'Loaded cog {_filename}')
|
||||
|
||||
except commands.ExtensionNotFound:
|
||||
logging.error(f"Error: {_filename} couldn't be found to load.")
|
||||
logger.error(f"Error: {_filename} couldn't be find to load.")
|
||||
|
||||
except commands.ExtensionFailed as error:
|
||||
logging.error(f'Error: {_filename} failed to load properly.', error)
|
||||
logger.error(f'Error: {_filename} failed to load properly.\n\t{error}\n\n{traceback.format_exc()}')
|
||||
|
||||
except commands.ExtensionError:
|
||||
logging.error(f'Error: unknown error with {_filename}')
|
||||
logger.error(f'Error: unknown error with {_filename}')
|
||||
|
||||
elif what_do == 'unload':
|
||||
bot.unload_extension(f'cogs.{_filename}')
|
||||
@@ -1,23 +1,26 @@
|
||||
import asyncio
|
||||
"""
|
||||
lib.Commands
|
||||
~~~~~~~~~~~~~~
|
||||
Some prepare for commands
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from typing import Union
|
||||
|
||||
import disnake
|
||||
|
||||
"""
|
||||
Some prepare for commands
|
||||
|
||||
"""
|
||||
import dotenv
|
||||
|
||||
|
||||
def check_conf():
|
||||
if not os.path.isfile(os.getenv('conf_file')):
|
||||
with open(os.getenv('conf_file'), 'w+', encoding='utf-8') as f:
|
||||
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)
|
||||
@@ -36,7 +39,7 @@ async def read_json(guild: int, _param: str):
|
||||
:return: value of parameter.
|
||||
"""
|
||||
parameter = None
|
||||
with open(os.getenv('conf_file'), 'r', encoding='utf-8') as f: # Open the JSON
|
||||
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:
|
||||
@@ -54,7 +57,7 @@ async def read_json(guild: int, _param: str):
|
||||
|
||||
|
||||
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:
|
||||
with open(os.getenv('CONF_FILE'), 'r', encoding='utf-8') as f:
|
||||
try:
|
||||
_json = json.load(f)
|
||||
except json.decoder.JSONDecodeError:
|
||||
@@ -65,7 +68,7 @@ async def write_json(guild: int, param_name: str, param: str or int):
|
||||
_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:
|
||||
with open(os.getenv('CONF_FILE'), 'w', encoding='utf-8') as f:
|
||||
json.dump(_json, f, indent=4)
|
||||
|
||||
|
||||
@@ -77,7 +80,7 @@ def determine_prefix(bot, msg):
|
||||
:return: prefix for server, default is $
|
||||
"""
|
||||
parameter = '$'
|
||||
with open(os.getenv('conf_file'), 'r', encoding='utf-8') as f: # Open the JSON
|
||||
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:
|
||||
@@ -97,7 +100,7 @@ def determine_time(msg):
|
||||
:return: prefix for server, default is $
|
||||
"""
|
||||
parameter = 15
|
||||
with open(os.getenv('conf_file'), 'r', encoding='utf-8') as f: # Open the JSON
|
||||
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:
|
||||
@@ -108,9 +111,3 @@ def determine_time(msg):
|
||||
except:
|
||||
pass
|
||||
return parameter
|
||||
|
||||
def maybe_defer(inter: disnake.Interaction, *, delay: Union[float, int] = 2.0, **options) -> asyncio.Task:
|
||||
"""Defer an interaction if it has not been responded to after ``delay`` seconds."""
|
||||
loop = inter.bot.loop
|
||||
if delay <= 0:
|
||||
return loop.create_task(inter.response.defer(**options))
|
||||
|
||||
96
lib/ListGenerator.py
Normal file
96
lib/ListGenerator.py
Normal file
@@ -0,0 +1,96 @@
|
||||
import mimetypes
|
||||
import os
|
||||
|
||||
|
||||
class FileAttrs:
|
||||
def __iter__(self, name, path, type):
|
||||
self.name = name
|
||||
self.path = path
|
||||
self.type = type
|
||||
|
||||
@self.name.setter
|
||||
def name(self, value):
|
||||
self.name = value
|
||||
|
||||
@self.type.setter
|
||||
def type(self, value):
|
||||
self.type = value
|
||||
|
||||
@self.path.setter
|
||||
def path(self, value):
|
||||
self.path = value
|
||||
|
||||
class ListGenerator:
|
||||
def __init__(self, path=None):
|
||||
self._path = path
|
||||
self.list: list = self._lister(self._path)
|
||||
self._current_index = 0
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.name
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return (
|
||||
f'<Audio file name={self.name} path={self.path} type={self.type} size={self._size}>'
|
||||
)
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return self.list[self._current_index]
|
||||
|
||||
@property
|
||||
def path(self) -> str:
|
||||
return str(self._path)
|
||||
|
||||
@property
|
||||
def type(self) -> str:
|
||||
guess = mimetypes.guess_type(f'{self._path}/{self.name}')[0].split('/')[0]
|
||||
return guess
|
||||
|
||||
@classmethod
|
||||
def _lister(cls, path) -> list:
|
||||
_dict: list = []
|
||||
for _files in os.walk(path):
|
||||
_dict.extend(_files)
|
||||
break
|
||||
return _dict[2]
|
||||
|
||||
def __iter__(self):
|
||||
return ListGenerationIter(self)
|
||||
|
||||
@name.setter
|
||||
def name(self, value):
|
||||
self.name = value
|
||||
|
||||
@type.setter
|
||||
def type(self, value):
|
||||
self.type = value
|
||||
|
||||
@path.setter
|
||||
def path(self, value):
|
||||
self.path = value
|
||||
|
||||
|
||||
class ListGenerationIter:
|
||||
def __init__(self, list_class):
|
||||
self._list = list_class.list
|
||||
self._name = list_class.name
|
||||
self._type = list_class.type
|
||||
self._path = list_class.path
|
||||
|
||||
self._size = len(self._list)
|
||||
self._current_index = 0
|
||||
|
||||
def __iter__(self):
|
||||
return self
|
||||
|
||||
def __next__(self):
|
||||
if self._current_index < self._size:
|
||||
|
||||
_name = self._list[self._current_index]
|
||||
_path = self._path
|
||||
_type = self._type
|
||||
self._current_index += 1
|
||||
memb = FileAttrs(_name, _path, _type)
|
||||
return memb
|
||||
raise StopIteration
|
||||
33
lib/Logger.py
Normal file
33
lib/Logger.py
Normal file
@@ -0,0 +1,33 @@
|
||||
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 = "%(asctime)s - %(levelname)s - %(module)s \t- %(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
|
||||
}
|
||||
|
||||
def format(self, record):
|
||||
log_fmt = self.FORMATS.get(record.levelno)
|
||||
formatter = logging.Formatter(log_fmt)
|
||||
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,16 +1,12 @@
|
||||
import logging
|
||||
from .Logger import logger
|
||||
from asyncio import sleep
|
||||
from typing import Union, Optional
|
||||
|
||||
import disnake
|
||||
from disnake import FFmpegPCMAudio
|
||||
from disnake.ext import commands
|
||||
|
||||
|
||||
async def play_audio(audio, bot, vc):
|
||||
if not bot.voice_clients:
|
||||
logging.info(audio)
|
||||
logging.error(f'Playing: {audio}')
|
||||
logger.info(audio)
|
||||
logger.error(f'Playing: {audio}')
|
||||
await sleep(1)
|
||||
vp = await vc.connect()
|
||||
if not vp.is_playing():
|
||||
@@ -19,11 +15,3 @@ async def play_audio(audio, bot, vc):
|
||||
await sleep(0.5)
|
||||
await sleep(1)
|
||||
await vp.disconnect()
|
||||
|
||||
|
||||
async def get_audio_list(inter: Union[disnake.ApplicationCommandInteraction, commands.Context],
|
||||
search: Optional[str],
|
||||
return_embed: bool = False,
|
||||
) -> None:
|
||||
|
||||
await list_files()
|
||||
|
||||
@@ -3,8 +3,9 @@ lib
|
||||
~~~~~~~~~~~~~
|
||||
Some libs for the bot whitch help him
|
||||
"""
|
||||
|
||||
from .DB import *
|
||||
from .Player import *
|
||||
from .ListGenerator import *
|
||||
from .Logger import *
|
||||
from .Comands import *
|
||||
from .CogsPrepare import *
|
||||
from .Player import *
|
||||
from .DB_Worker import *
|
||||
from .CogsPrep import *
|
||||
Reference in New Issue
Block a user