This commit is contained in:
tmddn3070 2023-12-06 19:49:31 +09:00
parent 67cca95a68
commit 6f1844f973
10 changed files with 86 additions and 23 deletions

View File

@ -21,7 +21,7 @@ class CAiart(Cog):
style2: Option(float, name="광선표현", description="그림의 광선 디테일 정도를 지정합니다. 0.8에 가까울수록 더 부드럽고 좋은 광선표현을 하지만 그림의 디테일이 떨어지거나 캐릭터일 경우 손이 제대로 생성되지 않을수 있습니다.", required=False, min_value=0,max_value=0.8, default=0), style2: Option(float, name="광선표현", description="그림의 광선 디테일 정도를 지정합니다. 0.8에 가까울수록 더 부드럽고 좋은 광선표현을 하지만 그림의 디테일이 떨어지거나 캐릭터일 경우 손이 제대로 생성되지 않을수 있습니다.", required=False, min_value=0,max_value=0.8, default=0),
afterprocess: Option(float, name="후처리정도", description="그림의 후처리 정도를 정합니다. 0.99에 가까울수록 후처리랑 강하게 합니다", required=False, min_value=0,max_value=0.99, default=0.5) afterprocess: Option(float, name="후처리정도", description="그림의 후처리 정도를 정합니다. 0.99에 가까울수록 후처리랑 강하게 합니다", required=False, min_value=0,max_value=0.99, default=0.5)
): ):
if not await database.get_guild(ctx.guild.id): return await ctx.respond(embed=ChristmasEmbed(title="❌ 에러!", description="서버가 가입되어있지 않아요! 서버를 가입해주세요!", color=Color.red()),ephemeral=True) if ctx.guild is not None and not await database.get_guild(ctx.guild.id): return await ctx.respond(embed=ChristmasEmbed(title="❌ 에러!", description="서버가 가입되어있지 않아요! 서버를 가입해주세요!", color=Color.red()),ephemeral=True)
nsfw = False nsfw = False
afterprocess = 1 - afterprocess afterprocess = 1 - afterprocess
if ctx.channel.is_nsfw(): nsfw = True if ctx.channel.is_nsfw(): nsfw = True
@ -40,7 +40,7 @@ class CAiart(Cog):
@guild_only() @guild_only()
async def _분석(self, ctx: Context, file: Option(Attachment, name="파일", description="분석할 그림을 업로드해주세요.", required=True)): async def _분석(self, ctx: Context, file: Option(Attachment, name="파일", description="분석할 그림을 업로드해주세요.", required=True)):
await ctx.defer(ephemeral=False) await ctx.defer(ephemeral=False)
if not await database.get_guild(ctx.guild.id): return await ctx.respond(embed=ChristmasEmbed(title="❌ 에러!", description="서버가 가입되어있지 않아요! 서버를 가입해주세요!", color=Color.red()),ephemeral=True) if ctx.guild is not None and not await database.get_guild(ctx.guild.id): return await ctx.respond(embed=ChristmasEmbed(title="❌ 에러!", description="서버가 가입되어있지 않아요! 서버를 가입해주세요!", color=Color.red()),ephemeral=True)
if not file.content_type.startswith("image/"): return await ctx.respond(embed=ChristmasEmbed(title="❌ 에러!", description="그림 파일만 업로드해주세요!", color=Color.red()),ephemeral=True) if not file.content_type.startswith("image/"): return await ctx.respond(embed=ChristmasEmbed(title="❌ 에러!", description="그림 파일만 업로드해주세요!", color=Color.red()),ephemeral=True)
buffer = await file.read() buffer = await file.read()
taging = Tagging(model=model) taging = Tagging(model=model)

View File

@ -2,9 +2,10 @@ from discord import ApplicationContext, DiscordException, slash_command, Color
from discord.ext.commands import Cog, cooldown, BucketType, has_permissions, guild_only, Context from discord.ext.commands import Cog, cooldown, BucketType, has_permissions, guild_only, Context
from Christmas.UI.Embed import Default_Embed, ChristmasEmbed from Christmas.UI.Embed import Default_Embed, ChristmasEmbed
from Christmas.UI.Buttons import Recommanded
from Christmas.Database import database from Christmas.Database import database
from Christmas.Module import get_gpuserver_status, Get_Backend_latency from Christmas.Module import get_gpuserver_status, Get_Backend_latency
from koreanbots import KoreanbotsRequester
class CUtil(Cog): class CUtil(Cog):
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
@ -27,13 +28,18 @@ class CUtil(Cog):
async def _info(self, ctx: Context): 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) 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) data = await get_gpuserver_status(url=None)
data2 = await Get_Backend_latency() await ctx.respond(embed=Default_Embed.BotInfo(data, bot=self.bot))
await ctx.respond(embed=Default_Embed.BotInfo(data, bot=self.bot, APIlatency=data2))
@cooldown(1, 10, BucketType.user) @cooldown(1, 10, BucketType.user)
@slash_command(name="도움말", description="도움말을 확인합니다.") @slash_command(name="도움말", description="도움말을 확인합니다.")
async def _help(self, ctx: Context): async def _help(self, ctx: Context):
await ctx.respond(embed=Default_Embed.help()) await ctx.respond(embed=Default_Embed.help())
@cooldown(1, 10, BucketType.user)
@guild_only()
@slash_command(name="추천", description="한디리의 추천링크를 표시해요! 추천 갯수는 추후 크돌이를 통해 오픈될 게임에 영향을 줘요!")
async def _recommand(self, ctx: Context):
await ctx.respond(embed=Default_Embed.recommend(), view=Recommanded(), ephemeral=True)
def setup(bot): def setup(bot):
bot.add_cog(CUtil(bot)) bot.add_cog(CUtil(bot))

View File

@ -4,12 +4,12 @@ import pendulum
import onnxruntime as rt import onnxruntime as rt
from discord import ApplicationContext, DiscordException, Game, Guild from discord import ApplicationContext, DiscordException, Game, Guild, Color
from discord.ext.commands import Cog from discord.ext.commands import Cog
from discord.ext import tasks from discord.ext import tasks
import sentry_sdk import sentry_sdk
from discord.ext.commands import CommandOnCooldown from discord.ext.commands import CommandOnCooldown, MissingPermissions
from Christmas.UI.Embed import Default_Embed, Music_Embed from Christmas.UI.Embed import Default_Embed, Music_Embed, ChristmasEmbed
from Christmas.config import ChristmasConfig from Christmas.config import ChristmasConfig
from Christmas.Database import database from Christmas.Database import database
@ -24,15 +24,20 @@ class Event(Cog):
async def on_application_command_error(self, ctx: ApplicationContext, exception: DiscordException) -> None: async def on_application_command_error(self, ctx: ApplicationContext, exception: DiscordException) -> None:
if isinstance(exception, CommandOnCooldown): if isinstance(exception, CommandOnCooldown):
await ctx.respond(Default_Embed.cooldown(exception.retry_after), ephemeral=True) await ctx.respond(Default_Embed.cooldown(exception.retry_after), ephemeral=True)
elif isinstance(exception, MissingPermissions):
need_permissions = ""
for perm in exception.missing_permissions:
need_permissions += f"{perm}, "
await ctx.respond(embed=ChristmasEmbed(title="❌ 에러!", description=f"권한이 부족해요! 필요한 권한: {need_permissions}", color=Color.red()),ephemeral=True)
else: else:
await ctx.respond(embed=ChristmasEmbed(title="❌ 에러!", description=f"알수 없는 에러가 발생했어요! 봇 소유자에게 연락해주세요.", color=Color.red()),ephemeral=True)
sentry_sdk.capture_exception(exception) sentry_sdk.capture_exception(exception)
@Cog.listener() @Cog.listener()
async def on_ready(self) -> None: async def on_ready(self) -> None:
print("Ready!") print("Ready!")
await self.bot.change_presence(activity=Game(name="크리스마스에 함께!")) await self.bot.change_presence(activity=Game(name="크리스마스에 함께!"))
# connect wavelink
@Cog.listener() @Cog.listener()
async def on_connect(self) -> None: async def on_connect(self) -> None:
await self.bot.wait_until_ready() await self.bot.wait_until_ready()

View File

@ -89,3 +89,7 @@ class database:
elif setting == "admin_run": elif setting == "admin_run":
await conn.guild.update_one({"_id": guild_id}, {"$set": {"admin_run": value}}) await conn.guild.update_one({"_id": guild_id}, {"$set": {"admin_run": value}})
async def insert_arcade_point(guild_id: int, user_id: int):
conn = await MongoDBClient().connect()
await conn.arcadepre.update_one({"_id": guild_id}, {"$inc": {"vote": 1}})
await conn.arcadepreuser.update_one({"_id": user_id}, {"$inc": {"vote": 1}})

View File

@ -137,5 +137,5 @@ async def Get_Backend_latency():
else: else:
return None return None
except Exception as e: except Exception as e:
print(e)
return None return None

View File

@ -5,6 +5,10 @@ from discord import Interaction, ButtonStyle, Embed, Color, TextChannel, Forbidd
from Christmas.UI.Embed import Mail_Embed, Arcade_Embed from Christmas.UI.Embed import Mail_Embed, Arcade_Embed
from Christmas.Database import database from Christmas.Database import database
from Christmas.SearchEngine.Snowball import Snowball from Christmas.SearchEngine.Snowball import Snowball
from Christmas.config import ChristmasConfig
from koreanbots import KoreanbotsRequester
class Mail_Confirm_Button(View): class Mail_Confirm_Button(View):
def __init__(self, editmode: bool, recive_user: Member, title: str, description: str, *args, **kwargs): def __init__(self, editmode: bool, recive_user: Member, title: str, description: str, *args, **kwargs):
self.editmode = editmode self.editmode = editmode
@ -54,3 +58,18 @@ class Arcade_Register_Agree(View):
await interaction.response.defer() await interaction.response.defer()
await interaction.edit_original_response(embed=Arcade_Embed.register_cancel(), view=None) await interaction.edit_original_response(embed=Arcade_Embed.register_cancel(), view=None)
class Recommanded(View):
def __init__(self, *args, **kwargs):
self.config = ChristmasConfig()
super().__init__(*args, **kwargs, timeout=None)
@button(label="추천완료", style=ButtonStyle.green, custom_id="arcade_recommanded")
async def finished(self, button, interaction: Interaction):
await interaction.response.defer()
data = await KoreanbotsRequester(self.config.KOREANBOT_TOKEN).get_bot_vote(int(interaction.user.id), interaction.guild.me.id)
if data["voted"] == True:
await database.insert_arcade_point(interaction.guild.id, interaction.user.id)
await interaction.edit_original_response(embed=Arcade_Embed.recommend_sucess(), view=None)
else:
await interaction.edit_original_response(embed=Arcade_Embed.recommend_failed(), view=None)

View File

@ -82,7 +82,15 @@ class Default_Embed:
return embed return embed
@staticmethod @staticmethod
def BotInfo(gpuserver: typing.Dict[str, typing.Any], bot, APIlatency) -> Embed: def recommend():
embed = ChristmasEmbed(title="🎉 크돌이를 추천해주세요!", description="크돌이를 추천해주세요!")
embed.add_field(name="안내", value="크돌이를 추천해주시면 크돌이가 더욱더 발전할 수 있어요!\n 아래의 추천링크를 통해 크돌이를 추천하였다면 ``추천완료``버튼을 눌러주세요", inline=False)
embed.add_field(name="추천 링크", value="https://koreanbots.dev/bots/974665354573930507", inline=False)
embed.set_footer()
return embed
@staticmethod
def BotInfo(gpuserver: typing.Dict[str, typing.Any], bot) -> Embed:
current_time = datetime.now() current_time = datetime.now()
uptime = current_time - start_time uptime = current_time - start_time
uptime = str(uptime).split(".")[0] uptime = str(uptime).split(".")[0]
@ -90,7 +98,7 @@ class Default_Embed:
gpuserver: [system_memory_usage,cuda_memory_usage,oom_count] gpuserver: [system_memory_usage,cuda_memory_usage,oom_count]
""" """
embed = Embed(title="**봇 정보**", description="크돌이의 정보에요!") embed = Embed(title="**봇 정보**", description="크돌이의 정보에요!")
embed.add_field(name="**봇 개요**", value=f"봇 ID: {bot.user.id}\n봇 버전: 1.1.0\n가동시간: {str(uptime)}\n개발자: RunaLab(tmddn3070,Flag_Fan,Pma,Gunu,i3l3,Non)", inline=False) embed.add_field(name="**봇 개요**", value=f"봇 ID: {bot.user.id}\n봇 버전: 1.2.0\n가동시간: {str(uptime)}\n개발자: RunaLab\n**tmddn3070**\nFlag_Fan\nPma\nGunu\ni3l2\nNon", inline=True)
orin = psutil.virtual_memory().used orin = psutil.virtual_memory().used
orin = orin / 1024 / 1024 / 1024 orin = orin / 1024 / 1024 / 1024
if gpuserver == None or gpuserver["status"] == "offline": if gpuserver == None or gpuserver["status"] == "offline":
@ -101,10 +109,11 @@ class Default_Embed:
oom_count = gpuserver["oom_count"] oom_count = gpuserver["oom_count"]
embed.add_field(name="**봇 자원**", value=f"현재 샤드 메모리 사용량: {round(orin)}GB\n\nGPU서버1 메모리 사용량: {mem_usage}GB/128GB\nGPU서버1 GPU 메모리 사용량: {cuda_memory_usage}GB/80GB\nGPU서버1 메모리 오류 횟수: {oom_count}", inline=False) embed.add_field(name="**봇 자원**", value=f"현재 샤드 메모리 사용량: {round(orin)}GB\n\nGPU서버1 메모리 사용량: {mem_usage}GB/128GB\nGPU서버1 GPU 메모리 사용량: {cuda_memory_usage}GB/80GB\nGPU서버1 메모리 오류 횟수: {oom_count}", inline=False)
embed.add_field(name="**봇 통계**", value=f"🏘️ **{len(bot.guilds)}**개의 서버에서 봇을 사용중이에요!\n🤖 **{len(bot.users)}**명의 유저와 함께하는 중이에요!", inline=False) embed.add_field(name="**봇 통계**", value=f"🏘️ **{len(bot.guilds)}**개의 서버에서 봇을 사용중이에요!\n🤖 **{len(bot.users)}**명의 유저와 함께하는 중이에요!", inline=False)
if APIlatency is None: embed.add_field(name="**봇 핑**", value=f"🏓 **디스코드 게이트웨이 핑**: {round(bot.latency * 1000)}ms")
embed.add_field(name="**봇 핑**", value=f"🏓 **디스코드 게이트웨이 핑**: {round(bot.latency * 1000)}ms\n🏓 **AI 게이트웨이 핑**: 오류", inline=False) #if APIlatency is None:
else: # embed.add_field(name="**봇 핑**", value=f"🏓 **디스코드 게이트웨이 핑**: {round(bot.latency * 1000)}ms\n🏓 **AI 게이트웨이 핑**: 오류", inline=False)
embed.add_field(name="**봇 핑**", value=f"🏓 **디스코드 게이트웨이 핑**: {round(bot.latency * 1000)}ms\n🏓 **AI 게이트웨이 핑**: {APIlatency}ms", inline=False) #else:
# embed.add_field(name="**봇 핑**", value=f"🏓 **디스코드 게이트웨이 핑**: {round(bot.latency * 1000)}ms\n🏓 **AI 게이트웨이 핑**: {APIlatency}ms", inline=False)
embed.set_footer() embed.set_footer()
return embed return embed
@ -334,3 +343,18 @@ class Arcade_Embed:
embed.add_field(name="진영", value=f"{region}", inline=False) embed.add_field(name="진영", value=f"{region}", inline=False)
embed.add_field(name="상대진영", value=f"{region}", inline=False) embed.add_field(name="상대진영", value=f"{region}", inline=False)
@staticmethod
def recommend_sucess():
embed = ChristmasEmbed(title="🎉 추천 완료!", description="크돌이를 추천해주셔서 감사해요!")
embed.add_field(name="안내", value="크돌이는 한디리에 등록되어있어요! 한디리에서 크돌이를 추천해주시면 크돌이가 더 많은 사람들에게 알려질수 있어요!", inline=False)
embed.set_footer()
return embed
@staticmethod
def recommend_failed():
embed = ChristmasEmbed(title="❌ 추천 실패!", description="크돌이를 추천했는지 확인하는데 실패했어요")
embed.add_field(name="안내", value="크돌이의 추천을 확인하는데 실패했어요! 이 현상이 지속된다면 서비스 서버에 문의해주세요!", inline=False)
embed.set_footer()
return embed

View File

@ -6,7 +6,7 @@ from typing import Any, cast
from discord import AutoShardedBot, Intents from discord import AutoShardedBot, Intents
from discord.ext import commands, tasks from discord.ext import commands, tasks
from Christmas.discord import Christmas, load_cogs, apply_uvloop from Christmas.discord import Christmas, load_cogs, apply_uvloop, inital_sentry_sdk
from Christmas.config import ChristmasConfig from Christmas.config import ChristmasConfig
from koreanbots.integrations.discord import DiscordpyKoreanbots from koreanbots.integrations.discord import DiscordpyKoreanbots
@ -20,4 +20,5 @@ if __name__ == "__main__":
DiscordpyKoreanbots(bot, config.KOREANBOT_TOKEN, run_task=True) DiscordpyKoreanbots(bot, config.KOREANBOT_TOKEN, run_task=True)
load_cogs(bot) load_cogs(bot)
apply_uvloop() apply_uvloop()
inital_sentry_sdk(config.SENTRY_DSN)
bot.run() bot.run()

View File

@ -56,3 +56,7 @@ class ChristmasConfig:
@property @property
def KOREANBOT_TOKEN(self): def KOREANBOT_TOKEN(self):
return self.json["KOREANBOT_TOKEN"] return self.json["KOREANBOT_TOKEN"]
@property
def SENTRY_DSN(self):
return self.json["SENTRY_DSN"]

View File

@ -40,7 +40,7 @@ def apply_uvloop() -> None:
uvloop.install() uvloop.install()
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
def inital_sentry_sdk() -> None: def inital_sentry_sdk(dsn: str) -> None:
logger = logging.getLogger('discord') logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w') handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
@ -51,7 +51,7 @@ def inital_sentry_sdk() -> None:
event_level=logging.ERROR event_level=logging.ERROR
) )
sentry_sdk.init( sentry_sdk.init(
dsn="https://ddb20b81432c3da07a42f0da207f9cf0@o4506343770357760.ingest.sentry.io/4506343772258304", dsn=dsn,
integrations=[sentry_logging, AsyncioIntegration()] integrations=[sentry_logging, AsyncioIntegration()]
) )
print("inital sentry_sdk") print("inital sentry_sdk")