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),
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
afterprocess = 1 - afterprocess
if ctx.channel.is_nsfw(): nsfw = True
@ -40,7 +40,7 @@ class CAiart(Cog):
@guild_only()
async def _분석(self, ctx: Context, file: Option(Attachment, name="파일", description="분석할 그림을 업로드해주세요.", required=True)):
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)
buffer = await file.read()
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 Christmas.UI.Embed import Default_Embed, ChristmasEmbed
from Christmas.UI.Buttons import Recommanded
from Christmas.Database import database
from Christmas.Module import get_gpuserver_status, Get_Backend_latency
from koreanbots import KoreanbotsRequester
class CUtil(Cog):
def __init__(self, bot):
self.bot = bot
@ -27,13 +28,18 @@ class CUtil(Cog):
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))
await ctx.respond(embed=Default_Embed.BotInfo(data, bot=self.bot))
@cooldown(1, 10, BucketType.user)
@slash_command(name="도움말", description="도움말을 확인합니다.")
async def _help(self, ctx: Context):
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):
bot.add_cog(CUtil(bot))

View File

@ -4,12 +4,12 @@ import pendulum
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 import tasks
import sentry_sdk
from discord.ext.commands import CommandOnCooldown
from Christmas.UI.Embed import Default_Embed, Music_Embed
from discord.ext.commands import CommandOnCooldown, MissingPermissions
from Christmas.UI.Embed import Default_Embed, Music_Embed, ChristmasEmbed
from Christmas.config import ChristmasConfig
from Christmas.Database import database
@ -24,15 +24,20 @@ class Event(Cog):
async def on_application_command_error(self, ctx: ApplicationContext, exception: DiscordException) -> None:
if isinstance(exception, CommandOnCooldown):
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:
await ctx.respond(embed=ChristmasEmbed(title="❌ 에러!", description=f"알수 없는 에러가 발생했어요! 봇 소유자에게 연락해주세요.", color=Color.red()),ephemeral=True)
sentry_sdk.capture_exception(exception)
@Cog.listener()
async def on_ready(self) -> None:
print("Ready!")
await self.bot.change_presence(activity=Game(name="크리스마스에 함께!"))
# connect wavelink
@Cog.listener()
async def on_connect(self) -> None:
await self.bot.wait_until_ready()

View File

@ -88,4 +88,8 @@ class database:
await conn.guild.update_one({"_id": guild_id}, {"$set": {"music": value}})
elif setting == "admin_run":
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:
return None
except Exception as e:
print(e)
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.Database import database
from Christmas.SearchEngine.Snowball import Snowball
from Christmas.config import ChristmasConfig
from koreanbots import KoreanbotsRequester
class Mail_Confirm_Button(View):
def __init__(self, editmode: bool, recive_user: Member, title: str, description: str, *args, **kwargs):
self.editmode = editmode
@ -53,4 +57,19 @@ class Arcade_Register_Agree(View):
async def disagree(self, button, interaction: Interaction):
await interaction.response.defer()
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

@ -80,9 +80,17 @@ class Default_Embed:
embed.add_field(name="**음악**", value="``/음악 재생``: 크돌이가 음악을(LOFI) 재생해요!\n``/음악 정지``: 크돌이가 음악을 정지해요!\n``/음악 설정 (설정이름) (값)``: 음악 설정을 변경해요!", inline=False)
embed.set_footer()
return embed
@staticmethod
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, APIlatency) -> Embed:
def BotInfo(gpuserver: typing.Dict[str, typing.Any], bot) -> Embed:
current_time = datetime.now()
uptime = current_time - start_time
uptime = str(uptime).split(".")[0]
@ -90,7 +98,7 @@ class Default_Embed:
gpuserver: [system_memory_usage,cuda_memory_usage,oom_count]
"""
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 = orin / 1024 / 1024 / 1024
if gpuserver == None or gpuserver["status"] == "offline":
@ -101,10 +109,11 @@ class Default_Embed:
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"🏘️ **{len(bot.guilds)}**개의 서버에서 봇을 사용중이에요!\n🤖 **{len(bot.users)}**명의 유저와 함께하는 중이에요!", inline=False)
if APIlatency is None:
embed.add_field(name="**봇 핑**", value=f"🏓 **디스코드 게이트웨이 핑**: {round(bot.latency * 1000)}ms\n🏓 **AI 게이트웨이 핑**: 오류", inline=False)
else:
embed.add_field(name="**봇 핑**", value=f"🏓 **디스코드 게이트웨이 핑**: {round(bot.latency * 1000)}ms\n🏓 **AI 게이트웨이 핑**: {APIlatency}ms", inline=False)
embed.add_field(name="**봇 핑**", value=f"🏓 **디스코드 게이트웨이 핑**: {round(bot.latency * 1000)}ms")
#if APIlatency is None:
# embed.add_field(name="**봇 핑**", value=f"🏓 **디스코드 게이트웨이 핑**: {round(bot.latency * 1000)}ms\n🏓 **AI 게이트웨이 핑**: 오류", inline=False)
#else:
# embed.add_field(name="**봇 핑**", value=f"🏓 **디스코드 게이트웨이 핑**: {round(bot.latency * 1000)}ms\n🏓 **AI 게이트웨이 핑**: {APIlatency}ms", inline=False)
embed.set_footer()
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)
@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.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 koreanbots.integrations.discord import DiscordpyKoreanbots
@ -20,4 +20,5 @@ if __name__ == "__main__":
DiscordpyKoreanbots(bot, config.KOREANBOT_TOKEN, run_task=True)
load_cogs(bot)
apply_uvloop()
inital_sentry_sdk(config.SENTRY_DSN)
bot.run()

View File

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