v0.0.6\nplay_audio fixes

This commit is contained in:
bot
2024-03-07 02:18:09 +03:00
parent d75add614b
commit 53939b4bc3
22 changed files with 1126 additions and 1104 deletions

View File

@@ -1,174 +1,172 @@
from asyncio import sleep
from typing import List
import disnake
from disnake import Option, OptionType, OptionChoice
from disnake.ext import commands, tasks
from lib import read_json, write_json
from lib import fill_bd, prepare_db, work_with_db
from lib import logger
class Admin(commands.Cog, name='Admin'):
def __init__(self, bot):
self.bot = bot # a defining bot as global var in class
@commands.Cog.listener() # this is a decorator for events/listeners
async def on_ready(self):
for g in self.bot.get_all_members():
await prepare_db(g.guild.id)
for g in self.bot.get_all_members():
await fill_bd(g.name, g.id, g.bot, g.nick, g.guild.id)
self.activity.start()
logger.info(f'Cog {__name__.split(".")[1]} is ready!.')
@tasks.loop(seconds=20)
async def activity(self):
await self.bot.change_presence(
activity=disnake.Activity(
name=f'at users: {str(len(self.bot.users))}',
type=3
)
)
await sleep(10)
await self.bot.change_presence(
activity=disnake.Activity(
name=f'at servers: {str(len(self.bot.guilds))}',
type=3
)
)
@commands.Cog.listener()
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)
await work_with_db(sql_update_query, data_tuple)
@commands.Cog.listener()
async def on_guild_join(self, guild):
for g in guild.members:
await fill_bd(g.name, g.id, g.bot, g.nick, guild.id)
@commands.Cog.listener()
async def on_member_join(self, member):
await fill_bd(member.name, member.id, member.bot, member.nick, member.guild.id)
bot_role = read_json(member.guild.id, 'bot_role') # Get bot role
guest_role = read_json(member.guild.id, 'guest_role') # Get guest role
if bot_role or guest_role:
if member.bot == 0:
role = disnake.utils.get(member.guild.roles, id=guest_role)
else:
role = disnake.utils.get(member.guild.roles, id=bot_role)
logger.info(f"Adding to {member} role {role}")
await member.add_roles(role)
@commands.slash_command(
name="set_guest_role",
description="Set Default bot role",
options=[
Option("role", "Specify role", OptionType.role, required=True),
]
)
@commands.has_permissions(administrator=True)
async def set_guest_role(self, inter, role):
await write_json(inter.guild.id, "guest_role", role.id)
await inter.response.send_message(f"Set up bot role to: `{role.name}`", ephemeral=True)
@commands.command(name="set_prefix")
@commands.has_permissions(administrator=True)
async def command_set_prefix(self, ctx, prefix: str):
await write_json(ctx.guild.id, "prefix", prefix)
await ctx.reply(f"Prefix set to: `{prefix}`")
@commands.guild_only()
@commands.slash_command(
name="set_prefix",
description="Setting up bot prefix",
options=[
Option("prefix", "Specify prefix", OptionType.string, required=True),
]
)
@commands.has_permissions(administrator=True)
async def slash_set_prefix(self, inter, prefix: str):
await write_json(inter.guild.id, "prefix", prefix)
await inter.response.send_message(f"Prefix set to: `{prefix}`", ephemeral=True)
@commands.guild_only()
@commands.slash_command(
name="set_trigger_role",
description="Setting up role to trigger bot",
options=[
Option("role", "Specify role", OptionType.role, required=True),
]
)
@commands.has_permissions(administrator=True)
async def set_trigger_role(self, inter, role):
await write_json(inter.guild.id, "tigger_role", role.id)
await inter.response.send_message(f"Role to trigger set to : `{role.name}`", ephemeral=True)
@commands.slash_command(
name="set_bot_role",
description="Set Default bot role",
options=[
Option("role", "Specify role", OptionType.role, required=True),
]
)
@commands.guild_only()
@commands.has_permissions(administrator=True)
async def set_bot_role(self, ctx, role):
await write_json(ctx.guild.id, "bot_role", role.id)
await ctx.send(f"Set up bot role to: `{role.name}`", ephemeral=True)
@set_bot_role.error
@set_trigger_role.error
@slash_set_prefix.error
async def set_prefix_error(self, inter, prefix):
await inter.response.send_message("You don`t have permissions", ephemeral=True)
@commands.has_permissions(administrator=True)
@commands.slash_command(
name="set_time",
description="Read list of tracks for user",
options=[
Option("seconds", "specify max duration", OptionType.integer, required=True),
]
)
async def set_time(self,
inter: disnake.ApplicationCommandInteraction,
seconds: commands.Range[5, 30]):
await write_json(inter.guild.id, "seconds", seconds)
await inter.response.send_message(f"Change max audio duration to {seconds} sec", ephemeral=True)
@commands.has_permissions(administrator=True)
@commands.slash_command(
name="set_bot_channel",
description="Set channel which iterate with bot",
options=[
Option("channel", "specify channel", OptionType.string, required=True),
]
)
async def set_bot_channel(self, inter, channel):
print(type(inter.guild.text_channels))
await write_json(inter.guild.id, "channel", channel.id)
await inter.response.send_message(f"Channel set up to {channel.mention}", ephemeral=True)
@set_bot_channel.autocomplete('channel')
async def _list_text_channels(self,
inter: disnake.ApplicationCommandInteraction,
current: str) -> List[OptionChoice]:
_list = []
for _channel in inter.guild.text_channels:
_list.append(_channel)
return [
OptionChoice(name=choice, value=choice)
for choice in _list if current in choice
]
def setup(bot): # an extension must have a setup function
bot.add_cog(Admin(bot)) # adding a cog
from asyncio import sleep
from typing import List
import disnake
from disnake import Option, OptionType, OptionChoice
from disnake.ext import commands, tasks
from lib import read_json, write_json
from lib import fill_bd, prepare_db, work_with_db
from lib import logger
class Admin(commands.Cog, name='Admin'):
def __init__(self, bot):
self.bot = bot # a defining bot as global var in class
@commands.Cog.listener() # this is a decorator for events/listeners
async def on_ready(self):
for g in self.bot.get_all_members():
await prepare_db(g.guild.id)
for g in self.bot.get_all_members():
await fill_bd(g.name, g.id, g.bot, g.nick, g.guild.id)
self.activity.start()
logger.info(f'Cog {__name__.split(".")[1]} is ready!.')
@tasks.loop(seconds=20)
async def activity(self):
await self.bot.change_presence(
activity=disnake.Activity(
name=f'at users: {str(len(self.bot.users))}',
type=3
)
)
await sleep(10)
await self.bot.change_presence(
activity=disnake.Activity(
name=f'at servers: {str(len(self.bot.guilds))}',
type=3
)
)
@commands.Cog.listener()
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)
await work_with_db(sql_update_query, data_tuple)
@commands.Cog.listener()
async def on_guild_join(self, guild):
for g in guild.members:
await fill_bd(g.name, g.id, g.bot, g.nick, guild.id)
@commands.Cog.listener()
async def on_member_join(self, member):
await fill_bd(member.name, member.id, member.bot, member.nick, member.guild.id)
bot_role = read_json(member.guild.id, 'bot_role') # Get bot role
guest_role = read_json(member.guild.id, 'guest_role') # Get guest role
if bot_role or guest_role:
if member.bot == 0:
role = disnake.utils.get(member.guild.roles, id=guest_role)
else:
role = disnake.utils.get(member.guild.roles, id=bot_role)
logger.info(f"Adding to {member} role {role}")
await member.add_roles(role)
@commands.slash_command(
name="set_guest_role",
description="Set Default bot role",
options=[
Option("role", "Specify role", OptionType.role, required=True),
]
)
@commands.has_permissions(administrator=True)
async def set_guest_role(self, inter, role):
await write_json(inter.guild.id, "guest_role", role.id)
await inter.response.send_message(f"Set up bot role to: `{role.name}`", ephemeral=True)
@commands.command(name="set_prefix")
@commands.has_permissions(administrator=True)
async def command_set_prefix(self, ctx, prefix: str):
await write_json(ctx.guild.id, "prefix", prefix)
await ctx.reply(f"Prefix set to: `{prefix}`")
@commands.guild_only()
@commands.slash_command(
name="set_prefix",
description="Setting up bot prefix",
options=[
Option("prefix", "Specify prefix", OptionType.string, required=True),
]
)
@commands.has_permissions(administrator=True)
async def slash_set_prefix(self, inter, prefix: str):
await write_json(inter.guild.id, "prefix", prefix)
await inter.response.send_message(f"Prefix set to: `{prefix}`", ephemeral=True)
@commands.guild_only()
@commands.slash_command(
name="set_trigger_role",
description="Setting up role to trigger bot",
options=[
Option("role", "Specify role", OptionType.role, required=True),
]
)
@commands.has_permissions(administrator=True)
async def set_trigger_role(self, inter, role):
await write_json(inter.guild.id, "tigger_role", role.id)
await inter.response.send_message(f"Role to trigger set to : `{role.name}`", ephemeral=True)
@commands.slash_command(
name="set_bot_role",
description="Set Default bot role",
options=[
Option("role", "Specify role", OptionType.role, required=True),
]
)
@commands.guild_only()
@commands.has_permissions(administrator=True)
async def set_bot_role(self, ctx, role):
await write_json(ctx.guild.id, "bot_role", role.id)
await ctx.send(f"Set up bot role to: `{role.name}`", ephemeral=True)
@set_bot_role.error
@set_trigger_role.error
@slash_set_prefix.error
async def set_prefix_error(self, inter, prefix):
await inter.response.send_message("You don`t have permissions", ephemeral=True)
logger.error(prefix)
@commands.has_permissions(administrator=True)
@commands.slash_command(
name="set_time",
description="Read list of tracks for user",
options=[
Option("seconds", "specify max duration", OptionType.integer, required=True),
]
)
async def set_time(self,
inter: disnake.ApplicationCommandInteraction,
seconds: commands.Range[int, 5, 30]):
await write_json(inter.guild.id, "seconds", seconds)
await inter.response.send_message(f"Change max audio duration to {seconds} sec", ephemeral=True)
@commands.has_permissions(administrator=True)
@commands.slash_command(
name="set_bot_channel",
description="Set channel which iterate with bot",
)
async def set_bot_channel(self, inter, channel: str):
await write_json(inter.guild.id,
"channel",
disnake.utils.find(lambda d: d.name == channel, inter.guild.channels).id)
await inter.response.send_message(f"Channel set up to {channel}", ephemeral=True)
@set_bot_channel.autocomplete('channel')
async def _list_text_channels(self,
inter: disnake.ApplicationCommandInteraction,
current: str) -> List[OptionChoice]:
_list = [r.name for r in inter.guild.text_channels]
return [
OptionChoice(name=choice, value=choice)
for choice in _list if current in choice
]
def setup(bot): # an extension must have a setup function
bot.add_cog(Admin(bot)) # adding a cog

View File

@@ -1,109 +1,83 @@
import random
from os import path, makedirs, rename, remove
from disnake.ext import commands
from lib import logger
from lib import determine_time
from lib import read_db, check_exist_audio, add_audio
from lib import play_audio
# todo: write chose audio from list by slash command
class Audio(commands.Cog, name='Audio'):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
logger.info(f'Cog {__name__.split(".")[1]} is ready!.')
# todo: complete check activity
@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
if before.channel is None and not member.bot:
if any('Escape from Tarkov' in str(user.activity) for user in after.channel.members):
logger.info('Skip playing by Game')
else:
# Prepare list of audio
from lib.Comands import read_json
_role = await read_json(member.guild.id, 'tigger_role')
# Read audio from DB
audio_db = await read_db(member.guild.id, member.id, 'usertracks')
def_audio_db = await read_db(member.guild.id, member.id, 'defaulttracks')
if audio_db is not None:
audio_db = audio_db.split(', ') # Need to fix creating list
for i in range(len(audio_db)):
audio_db[i] = f'{member.id}/{audio_db[i]}'
if def_audio_db is not None:
def_audio_db = def_audio_db.split(', ')
from lib.Comands import list_files
def_audio_ls = await list_files()
if def_audio_db or audio_db is not None:
if not def_audio_db: def_audio_db = []
if not audio_db: audio_db = []
logger.info(f'Play audio from DB')
full_audio = def_audio_db + audio_db
await play_audio(f'audio/{random.choice(full_audio)}', self.bot, after.channel)
elif len(member.roles) == 1 or _role is None:
logger.info(f'Skip playing by role')
elif any(str(role.id) in _role for role in member.roles):
logger.info(f'Play audio from list by role')
await play_audio(f'audio/{random.choice(def_audio_ls)}', self.bot, after.channel)
else:
logger.info(f'Skip playing by any else')
@commands.command(name="upload_audio",
description=f"Add audio to bot")
async def upload_audio(self, ctx, user=None):
user = user or ctx.author
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:
pass
if not path.isdir(f'audio/{user.id}'):
try:
makedirs(f'audio/{user.id}')
except error as _error:
pass
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}')
if guess[0].split('/')[0] == 'audio':
from pymediainfo import MediaInfo
file = f'tmp/{user.id}/{at.filename}'
duration = round(MediaInfo.parse(file).tracks[0].duration / 1000)
max_duration = int(determine_time(ctx))
print(type(max_duration))
if duration > max_duration:
await ctx.reply(f'Audio duration is {duration}, but max is {max_duration}')
remove(f'tmp/{user.id}/{at.filename}')
else:
a = await read_db(ctx.guild.id, user.id, 'usertracks')
if a:
audiolist = a + ", " + f'{at.filename}'
else:
audiolist = f'{at.filename}'
await check_exist_audio(ctx, ctx.guild.id, user.id, 'usertracks', at.filename)
await add_audio(ctx.guild.id, user.id, audiolist)
rename(f'tmp/{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}')
else:
await ctx.reply("Has no Attachment")
else:
await ctx.reply(f'You`re not admin. You can add audio only for your own account')
def setup(bot): # an extension must have a setup function
bot.add_cog(Audio(bot)) # adding a cog
import random
from itertools import islice
from typing import List
import disnake
from disnake import OptionChoice, Option, OptionType
from disnake.ext import commands
from lib import logger, ListGenerator
from lib import read_db
from lib import play_audio
# todo: write chose audio from list by slash command
class Audio(commands.Cog, name='Audio'):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
logger.info(f'Cog {__name__.split(".")[1]} is ready!.')
# todo: complete check activity
@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
if before.channel is None and not member.bot:
if any('Escape from Tarkov' in str(user.activity) for user in after.channel.members):
logger.info('Skip playing by Game')
else:
# Prepare list of audio
from lib.Comands import read_json
_role = await read_json(member.guild.id, 'tigger_role')
# Read audio from DB
audio_db = await read_db(member.guild.id, member.id, 'defaulttracks')
if audio_db is not None:
audio = audio_db.split(', ')
else:
from lib.Comands import list_files
audio = await list_files()
if audio_db is not None:
logger.info(f'Play audio from DB')
await play_audio(f'audio/{random.choice(audio)}', self.bot, after.channel)
elif len(member.roles) == 1 or _role is None:
logger.info(f'Skip playing by role')
elif any(str(role.id) in _role for role in member.roles):
logger.info(f'Play audio from list by role')
await play_audio(f'audio/{random.choice(audio)}', self.bot, after.channel)
else:
logger.info(f'Skip playing by any else')
@commands.slash_command(name="play_audio",
description="Make possible playing audio by command",
options=[
Option(name="audio",
type=OptionType.string,
required=True
)
])
async def playaudio(self, inter: disnake.ApplicationCommandInteraction,
audio: str
):
if inter.author.voice is not None:
await inter.response.send_message(f'Played {audio}', ephemeral=True)
await play_audio(audio, self.bot, inter.author.voice.channel)
else:
await inter.response.send_message('You`re not in voice', ephemeral=True)
@playaudio.autocomplete('audio')
async def list_to_play(self, inter: disnake.ApplicationCommandInteraction, current: str):
current = current.lower()
_dict: dict = {}
for f in ListGenerator('audio'):
_dict[f.name] = f'{f.path}/{f.name}'
return [
OptionChoice(name=choice, value=f'{_dict[choice]}')
for choice in _dict if current in choice.lower()
]
def setup(bot): # an extension must have a setup function
bot.add_cog(Audio(bot)) # adding a cog

View File

@@ -1,15 +1,15 @@
from disnake.ext import commands
from lib import logger
class Fun(commands.Cog, name='Fun'):
def __init__(self, bot):
self.bot = bot # defining bot as global var in class
@commands.Cog.listener() # this is a decorator for events/listeners
async def on_ready(self):
logger.info(f'Cog {__name__.split(".")[1]} is ready!.')
def setup(bot): # an extension must have a setup function
bot.add_cog(Fun(bot)) # adding a cog
from disnake.ext import commands
from lib import logger
class Fun(commands.Cog, name='Fun'):
def __init__(self, bot):
self.bot = bot # defining bot as global var in class
@commands.Cog.listener() # this is a decorator for events/listeners
async def on_ready(self):
logger.info(f'Cog {__name__.split(".")[1]} is ready!.')
def setup(bot): # an extension must have a setup function
bot.add_cog(Fun(bot)) # adding a cog

33
cogs/disabled/test.py Normal file
View File

@@ -0,0 +1,33 @@
from typing import List
import disnake
from disnake import OptionChoice
from disnake.ext import commands
from lib import logger
class Testing(commands.Cog, name='Testing'):
def __init__(self, bot):
self.bot = bot # defining bot as global var in class
@commands.Cog.listener() # this is a decorator for events/listeners
async def on_ready(self):
logger.info(f'Cog {__name__.split(".")[1]} is ready!.')
@commands.slash_command(
name='select_audio',
description='Select Audios from List'
)
async def select_audio(self, inter, audios: str):
pass
@select_audio.autocomplete('audios')
async def _list_audios(self,
inter: disnake.ApplicationCommandInteraction,
current: str) -> List[OptionChoice]:
pass
def setup(bot): # an extension must have a setup function
bot.add_cog(Testing(bot)) # adding a cog

View File

@@ -1,69 +1,61 @@
import disnake
from disnake import Option, OptionType, Colour
from disnake.ext import commands
from lib import DB_Reader
from lib import logger
class General(commands.Cog):
def __init__(self, bot):
self.bot = bot # defining bot as global var in class
@commands.Cog.listener() # this is a decorator for events/listeners
async def on_ready(self):
logger.info(f'Cog {__name__.split(".")[1]} is ready!.')
@commands.slash_command(
name="info",
description="Read list of tracks for user",
options=[
Option("user", "Specify any user", OptionType.user),
]
)
async def info(self, inter, user=None):
user_audio = None
default_audio = None
user = user or inter.author
_user = DB_Reader(inter.guild.id)
for r in _user:
if r.userid == user.id:
user_audio = r.usertracks
default_audio = r.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 user_audio:
audios = "" + "\n".join(sorted(user_audio.split(", ")))
else:
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}",
color=Colour.random()
)
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="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))
await inter.response.send_message(embed=emb, ephemeral=True)
def setup(bot): # an extension must have a setup function
bot.add_cog(General(bot)) # adding a cog
import disnake
from disnake import Option, OptionType, Colour
from disnake.ext import commands
from lib import DBReader
from lib import logger
class General(commands.Cog):
def __init__(self, bot):
self.bot = bot # defining bot as global var in class
@commands.Cog.listener() # this is a decorator for events/listeners
async def on_ready(self):
logger.info(f'Cog {__name__.split(".")[1]} is ready!.')
@commands.slash_command(
name="info",
description="Read list of tracks for user",
options=[
Option("user", "Specify any user", OptionType.user),
]
)
async def info(self, inter, user=None):
audio = None
user = user or inter.author
_user = DBReader(inter.guild.id)
for r in _user:
if r.userid == user.id:
audio = r.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:
audios = "" + "\n".join(sorted(audio.split(", ")))
else:
audios = "Not selected audio"
emb = disnake.Embed(
title=f"General information",
description=f"General information on server about {user}",
color=Colour.random()
)
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="Default 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(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(General(bot)) # adding a cog

View File

@@ -1,44 +1,44 @@
import os
import disnake
import psutil
from disnake.ext import commands
from __init__ import version_info as ver
from lib import determine_prefix, determine_time
from lib import logger
class BotInfo(commands.Cog, name='Bot Info'):
def __init__(self, bot):
self.bot = bot # defining bot as global var in class
@commands.Cog.listener() # this is a decorator for events/listeners
async def on_ready(self):
logger.info(f'Cog {__name__.split(".")[1]} is ready!.')
@commands.slash_command(name="info_bot",
description='Shows general info about bot') # this is for making a command
async def info_bot(self, inter):
_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.user.avatar.url)
emb.add_field(name="System info:", value=f"Memory Usage: {round(_process.memory_info().rss / 2 ** 20, 2)} Mb\n"
f"CPU Usage: {_process.cpu_percent()}%\n"
f'Bot ping: {round(self.bot.latency * 1000)}\n'
f'Prefix: `{determine_prefix(self.bot, inter)}\n`'
f"Max audio duration: {determine_time(inter)} sec\n"
)
emb.add_field(name="Bot info:", value=f"Bot owner: <@{self.bot.owner_id}>\n"
f"Bot version: {ver.major}.{ver.minor}.{ver.micro}-{ver.releaselevel}")
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(BotInfo(bot)) # adding a cog
import os
import disnake
import psutil
from disnake.ext import commands
from __init__ import version_info as ver
from lib import determine_prefix, determine_time
from lib import logger
class BotInfo(commands.Cog, name='Bot Info'):
def __init__(self, bot):
self.bot = bot # defining bot as global var in class
@commands.Cog.listener() # this is a decorator for events/listeners
async def on_ready(self):
logger.info(f'Cog {__name__.split(".")[1]} is ready!.')
@commands.slash_command(name="info_bot",
description='Shows general info about bot') # this is for making a command
async def info_bot(self, inter):
_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.user.avatar.url)
emb.add_field(name="System info:", value=f"Memory Usage: {round(_process.memory_info().rss / 2 ** 20, 2)} Mb\n"
f"CPU Usage: {_process.cpu_percent()}%\n"
f'Bot ping: {round(self.bot.latency * 1000)}\n'
f'Prefix: `{determine_prefix(self.bot, inter)}\n`'
f"Max audio duration: {determine_time(inter)} sec\n"
)
emb.add_field(name="Bot info:", value=f"Bot owner: <@386629192743256065>\n"
f"Bot version: {ver.major}.{ver.minor}.{ver.micro}-{ver.releaselevel}")
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(BotInfo(bot)) # adding a cog

View File

@@ -1,67 +0,0 @@
from typing import List
import disnake
from disnake import Option, OptionType, OptionChoice
from disnake.ext import commands
from lib import ListGenerator
from lib import logger
from lib import play_audio
class Testing(commands.Cog, name='Testing'):
def __init__(self, bot):
self.bot = bot # defining bot as global var in class
@commands.Cog.listener() # this is a decorator for events/listeners
async def on_ready(self):
logger.info(f'Cog {__name__.split(".")[1]} is ready!.')
@commands.slash_command(name="play_audio",
description="Make possible playing audio by command",
options=[
Option(name="audio",
type=OptionType.string,
required=True
)
])
async def playaudio(self, inter: disnake.ApplicationCommandInteraction,
audio: str
):
if inter.author.voice is not None:
await inter.response.send_message(f'Played {audio}', ephemeral=True)
await play_audio(audio, self.bot, inter.author.voice.channel)
else:
await inter.response.send_message('You`re not in voice', ephemeral=True)
@playaudio.autocomplete('audio')
async def list_to_play(self, inter: disnake.ApplicationCommandInteraction, current: str) -> List[OptionChoice]:
_def_iter = ListGenerator('audio')
_def_dict: dict = {}
for f in _def_iter:
_def_dict[f.name] = f'{f.path}/{f.name}'
_user_dict: dict = {}
try:
_user_iter = ListGenerator(f'audio/{inter.author.id}')
for f in _user_iter:
_user_dict[f.name] = f'{f.path}/{f.name}'
# user_dict = []
# for _track in user_list:
except IndexError:
pass
_dict = {}
_dict.update(_def_dict)
_dict.update(_user_dict)
return [
OptionChoice(name=choice, value=f'{_dict[choice]}')
for choice in _dict if current.lower() in choice.lower()
]
def setup(bot): # an extension must have a setup function
bot.add_cog(Testing(bot)) # adding a cog