From 369fe4829c2cff41ab28b79d1d73c1f2d1eb6ad7 Mon Sep 17 00:00:00 2001 From: tmddn3070 Date: Sat, 2 Dec 2023 19:42:36 +0900 Subject: [PATCH] Add dependencies and update code --- Christmas/Cogs/Commands_Arcade.py | 33 +++++++++++++ Christmas/Cogs/Commands_Music.py | 74 +++++++++++++++-------------- Christmas/Cogs/Commands_Util.py | 6 ++- Christmas/Cogs/Event.py | 16 +++++-- Christmas/Database/__init__.py | 15 +++++- Christmas/UI/Buttons.py | 23 ++++++++- Christmas/UI/Embed.py | 77 ++++++++++++++++++++++++++++--- Christmas/config.py | 9 +++- Dockerfile | 2 + Scheduler.py | 0 requirement.txt | 3 +- 11 files changed, 205 insertions(+), 53 deletions(-) create mode 100644 Christmas/Cogs/Commands_Arcade.py create mode 100644 Scheduler.py diff --git a/Christmas/Cogs/Commands_Arcade.py b/Christmas/Cogs/Commands_Arcade.py new file mode 100644 index 0000000..9bdd9ce --- /dev/null +++ b/Christmas/Cogs/Commands_Arcade.py @@ -0,0 +1,33 @@ +import io +from discord import SlashCommandGroup, Option, Member, Color, File, Attachment +from discord.ext.commands import Cog, BucketType, cooldown, guild_only, Context, has_permissions +from Christmas.Database import database +from Christmas.UI.Embed import ChristmasEmbed, Arcade_Embed, Default_Embed +from Christmas.UI.Buttons import Arcade_Register_Agree +from Christmas.Cogs.Event import model +class CArcade(Cog): + def __init__(self, bot): + self.bot = bot + + ARCADE = SlashCommandGroup(name="눈싸움", description="눈싸움 관련 명령어") + + @cooldown(1, 5, BucketType.user) + @has_permissions(administrator=True) + @guild_only() + @ARCADE.command(name="등록", description="눈싸움 등록") + async def _등록(self, ctx: Context): + if not await database.get_guild(ctx.guild.id): return await ctx.respond(embed=ChristmasEmbed(title="❌ 에러!", description="서버가 가입되어있지 않아요! 서버를 가입해주세요!", color=Color.red()),ephemeral=True) + #if await database.get_arcade(ctx.guild.id): return await ctx.respond(embed=Arcade_Embed.register_already(), ephemeral=True) + await ctx.respond(embed=Arcade_Embed.register_inital(), view=Arcade_Register_Agree(), ephemeral=True) + + @guild_only() + @cooldown(1, 10, BucketType.user) + @ARCADE.command(name="정보", description="눈싸움 정보") + async def _정보(self, ctx: Context): + if not await database.get_guild(ctx.guild.id): return await ctx.respond(embed=ChristmasEmbed(title="❌ 에러!", description="서버가 가입되어있지 않아요! 서버를 가입해주세요!", color=Color.red()),ephemeral=True) + if await database.get_arcade(ctx.guild.id): return await ctx.respond(embed=Arcade_Embed.register_already(), ephemeral=True) + pass + + +def setup(bot): + bot.add_cog(CArcade(bot)) \ No newline at end of file diff --git a/Christmas/Cogs/Commands_Music.py b/Christmas/Cogs/Commands_Music.py index 370e37f..e685ed3 100644 --- a/Christmas/Cogs/Commands_Music.py +++ b/Christmas/Cogs/Commands_Music.py @@ -1,54 +1,58 @@ from discord.utils import basic_autocomplete -from discord import Member, SlashCommandGroup, Option, AutocompleteContext +from discord import Member, SlashCommandGroup, Option, AutocompleteContext, Color from discord.ext.commands import Cog, cooldown, BucketType, command, has_permissions, bot_has_permissions, Context, guild_only, bot_has_guild_permissions, check import wavelink - +import random from Christmas.Database import database -from Christmas.UI.Embed import Music_Embed -async def search_music(ctx: AutocompleteContext): - try: - query_result = await wavelink.Playable.search(str(ctx.value), source=wavelink.TrackSource.YouTube) - data = [] - for query in query_result: - if query is None: continue - if len(query.title) > 50: title = query.title[:50]+"..." - else: title = query.title - data.append(title) - return data - except Exception as e: - print(e) - return ["검색에 실패했어요!"] +from Christmas.UI.Embed import Music_Embed, ChristmasEmbed +from Christmas.config import ChristmasConfig class CMusic(Cog): def __init__(self, bot): self.bot = bot + self.config = ChristmasConfig() MUSIC = SlashCommandGroup(name="음악", description="음악을 재생합니다.") # - @MUSIC.command(name="재생", description="음악을 재생합니다.") + @MUSIC.command(name="재생", description="LOFI 음악을 재생합니다.") @cooldown(1, 10, BucketType.user) @guild_only() - async def _play(self, ctx: Context, search: Option(str, name="검색", description="검색할 음악을 입력해주세요.", required=True, autocomplete=basic_autocomplete(search_music))): - if not database.get_guild(ctx.guild.id)["music"] == True: return await ctx.respond(embed=Music_Embed.music_notenable(), ephemeral=True) + async def _play(self, ctx: Context): + if not await database.get_guild(ctx.guild.id): return await ctx.respond(embed=ChristmasEmbed(title="❌ 에러!", description="서버가 가입되어있지 않아요! 서버를 가입해주세요!", color=Color.red()),ephemeral=True) + await ctx.defer(ephemeral=True) + get_guild = await database.get_guild(ctx.guild.id) + if not get_guild["music"] == True: return await ctx.respond(embed=Music_Embed.music_notenable(), ephemeral=True) if ctx.author.voice == None or ctx.author.voice.channel == None: return await ctx.respond(embed=Music_Embed.author_not_voice(), ephemeral=True) player = None - if ctx.guild.me.voice == None or ctx.guild.me.voice.channel == None: + node = wavelink.Pool.get_node() + if node.get_player(ctx.guild.id) == None: player = await ctx.author.voice.channel.connect(cls=wavelink.Player) - elif ctx.author.voice.channel != ctx.guild.me.voice.channel: - await ctx.guild.me.voice.channel.move(ctx.author.voice.channel) - player = await ctx.guild.me.voice.channel.connect(cls=wavelink.Player) - else: - player = wavelink.Node.get_player(ctx.guild.id) - #try: - # query_result = await wavelink.Playable.search(str(search), source=wavelink.TrackSource.YouTube) - # if query_result == None: return await ctx.respond(embed=Music_Embed.music_notfound(), ephemeral=True) - # if player.is_playing: - # await wavelink.Queue.put_wait(query_result[0]) - # await ctx.respond(embed=Music_Embed.music_queue(query_result[0].title), ephemeral=True) - # else: - # - # await player.play(query_result[0]) - # await ctx.respond(embed=Music_Embed.music_play(query_result[0].title), ephemeral=True) + else: + player = node.get_player(ctx.guild.id) + try: + query = await wavelink.Playable.search(random.choice(self.config.LOFI()), source=wavelink.TrackSource.YouTube) + await player.play(query[0]) + await ctx.respond(embed=Music_Embed.music_play()) + except Exception as e: + print(e) + + + @MUSIC.command(name="정지", description="음악을 정지합니다.") + @cooldown(1, 10, BucketType.user) + @guild_only() + async def _stop(self, ctx: Context): + if not await database.get_guild(ctx.guild.id): return await ctx.respond(embed=ChristmasEmbed(title="❌ 에러!", description="서버가 가입되어있지 않아요! 서버를 가입해주세요!", color=Color.red()),ephemeral=True) + await ctx.defer(ephemeral=True) + get_guild = await database.get_guild(ctx.guild.id) + if not get_guild["music"] == True: return await ctx.respond(embed=Music_Embed.music_notenable(), ephemeral=True) + if ctx.author.voice == None or ctx.author.voice.channel == None: return await ctx.respond(embed=Music_Embed.author_not_voice(), ephemeral=True) + node = wavelink.Pool.get_node() + player = node.get_player(ctx.guild.id) + if player == None: return await ctx.respond(embed=Music_Embed.music_not_playing(), ephemeral=True) + await player.stop() + await ctx.me.voice.disconnect() + await ctx.respond(embed=Music_Embed.music_stop()) + def setup(bot): bot.add_cog(CMusic(bot)) \ No newline at end of file diff --git a/Christmas/Cogs/Commands_Util.py b/Christmas/Cogs/Commands_Util.py index 07b8b3d..596cc2c 100644 --- a/Christmas/Cogs/Commands_Util.py +++ b/Christmas/Cogs/Commands_Util.py @@ -1,7 +1,7 @@ -from discord import ApplicationContext, DiscordException, slash_command +from discord import ApplicationContext, DiscordException, slash_command, Color from discord.ext.commands import Cog, cooldown, BucketType, has_permissions, guild_only, Context -from Christmas.UI.Embed import Default_Embed +from Christmas.UI.Embed import Default_Embed, ChristmasEmbed from Christmas.Database import database from Christmas.Module import get_gpuserver_status, Get_Backend_latency @@ -25,8 +25,10 @@ class CUtil(Cog): @cooldown(1, 10, BucketType.user) @slash_command(name="봇정보", description="봇의 정보를 확인합니다.") async def _info(self, ctx: Context): + if not await database.get_guild(ctx.guild.id): return await ctx.respond(embed=ChristmasEmbed(title="❌ 에러!", description="서버가 가입되어있지 않아요! 서버를 가입해주세요!", color=Color.red()),ephemeral=True) data = await get_gpuserver_status(url=None) data2 = await Get_Backend_latency() await ctx.respond(embed=Default_Embed.BotInfo(data, bot=self.bot, APIlatency=data2)) + def setup(bot): bot.add_cog(CUtil(bot)) \ No newline at end of file diff --git a/Christmas/Cogs/Event.py b/Christmas/Cogs/Event.py index bcca61c..aa59585 100644 --- a/Christmas/Cogs/Event.py +++ b/Christmas/Cogs/Event.py @@ -9,6 +9,7 @@ from discord.ext.commands import Cog from discord.ext.commands import CommandOnCooldown from Christmas.UI.Embed import Default_Embed from Christmas.config import ChristmasConfig +from Christmas.Database import database model = rt.InferenceSession("Christmas/Tagging/model.onnx", provider_options="CPUExecutionProvider") @@ -21,14 +22,13 @@ class Event(Cog): async def on_application_command_error(self, ctx: ApplicationContext, exception: DiscordException) -> None: if isinstance(exception, CommandOnCooldown): await ctx.respond(embed=Default_Embed.cooldown(exception.retry_after), ephemeral=True) - + else: + print(exception) @Cog.listener() async def on_ready(self) -> None: print("Ready!") await self.bot.change_presence(activity=Game(name="크리스마스에 함께!")) - global model - model = rt.InferenceSession("Christmas/Tagging/model.onnx", provider_options="CPUExecutionProvider") - print("Model Loaded!") + # connect wavelink @Cog.listener() @@ -46,6 +46,14 @@ class Event(Cog): else: await random.choice(guild.text_channels).send(embed=Default_Embed.guild_join()) + @Cog.listener() + async def on_guild_update(self, before: Guild, after: Guild) -> None: + if before.name != after.name: + await database.update_guild_name(after.id, after.name) + + #@Cog.listener() + #async def on_wavelink_track_end(self, payload): + #@Cog.listener() #async def on_wavelink_node_ready(self, node: wavelink.Node): # print(f"Node {node.id} is ready!") diff --git a/Christmas/Database/__init__.py b/Christmas/Database/__init__.py index 343e843..e493c68 100644 --- a/Christmas/Database/__init__.py +++ b/Christmas/Database/__init__.py @@ -68,4 +68,17 @@ class database: for mail in data["mails"]: if mail["userid"] == two_user_id: return True - \ No newline at end of file + + + async def register_arcade(guild_id: int, guild_name: str, region): + conn = await MongoDBClient().connect() + await conn.arcade.insert_one({"_id": guild_id, "guild_name": guild_name, "region": region, "normal_snowball": 10000}) + + async def update_guild_name(guild_id: int, guild_name: str): + conn = await MongoDBClient().connect() + await conn.arcade.update_one({"_id": guild_id}, {"$set": {"guild_name": guild_name}}) + + async def get_arcade(guild_id: int): + conn = await MongoDBClient().connect() + return await conn.arcade.find_one({"_id": guild_id}) + \ No newline at end of file diff --git a/Christmas/UI/Buttons.py b/Christmas/UI/Buttons.py index 32797e4..b57f241 100644 --- a/Christmas/UI/Buttons.py +++ b/Christmas/UI/Buttons.py @@ -1,9 +1,9 @@ +import random from discord.ui import View, button from discord import Interaction, ButtonStyle, Embed, Color, TextChannel, Forbidden, Message, Member, User, File, HTTPException -from Christmas.UI.Embed import Mail_Embed +from Christmas.UI.Embed import Mail_Embed, Arcade_Embed from Christmas.Database import database - class Mail_Confirm_Button(View): def __init__(self, editmode: bool, recive_user: Member, title: str, description: str, *args, **kwargs): self.editmode = editmode @@ -30,4 +30,23 @@ class Mail_Confirm_Button(View): async def cancel(self, button, interaction: Interaction): await interaction.response.defer() await interaction.edit_original_response(embed=Embed(title="✅ 전송취소!", description="편지 전송을 취소했어요!"), view=None) + +class Arcade_Register_Agree(View): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs, timeout=None) + + @button(label="동의", style=ButtonStyle.green, custom_id="arcade_register_agree") + async def agree(self, button, interaction: Interaction): + await interaction.response.defer() + try: + await database.register_arcade(interaction.guild.id, interaction.guild.name, random.choice(["south", "north"])) + except Exception as e: + await interaction.edit_original_response(embed=Arcade_Embed.register_failed(), view=None) + return + await interaction.edit_original_response(embed=Arcade_Embed.register_sucessfull(), view=None) + + @button(label="거절", style=ButtonStyle.red, custom_id="arcade_register_disagree") + async def disagree(self, button, interaction: Interaction): + await interaction.response.defer() + await interaction.edit_original_response(embed=Arcade_Embed.register_cancel(), view=None) \ No newline at end of file diff --git a/Christmas/UI/Embed.py b/Christmas/UI/Embed.py index 3145881..d0b3eac 100644 --- a/Christmas/UI/Embed.py +++ b/Christmas/UI/Embed.py @@ -2,7 +2,7 @@ import wavelink import typing import psutil from typing import Any, Optional -from discord import Embed, Colour, Embed, Member +from discord import Embed, Colour, Embed, Member, Guild from discord.types.embed import EmbedType from datetime import datetime from korcen import korcen @@ -237,9 +237,72 @@ class Music_Embed: embed.set_footer() return embed - #@staticmethod - #def music_queue(music: wavelink.Playable): - #음악을 queue에 넣음 - #embed = ChristmasEmbed(title="✅ 음악 재생 성공!", description="음악 재생에 성공했어요!") - - #embed = \ No newline at end of file + @staticmethod + def music_play(): + embed = ChristmasEmbed(title="✅ 재생 시작!", description="LOFI 재생을 시작했어요!") + embed.set_footer() + return embed + + @staticmethod + def music_stop(): + embed = ChristmasEmbed(title="✅ 재생 정지!", description="LOFI 재생을 정지했어요!") + embed.set_footer() + return embed + + @staticmethod + def changed_christmas(): + embed = ChristmasEmbed(title="✅ 크리스마스 모드 변경!", description="크리스마스 모드를 변경했어요! 이 시간부터 25일 11시 59분까지 크리스마스 모드가 적용되요!") + embed.set_footer() + return embed + +class Arcade_Embed: + + + @staticmethod + def register_inital(): + embed = ChristmasEmbed(title="🎉 눈싸움 등록!", description="눈싸움 등록을 시작해요!") + embed.add_field(name="안내", value="크돌이의 눈싸움은 서버대 서버로 경쟁하며 그 안의 유저들이 서로 협동하여 이뤄지는 게임이에요!\n1.눈싸움은 매일 항상 열려있어요! \n2.눈싸움은 시즌당 1달로 구성되있어요!\n3.시즌은 1주일 간격으로 준비-싸움-준비-싸움으로 구성되있어요!\n4.이 과정에서 절대로 봇을 이용한 싸움은 허락되지 않아요!\n5.눈싸움의 규정을 위반할경우 통보없이 눈싸움에서 제외될수 있어요!", inline=False) + embed.add_field(name="약관", value="다음의 약관을 읽고 동의한다면 `동의`버튼을 눌러주세요.", inline=False) + embed.set_footer() + return embed + + + @staticmethod + def register_sucessfull(): + embed = ChristmasEmbed(title="🎉 눈싸움 등록 성공!", description="눈싸움 등록을 성공했어요!") + embed.add_field(name="안내", value="이제 이 서버에서 눈싸움을 즐겨보세요!", inline=False) + embed.add_field(name="안내", value="초기금으로 ``10000 눈덩이``가 지급되었어요!") + embed.set_footer() + return embed + + @staticmethod + def register_already(): + embed = ChristmasEmbed(title="❌ 눈싸움 등록 실패!", description="눈싸움 등록에 실패했어요!") + embed.add_field(name="안내", value="이미 서버가 눈싸움에 등록되어있어요!", inline=False) + embed.set_footer() + return embed + + @staticmethod + def register_failed(): + embed = ChristmasEmbed(title="❌ 눈싸움 등록 실패!", description="눈싸움 등록에 실패했어요!") + embed.add_field(name="안내", value="알수없는 오류로 인해 눈싸움 등록에 실패했어요! 이 현상이 지속된다면 서비스 서버에 문의해주세요!", inline=False) + embed.set_footer() + return embed + + @staticmethod + def register_cancel(): + embed = ChristmasEmbed(title="❌ 눈싸움 등록 실패!", description="눈싸움 등록에 실패했어요!") + embed.add_field(name="안내", value="눈싸움 등록을 취소했어요!", inline=False) + embed.set_footer() + return embed + + @staticmethod + def static_info(guild: Guild, region: str): + region_dict = { + "south": "남쪽", + "north": "북쪽" + } + region = region_dict[region] + embed = ChristmasEmbed(title="🎉 눈싸움 정보!", description=f"{guild.name}서버의 눈싸움 정보에요!") + embed.add_field(name="진영", value=f"{region}", inline=False) + embed.add_field(name="상대진영", value=f"{region}", inline=False) diff --git a/Christmas/config.py b/Christmas/config.py index d6bee72..1e7def1 100644 --- a/Christmas/config.py +++ b/Christmas/config.py @@ -39,4 +39,11 @@ class ChristmasConfig: @property def AI(self): - return self.json["AI_GATEWAY"] \ No newline at end of file + return self.json["AI_GATEWAY"] + + def LOFI(self): + return self.json["LOFI"] + + @property + def CHRISTMAS(self): + return self.json["CHRISTMAS"] \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index c9e5907..8b16b9d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -16,6 +16,8 @@ FROM python:3.12-alpine AS Main COPY --from=Prepare /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages COPY --from=Prepare /usr/local/bin /usr/local/bin +RUN pip install uvloop + COPY . /app WORKDIR /app diff --git a/Scheduler.py b/Scheduler.py new file mode 100644 index 0000000..e69de29 diff --git a/requirement.txt b/requirement.txt index 3dee59a..b7bdcc6 100644 --- a/requirement.txt +++ b/requirement.txt @@ -6,4 +6,5 @@ nanoid pendulum Wavelink onnxruntime -psutil \ No newline at end of file +psutil +meilisearch-python-async \ No newline at end of file