fixed start after move

This commit is contained in:
bacon
2024-03-18 02:27:01 +03:00
parent 76d1625346
commit 98e71f66e9
43 changed files with 30 additions and 27 deletions

148
src/cogs/admin.py Normal file
View File

@@ -0,0 +1,148 @@
from asyncio import sleep
import disnake
from disnake import Option, OptionType, Localized
from disnake.ext import tasks
from integral_lib.Comands import *
from integral_lib.DB_Worker import fill_bd, prepare_db, work_with_db
from integral_lib.Logger import logger
class Admin(commands.Cog, name='Admin'):
def __init__(self, bot: commands.Bot):
self.bot = bot # a defining src 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 src 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_default_role",
description=Localized("Set Default src role", key="DEF_ROLE"),
options=[
Option("role",
"Specify role",
OptionType.role,
required=True),
]
)
@commands.has_permissions(administrator=True)
async def set_guest_role(self, inter: disnake.ApplicationCommandInteraction, role):
await write_json(inter.guild.id, "guest_role", role.id)
await inter.response.send_message(f"Set up src 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 src prefix",
options=[
Option("prefix",
"Specify prefix",
OptionType.string,
required=True),
]
)
@commands.has_permissions(administrator=True)
async def slash_set_prefix(self, inter: disnake.ApplicationCommandInteraction, 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.has_permissions(administrator=True)
@commands.slash_command(
name="set_trigger_role",
description=Localized("Setting up role to trigger src", key="KEY_ROLE"),
options=[
Option("role",
Localized("Specify role", key="SETUP_ROLE"),
OptionType.role,
required=True),
]
)
async def set_trigger_role(self, inter: disnake.ApplicationCommandInteraction, role):
await write_json(inter.guild.id, "tigger_role", role.id)
await inter.response.send_message(f"Role set to: `{role.name}`", ephemeral=True)
@commands.slash_command(
name="set_bot_role",
description=Localized("Set src role", key="BOT_ROLE"),
options=[
Option("role",
Localized("Specify role", key="SETUP_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 src 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: disnake.ApplicationCommandInteraction, prefix):
await inter.response.send_message("You don`t have permissions", ephemeral=True)
logger.error(prefix)
def setup(bot): # an extension must have a setup function
bot.add_cog(Admin(bot)) # adding a cog

84
src/cogs/audio.py Normal file
View File

@@ -0,0 +1,84 @@
import random
import disnake
from disnake import OptionChoice, Option, OptionType, Member, VoiceState, ApplicationCommandInteraction
from disnake.ext import commands
from integral_lib.ListGenerator import ListGenerator
from integral_lib.Logger import logger
from integral_lib.Player import play_audio
class Audio(commands.Cog, name='Audio'):
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
logger.info(f'Cog {__name__.split(".")[1]} is ready!.')
@commands.Cog.listener()
async def on_voice_state_update(self, member: Member,
before: VoiceState,
after: VoiceState):
if before.channel is None and not member.bot:
logger.info(f'Coneccted {member.name} to {after.channel.name}')
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 src.integral_lib.Comands import read_json
_role = await read_json(member.guild.id, 'tigger_role')
audio: list = []
for _a in ListGenerator('audio'):
audio.append(_a.name)
if len(member.roles) == 1 or _role is None:
logger.info('Skip playing by role')
elif any(str(role.id) in _role for role in member.roles):
logger.info('Play audio from list by role')
await play_audio(f'audio/{random.choice(audio)}', self.bot, after.channel)
else:
logger.info('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: ApplicationCommandInteraction, current: str):
"""
Asynchronously generates a list of OptionChoices for the given audio files based on the user input.
Parameters:
- inter: disnake.ApplicationCommandInteraction - The interaction context for the command.
- current: str - The current user input to filter the audio file choices.
Returns:
- list[OptionChoice] - A list of OptionChoice objects representing the available audio file choices.
:param current:
:param inter: ApplicationCommandInteraction
"""
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

@@ -0,0 +1,43 @@
from typing import List
import disnake
from disnake import OptionChoice
from disnake.ext import commands
from integral_lib.Comands import write_json
from integral_lib.Logger import logger
class Fun(commands.Cog, name='Fun'):
def __init__(self, bot: commands.Bot):
self.bot = bot # defining src 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.has_permissions(administrator=True)
@commands.slash_command(
name="set_bot_channel",
description="Set channel which iterate with src",
)
async def set_bot_channel(self, inter: disnake.ApplicationCommandInteraction, 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(Fun(bot)) # adding a cog

29
src/cogs/disabled/test.py Normal file
View File

@@ -0,0 +1,29 @@
import disnake
from disnake import Option
from disnake.ext import commands
from integral_lib import YandexPlayer
from integral_lib.Logger import logger
class Testing(commands.Cog, name='Testing'):
def __init__(self, bot: commands.Bot):
self.bot = bot # defining src 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', description='play audio test from yandex.music', options=[
Option(name='search',
description='seach track/artist',
required=True),
])
async def play(self, inter: disnake.ApplicationCommandInteraction, search: str):
# TODO add yandex_music player with queue, playlists
result = YandexPlayer.search(search)
await inter.response.send_message(result, ephemeral=True)
def setup(bot): # an extension must have a setup function
bot.add_cog(Testing(bot)) # adding a cog

59
src/cogs/general.py Normal file
View File

@@ -0,0 +1,59 @@
import disnake
from disnake import Option, OptionType, Colour
from disnake.ext import commands
from integral_lib.Logger import logger
class General(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot # defining src 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",
options=[
Option("user",
"Specify any user",
OptionType.user),
]
)
async def info(self, inter: disnake.ApplicationCommandInteraction, user=None):
"""
Shows user info {{SLASH_INFO}}
Parameters
----------
:param inter:
:param user:
:return:
"""
user = user or inter.author
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"
emb = disnake.Embed(
title="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="Roles list", value=f"{roles}")
emb.set_footer(text=f"Information requested by: {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

44
src/cogs/info.py Normal file
View File

@@ -0,0 +1,44 @@
import os
import disnake
import psutil
from disnake import ApplicationCommandInteraction
from disnake.ext import commands
from __init__ import version_info as ver
from integral_lib.Comands import determine_prefix
from integral_lib.Logger import logger
class BotInfo(commands.Cog, name='Bot Info'):
def __init__(self, bot: commands.Bot):
self.bot = bot # defining src 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 src') # this is for making a command
async def info_bot(self, inter: ApplicationCommandInteraction):
_pid = os.getpid()
_process = psutil.Process(_pid)
emb = disnake.Embed(
title="General information",
description="General information on about src",
)
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`'
)
emb.add_field(name="Bot info:", value="Bot owner: <@386629192743256065>\n"
f"Bot version: {ver.major}.{ver.minor}.{ver.micro}-{ver.releaselevel}")
emb.set_footer(text=f"Information requested by: {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