FEAT: Inital commit
This Commit Contained Rebrand Patches
This commit is contained in:
parent
3941a13df5
commit
6693186d40
3
.gitignore
vendored
3
.gitignore
vendored
@ -6,6 +6,7 @@ __pycache__/
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
.idea
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
@ -159,5 +160,3 @@ cython_debug/
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
Christmas/config.json
|
||||
|
@ -1,82 +0,0 @@
|
||||
import io
|
||||
from discord import SlashCommandGroup, Option, Member, Color, File, Attachment
|
||||
from discord.ext.commands import Cog, BucketType, cooldown, guild_only, Context
|
||||
from Christmas.Database import database
|
||||
from Christmas.UI.Embed import ChristmasEmbed, Aiart_Embed
|
||||
from Christmas.UI.Modal import Aiart
|
||||
from Christmas.Tagging import Tagging
|
||||
from Christmas.Cogs.Event import model
|
||||
class CAiart(Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
|
||||
|
||||
ART = SlashCommandGroup("그림", "그림 기능")
|
||||
|
||||
@ART.command(name="생성", description="크돌이가 그림을 그려줍니다.")
|
||||
@cooldown(1, 10, BucketType.user)
|
||||
async def _생성(self, ctx, ress: Option(str, name="해상도",description="그림의 해상도를 입력해주세요. (기본값: 512x512)", required=False, choices=["1:1", "2:3", "7:4","3:4"], default="1:1"),
|
||||
shows: Option(str, name="보기여부",description="생성된 그림을 나를 제외한 사람한테 보여줄지 말지를 지정합니다.", choices=["보여주기","보여주지 말기"],required=False, default="보여주기"),
|
||||
style1: Option(float, name="디테일표현",description="그림의 디테일정도를 지정합니다. -1에 가까울수록 단순한 그림이 나오고 1에 가까울수록 높은 디테일을 구현 합니다.", required=False, min_value=-1,max_value=1, default=0),
|
||||
style2: Option(float, name="광선표현", description="그림의 광선 디테일 정도를 지정합니다. 0.8에 가까울수록 더 부드럽고 좋은 광선표현을 하지만 그림의 디테일이 떨어지거나 캐릭터일 경우 손이 제대로 생성되지 않을수 있습니다.", required=False, min_value=0,max_value=0.8, default=0),
|
||||
highquality: Option(str, name="고퀄리티모드", description="그림을 뽑을때 고퀄리티 모드를 사용할지 정합니다. 고퀄리티 모드는 크돌이의 추천 이후 얻는 아트포인트로 사용할수 있습니다.", required=False, choices=["사용하기", "사용하지 않기"], default="사용하지 않기")
|
||||
):
|
||||
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
|
||||
if highquality == "사용하기": afterprocess = True
|
||||
else: afterprocess = False
|
||||
if ctx.channel.is_nsfw():
|
||||
nsfw = True
|
||||
else:
|
||||
nsfw = False
|
||||
if shows == "보여주기": shows = False
|
||||
else: shows = True
|
||||
if ress == "1:1": resoultion = [512,512]
|
||||
elif ress == "2:3": resoultion = [512,768]
|
||||
elif ress == "7:4": resoultion = [896,512]
|
||||
elif ress == "3:4": resoultion = [600,800]
|
||||
await database.put_use_art(ctx.guild.id)
|
||||
if afterprocess == True:
|
||||
result = await database.use_guild_art_point(ctx.guild.id)
|
||||
if result is False: return await ctx.respond(embed=ChristmasEmbed(title="❌ 에러!", description="아트포인트가 부족해요! 아트포인트를 충전해주세요! 아트포인트는 ``/추천``명령어를 통해 충전 가능해요!", color=Color.red()),ephemeral=True)
|
||||
# allownsfw: bool, res: list, style1: float, style2: float, afterprocess: float
|
||||
modal = Aiart(title="태그를 입력해주세요",allownsfw=nsfw, res=resoultion, style1=style1, style2=style2, afterprocess=afterprocess, show=shows)
|
||||
await ctx.send_modal(modal)
|
||||
|
||||
@ART.command(name="분석", description="그림을 분석합니다.")
|
||||
@cooldown(1, 10, BucketType.user)
|
||||
@guild_only()
|
||||
async def _분석(self, ctx: Context, file: Option(Attachment, name="파일", description="분석할 그림을 업로드해주세요.", required=True)):
|
||||
await ctx.defer(ephemeral=False)
|
||||
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)
|
||||
tag = await taging.predict(buffer)
|
||||
rating = tag[2]
|
||||
tags = tag[4]
|
||||
hangul = {
|
||||
"general": "건전함",
|
||||
"sensitive": "매우조금 불건전",
|
||||
"questionable": "조금 불건전",
|
||||
"explicit": "매우 불건전"
|
||||
}
|
||||
ratings = max(rating, key=rating.get)
|
||||
rating = hangul[ratings]
|
||||
sorted_tags = sorted(tags.items(), key=lambda x: x[1], reverse=True)[:8]
|
||||
# UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
|
||||
await ctx.respond(embed=Aiart_Embed.evalate(sorted_tags, rating), ephemeral=False, file=File(fp=io.BytesIO(buffer), filename="image.png"))
|
||||
|
||||
@ART.command(name="포인트", description="아트포인트를 확인합니다.")
|
||||
@cooldown(1, 10, BucketType.user)
|
||||
@guild_only()
|
||||
async def _포인트(self, ctx: Context):
|
||||
await ctx.defer(ephemeral=False)
|
||||
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)
|
||||
point = await database.get_guild_art_point(ctx.guild.id)
|
||||
use = await database.get_use_art(ctx.guild.id)
|
||||
await ctx.respond(embed=ChristmasEmbed(title="🎨 아트포인트", description=f"현재 서버의 아트포인트는 {point}개에요!\n 이서버에서는 그림 기능을 {use}번 사용했어요! ", color=Color.green()), ephemeral=False)
|
||||
|
||||
|
||||
def setup(bot):
|
||||
bot.add_cog(CAiart(bot))
|
@ -1,57 +0,0 @@
|
||||
import pendulum
|
||||
|
||||
from discord import Member, SlashCommandGroup, Option, Color
|
||||
from discord.ext.commands import Cog, cooldown, BucketType, command, has_permissions, bot_has_permissions, Context, guild_only, bot_has_guild_permissions, check
|
||||
|
||||
from Christmas.UI.Modal import Send_Mail_Modal
|
||||
from Christmas.UI.Embed import Mail_Embed, ChristmasEmbed
|
||||
from Christmas.Database import database
|
||||
from Christmas.UI.Paginator import Mail_Paginator
|
||||
class CMail(Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
|
||||
MAIL = SlashCommandGroup(name="편지", description="편지를 보내거나 확인합니다.")
|
||||
|
||||
@MAIL.command(name="보내기", description="편지를 보냅니다.")
|
||||
@cooldown(1, 10, BucketType.user)
|
||||
@guild_only()
|
||||
async def _send(self, ctx: Context, member: Option(Member, name="보낼사람", description="편지를 받을 사람을 선택해주세요.", required=True)):
|
||||
christmas = pendulum.datetime(2023, 12, 25, 0, 0, 0)
|
||||
if pendulum.now() > christmas:
|
||||
await ctx.respond("이미 편지를 보낼수 있는 기간이 지났어요! 받은 편지가 있다면 확인해보세요!", ephemeral=True)
|
||||
return
|
||||
if ctx.author == member: return await ctx.respond(embed=ChristmasEmbed(title="❌ 에러!", description="자기 자신에게 편지를 보낼수 없어요!", color=Color.red()),ephemeral=True)
|
||||
if await database.get_mail_user(member.id, ctx.author.id):
|
||||
if await database.get_instered_mail_edited(member.id, ctx.author.id):
|
||||
await ctx.respond(embed=Mail_Embed.mail_cant_edit(), ephemeral=True)
|
||||
return
|
||||
else:
|
||||
modal = Send_Mail_Modal(reciveuser=member, editmode=True, title="편지 수정하기")
|
||||
await ctx.send_modal(modal)
|
||||
return
|
||||
else:
|
||||
modal = Send_Mail_Modal(editmode=False, reciveuser=member, title="편지 보내기")
|
||||
await ctx.send_modal(modal)
|
||||
|
||||
@MAIL.command(name="확인", description="받은 편지를 확인합니다.")
|
||||
@cooldown(1, 10, BucketType.user)
|
||||
async def _check(self, ctx: Context):
|
||||
#2023년 12월 25일 00시 00분 00초 이후부터 확인 가능
|
||||
christmas = pendulum.datetime(2023, 12, 25, 0, 0, 0)
|
||||
if pendulum.now() < christmas:
|
||||
await ctx.respond("아직 편지를 확인할수 있는 기간이 아니에요! 조금만 기다려주세요!", ephemeral=True)
|
||||
return
|
||||
mails = await database.get_mail(ctx.author.id)
|
||||
if mails == None:
|
||||
await ctx.respond(embed=Mail_Embed.mail_notfound(), ephemeral=True)
|
||||
return
|
||||
else:
|
||||
mails = mails["mails"]
|
||||
embeds = []
|
||||
for data in mails:
|
||||
embeds.append(Mail_Embed.mail_page(data))
|
||||
paginator = Mail_Paginator(embeds=embeds, senduser=ctx.author, timeout=None)
|
||||
await ctx.respond(embed=embeds[0], view=paginator, ephemeral=True)
|
||||
def setup(bot):
|
||||
bot.add_cog(CMail(bot))
|
@ -1,88 +0,0 @@
|
||||
from discord.utils import basic_autocomplete
|
||||
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
|
||||
import pendulum
|
||||
from Christmas.Database import database
|
||||
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="LOFI 음악을 재생합니다.")
|
||||
@cooldown(1, 10, BucketType.user)
|
||||
@guild_only()
|
||||
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()
|
||||
get_guild = await database.get_guild(ctx.guild.id)
|
||||
if not get_guild["music"] == True: return await ctx.respond(embed=Music_Embed.music_notenable())
|
||||
if get_guild["admin_run"] == True:
|
||||
if not ctx.author.guild_permissions.administrator: return await ctx.respond(embed=ChristmasEmbed(title="❌ 에러!", description="관리자만 사용할수 있는 명령어에요!", color=Color.red()),ephemeral=True)
|
||||
if ctx.author.voice == None or ctx.author.voice.channel == None: return await ctx.respond(embed=Music_Embed.author_not_voice())
|
||||
player = None
|
||||
node = wavelink.Pool.get_node()
|
||||
if node.get_player(ctx.guild.id) == None:
|
||||
player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
|
||||
else:
|
||||
player = node.get_player(ctx.guild.id)
|
||||
try:
|
||||
query = None
|
||||
if pendulum.now() > pendulum.datetime(2023, 12, 24, 12, 0, 0):
|
||||
query = await wavelink.Playable.search(self.config.CHRISTMAS, source=wavelink.TrackSource.YouTube)
|
||||
else:
|
||||
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()
|
||||
get_guild = await database.get_guild(ctx.guild.id)
|
||||
if not get_guild["music"] == True: return await ctx.respond(embed=Music_Embed.music_notenable())
|
||||
if get_guild["admin_run"] == True:
|
||||
if not ctx.author.guild_permissions.administrator: return await ctx.respond(embed=ChristmasEmbed(title="❌ 에러!", description="관리자만 사용할수 있는 명령어에요!", color=Color.red()),ephemeral=True)
|
||||
if ctx.author.voice == None or ctx.author.voice.channel == None: return await ctx.respond(embed=Music_Embed.author_not_voice())
|
||||
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 player.disconnect()
|
||||
await ctx.respond(embed=Music_Embed.music_stop())
|
||||
|
||||
@MUSIC.command(name="설정", description="음악 설정을 변경합니다.")
|
||||
@cooldown(1, 10, BucketType.user)
|
||||
@guild_only()
|
||||
async def _setting(self, ctx: Context, setting: Option(str, name="설정", description="설정할 항목을 선택해주세요!", choices=["음악 활성화", "관리자만 재생 가능"], required=True), value: Option(str, name="값", description="설정할 값을 선택해주세요!", choices=["켜기", "끄기"], required=True)):
|
||||
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()
|
||||
if not ctx.author.guild_permissions.administrator: return await ctx.respond(embed=ChristmasEmbed(title="❌ 에러!", description="관리자만 사용할수 있는 명령어에요!", color=Color.red()),ephemeral=True)
|
||||
if setting == "관리자만 재생 가능":
|
||||
if value == "켜기":
|
||||
await database.update_music_setting(ctx.guild.id, True, "admin_run")
|
||||
await ctx.respond(embed=Music_Embed.music_setting(True, "admin_run"), ephemeral=True)
|
||||
else:
|
||||
await database.update_music_setting(ctx.guild.id, False, "admin_run")
|
||||
await ctx.respond(embed=Music_Embed.music_setting(False, "admin_run"), ephemeral=True)
|
||||
if setting == "음악 활성화":
|
||||
if value == "켜기":
|
||||
await database.update_music_setting(ctx.guild.id, True, "music")
|
||||
await ctx.respond(embed=Music_Embed.music_setting(True, "music"), ephemeral=True)
|
||||
else:
|
||||
await database.update_music_setting(ctx.guild.id, False, "music")
|
||||
await ctx.respond(embed=Music_Embed.music_setting(False, "music"), ephemeral=True)
|
||||
def setup(bot):
|
||||
bot.add_cog(CMusic(bot))
|
@ -1,137 +0,0 @@
|
||||
from motor.motor_asyncio import AsyncIOMotorClient
|
||||
|
||||
from Christmas.config import ChristmasConfig
|
||||
|
||||
class MongoDBClient:
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.config = ChristmasConfig()
|
||||
self.client = AsyncIOMotorClient(self.config.DATABASE["HOST"], int(self.config.DATABASE["PORT"]), username=self.config.DATABASE["USERNAME"], password=self.config.DATABASE["PASSWORD"])[self.config.DATABASE["DATABASE"]]
|
||||
|
||||
async def connect(self):
|
||||
return self.client
|
||||
|
||||
class database:
|
||||
|
||||
async def get_guild(guild_id: int) -> dict:
|
||||
conn = await MongoDBClient().connect()
|
||||
return await conn.guild.find_one({"_id": guild_id})
|
||||
|
||||
async def register_guild(guild_id: int) -> None:
|
||||
conn = await MongoDBClient().connect()
|
||||
await conn.guild.insert_one({"_id": guild_id, "admin_run": False, "music": True})
|
||||
|
||||
async def leave_guild(guild_id: int) -> None:
|
||||
conn = await MongoDBClient().connect()
|
||||
await conn.guild.delete_one({"_id": guild_id})
|
||||
|
||||
async def insert_mail(send_user_id: int, user_id: int, user_name: str, mail_title: str, mail_content: str):
|
||||
try:
|
||||
conn = await MongoDBClient().connect()
|
||||
mail_title = f"""{mail_title}"""
|
||||
mail_content = f"""{mail_content}"""
|
||||
if await conn.mail.find_one({"_id": user_id}) == None:
|
||||
await conn.mail.insert_one({"_id": user_id, "mails": [{"userid": send_user_id, "username": user_name, "title": mail_title, "content": mail_content, "edited": False}]})
|
||||
else:
|
||||
result = await conn.mail.update_one({"_id": user_id}, {"$push": {"mails": {"userid": send_user_id, "username": user_name, "title": mail_title, "content": mail_content, "edited": False}}})
|
||||
print(result)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
|
||||
async def update_inserted_mail(send_user_id: int, user_id: int, mail_title: str, mail_content: str):
|
||||
try:
|
||||
conn = await MongoDBClient().connect()
|
||||
await conn.mail.update_one({"_id": user_id, "mails.userid": send_user_id}, {"$set": {"mails.$.title": mail_title, "mails.$.content": mail_content, "mails.$.edited": True}})
|
||||
return True
|
||||
except Exception as e:
|
||||
print(e)
|
||||
return None
|
||||
|
||||
async def get_instered_mail_edited(send_user_id: int, user_id: int):
|
||||
try:
|
||||
conn = await MongoDBClient().connect()
|
||||
data = await conn.mail.find_one({"_id": user_id})
|
||||
if data == None: return None
|
||||
for mail in data["mails"]:
|
||||
if mail["userid"] == send_user_id:
|
||||
return mail["edited"]
|
||||
except Exception as e:
|
||||
print(e)
|
||||
return None
|
||||
|
||||
async def get_mail(user_id: int):
|
||||
conn = await MongoDBClient().connect()
|
||||
data = await conn.mail.find_one({"_id": user_id})
|
||||
if data == None: return None
|
||||
return data
|
||||
|
||||
async def get_mail_user(one_user_id: int, two_user_id: int):
|
||||
conn = await MongoDBClient().connect()
|
||||
data = await conn.mail.find_one({"_id": one_user_id})
|
||||
if data == None: return False
|
||||
for mail in data["mails"]:
|
||||
if mail["userid"] == two_user_id:
|
||||
return True
|
||||
|
||||
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})
|
||||
|
||||
async def update_music_setting(guild_id: int, value: bool, setting: str):
|
||||
conn = await MongoDBClient().connect()
|
||||
if setting == "music":
|
||||
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()
|
||||
if await conn.arcadepre.find_one({"_id": guild_id}) == None:
|
||||
await conn.arcadepre.insert_one({"_id": guild_id, "user": [{"_id": user_id, "point": 1}], "vote": 0})
|
||||
else:
|
||||
await conn.arcadepre.update_one({"_id": guild_id}, {"$inc": {"user.$[elem].point": 1}}, array_filters=[{"elem._id": user_id}])
|
||||
|
||||
async def insert_guild_art_point(guild_id: int, amount: int):
|
||||
conn = await MongoDBClient().connect()
|
||||
if await conn.guild.find_one({"_id": guild_id}) == None:
|
||||
await conn.guild.insert_one({"_id": guild_id, "art_point": 1})
|
||||
else:
|
||||
await conn.guild.update_one({"_id": guild_id}, {"$inc": {"art_point": amount}})
|
||||
|
||||
async def use_guild_art_point(guild_id: int):
|
||||
conn = await MongoDBClient().connect()
|
||||
if await conn.guild.find_one({"_id": guild_id, "art_point": {"$gt": 0}}) == None:
|
||||
return False
|
||||
await conn.guild.update_one({"_id": guild_id}, {"$inc": {"art_point": -1}})
|
||||
return True
|
||||
|
||||
async def get_guild_art_point(guild_id: int):
|
||||
conn = await MongoDBClient().connect()
|
||||
if await conn.guild.find_one({"_id": guild_id, "art_point": {"$exists": True}}) == None:
|
||||
return 0
|
||||
else:
|
||||
result = await conn.guild.find_one({"_id": guild_id})
|
||||
return result["art_point"]
|
||||
|
||||
async def get_use_art(guild_id: int):
|
||||
conn = await MongoDBClient().connect()
|
||||
if await conn.guild.find_one({"_id": guild_id, "art": {"$exists": True}}) == None:
|
||||
return 0
|
||||
else:
|
||||
result = await conn.guild.find_one({"_id": guild_id})
|
||||
return result["art"]
|
||||
|
||||
async def put_use_art(guild_id: int):
|
||||
conn = await MongoDBClient().connect()
|
||||
if await conn.guild.find_one({"_id": guild_id, "art": {"$exists": True}}) == None:
|
||||
await conn.guild.update_one({"_id": guild_id}, {"$set": {"art": 1}})
|
||||
else:
|
||||
await conn.guild.update_one({"_id": guild_id}, {"$inc": {"art": 1}})
|
@ -1,16 +0,0 @@
|
||||
from Christmas.SearchEngine import Search
|
||||
|
||||
|
||||
|
||||
class Snowball:
|
||||
|
||||
async def register_guild(guild_id: int, guild_name: str, region: str):
|
||||
search = Search()
|
||||
index = await search.connect()
|
||||
await index.add_documents([{"guild_id": guild_id, "guild_name": guild_name, "region": region}])
|
||||
|
||||
async def query_guild(query: str):
|
||||
search = Search()
|
||||
index = await search.connect()
|
||||
result = await index.search(query)
|
||||
return result
|
@ -1,15 +0,0 @@
|
||||
from meilisearch_python_sdk import AsyncClient as Client
|
||||
from Christmas.config import ChristmasConfig
|
||||
|
||||
|
||||
class Search:
|
||||
def __init__(self):
|
||||
self.config = ChristmasConfig()
|
||||
|
||||
async def connect(self):
|
||||
self.client = Client(self.config.SEARCH_ENGINE["HOST"], self.config.SEARCH_ENGINE["KEY"])
|
||||
self.index = self.client.index(self.config.SEARCH_ENGINE["INDEX"])
|
||||
return self.index
|
||||
|
||||
async def close(self):
|
||||
await self.client.aclose()
|
@ -1,24 +0,0 @@
|
||||
import sentry_sdk
|
||||
|
||||
from types import SimpleNamespace
|
||||
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, inital_sentry_sdk
|
||||
from Christmas.config import ChristmasConfig
|
||||
from koreanbots.integrations.discord import DiscordpyKoreanbots
|
||||
|
||||
if __name__ == "__main__":
|
||||
bot = Christmas(
|
||||
command_prefix=commands.when_mentioned_or("c!"),
|
||||
case_insensitive=True,
|
||||
intents=Intents.default()
|
||||
)
|
||||
config = ChristmasConfig()
|
||||
DiscordpyKoreanbots(bot, config.KOREANBOT_TOKEN, run_task=True)
|
||||
load_cogs(bot)
|
||||
apply_uvloop()
|
||||
inital_sentry_sdk(config.SENTRY_DSN)
|
||||
bot.run()
|
@ -1,62 +0,0 @@
|
||||
import json
|
||||
|
||||
|
||||
class ChristmasConfig:
|
||||
def __init__(self):
|
||||
self.json = json.load(open("Christmas/config.json", "r"))
|
||||
|
||||
@property
|
||||
def MODE(self):
|
||||
return self.json["MODE"]
|
||||
|
||||
@property
|
||||
def TOKEN(self):
|
||||
return self.json["TOKEN"]
|
||||
|
||||
@property
|
||||
def PREFIX(self):
|
||||
return self.json["PREFIX"]
|
||||
|
||||
@property
|
||||
def OWNER(self):
|
||||
return self.json["OWNER"]
|
||||
|
||||
@property
|
||||
def LOG_CHANNEL(self):
|
||||
return self.json["LOG_CHANNEL"]
|
||||
|
||||
@property
|
||||
def OWN_GUILD(self):
|
||||
return self.json["OWN_GUILD"]
|
||||
|
||||
@property
|
||||
def DATABASE(self):
|
||||
return self.json["DATABASE"]
|
||||
|
||||
@property
|
||||
def LAVALINK(self):
|
||||
return self.json["LAVALINKS"]
|
||||
|
||||
@property
|
||||
def AI(self):
|
||||
return self.json["AI_GATEWAY"]
|
||||
|
||||
@property
|
||||
def LOFI(self):
|
||||
return self.json["LOFI"]
|
||||
|
||||
@property
|
||||
def CHRISTMAS(self):
|
||||
return self.json["CHRISTMAS"]
|
||||
|
||||
@property
|
||||
def SEARCH_ENGINE(self):
|
||||
return self.json["SEARCH_ENGINE"]
|
||||
|
||||
@property
|
||||
def KOREANBOT_TOKEN(self):
|
||||
return self.json["KOREANBOT_TOKEN"]
|
||||
|
||||
@property
|
||||
def SENTRY_DSN(self):
|
||||
return self.json["SENTRY_DSN"]
|
@ -1,57 +0,0 @@
|
||||
import os
|
||||
import sentry_sdk
|
||||
import asyncio
|
||||
import logging
|
||||
from sentry_sdk.integrations.asyncio import AsyncioIntegration
|
||||
from sentry_sdk.integrations.logging import LoggingIntegration
|
||||
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, cast
|
||||
|
||||
from discord import AutoShardedBot
|
||||
from discord.ext import commands, tasks
|
||||
|
||||
from Christmas.config import ChristmasConfig
|
||||
|
||||
class Christmas(AutoShardedBot):
|
||||
def __init__(self, *args: Any, **kwargs: Any):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.config = ChristmasConfig()
|
||||
#self.debug_guilds = [1090621667778244638,1015236495910649926,957142859629342790,1125370139165081612,1170310470503247993]
|
||||
|
||||
def run(self, *args: Any, **kwargs: Any) -> None:
|
||||
kwargs.update({"token": self.config.TOKEN})
|
||||
super().run(*args, **kwargs)
|
||||
|
||||
|
||||
def load_cogs(bot: AutoShardedBot) -> None:
|
||||
for filename in os.listdir("Christmas/Cogs"):
|
||||
if filename.endswith(".py"):
|
||||
bot.load_extension(f"Christmas.Cogs.{filename[:-3]}")
|
||||
|
||||
|
||||
def apply_uvloop() -> None:
|
||||
try:
|
||||
import uvloop
|
||||
import asyncio
|
||||
except ImportError:
|
||||
pass
|
||||
else:
|
||||
uvloop.install()
|
||||
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
|
||||
|
||||
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')
|
||||
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
|
||||
logger.addHandler(handler)
|
||||
sentry_logging = LoggingIntegration(
|
||||
level=logging.WARNING,
|
||||
event_level=logging.ERROR
|
||||
)
|
||||
sentry_sdk.init(
|
||||
dsn=dsn,
|
||||
integrations=[sentry_logging, AsyncioIntegration()]
|
||||
)
|
||||
print("inital sentry_sdk")
|
32
Dockerfile
32
Dockerfile
@ -1,14 +1,28 @@
|
||||
FROM python:3.11.5-slim
|
||||
FROM python:3.12.2-slim-bookworm
|
||||
|
||||
WORKDIR /app
|
||||
ENV PYTHONFAULTHANDLER=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
PYTHONHASHSEED=random \
|
||||
PIP_NO_CACHE_DIR=off \
|
||||
PIP_DISABLE_PIP_VERSION_CHECK=on \
|
||||
PIP_DEFAULT_TIMEOUT=100 \
|
||||
POETRY_NO_INTERACTION=1 \
|
||||
POETRY_VIRTUALENVS_CREATE=false \
|
||||
POETRY_CACHE_DIR='/var/cache/pypoetry' \
|
||||
POETRY_HOME='/usr/local' \
|
||||
POETRY_VERSION=1.7.1
|
||||
|
||||
#COPY requirements.txt .
|
||||
RUN apt-get update && apt-get install ffmpeg libsm6 libxext6 -y
|
||||
RUN pip install pandas py-cord koreanbots motor uvloop korcen nanoid pendulum Wavelink onnxruntime psutil meilisearch_python_sdk Pillow opencv-python aiogoogletrans sentry-sdk
|
||||
RUN pip uninstall -y discord.py py-cord
|
||||
RUN pip install --no-cache-dir py-cord[speed] py-cord[voice]
|
||||
RUN apt-get update && apt-get install -y curl libgl1-mesa-glx libglib2.0-0 libsm6 libxrender1 libxext6
|
||||
|
||||
RUN curl -sSL https://install.python-poetry.org | python3 -
|
||||
|
||||
RUN ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime
|
||||
COPY . .
|
||||
|
||||
CMD ["python", "-m", "Christmas"]
|
||||
WORKDIR /app
|
||||
COPY poetry.lock pyproject.toml /app/
|
||||
|
||||
RUN poetry install --no-interaction --no-ansi
|
||||
|
||||
COPY . /app
|
||||
|
||||
CMD ["python", "-m", "RUNA"]
|
97
LICENSE
97
LICENSE
@ -1,80 +1,23 @@
|
||||
Eclipse Public License - v 2.0
|
||||
THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE (“AGREEMENT”). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
|
||||
Boost Software License - Version 1.0 - August 17th, 2003
|
||||
|
||||
1. DEFINITIONS
|
||||
“Contribution” means:
|
||||
Permission is hereby granted, free of charge, to any person or organization
|
||||
obtaining a copy of the software and accompanying documentation covered by
|
||||
this license (the "Software") to use, reproduce, display, distribute,
|
||||
execute, and transmit the Software, and to prepare derivative works of the
|
||||
Software, and to permit third-parties to whom the Software is furnished to
|
||||
do so, all subject to the following:
|
||||
|
||||
a) in the case of the initial Contributor, the initial content Distributed under this Agreement, and
|
||||
b) in the case of each subsequent Contributor:
|
||||
i) changes to the Program, and
|
||||
ii) additions to the Program;
|
||||
where such changes and/or additions to the Program originate from and are Distributed by that particular Contributor. A Contribution “originates” from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include changes or additions to the Program that are not Modified Works.
|
||||
“Contributor” means any person or entity that Distributes the Program.
|
||||
The copyright notices in the Software and this entire statement, including
|
||||
the above license grant, this restriction and the following disclaimer,
|
||||
must be included in all copies of the Software, in whole or in part, and
|
||||
all derivative works of the Software, unless such copies or derivative
|
||||
works are solely in the form of machine-executable object code generated by
|
||||
a source language processor.
|
||||
|
||||
“Licensed Patents” mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.
|
||||
|
||||
“Program” means the Contributions Distributed in accordance with this Agreement.
|
||||
|
||||
“Recipient” means anyone who receives the Program under this Agreement or any Secondary License (as applicable), including Contributors.
|
||||
|
||||
“Derivative Works” shall mean any work, whether in Source Code or other form, that is based on (or derived from) the Program and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship.
|
||||
|
||||
“Modified Works” shall mean any work in Source Code or other form that results from an addition to, deletion from, or modification of the contents of the Program, including, for purposes of clarity any new file in Source Code form that contains any contents of the Program. Modified Works shall not include works that contain only declarations, interfaces, types, classes, structures, or files of the Program solely in each case in order to link to, bind by name, or subclass the Program or Modified Works thereof.
|
||||
|
||||
“Distribute” means the acts of a) distributing or b) making available in any manner that enables the transfer of a copy.
|
||||
|
||||
“Source Code” means the form of a Program preferred for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
||||
|
||||
“Secondary License” means either the GNU General Public License, Version 2.0, or any later versions of that license, including any exceptions or additional permissions as identified by the initial Contributor.
|
||||
|
||||
2. GRANT OF RIGHTS
|
||||
a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, Distribute and sublicense the Contribution of such Contributor, if any, and such Derivative Works.
|
||||
b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in Source Code or other form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
|
||||
c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to Distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program.
|
||||
d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement.
|
||||
e) Notwithstanding the terms of any Secondary License, no Contributor makes additional grants to any Recipient (other than those set forth in this Agreement) as a result of such Recipient's receipt of the Program under the terms of a Secondary License (if permitted under the terms of Section 3).
|
||||
3. REQUIREMENTS
|
||||
3.1 If a Contributor Distributes the Program in any form, then:
|
||||
|
||||
a) the Program must also be made available as Source Code, in accordance with section 3.2, and the Contributor must accompany the Program with a statement that the Source Code for the Program is available under this Agreement, and informs Recipients how to obtain it in a reasonable manner on or through a medium customarily used for software exchange; and
|
||||
b) the Contributor may Distribute the Program under a license different than this Agreement, provided that such license:
|
||||
i) effectively disclaims on behalf of all other Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
|
||||
ii) effectively excludes on behalf of all other Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;
|
||||
iii) does not attempt to limit or alter the recipients' rights in the Source Code under section 3.2; and
|
||||
iv) requires any subsequent distribution of the Program by any party to be under a license that satisfies the requirements of this section 3.
|
||||
3.2 When the Program is Distributed as Source Code:
|
||||
|
||||
a) it must be made available under this Agreement, or if the Program (i) is combined with other material in a separate file or files made available under a Secondary License, and (ii) the initial Contributor attached to the Source Code the notice described in Exhibit A of this Agreement, then the Program may be made available under the terms of such Secondary Licenses, and
|
||||
b) a copy of this Agreement must be included with each copy of the Program.
|
||||
3.3 Contributors may not remove or alter any copyright, patent, trademark, attribution notices, disclaimers of warranty, or limitations of liability (‘notices’) contained within the Program from any copy of the Program which they Distribute, provided that Contributors may add their own appropriate notices.
|
||||
|
||||
4. COMMERCIAL DISTRIBUTION
|
||||
Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor (“Commercial Contributor”) hereby agrees to defend and indemnify every other Contributor (“Indemnified Contributor”) against any losses, damages and costs (collectively “Losses”) arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.
|
||||
|
||||
For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.
|
||||
|
||||
5. NO WARRANTY
|
||||
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement, including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.
|
||||
|
||||
6. DISCLAIMER OF LIABILITY
|
||||
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
7. GENERAL
|
||||
If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
|
||||
|
||||
If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed.
|
||||
|
||||
All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.
|
||||
|
||||
Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be Distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to Distribute the Program (including its Contributions) under the new version.
|
||||
|
||||
Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. Nothing in this Agreement is intended to be enforceable by any entity that is not a Contributor or Recipient. No third-party beneficiary rights are created under this Agreement.
|
||||
|
||||
Exhibit A – Form of Secondary Licenses Notice
|
||||
“This Source Code may also be made available under the following Secondary Licenses when the conditions for such availability set forth in the Eclipse Public License, v. 2.0 are satisfied: {name license(s), version(s), and exceptions or additional permissions here}.”
|
||||
|
||||
Simply including a copy of this Agreement, including this Exhibit A is not sufficient to license the Source Code under Secondary Licenses.
|
||||
|
||||
If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice.
|
||||
|
||||
You may add additional accurate notices of copyright ownership.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
|
||||
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
|
||||
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
|
||||
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
34
README.md
34
README.md
@ -1,3 +1,33 @@
|
||||
# Ce-dol-e
|
||||
# Runa Bot
|
||||
|
||||
크리스마스 기념 봇
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## Usage
|
||||
|
||||
### Install
|
||||
```bash
|
||||
poetry install
|
||||
```
|
||||
|
||||
### Run
|
||||
```bash
|
||||
poetry run python -m RUNA
|
||||
```
|
||||
|
||||
### Docker Build
|
||||
```bash
|
||||
docker build -t runa:latest .
|
||||
```
|
||||
|
||||
### Docker Run
|
||||
|
||||
```bash
|
||||
docker run -d --name runa runa:latest --restart=unless-stopped -e TOKEN="pmababo" -e KOREANBOT_TOKEN="test" -e OWNER_GUILD="1234567890" -e MONGODB_HOST="localhost" -e MONGODB_PORT="27017" -e MONGODB_ID="runa" -e MONGODB_PASSWORD="runa" -e MONGODB_DATABSE="runa"
|
||||
```
|
||||
|
||||
## License
|
||||
[BSL-1.0](https://opensource.org/licenses/BSL-1.0)
|
||||
```
|
114
RUNA/Cogs/Commands_Aiart.py
Normal file
114
RUNA/Cogs/Commands_Aiart.py
Normal file
@ -0,0 +1,114 @@
|
||||
import io
|
||||
from discord import SlashCommandGroup, Option, Member, Color, File, Attachment
|
||||
from discord.ext.commands import Cog, BucketType, cooldown, guild_only, Context
|
||||
from RUNA.Database import database
|
||||
from RUNA.UI.Embed import RunaEmbed, Aiart_Embed
|
||||
from RUNA.UI.Modal import Aiart
|
||||
from RUNA.Tagging import Tagging
|
||||
from RUNA.Cogs.Event import model
|
||||
|
||||
|
||||
class CogAiart(Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
|
||||
ART = SlashCommandGroup("그림", "AI 그림 기능")
|
||||
|
||||
@ART.command(name="생성", description="루나가 그림을 그려줍니다.")
|
||||
@cooldown(1, 10, BucketType.user)
|
||||
async def _generate(self, ctx: Context,
|
||||
resolution: Option(str, name="해상도", description="그림의 해상도를 입력해주세요. (기본값: 512x512)",
|
||||
required=False, choices=["1:1", "2:3", "7:4", "3:4"], default="1:1"),
|
||||
shows: Option(str, name="보기여부", description="생성된 그림을 나를 제외한 사람한테 보여줄지 말지를 지정합니다.",
|
||||
choices=["보여주기", "보여주지 말기"], required=False, default="보여주기"),
|
||||
style1: Option(float, name="디테일표현",
|
||||
description="그림의 디테일정도를 지정합니다. -1에 가까울수록 단순한 그림이 나오고 1에 가까울수록 높은 디테일을 구현 합니다.",
|
||||
required=False, min_value=-1, max_value=1, default=0),
|
||||
style2: Option(float, name="광선표현",
|
||||
description="그림의 광선 디테일 정도를 지정합니다. 0.8에 가까울수록 더 부드럽고 좋은 광선표현을 하지만 그림의 디테일이 떨어지거나 캐릭터일 경우 손이 제대로 생성되지 않을수 있습니다.",
|
||||
required=False, min_value=0, max_value=0.8, default=0),
|
||||
high_quality: Option(str, name="고퀄리티모드",
|
||||
description="그림을 뽑을때 고퀄리티 모드를 사용할지 정합니다. 고퀄리티 모드는 크돌이의 추천 이후 얻는 아트포인트로 사용할수 있습니다.",
|
||||
required=False, choices=["사용하기", "사용하지 않기"], default="사용하지 않기")
|
||||
):
|
||||
if ctx.guild is not None and not await database.get_guild(ctx.guild.id): return await ctx.respond(
|
||||
embed=RunaEmbed(title="❌ 에러!", description="서버가 가입되어있지 않아요! 서버를 가입해주세요!", color=Color.red()),
|
||||
ephemeral=True)
|
||||
nsfw = False
|
||||
if high_quality == "사용하기":
|
||||
after_process = True
|
||||
else:
|
||||
after_process = False
|
||||
if ctx.channel.is_nsfw():
|
||||
nsfw = True
|
||||
else:
|
||||
nsfw = False
|
||||
if shows == "보여주기":
|
||||
shows = False
|
||||
else:
|
||||
shows = True
|
||||
if resolution == "1:1":
|
||||
resoultion = [512, 512]
|
||||
elif resolution == "2:3":
|
||||
resoultion = [512, 768]
|
||||
elif resolution == "7:4":
|
||||
resoultion = [896, 512]
|
||||
elif resolution == "3:4":
|
||||
resoultion = [600, 800]
|
||||
await database.put_use_art(ctx.guild.id)
|
||||
if after_process == True:
|
||||
result = await database.use_guild_art_point(ctx.guild.id)
|
||||
if result is False: return await ctx.respond(
|
||||
embed=RunaEmbed(title="❌ 에러!", description="아트포인트가 부족해요! 아트포인트를 충전해주세요! 아트포인트는 ``/추천``명령어를 통해 충전 가능해요!",
|
||||
color=Color.red()), ephemeral=True)
|
||||
# allownsfw: bool, res: list, style1: float, style2: float, afterprocess: float
|
||||
modal = Aiart(title="태그를 입력해주세요", allownsfw=nsfw, res=resoultion, style1=style1, style2=style2,
|
||||
afterprocess=after_process, show=shows)
|
||||
await ctx.send_modal(modal)
|
||||
|
||||
@ART.command(name="분석", description="그림을 분석합니다.")
|
||||
@cooldown(1, 10, BucketType.user)
|
||||
@guild_only()
|
||||
async def _evulate(self, ctx: Context,
|
||||
file: Option(Attachment, name="파일", description="분석할 그림을 업로드해주세요.", required=True)):
|
||||
await ctx.defer(ephemeral=False)
|
||||
if ctx.guild is not None and not await database.get_guild(ctx.guild.id): return await ctx.respond(
|
||||
embed=RunaEmbed(title="❌ 에러!", description="서버가 가입되어있지 않아요! 서버를 가입해주세요!", color=Color.red()),
|
||||
ephemeral=True)
|
||||
if not file.content_type.startswith("image/"): return await ctx.respond(
|
||||
embed=RunaEmbed(title="❌ 에러!", description="그림 파일만 업로드해주세요!", color=Color.red()), ephemeral=True)
|
||||
buffer = await file.read()
|
||||
taging = Tagging()
|
||||
tag = await taging.predict(buffer)
|
||||
rating = tag[2]
|
||||
tags = tag[4]
|
||||
hangul = {
|
||||
"general": "건전함",
|
||||
"sensitive": "매우조금 불건전",
|
||||
"questionable": "조금 불건전",
|
||||
"explicit": "매우 불건전"
|
||||
}
|
||||
ratings = max(rating, key=rating.get)
|
||||
rating = hangul[ratings]
|
||||
sorted_tags = sorted(tags.items(), key=lambda x: x[1], reverse=True)[:8]
|
||||
# UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
|
||||
await ctx.respond(embed=Aiart_Embed.evalate(sorted_tags, rating), ephemeral=False,
|
||||
file=File(fp=io.BytesIO(buffer), filename="image.png"))
|
||||
|
||||
@ART.command(name="포인트", description="아트포인트를 확인합니다.")
|
||||
@cooldown(1, 10, BucketType.user)
|
||||
@guild_only()
|
||||
async def _point(self, ctx: Context):
|
||||
await ctx.defer(ephemeral=False)
|
||||
if ctx.guild is not None and not await database.get_guild(ctx.guild.id): return await ctx.respond(
|
||||
embed=RunaEmbed(title="❌ 에러!", description="서버가 가입되어있지 않아요! 서버를 가입해주세요!", color=Color.red()),
|
||||
ephemeral=True)
|
||||
point = await database.get_guild_art_point(ctx.guild.id)
|
||||
use = await database.get_use_art(ctx.guild.id)
|
||||
await ctx.respond(
|
||||
embed=RunaEmbed(title="🎨 아트포인트", description=f"현재 서버의 아트포인트는 {point}개에요!\n 이서버에서는 그림 기능을 {use}번 사용했어요! ",
|
||||
color=Color.green()), ephemeral=False)
|
||||
|
||||
|
||||
def setup(bot):
|
||||
bot.add_cog(CogAiart(bot))
|
@ -1,55 +1,60 @@
|
||||
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
|
||||
|
||||
@guild_only()
|
||||
@has_permissions(administrator=True)
|
||||
@cooldown(1, 10, BucketType.user)
|
||||
@slash_command(name="서버가입", description="서버에 가입합니다.")
|
||||
async def _join(self, ctx: Context):
|
||||
try:
|
||||
if await database.get_guild(ctx.guild.id): return await ctx.respond(embed=Default_Embed.already_register(), ephemeral=True)
|
||||
await database.register_guild(ctx.guild.id)
|
||||
await ctx.respond(embed=Default_Embed.register_sucess())
|
||||
except Exception as e:
|
||||
await ctx.respond(embed=Default_Embed.register_failed())
|
||||
|
||||
@guild_only()
|
||||
@has_permissions(administrator=True)
|
||||
@cooldown(1, 10, BucketType.user)
|
||||
@slash_command(name="서버탈퇴", description="서버에서 탈퇴합니다.")
|
||||
async def _leave(self, ctx: Context):
|
||||
if not await database.get_guild(ctx.guild.id): return await ctx.respond(embed=Default_Embed.not_register(), ephemeral=True)
|
||||
await database.leave_guild(ctx.guild.id)
|
||||
await ctx.respond(embed=Default_Embed.leave_sucess())
|
||||
|
||||
|
||||
@guild_only()
|
||||
@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)
|
||||
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))
|
||||
from discord import ApplicationContext, DiscordException, slash_command, Color
|
||||
from discord.ext.commands import Cog, cooldown, BucketType, has_permissions, guild_only, Context
|
||||
|
||||
from RUNA.UI.Embed import Default_Embed, ChristmasEmbed
|
||||
from RUNA.UI.Buttons import Recommanded
|
||||
from RUNA.Database import database
|
||||
from RUNA.Module import get_gpuserver_status, Get_Backend_latency
|
||||
|
||||
|
||||
class CogUtil(Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
|
||||
@guild_only()
|
||||
@has_permissions(administrator=True)
|
||||
@cooldown(1, 10, BucketType.user)
|
||||
@slash_command(name="서버가입", description="서버에 가입합니다.")
|
||||
async def _join(self, ctx: Context):
|
||||
try:
|
||||
if await database.get_guild(ctx.guild.id): return await ctx.respond(embed=Default_Embed.already_register(),
|
||||
ephemeral=True)
|
||||
await database.register_guild(ctx.guild.id)
|
||||
await ctx.respond(embed=Default_Embed.register_sucess())
|
||||
except Exception as e:
|
||||
await ctx.respond(embed=Default_Embed.register_failed())
|
||||
|
||||
@guild_only()
|
||||
@has_permissions(administrator=True)
|
||||
@cooldown(1, 10, BucketType.user)
|
||||
@slash_command(name="서버탈퇴", description="서버에서 탈퇴합니다.")
|
||||
async def _leave(self, ctx: Context):
|
||||
if not await database.get_guild(ctx.guild.id): return await ctx.respond(embed=Default_Embed.not_register(),
|
||||
ephemeral=True)
|
||||
await database.leave_guild(ctx.guild.id)
|
||||
await ctx.respond(embed=Default_Embed.leave_sucess())
|
||||
|
||||
@guild_only()
|
||||
@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)
|
||||
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 _recommend(self, ctx: Context):
|
||||
await ctx.respond(embed=Default_Embed.recommend(), view=Recommanded(), ephemeral=True)
|
||||
|
||||
|
||||
def setup(bot):
|
||||
bot.add_cog(CogUtil(bot))
|
@ -1,76 +1,67 @@
|
||||
import random
|
||||
import wavelink
|
||||
import pendulum
|
||||
|
||||
import onnxruntime as rt
|
||||
|
||||
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, MissingPermissions
|
||||
from Christmas.UI.Embed import Default_Embed, Music_Embed, ChristmasEmbed
|
||||
from Christmas.config import ChristmasConfig
|
||||
from Christmas.Database import database
|
||||
|
||||
model = rt.InferenceSession("Christmas/Tagging/model.onnx", provider_options="CPUExecutionProvider")
|
||||
|
||||
class Event(Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
self.config = ChristmasConfig()
|
||||
|
||||
@Cog.listener()
|
||||
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="크리스마스에 함께!"))
|
||||
|
||||
@Cog.listener()
|
||||
async def on_connect(self) -> None:
|
||||
await self.bot.wait_until_ready()
|
||||
nodes = []
|
||||
for node in self.config.LAVALINK:
|
||||
nodes.append(wavelink.Node(uri=node["HOST"], password=node["PASSWORD"], identifier=node["IDENTIFIER"]))
|
||||
await wavelink.Pool.connect(nodes=nodes, client=self.bot)
|
||||
|
||||
@Cog.listener()
|
||||
async def on_guild_join(self, guild: Guild) -> None:
|
||||
if guild.system_channel is not None:
|
||||
await guild.system_channel.send(embed=Default_Embed.default_join_embed())
|
||||
else:
|
||||
await random.choice(guild.text_channels).send(embed=Default_Embed.default_join_embed())
|
||||
|
||||
@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)
|
||||
|
||||
@tasks.loop(seconds=600)
|
||||
async def notify_all_guild_christmas(self) -> None:
|
||||
if pendulum.now() > pendulum.datetime(2023, 12, 24, 12, 0, 0):
|
||||
self.notify_all_guild_christmas.cancel()
|
||||
return
|
||||
for guild in self.bot.guilds:
|
||||
if not await database.get_guild(guild.id): continue
|
||||
if not await database.get_guild_christmas(guild.id):
|
||||
await database.update_guild_christmas(guild.id, True)
|
||||
if guild.system_channel is not None:
|
||||
await guild.system_channel.send(embed=Music_Embed.changed_christmas())
|
||||
else:
|
||||
await random.choice(guild.text_channels).send(embed=Music_Embed.changed_christmas())
|
||||
|
||||
def setup(bot):
|
||||
import random
|
||||
import pendulum
|
||||
|
||||
import onnxruntime as rt
|
||||
|
||||
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, MissingPermissions
|
||||
from RUNA.UI.Embed import Default_Embed, Music_Embed, RunaEmbed
|
||||
from RUNA.Database import database
|
||||
|
||||
model = rt.InferenceSession("RUNA/Tagging/model.onnx", provider_options="CPUExecutionProvider")
|
||||
|
||||
class Event(Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
self.config = ChristmasConfig()
|
||||
|
||||
@Cog.listener()
|
||||
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=RunaEmbed(title="❌ 에러!", description=f"권한이 부족해요! 필요한 권한: {need_permissions}", color=Color.red()),ephemeral=True)
|
||||
else:
|
||||
await ctx.respond(embed=RunaEmbed(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="루나봇"))
|
||||
|
||||
|
||||
@Cog.listener()
|
||||
async def on_guild_join(self, guild: Guild) -> None:
|
||||
if guild.system_channel is not None:
|
||||
await guild.system_channel.send(embed=Default_Embed.default_join_embed())
|
||||
else:
|
||||
await random.choice(guild.text_channels).send(embed=Default_Embed.default_join_embed())
|
||||
|
||||
@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)
|
||||
|
||||
@tasks.loop(seconds=600)
|
||||
async def notify_all_guild_christmas(self) -> None:
|
||||
if pendulum.now() > pendulum.datetime(2023, 12, 24, 12, 0, 0):
|
||||
self.notify_all_guild_christmas.cancel()
|
||||
return
|
||||
for guild in self.bot.guilds:
|
||||
if not await database.get_guild(guild.id): continue
|
||||
if not await database.get_guild_christmas(guild.id):
|
||||
await database.update_guild_christmas(guild.id, True)
|
||||
if guild.system_channel is not None:
|
||||
await guild.system_channel.send(embed=Music_Embed.changed_christmas())
|
||||
else:
|
||||
await random.choice(guild.text_channels).send(embed=Music_Embed.changed_christmas())
|
||||
|
||||
def setup(bot):
|
||||
bot.add_cog(Event(bot))
|
19
RUNA/Database/MeiliSearch/__init__.py
Normal file
19
RUNA/Database/MeiliSearch/__init__.py
Normal file
@ -0,0 +1,19 @@
|
||||
import os
|
||||
from meilisearch_python_sdk import AsyncClient as Client
|
||||
from dotenv import load_dotenv, find_dotenv
|
||||
|
||||
load_dotenv(find_dotenv())
|
||||
|
||||
|
||||
class Search:
|
||||
def __init__(self):
|
||||
self.index = None
|
||||
self.client = None
|
||||
|
||||
async def connect(self):
|
||||
self.client = Client(os.getenv("MEILI_ADDRESS"), os.getenv("MEILI_MASTER_KEY"))
|
||||
self.index = self.client.index(os.getenv("MEILI_INDEX"))
|
||||
return self.index
|
||||
|
||||
async def close(self):
|
||||
await self.client.aclose()
|
18
RUNA/Database/Mongo/__init__.py
Normal file
18
RUNA/Database/Mongo/__init__.py
Normal file
@ -0,0 +1,18 @@
|
||||
import os
|
||||
|
||||
from motor.motor_asyncio import AsyncIOMotorClient
|
||||
from dotenv import load_dotenv, find_dotenv
|
||||
|
||||
load_dotenv(find_dotenv())
|
||||
|
||||
|
||||
class MongoDBClient:
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.client = \
|
||||
AsyncIOMotorClient(os.getenv("MONGODB_HOST"), int(os.getenv("MONGODB_PORT")),
|
||||
username=os.getenv("MONGODB_ID"),
|
||||
password=os.getenv("MONGODB_PASSWORD"))[os.getenv("MONGODB_DATABASE")]
|
||||
|
||||
async def connect(self):
|
||||
return self.client
|
0
RUNA/Database/Mongo/guild.py
Normal file
0
RUNA/Database/Mongo/guild.py
Normal file
0
RUNA/Database/__init__.py
Normal file
0
RUNA/Database/__init__.py
Normal file
16
RUNA/Enum.py
Normal file
16
RUNA/Enum.py
Normal file
@ -0,0 +1,16 @@
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class STATUS(Enum):
|
||||
SUCCESS = 0
|
||||
ERROR = 1
|
||||
NOT_AVAILABLE = 2
|
||||
NOT_FOUND = 3
|
||||
NOT_AUTHORIZED = 4
|
||||
NOT_ALLOWED = 5
|
||||
|
||||
def __str__(self):
|
||||
return str(self.value)
|
||||
|
||||
|
||||
|
@ -1,204 +1,204 @@
|
||||
import io
|
||||
import time
|
||||
import PIL
|
||||
import base64
|
||||
import re
|
||||
import random
|
||||
import aiohttp
|
||||
import asyncio
|
||||
import sentry_sdk
|
||||
from aiogoogletrans import Translator
|
||||
from typing import Any, Dict
|
||||
from discord import File, Asset
|
||||
from Christmas.Tagging import Tagging
|
||||
from Christmas.Cogs.Event import model
|
||||
translator = Translator()
|
||||
BLOCKTAG = [
|
||||
"nsfw",
|
||||
"nude",
|
||||
"nipples",
|
||||
"nipple",
|
||||
"pussy",
|
||||
"public hair",
|
||||
"gay",
|
||||
"lesbian",
|
||||
"corpse",
|
||||
"no panties",
|
||||
"no panty",
|
||||
"no bra",
|
||||
"bra",
|
||||
"panty",
|
||||
"panties",
|
||||
"underwear",
|
||||
"undergarment",
|
||||
"underpants",
|
||||
"underpant",
|
||||
"blowjob",
|
||||
"sex",
|
||||
"sexy",
|
||||
"pennis"
|
||||
"realistic",
|
||||
"open breasts",
|
||||
"breasts",
|
||||
"bikini",
|
||||
"swimsuit",
|
||||
"give birth",
|
||||
"slave"
|
||||
]
|
||||
|
||||
weight = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.7, 0.8, 0.9]
|
||||
cfg = [6, 7, 8, 9, 10, 11]
|
||||
#def check_curse(text: str):
|
||||
# return korcen_checker.check(text)
|
||||
def is_korean(string):
|
||||
pattern = re.compile(r"[ㄱ-ㅎㅏ-ㅣ가-힣]")
|
||||
match = pattern.search(string)
|
||||
return bool(match)
|
||||
|
||||
async def process_prompt(prompt: str, remove: str, res: list, isnsfw: bool, style1: float, style2: float, afterprocess: bool, avatar):
|
||||
tags = None
|
||||
if not avatar == None:
|
||||
# gif인 경우 png로 변환
|
||||
try:
|
||||
if avatar.url.endswith(".gif"):
|
||||
avatar = avatar.replace(format="png")
|
||||
avatar = await avatar.read()
|
||||
# TypeError: a bytes-like object is required, not 'PngImageFile'
|
||||
taging = Tagging(model=model)
|
||||
tags = await taging.predict(avatar)
|
||||
tags = tags[0]
|
||||
except Exception as e:
|
||||
tags = None
|
||||
man = False
|
||||
if "남자" in prompt and "여자" in remove:
|
||||
man = True
|
||||
if is_korean(prompt):
|
||||
prompt = await translator.translate(prompt, dest="en")
|
||||
prompt = prompt.text
|
||||
if is_korean(remove):
|
||||
remove = await translator.translate(remove, dest="en")
|
||||
remove = remove.text
|
||||
if isnsfw == False:
|
||||
for i in BLOCKTAG:
|
||||
if i in prompt:
|
||||
prompt = prompt.replace(i, "")
|
||||
default_negative = """(KHFB, AuroraNegative, easynegative, negative_hand-neg, verybadimagenegative_v1.3:0.8), (Worst Quality, Low Quality:1.4), border, skimpy, grayscale, multiple_girls, 3d, realistic, string, multiple hands, chinese, thick abs, chubby abs, lowres, bad anatomy, asymmetric wings, elf, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, large areolae, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry, Multiple legs, multiple feet, tie, (necktie:1.5), several hands, three feet, four legs, three legs,animal ears"""
|
||||
if style1 != 0:
|
||||
prompt = prompt + f"<lora:addDetail:{style1}>"
|
||||
if style2 != 0:
|
||||
prompt = prompt + f"<lora:光影:{style2}>"
|
||||
if remove != None:
|
||||
negative_prompt = default_negative + "," + remove
|
||||
if man == True:
|
||||
prompt = prompt + "," + "(1boy)"
|
||||
negative_prompt = negative_prompt + "," + "(1girl)"
|
||||
add_prompt = random.choice([True, False])
|
||||
if add_prompt == True:
|
||||
prompt = prompt + f"<lora:canistermix1.1:{random.choice(weight)}>"
|
||||
if tags != None:
|
||||
prompt = prompt + "," + tags
|
||||
payloads = {}
|
||||
if afterprocess == True:
|
||||
payloads = {
|
||||
"prompt": prompt,
|
||||
"negative_prompt": negative_prompt,
|
||||
"enable_hr": True,
|
||||
"hr_scale": 1.5,
|
||||
"hr_upscaler": "R-ESRGAN 4x+ Anime6B",
|
||||
"seed": random.randint(0, 1000000000),
|
||||
"steps": 25,
|
||||
"cfg_scale": random.choice(cfg),
|
||||
"width": res[0],
|
||||
"height": res[1],
|
||||
"sampler_index": "DPM++ 2M Karras",
|
||||
"refiner_checkpoint": "smooREFINERV2R10_half",
|
||||
"refiner_switch_at": 0.45,
|
||||
"alwayson_scripts": {
|
||||
"ADetailer": {
|
||||
'args': [
|
||||
{
|
||||
'ad_model': 'face_yolov8n.pt',
|
||||
'ad_inpaint_only_masked': True
|
||||
}]
|
||||
}}}
|
||||
else:
|
||||
payloads = {
|
||||
"prompt": prompt,
|
||||
"negative_prompt": negative_prompt,
|
||||
"seed": random.randint(0, 1000000000),
|
||||
"steps": 25,
|
||||
"cfg_scale": random.choice(cfg),
|
||||
"width": res[0],
|
||||
"height": res[1],
|
||||
"sampler_index": "DPM++ 2M Karras",
|
||||
"refiner_checkpoint": "smooREFINERV2R10_half",
|
||||
"refiner_switch_at": 0.45,
|
||||
"alwayson_scripts": {
|
||||
"ADetailer": {
|
||||
'args': [
|
||||
{
|
||||
'ad_model': 'face_yolov8n.pt',
|
||||
'ad_inpaint_only_masked': True
|
||||
}]
|
||||
}}}
|
||||
return payloads
|
||||
|
||||
|
||||
async def post_gpu_server(url: str, payload: Dict[str, Any]):
|
||||
async with aiohttp.ClientSession() as session:
|
||||
try:
|
||||
async with session.post(url, json=payload, timeout=300) as response:
|
||||
if response.status == 200:
|
||||
return {"status": True, "data": await response.json()}
|
||||
else:
|
||||
return {"status": False, "data": None}
|
||||
except Exception as e:
|
||||
if isinstance(e, asyncio.TimeoutError):
|
||||
return {"status": False, "data": None}
|
||||
|
||||
|
||||
async def image_to_base64(image) -> str:
|
||||
img = PIL.Image.open(image)
|
||||
img = img.convert("RGB")
|
||||
img_byte_arr = io.BytesIO()
|
||||
img.save(img_byte_arr, format='PNG')
|
||||
img_byte_arr = img_byte_arr.getvalue()
|
||||
img_str = base64.b64encode(img_byte_arr).decode("utf-8")
|
||||
return img_str
|
||||
|
||||
|
||||
async def base64_to_image(base642) -> File:
|
||||
attachment = File(io.BytesIO(base64.b64decode(base642)), filename="image.png")
|
||||
return attachment
|
||||
|
||||
async def get_gpuserver_status(url) -> Dict:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
try:
|
||||
async with session.get(f"http://172.30.1.49:7860/sdapi/v1/memory", timeout=10) as response:
|
||||
|
||||
if response.status == 200:
|
||||
result = await response.json()
|
||||
memstatus = result["ram"]["used"]
|
||||
cudamemstatus = result["cuda"]["system"]["used"]
|
||||
oomcount = result["cuda"]["events"]["oom"]
|
||||
return {"status": "online", "system_memory_usage": bytes_to_gb(memstatus), "cuda_memory_usage": bytes_to_gb(cudamemstatus), "oom_count": oomcount}
|
||||
except Exception as e:
|
||||
sentry_sdk.capture_exception(e)
|
||||
return {"status": "offline"}
|
||||
|
||||
def bytes_to_gb(bytes: int) -> float:
|
||||
return round(bytes / 1024 / 1024 / 1024, 2)
|
||||
|
||||
|
||||
async def Get_Backend_latency():
|
||||
start_time = time.time()
|
||||
async with aiohttp.ClientSession() as client:
|
||||
try:
|
||||
async with client.get("http://172.30.1.49:7860/sdapi/v1/memory", timeout=10) as response:
|
||||
if response.status_code == 200 or response.status_code == 404:
|
||||
return round(time.time() - start_time, 2)
|
||||
else:
|
||||
return None
|
||||
except Exception as e:
|
||||
print(e)
|
||||
import io
|
||||
import time
|
||||
import PIL
|
||||
import base64
|
||||
import re
|
||||
import random
|
||||
import aiohttp
|
||||
import asyncio
|
||||
import sentry_sdk
|
||||
from aiogoogletrans import Translator
|
||||
from typing import Any, Dict
|
||||
from discord import File, Asset
|
||||
from RUNA.Tagging import Tagging
|
||||
from RUNA.Cogs.Event import model
|
||||
translator = Translator()
|
||||
BLOCKTAG = [
|
||||
"nsfw",
|
||||
"nude",
|
||||
"nipples",
|
||||
"nipple",
|
||||
"pussy",
|
||||
"public hair",
|
||||
"gay",
|
||||
"lesbian",
|
||||
"corpse",
|
||||
"no panties",
|
||||
"no panty",
|
||||
"no bra",
|
||||
"bra",
|
||||
"panty",
|
||||
"panties",
|
||||
"underwear",
|
||||
"undergarment",
|
||||
"underpants",
|
||||
"underpant",
|
||||
"blowjob",
|
||||
"sex",
|
||||
"sexy",
|
||||
"pennis"
|
||||
"realistic",
|
||||
"open breasts",
|
||||
"breasts",
|
||||
"bikini",
|
||||
"swimsuit",
|
||||
"give birth",
|
||||
"slave"
|
||||
]
|
||||
|
||||
weight = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.7, 0.8, 0.9]
|
||||
cfg = [6, 7, 8, 9, 10, 11]
|
||||
#def check_curse(text: str):
|
||||
# return korcen_checker.check(text)
|
||||
def is_korean(string):
|
||||
pattern = re.compile(r"[ㄱ-ㅎㅏ-ㅣ가-힣]")
|
||||
match = pattern.search(string)
|
||||
return bool(match)
|
||||
|
||||
async def process_prompt(prompt: str, remove: str, res: list, isnsfw: bool, style1: float, style2: float, afterprocess: bool, avatar):
|
||||
tags = None
|
||||
if not avatar == None:
|
||||
# gif인 경우 png로 변환
|
||||
try:
|
||||
if avatar.url.endswith(".gif"):
|
||||
avatar = avatar.replace(format="png")
|
||||
avatar = await avatar.read()
|
||||
# TypeError: a bytes-like object is required, not 'PngImageFile'
|
||||
taging = Tagging(model=model)
|
||||
tags = await taging.predict(avatar)
|
||||
tags = tags[0]
|
||||
except Exception as e:
|
||||
tags = None
|
||||
man = False
|
||||
if "남자" in prompt and "여자" in remove:
|
||||
man = True
|
||||
if is_korean(prompt):
|
||||
prompt = await translator.translate(prompt, dest="en")
|
||||
prompt = prompt.text
|
||||
if is_korean(remove):
|
||||
remove = await translator.translate(remove, dest="en")
|
||||
remove = remove.text
|
||||
if isnsfw == False:
|
||||
for i in BLOCKTAG:
|
||||
if i in prompt:
|
||||
prompt = prompt.replace(i, "")
|
||||
default_negative = """(KHFB, AuroraNegative, easynegative, negative_hand-neg, verybadimagenegative_v1.3:0.8), (Worst Quality, Low Quality:1.4), border, skimpy, grayscale, multiple_girls, 3d, realistic, string, multiple hands, chinese, thick abs, chubby abs, lowres, bad anatomy, asymmetric wings, elf, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, large areolae, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry, Multiple legs, multiple feet, tie, (necktie:1.5), several hands, three feet, four legs, three legs,animal ears, nsfw, exposure"""
|
||||
if style1 != 0:
|
||||
prompt = prompt + f"<lora:addDetail:{style1}>"
|
||||
if style2 != 0:
|
||||
prompt = prompt + f"<lora:光影:{style2}>"
|
||||
if remove != None:
|
||||
negative_prompt = default_negative + "," + remove
|
||||
if man == True:
|
||||
prompt = prompt + "," + "(1boy)"
|
||||
negative_prompt = negative_prompt + "," + "(1girl)"
|
||||
add_prompt = random.choice([True, False])
|
||||
if add_prompt == True:
|
||||
prompt = prompt + f"<lora:canistermix1.1:{random.choice(weight)}>"
|
||||
if tags != None:
|
||||
prompt = prompt + "," + tags
|
||||
payloads = {}
|
||||
if afterprocess == True:
|
||||
payloads = {
|
||||
"prompt": prompt,
|
||||
"negative_prompt": negative_prompt,
|
||||
"enable_hr": True,
|
||||
"hr_scale": 1.5,
|
||||
"hr_upscaler": "R-ESRGAN 4x+ Anime6B",
|
||||
"seed": random.randint(0, 1000000000),
|
||||
"steps": 25,
|
||||
"cfg_scale": random.choice(cfg),
|
||||
"width": res[0],
|
||||
"height": res[1],
|
||||
"sampler_index": "DPM++ 2M Karras",
|
||||
"refiner_checkpoint": "smooREFINERV2R10_half",
|
||||
"refiner_switch_at": 0.45,
|
||||
"alwayson_scripts": {
|
||||
"ADetailer": {
|
||||
'args': [
|
||||
{
|
||||
'ad_model': 'face_yolov8n.pt',
|
||||
'ad_inpaint_only_masked': True
|
||||
}]
|
||||
}}}
|
||||
else:
|
||||
payloads = {
|
||||
"prompt": prompt,
|
||||
"negative_prompt": negative_prompt,
|
||||
"seed": random.randint(0, 1000000000),
|
||||
"steps": 25,
|
||||
"cfg_scale": random.choice(cfg),
|
||||
"width": res[0],
|
||||
"height": res[1],
|
||||
"sampler_index": "DPM++ 2M Karras",
|
||||
"refiner_checkpoint": "smooREFINERV2R10_half",
|
||||
"refiner_switch_at": 0.45,
|
||||
"alwayson_scripts": {
|
||||
"ADetailer": {
|
||||
'args': [
|
||||
{
|
||||
'ad_model': 'face_yolov8n.pt',
|
||||
'ad_inpaint_only_masked': True
|
||||
}]
|
||||
}}}
|
||||
return payloads
|
||||
|
||||
|
||||
async def post_gpu_server(url: str, payload: Dict[str, Any]):
|
||||
async with aiohttp.ClientSession() as session:
|
||||
try:
|
||||
async with session.post(url, json=payload, timeout=300) as response:
|
||||
if response.status == 200:
|
||||
return {"status": True, "data": await response.json()}
|
||||
else:
|
||||
return {"status": False, "data": None}
|
||||
except Exception as e:
|
||||
if isinstance(e, asyncio.TimeoutError):
|
||||
return {"status": False, "data": None}
|
||||
|
||||
|
||||
async def image_to_base64(image) -> str:
|
||||
img = PIL.Image.open(image)
|
||||
img = img.convert("RGB")
|
||||
img_byte_arr = io.BytesIO()
|
||||
img.save(img_byte_arr, format='PNG')
|
||||
img_byte_arr = img_byte_arr.getvalue()
|
||||
img_str = base64.b64encode(img_byte_arr).decode("utf-8")
|
||||
return img_str
|
||||
|
||||
|
||||
async def base64_to_image(base642) -> File:
|
||||
attachment = File(io.BytesIO(base64.b64decode(base642)), filename="image.png")
|
||||
return attachment
|
||||
|
||||
async def get_gpuserver_status(url) -> Dict:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
try:
|
||||
async with session.get(f"http://172.30.1.49:7860/sdapi/v1/memory", timeout=10) as response:
|
||||
|
||||
if response.status == 200:
|
||||
result = await response.json()
|
||||
memstatus = result["ram"]["used"]
|
||||
cudamemstatus = result["cuda"]["system"]["used"]
|
||||
oomcount = result["cuda"]["events"]["oom"]
|
||||
return {"status": "online", "system_memory_usage": bytes_to_gb(memstatus), "cuda_memory_usage": bytes_to_gb(cudamemstatus), "oom_count": oomcount}
|
||||
except Exception as e:
|
||||
sentry_sdk.capture_exception(e)
|
||||
return {"status": "offline"}
|
||||
|
||||
def bytes_to_gb(bytes: int) -> float:
|
||||
return round(bytes / 1024 / 1024 / 1024, 2)
|
||||
|
||||
|
||||
async def Get_Backend_latency():
|
||||
start_time = time.time()
|
||||
async with aiohttp.ClientSession() as client:
|
||||
try:
|
||||
async with client.get("http://172.30.1.49:7860/sdapi/v1/memory", timeout=10) as response:
|
||||
if response.status_code == 200 or response.status_code == 404:
|
||||
return round(time.time() - start_time, 2)
|
||||
else:
|
||||
return None
|
||||
except Exception as e:
|
||||
print(e)
|
||||
return None
|
42
RUNA/Modules/Exception.py
Normal file
42
RUNA/Modules/Exception.py
Normal file
@ -0,0 +1,42 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
class RUNAException(Exception):
|
||||
def __init__(self, message):
|
||||
self.message = message
|
||||
super().__init__(self.message)
|
||||
|
||||
def __str__(self):
|
||||
return self.message
|
||||
|
||||
def __repr__(self):
|
||||
return self.message
|
||||
|
||||
|
||||
class RUNAWarning(Warning):
|
||||
def __init__(self, message):
|
||||
self.message = message
|
||||
super().__init__(self.message)
|
||||
|
||||
def __str__(self):
|
||||
return self.message
|
||||
|
||||
def __repr__(self):
|
||||
return self.message
|
||||
|
||||
|
||||
class RUNAInfo(Warning):
|
||||
def __init__(self, message):
|
||||
self.message = message
|
||||
super().__init__(self.message)
|
||||
|
||||
def __str__(self):
|
||||
return self.message
|
||||
|
||||
def __repr__(self):
|
||||
return self.message
|
||||
|
||||
|
20
RUNA/Modules/Logging.py
Normal file
20
RUNA/Modules/Logging.py
Normal file
@ -0,0 +1,20 @@
|
||||
import loguru
|
||||
|
||||
|
||||
class Logging:
|
||||
def __init__(self):
|
||||
self.logger = loguru.logger
|
||||
self.logger.add("Logs/Latest.log", rotation="1 day", retention="7 days", level="DEBUG",
|
||||
format="{time} {level} {message}")
|
||||
|
||||
def error(self, message: str):
|
||||
self.logger.error(message)
|
||||
|
||||
def warning(self, message: str):
|
||||
self.logger.warning(message)
|
||||
|
||||
def info(self, message: str):
|
||||
self.logger.info(message)
|
||||
|
||||
def debug(self, message: str):
|
||||
self.logger.debug(message)
|
@ -1,110 +1,101 @@
|
||||
from Christmas.Cogs.Event import model
|
||||
|
||||
|
||||
import typing
|
||||
import asyncio
|
||||
import io
|
||||
import PIL
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
import onnxruntime as rt
|
||||
import pandas as pd
|
||||
import cv2
|
||||
|
||||
|
||||
|
||||
|
||||
class Tagging:
|
||||
def __init__(self, model, ProviderOptions: typing.Optional[str] = "CPUExecutionProvider"):
|
||||
self.model_path = "Christmas/Tagging/model.onnx"
|
||||
self.tag_path = "Christmas/Tagging/tags.csv"
|
||||
self.model = model
|
||||
self.general_threshold: typing.Optional[float] = 0.35
|
||||
self.character_threshold: typing.Optional[float] = 0.85
|
||||
|
||||
|
||||
|
||||
def make_square(self, img, target_size):
|
||||
old_size = img.shape[:2]
|
||||
desired_size = max(old_size)
|
||||
desired_size = max(desired_size, target_size)
|
||||
|
||||
delta_w = desired_size - old_size[1]
|
||||
delta_h = desired_size - old_size[0]
|
||||
top, bottom = delta_h // 2, delta_h - (delta_h // 2)
|
||||
left, right = delta_w // 2, delta_w - (delta_w // 2)
|
||||
|
||||
color = [255, 255, 255]
|
||||
new_im = cv2.copyMakeBorder(
|
||||
img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color
|
||||
)
|
||||
return new_im
|
||||
|
||||
|
||||
def smart_resize(self, img, size):
|
||||
# Assumes the image has already gone through make_square
|
||||
if img.shape[0] > size:
|
||||
img = cv2.resize(img, (size, size), interpolation=cv2.INTER_AREA)
|
||||
elif img.shape[0] < size:
|
||||
img = cv2.resize(img, (size, size), interpolation=cv2.INTER_CUBIC)
|
||||
return img
|
||||
|
||||
def load_labels(self, path):
|
||||
df = pd.read_csv(path)
|
||||
tag_names = df["name"].tolist()
|
||||
category = df["category"].tolist()
|
||||
rating_indexes = [i for i, cat in enumerate(category) if cat == 9]
|
||||
general_indexes = [i for i, cat in enumerate(category) if cat == 0]
|
||||
character_indexes = [i for i, cat in enumerate(category) if cat == 4]
|
||||
return tag_names, rating_indexes, general_indexes, character_indexes
|
||||
|
||||
def preprocess_image(self, image):
|
||||
image = image.convert("RGBA")
|
||||
new_image = Image.new("RGBA", image.size, "WHITE")
|
||||
new_image.paste(image, mask=image)
|
||||
image = new_image.convert("RGB")
|
||||
image = np.asarray(image)[:, :, ::-1]
|
||||
return image
|
||||
|
||||
def _predict_image(self, image, general_threshold, character_threshold):
|
||||
"""discord.File의 byteio를 받아서 이미지를 예측합니다."""
|
||||
image = Image.open(io.BytesIO(image))
|
||||
tag_names, rating_indexes, general_indexes, character_indexes = self.load_labels(self.tag_path)
|
||||
model = self.model
|
||||
|
||||
_, height, width, _ = model.get_inputs()[0].shape
|
||||
|
||||
image = self.preprocess_image(image)
|
||||
image = self.make_square(image, height)
|
||||
image = self.smart_resize(image, height)
|
||||
image = image.astype(np.float32)
|
||||
image = np.expand_dims(image, 0)
|
||||
|
||||
input_name = model.get_inputs()[0].name
|
||||
label_name = model.get_outputs()[0].name
|
||||
probs = model.run([label_name], {input_name: image})[0]
|
||||
|
||||
labels = list(zip(tag_names, probs[0].astype(float)))
|
||||
|
||||
# Extract ratings, general, and character labels
|
||||
ratings_names = [labels[i] for i in rating_indexes]
|
||||
general_names = [labels[i] for i in general_indexes]
|
||||
character_names = [labels[i] for i in character_indexes]
|
||||
|
||||
rating = dict(ratings_names)
|
||||
general_res = {name: prob for name, prob in general_names if prob > general_threshold}
|
||||
character_res = {name: prob for name, prob in character_names if prob > character_threshold}
|
||||
|
||||
general_res_sorted = dict(sorted(general_res.items(), key=lambda item: item[1], reverse=True))
|
||||
a = ", ".join(general_res_sorted.keys()).replace("_", " ").replace("(", "\(").replace(")", "\)")
|
||||
c = ", ".join(general_res_sorted.keys())
|
||||
|
||||
return a, c, rating, character_res, general_res_sorted
|
||||
|
||||
|
||||
async def predict(self, image, general_threshold: typing.Optional[float] = None, character_threshold: typing.Optional[float] = None):
|
||||
if general_threshold is None:
|
||||
general_threshold = self.general_threshold
|
||||
if character_threshold is None:
|
||||
character_threshold = self.character_threshold
|
||||
return await asyncio.to_thread(self._predict_image, image, general_threshold, character_threshold)
|
||||
import typing
|
||||
import asyncio
|
||||
import io
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
import onnxruntime as rt
|
||||
import pandas as pd
|
||||
import cv2
|
||||
|
||||
model = rt.InferenceSession("RUNA/Tagging/model.onnx", provider_options=["CPUExecutionProvider"])
|
||||
|
||||
|
||||
class Tagging:
|
||||
def __init__(self):
|
||||
self.model_path = "RUNA/Tagging/model.onnx"
|
||||
self.tag_path = "RUNA/Tagging/tags.csv"
|
||||
self.model = model
|
||||
self.general_threshold: typing.Optional[float] = 0.35
|
||||
self.character_threshold: typing.Optional[float] = 0.85
|
||||
|
||||
def make_square(self, img, target_size):
|
||||
old_size = img.shape[:2]
|
||||
desired_size = max(old_size)
|
||||
desired_size = max(desired_size, target_size)
|
||||
|
||||
delta_w = desired_size - old_size[1]
|
||||
delta_h = desired_size - old_size[0]
|
||||
top, bottom = delta_h // 2, delta_h - (delta_h // 2)
|
||||
left, right = delta_w // 2, delta_w - (delta_w // 2)
|
||||
|
||||
color = [255, 255, 255]
|
||||
new_im = cv2.copyMakeBorder(
|
||||
img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color
|
||||
)
|
||||
return new_im
|
||||
|
||||
def smart_resize(self, img, size):
|
||||
# Assumes the image has already gone through make_square
|
||||
if img.shape[0] > size:
|
||||
img = cv2.resize(img, (size, size), interpolation=cv2.INTER_AREA)
|
||||
elif img.shape[0] < size:
|
||||
img = cv2.resize(img, (size, size), interpolation=cv2.INTER_CUBIC)
|
||||
return img
|
||||
|
||||
def load_labels(self, path):
|
||||
df = pd.read_csv(path)
|
||||
tag_names = df["name"].tolist()
|
||||
category = df["category"].tolist()
|
||||
rating_indexes = [i for i, cat in enumerate(category) if cat == 9]
|
||||
general_indexes = [i for i, cat in enumerate(category) if cat == 0]
|
||||
character_indexes = [i for i, cat in enumerate(category) if cat == 4]
|
||||
return tag_names, rating_indexes, general_indexes, character_indexes
|
||||
|
||||
def preprocess_image(self, image):
|
||||
image = image.convert("RGBA")
|
||||
new_image = Image.new("RGBA", image.size, "WHITE")
|
||||
new_image.paste(image, mask=image)
|
||||
image = new_image.convert("RGB")
|
||||
image = np.asarray(image)[:, :, ::-1]
|
||||
return image
|
||||
|
||||
def _predict_image(self, image, general_threshold, character_threshold):
|
||||
image = Image.open(io.BytesIO(image))
|
||||
tag_names, rating_indexes, general_indexes, character_indexes = self.load_labels(self.tag_path)
|
||||
|
||||
_, height, width, _ = self.model.get_inputs()[0].shape
|
||||
|
||||
image = self.preprocess_image(image)
|
||||
image = self.make_square(image, height)
|
||||
image = self.smart_resize(image, height)
|
||||
image = image.astype(np.float32)
|
||||
image = np.expand_dims(image, 0)
|
||||
|
||||
input_name = model.get_inputs()[0].name
|
||||
label_name = model.get_outputs()[0].name
|
||||
probs = model.run([label_name], {input_name: image})[0]
|
||||
|
||||
labels = list(zip(tag_names, probs[0].astype(float)))
|
||||
|
||||
# Extract ratings, general, and character labels
|
||||
ratings_names = [labels[i] for i in rating_indexes]
|
||||
general_names = [labels[i] for i in general_indexes]
|
||||
character_names = [labels[i] for i in character_indexes]
|
||||
|
||||
rating = dict(ratings_names)
|
||||
general_res = {name: prob for name, prob in general_names if prob > general_threshold}
|
||||
character_res = {name: prob for name, prob in character_names if prob > character_threshold}
|
||||
|
||||
general_res_sorted = dict(sorted(general_res.items(), key=lambda item: item[1], reverse=True))
|
||||
a = ", ".join(general_res_sorted.keys()).replace("_", " ").replace("(", "\(").replace(")", "\)")
|
||||
c = ", ".join(general_res_sorted.keys())
|
||||
|
||||
return a, c, rating, character_res, general_res_sorted
|
||||
|
||||
async def predict(self, image, general_threshold: typing.Optional[float] = None,
|
||||
character_threshold: typing.Optional[float] = None):
|
||||
if general_threshold is None:
|
||||
general_threshold = self.general_threshold
|
||||
if character_threshold is None:
|
||||
character_threshold = self.character_threshold
|
||||
return await asyncio.to_thread(self._predict_image, image, general_threshold, character_threshold)
|
File diff suppressed because it is too large
Load Diff
@ -1,16 +1,16 @@
|
||||
from discord import AutocompleteContext
|
||||
|
||||
from Christmas.SearchEngine.Snowball import Snowball
|
||||
|
||||
|
||||
async def Guild_Autocomplete(ctx: AutocompleteContext):
|
||||
snowball = Snowball()
|
||||
query = ctx.value
|
||||
print(query)
|
||||
result = await snowball.query_guild(query)
|
||||
results = []
|
||||
for i in result["hits"]:
|
||||
gname = i["guild_name"]
|
||||
gid = i["guild_id"]
|
||||
results.append(f"{gname} ({gid})")
|
||||
from discord import AutocompleteContext
|
||||
|
||||
from RUNA.Database.MeiliSearch import Snowball
|
||||
|
||||
|
||||
async def Guild_Autocomplete(ctx: AutocompleteContext):
|
||||
snowball = Snowball()
|
||||
query = ctx.value
|
||||
print(query)
|
||||
result = await snowball.query_guild(query)
|
||||
results = []
|
||||
for i in result["hits"]:
|
||||
gname = i["guild_name"]
|
||||
gid = i["guild_id"]
|
||||
results.append(f"{gname} ({gid})")
|
||||
return results
|
@ -1,76 +1,80 @@
|
||||
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, 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
|
||||
self.recive_user = recive_user
|
||||
self.title = title
|
||||
self.description = description
|
||||
super().__init__(timeout=None)
|
||||
|
||||
@button(label="전송", style=ButtonStyle.green, custom_id="mail_send")
|
||||
async def send(self, button, interaction: Interaction):
|
||||
await interaction.response.defer()
|
||||
if await database.get_guild(interaction.guild.id) == None:
|
||||
await interaction.edit_original_response(embed=Embed(title="❌ 에러!", description="서버가 가입되어있지 않아요! 서버에 가입해주세요!"), view=None)
|
||||
return
|
||||
else:
|
||||
if self.editmode == True:
|
||||
await database.update_inserted_mail(self.recive_user.id, interaction.user.id, self.title, self.description)
|
||||
await interaction.edit_original_response(embed=Mail_Embed.mail_edit_sended(receive_user=self.recive_user), view=None)
|
||||
else:
|
||||
await database.insert_mail(interaction.user.id, self.recive_user.id, interaction.user.name, self.title, self.description)
|
||||
await interaction.edit_original_response(embed=Mail_Embed.mail_sended(receive_user=self.recive_user), view=None)
|
||||
|
||||
@button(label="취소", style=ButtonStyle.red, custom_id="mail_cancel")
|
||||
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:
|
||||
region = random.choice(["south", "north"])
|
||||
await database.register_arcade(interaction.guild.id, interaction.guild.name, region)
|
||||
await Snowball.register_guild(interaction.guild.id, interaction.guild.name, region)
|
||||
except Exception as e:
|
||||
print(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)
|
||||
|
||||
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["data"]["voted"] == True:
|
||||
await database.insert_guild_art_point(interaction.guild.id, 5)
|
||||
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=self)
|
||||
import random
|
||||
import os
|
||||
from discord.ui import View, button
|
||||
from discord import Interaction, ButtonStyle, Embed, Member
|
||||
from dotenv import load_dotenv, find_dotenv
|
||||
|
||||
from RUNA.UI.Embed import Mail_Embed, Arcade_Embed
|
||||
from RUNA.Database import database
|
||||
from RUNA.Database.MeiliSearch import Snowball
|
||||
|
||||
from koreanbots import KoreanbotsRequester
|
||||
|
||||
|
||||
load_dotenv(find_dotenv())
|
||||
|
||||
class Mail_Confirm_Button(View):
|
||||
def __init__(self, editmode: bool, recive_user: Member, title: str, description: str, *args, **kwargs):
|
||||
self.editmode = editmode
|
||||
self.recive_user = recive_user
|
||||
self.title = title
|
||||
self.description = description
|
||||
super().__init__(timeout=None)
|
||||
|
||||
@button(label="전송", style=ButtonStyle.green, custom_id="mail_send")
|
||||
async def send(self, button, interaction: Interaction):
|
||||
await interaction.response.defer()
|
||||
if await database.get_guild(interaction.guild.id) == None:
|
||||
await interaction.edit_original_response(embed=Embed(title="❌ 에러!", description="서버가 가입되어있지 않아요! 서버에 가입해주세요!"), view=None)
|
||||
return
|
||||
else:
|
||||
if self.editmode == True:
|
||||
await database.update_inserted_mail(self.recive_user.id, interaction.user.id, self.title, self.description)
|
||||
await interaction.edit_original_response(embed=Mail_Embed.mail_edit_sended(receive_user=self.recive_user), view=None)
|
||||
else:
|
||||
await database.insert_mail(interaction.user.id, self.recive_user.id, interaction.user.name, self.title, self.description)
|
||||
await interaction.edit_original_response(embed=Mail_Embed.mail_sended(receive_user=self.recive_user), view=None)
|
||||
|
||||
@button(label="취소", style=ButtonStyle.red, custom_id="mail_cancel")
|
||||
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:
|
||||
region = random.choice(["south", "north"])
|
||||
await database.register_arcade(interaction.guild.id, interaction.guild.name, region)
|
||||
await Snowball.register_guild(interaction.guild.id, interaction.guild.name, region)
|
||||
except Exception as e:
|
||||
print(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)
|
||||
|
||||
class Recommanded(View):
|
||||
def __init__(self, *args, **kwargs):
|
||||
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(os.getenv("KOREANBOT_TOKEN")).get_bot_vote(int(interaction.user.id), interaction.guild.me.id)
|
||||
if data["data"]["voted"] == True:
|
||||
if database.
|
||||
await database.insert_guild_art_point(interaction.guild.id, 5)
|
||||
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=self)
|
||||
|
@ -1,374 +1,392 @@
|
||||
import wavelink
|
||||
import typing
|
||||
import psutil
|
||||
from typing import Any, Optional
|
||||
from discord import Embed, Colour, Embed, Member, Guild
|
||||
from discord.types.embed import EmbedType
|
||||
from datetime import datetime
|
||||
from korcen import korcen
|
||||
|
||||
|
||||
start_time = datetime.now()
|
||||
|
||||
class ChristmasEmbed(Embed):
|
||||
def __init__(self, *,
|
||||
color: int | Colour | None = 0xf4f9ff,
|
||||
title: Any | None = None,
|
||||
type: EmbedType = "rich",
|
||||
url: Any | None = None,
|
||||
description: Any | None = None,
|
||||
timestamp: datetime | None = None,
|
||||
):
|
||||
super().__init__(
|
||||
color=color,
|
||||
title=title,
|
||||
type=type,
|
||||
url=url,
|
||||
description=description,
|
||||
timestamp=timestamp,
|
||||
)
|
||||
|
||||
def set_footer(self, *, text: Any | None = "크돌이⛄", icon_url: Any | None = "https://discord.com/assets/6dbfff5aae6b1de2b83f.svg") -> None:
|
||||
super().set_footer(text=text)
|
||||
|
||||
class Default_Embed:
|
||||
|
||||
@staticmethod
|
||||
def default_join_embed():
|
||||
embed = ChristmasEmbed(title="🎉 크돌이를 추가해주셔서 감사해요!", description="봇을 사용하기 전에 이 서버의 관리자라면 다음의 절차를 따라주세요!")
|
||||
embed.add_field(name="1. 약관 동의", value="다음의 약관을 읽고 ``/서버 가입``명령어를 실행해주세요", inline=False)
|
||||
embed.add_field(name="1.1 약관", value="크돌이는 음악 재생과 명령어 전송을 위해 사용자가 쓴 커맨드를 확인할수 있어요, 또한 그림생성은 어떤 결과물이 나오든 크돌이는 책임지지 않아요!")
|
||||
embed.add_field(name="2. 설정", value="``/설정`` 명령어를 통해 크돌이의 여러 기능을 설정할수 있어요!", inline=False)
|
||||
embed.add_field(name="3. 도움말", value="``/도움말`` 명령어를 통해 크돌이의 명령어를 확인할 수 있어요!", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
|
||||
@staticmethod
|
||||
def register_sucess():
|
||||
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 already_register():
|
||||
embed = ChristmasEmbed(title="❌ 가입 실패!", description="이미 가입된 서버에요!")
|
||||
embed.add_field(name="안내", value="이미 가입된 서버에요!", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def cooldown(sec):
|
||||
return "이 명령어는 " + f"``{round(sec, 2)}``" + "초 뒤에 다시 사용할 수 있어요!"
|
||||
|
||||
@staticmethod
|
||||
def leave_sucess():
|
||||
embed = ChristmasEmbed(title="🎉 탈퇴 성공!", description="서버에서 탈퇴했어요!")
|
||||
embed.add_field(name="안내", value="크돌이를 이용해주셔서 감사해요!", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def help():
|
||||
embed = ChristmasEmbed(title="🎉 크돌이 도움말", description="크리스마스를 즐겨보세요!")
|
||||
embed.add_field(name="``/도움말``", value="크돌이의 도움말을 확인해요!", inline=False)
|
||||
embed.add_field(name="``/서버가입``", value="이 서버에 크돌이를 가입해요!", inline=False)
|
||||
embed.add_field(name="``/봇정보``", value="크돌이의 정보를 확인해요!", inline=False)
|
||||
embed.add_field(name="**편지**", value="``/편지 보내기 (유저)``: 유저에게 편지를 보내요!\n``/편지 확인``: 받은 편지를 확인해요!", inline=False)
|
||||
embed.add_field(name="**그림**", value="``/그림 생성``: 크돌이가 그림을 그려줘요!\n``/그림 분석``: 그림을 분석해요!", inline=False)
|
||||
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) -> Embed:
|
||||
current_time = datetime.now()
|
||||
uptime = current_time - start_time
|
||||
uptime = str(uptime).split(".")[0]
|
||||
"""
|
||||
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.3.0\n가동시간: {str(uptime)}\n개발자: RunaLab,PvPConnect", inline=True)
|
||||
orin = psutil.virtual_memory().used
|
||||
orin = orin / 1024 / 1024 / 1024
|
||||
if gpuserver == None or gpuserver["status"] == "offline":
|
||||
embed.add_field(name="**봇 자원**", value=f"GPU서버1 메모리 사용량: **오류**\nGPU서버1 CUDA 메모리 사용량: **오류**\nGPU서버1 메모리 오류 횟수: **오류**\n 현재 샤드 메모리 사용량:{round(orin)}GB", inline=False)
|
||||
else:
|
||||
mem_usage = gpuserver["system_memory_usage"]
|
||||
cuda_memory_usage = gpuserver["cuda_memory_usage"]
|
||||
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)
|
||||
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
|
||||
|
||||
class Mail_Embed:
|
||||
|
||||
@staticmethod
|
||||
def mail_confirm(title: str, description: str, receive_user: Member) -> Embed:
|
||||
embed = ChristmasEmbed(title="⚠️ 전송전 확인", description="편지를 정말로 전송하시겠습니까?")
|
||||
embed.add_field(name="⚠️ 주의사항 ⚠️", value="편지는 한 번 전송하면 한번의 수정 기회 이후에는 취소할 수 없어요!\n 내용을 잘 읽고 ``전송``버튼을 눌러주세요!", inline=False)
|
||||
embed.add_field(name="받는이", value=f"{receive_user.mention}", inline=False)
|
||||
embed.add_field(name="제목", value=title, inline=False)
|
||||
embed.add_field(name="내용", value=description, inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def mail_confirm_edit(title: str, description: str, receive_user: Member) -> Embed:
|
||||
embed = ChristmasEmbed(title="⚠️ 수정전 확인", description="편지를 정말로 수정하시겠습니까?")
|
||||
embed.add_field(name="⚠️ 주의사항 ⚠️", value="이번에 편지를 수정하면 다시는 수정할 수 없게 되요!\n 내용을 잘 읽고 ``전송``버튼을 눌러주세요!", inline=False)
|
||||
embed.add_field(name="받는이", value=f"{receive_user.mention}", inline=False)
|
||||
embed.add_field(name="제목", value=title, inline=False)
|
||||
embed.add_field(name="내용", value=description, inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def mail_cant_edit():
|
||||
embed = ChristmasEmbed(title="❌ 편지 수정 실패!", description="편지 수정에 실패했어요!")
|
||||
embed.add_field(name="안내", value="편지는 한 번 전송하면 한번의 수정 기회 이후에는 취소하거나 수정 할 수 없어요!", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
|
||||
@staticmethod
|
||||
def mail_sended(receive_user: Member) -> Embed:
|
||||
embed = ChristmasEmbed(title="✅ 전송완료!", description="편지 전송을 완료했어요!")
|
||||
embed.add_field(name="안내", value="보낸 편지는 2023년 12월 25일부터 열람 가능해요!", inline=False)
|
||||
embed.add_field(name="받는이", value=f"{receive_user.mention}", inline=False)
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def mail_edit_sended(receive_user: Member) -> Embed:
|
||||
embed = ChristmasEmbed(title="✅ 수정완료!", description="편지 수정을 완료했어요!")
|
||||
embed.add_field(name="안내", value="수정된 편지는 2023년 12월 25일부터 열람 가능해요!", inline=False)
|
||||
embed.add_field(name="받는이", value=f"{receive_user.mention}", inline=False)
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def mail_notfound() -> Embed:
|
||||
embed = ChristmasEmbed(title="❌ 편지 없음!", description="편지가 없어요!")
|
||||
embed.add_field(name="안내", value="받은 편지가 없어요!", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def mail_already_sended() -> Embed:
|
||||
embed = ChristmasEmbed(title="❌ 편지 전송 실패!", description="이미 편지를 보냈어요!")
|
||||
embed.add_field(name="안내", value="이미 편지를 보냈어요!", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def mail_page(data) -> Embed:
|
||||
embed = ChristmasEmbed(title="📨 편지", description="편지를 확인해보세요!(욕설등 민감한 내용이 포함된 내용은 자동으로 스포일러처리되요!)")
|
||||
username = data["username"]
|
||||
userid = data["userid"]
|
||||
title = data["title"]
|
||||
description = data["content"]
|
||||
if korcen.check(title) == True:
|
||||
title = "||" + title + "||"
|
||||
if korcen.check(description) == True:
|
||||
description = "||" + description + "||"
|
||||
embed.add_field(name="보낸이", value=f"{username}({userid})", inline=False)
|
||||
embed.add_field(name="제목", value=title, inline=False)
|
||||
embed.add_field(name="내용", value=description, inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
class Aiart_Embed:
|
||||
|
||||
@staticmethod
|
||||
def failed_generate() -> Embed:
|
||||
embed = ChristmasEmbed(title="❌ 그림 생성 실패!", description="그림 생성에 실패했어요!")
|
||||
embed.add_field(name="안내", value="그림 생성에 실패했어요! 이 현상이 지속된다면 서비스 서버에 문의해주세요!", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def sucess_generate(prompt: str, remove: str) -> Embed:
|
||||
embed = ChristmasEmbed(title="✅ 그림 생성 성공!", description="그림 생성에 성공했어요!")
|
||||
embed.add_field(name="프롬포트", value=prompt, inline=False)
|
||||
embed.add_field(name="지운 프롬포트", value=remove, inline=False)
|
||||
embed.set_image(url="attachment://image.png")
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def generating() -> Embed:
|
||||
embed = ChristmasEmbed(title="그림 생성중...", description="그림을 생성하는 중이에요!")
|
||||
embed.add_field(name="안내", value="그림 생성에는 최대 2분이 소요될 수 있어요!(크돌이는 돈이 없어요...)", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def evalate(tags, rating) -> ChristmasEmbed:
|
||||
if tags == None:
|
||||
embed = ChristmasEmbed(name="**오류**", value="그림 분석에 실패했어요. 나중에 다시 시도해주세요", inline=False)
|
||||
return embed
|
||||
else:
|
||||
embed = ChristmasEmbed(title="**그림 분석 완료**", description="그림 분석이 완료되었어요!")
|
||||
embed.set_image(url="attachment://image.png")
|
||||
embed.add_field(name="**등급**", value=f"{rating}", inline=False)
|
||||
texts = ""
|
||||
for tag, score in tags:
|
||||
percentage = score * 100
|
||||
texts = texts + f"{tag} : {percentage:.1f}%\n"
|
||||
embed.add_field(name="**분석된 요소**", value=f"{texts}", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def gen_nsfw():
|
||||
embed = ChristmasEmbed(title="❌ 그림 생성 실패!", description="그림 생성에 실패했어요!")
|
||||
embed.add_field(name="안내", value="NSFW 채널이 아닌경우 NSFW 그림을 생성을 할수 없어요!", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
class Music_Embed:
|
||||
|
||||
@staticmethod
|
||||
def music_notenable():
|
||||
embed = ChristmasEmbed(title="❌ 음악 재생 실패!", description="음악 재생에 실패했어요!")
|
||||
embed.add_field(name="안내", value="이 서버에서는 음악을 재생할수 없어요! \n만약 서버의 관리자라면 ``/설정`` 명령어로 음악 기능을 다시 활성화사킬수 있어요!", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def author_not_voice():
|
||||
embed = ChristmasEmbed(title="❌ 음악 재생 실패!", description="음악 재생에 실패했어요!")
|
||||
embed.add_field(name="안내", value="음악을 재생하려면 음성채널에 들어가야 해요!", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def author_diffrent_voice():
|
||||
embed = ChristmasEmbed(title="❌ 음악 재생 실패!", description="음악 재생에 실패했어요!")
|
||||
embed.add_field(name="안내", value="이미 다른 채널에 접속되어있어요!", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@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
|
||||
|
||||
@staticmethod
|
||||
def music_setting(value: bool, settings: str):
|
||||
embed = ChristmasEmbed(title="✅ 음악 설정 변경!", description="음악 설정을 변경했어요!")
|
||||
if settings == "music":
|
||||
if value == True:
|
||||
embed.add_field(name="안내", value="이제 이 서버에서 음악을 재생할수 있어요!", inline=False)
|
||||
else:
|
||||
embed.add_field(name="안내", value="이제 이 서버에서 음악을 재생할수 없어요!", inline=False)
|
||||
elif settings == "admin_run":
|
||||
if value == False:
|
||||
embed.add_field(name="안내", value="이제 이 서버에서 관리자를 제외한 사람들도 음악을 재생할수 있어요!", inline=False)
|
||||
else:
|
||||
embed.add_field(name="안내", value="이제 이 서버에서 관리자를 제외한 사람은 음악을 재생할수 없어요!", inline=False)
|
||||
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)
|
||||
|
||||
|
||||
@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
|
||||
|
||||
import wavelink
|
||||
import typing
|
||||
import psutil
|
||||
from typing import Any, Optional
|
||||
from discord import Embed, Colour, Embed, Member, Guild
|
||||
from discord.types.embed import EmbedType
|
||||
from datetime import datetime
|
||||
from korcen import korcen
|
||||
|
||||
start_time = datetime.now()
|
||||
|
||||
|
||||
class RunaEmbed(Embed):
|
||||
def __init__(self, *,
|
||||
color: int | Colour | None = 0xf4f9ff,
|
||||
title: Any | None = None,
|
||||
type: EmbedType = "rich",
|
||||
url: Any | None = None,
|
||||
description: Any | None = None,
|
||||
timestamp: datetime | None = None,
|
||||
):
|
||||
super().__init__(
|
||||
color=color,
|
||||
title=title,
|
||||
type=type,
|
||||
url=url,
|
||||
description=description,
|
||||
timestamp=timestamp,
|
||||
)
|
||||
|
||||
def set_footer(self, *, text: Any | None = "루나",
|
||||
icon_url: Any | None = "https://discord.com/assets/6dbfff5aae6b1de2b83f.svg") -> None:
|
||||
super().set_footer(text=text)
|
||||
|
||||
|
||||
class Default_Embed:
|
||||
|
||||
@staticmethod
|
||||
def default_join_embed():
|
||||
embed = ChristmasEmbed(title="🎉 크돌이를 추가해주셔서 감사해요!", description="봇을 사용하기 전에 이 서버의 관리자라면 다음의 절차를 따라주세요!")
|
||||
embed.add_field(name="1. 약관 동의", value="다음의 약관을 읽고 ``/서버 가입``명령어를 실행해주세요", inline=False)
|
||||
embed.add_field(name="1.1 약관",
|
||||
value="크돌이는 음악 재생과 명령어 전송을 위해 사용자가 쓴 커맨드를 확인할수 있어요, 또한 그림생성은 어떤 결과물이 나오든 크돌이는 책임지지 않아요!")
|
||||
embed.add_field(name="2. 설정", value="``/설정`` 명령어를 통해 크돌이의 여러 기능을 설정할수 있어요!", inline=False)
|
||||
embed.add_field(name="3. 도움말", value="``/도움말`` 명령어를 통해 크돌이의 명령어를 확인할 수 있어요!", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def register_sucess():
|
||||
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 already_register():
|
||||
embed = ChristmasEmbed(title="❌ 가입 실패!", description="이미 가입된 서버에요!")
|
||||
embed.add_field(name="안내", value="이미 가입된 서버에요!", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def cooldown(sec):
|
||||
return "이 명령어는 " + f"``{round(sec, 2)}``" + "초 뒤에 다시 사용할 수 있어요!"
|
||||
|
||||
@staticmethod
|
||||
def leave_sucess():
|
||||
embed = ChristmasEmbed(title="🎉 탈퇴 성공!", description="서버에서 탈퇴했어요!")
|
||||
embed.add_field(name="안내", value="크돌이를 이용해주셔서 감사해요!", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def help():
|
||||
embed = ChristmasEmbed(title="🎉 크돌이 도움말", description="크리스마스를 즐겨보세요!")
|
||||
embed.add_field(name="``/도움말``", value="크돌이의 도움말을 확인해요!", inline=False)
|
||||
embed.add_field(name="``/서버가입``", value="이 서버에 크돌이를 가입해요!", inline=False)
|
||||
embed.add_field(name="``/봇정보``", value="크돌이의 정보를 확인해요!", inline=False)
|
||||
embed.add_field(name="**편지**", value="``/편지 보내기 (유저)``: 유저에게 편지를 보내요!\n``/편지 확인``: 받은 편지를 확인해요!", inline=False)
|
||||
embed.add_field(name="**그림**", value="``/그림 생성``: 크돌이가 그림을 그려줘요!\n``/그림 분석``: 그림을 분석해요!", inline=False)
|
||||
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) -> Embed:
|
||||
current_time = datetime.now()
|
||||
uptime = current_time - start_time
|
||||
uptime = str(uptime).split(".")[0]
|
||||
"""
|
||||
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.3.0\n가동시간: {str(uptime)}\n개발자: RunaLab,PvPConnect",
|
||||
inline=True)
|
||||
orin = psutil.virtual_memory().used
|
||||
orin = orin / 1024 / 1024 / 1024
|
||||
if gpuserver == None or gpuserver["status"] == "offline":
|
||||
embed.add_field(name="**봇 자원**",
|
||||
value=f"GPU서버1 메모리 사용량: **오류**\nGPU서버1 CUDA 메모리 사용량: **오류**\nGPU서버1 메모리 오류 횟수: **오류**\n 현재 샤드 메모리 사용량:{round(orin)}GB",
|
||||
inline=False)
|
||||
else:
|
||||
mem_usage = gpuserver["system_memory_usage"]
|
||||
cuda_memory_usage = gpuserver["cuda_memory_usage"]
|
||||
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)
|
||||
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
|
||||
|
||||
|
||||
class Mail_Embed:
|
||||
|
||||
@staticmethod
|
||||
def mail_confirm(title: str, description: str, receive_user: Member) -> Embed:
|
||||
embed = ChristmasEmbed(title="⚠️ 전송전 확인", description="편지를 정말로 전송하시겠습니까?")
|
||||
embed.add_field(name="⚠️ 주의사항 ⚠️", value="편지는 한 번 전송하면 한번의 수정 기회 이후에는 취소할 수 없어요!\n 내용을 잘 읽고 ``전송``버튼을 눌러주세요!",
|
||||
inline=False)
|
||||
embed.add_field(name="받는이", value=f"{receive_user.mention}", inline=False)
|
||||
embed.add_field(name="제목", value=title, inline=False)
|
||||
embed.add_field(name="내용", value=description, inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def mail_confirm_edit(title: str, description: str, receive_user: Member) -> Embed:
|
||||
embed = ChristmasEmbed(title="⚠️ 수정전 확인", description="편지를 정말로 수정하시겠습니까?")
|
||||
embed.add_field(name="⚠️ 주의사항 ⚠️", value="이번에 편지를 수정하면 다시는 수정할 수 없게 되요!\n 내용을 잘 읽고 ``전송``버튼을 눌러주세요!",
|
||||
inline=False)
|
||||
embed.add_field(name="받는이", value=f"{receive_user.mention}", inline=False)
|
||||
embed.add_field(name="제목", value=title, inline=False)
|
||||
embed.add_field(name="내용", value=description, inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def mail_cant_edit():
|
||||
embed = ChristmasEmbed(title="❌ 편지 수정 실패!", description="편지 수정에 실패했어요!")
|
||||
embed.add_field(name="안내", value="편지는 한 번 전송하면 한번의 수정 기회 이후에는 취소하거나 수정 할 수 없어요!", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def mail_sended(receive_user: Member) -> Embed:
|
||||
embed = ChristmasEmbed(title="✅ 전송완료!", description="편지 전송을 완료했어요!")
|
||||
embed.add_field(name="안내", value="보낸 편지는 2023년 12월 25일부터 열람 가능해요!", inline=False)
|
||||
embed.add_field(name="받는이", value=f"{receive_user.mention}", inline=False)
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def mail_edit_sended(receive_user: Member) -> Embed:
|
||||
embed = ChristmasEmbed(title="✅ 수정완료!", description="편지 수정을 완료했어요!")
|
||||
embed.add_field(name="안내", value="수정된 편지는 2023년 12월 25일부터 열람 가능해요!", inline=False)
|
||||
embed.add_field(name="받는이", value=f"{receive_user.mention}", inline=False)
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def mail_notfound() -> Embed:
|
||||
embed = ChristmasEmbed(title="❌ 편지 없음!", description="편지가 없어요!")
|
||||
embed.add_field(name="안내", value="받은 편지가 없어요!", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def mail_already_sended() -> Embed:
|
||||
embed = ChristmasEmbed(title="❌ 편지 전송 실패!", description="이미 편지를 보냈어요!")
|
||||
embed.add_field(name="안내", value="이미 편지를 보냈어요!", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def mail_page(data) -> Embed:
|
||||
embed = ChristmasEmbed(title="📨 편지", description="편지를 확인해보세요!(욕설등 민감한 내용이 포함된 내용은 자동으로 스포일러처리되요!)")
|
||||
username = data["username"]
|
||||
userid = data["userid"]
|
||||
title = data["title"]
|
||||
description = data["content"]
|
||||
if korcen.check(title) == True:
|
||||
title = "||" + title + "||"
|
||||
if korcen.check(description) == True:
|
||||
description = "||" + description + "||"
|
||||
embed.add_field(name="보낸이", value=f"{username}({userid})", inline=False)
|
||||
embed.add_field(name="제목", value=title, inline=False)
|
||||
embed.add_field(name="내용", value=description, inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
|
||||
class Aiart_Embed:
|
||||
|
||||
@staticmethod
|
||||
def failed_generate() -> Embed:
|
||||
embed = ChristmasEmbed(title="❌ 그림 생성 실패!", description="그림 생성에 실패했어요!")
|
||||
embed.add_field(name="안내", value="그림 생성에 실패했어요! 이 현상이 지속된다면 서비스 서버에 문의해주세요!", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def sucess_generate(prompt: str, remove: str) -> Embed:
|
||||
embed = ChristmasEmbed(title="✅ 그림 생성 성공!", description="그림 생성에 성공했어요!")
|
||||
embed.add_field(name="프롬포트", value=prompt, inline=False)
|
||||
embed.add_field(name="지운 프롬포트", value=remove, inline=False)
|
||||
embed.set_image(url="attachment://image.png")
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def generating() -> Embed:
|
||||
embed = ChristmasEmbed(title="그림 생성중...", description="그림을 생성하는 중이에요!")
|
||||
embed.add_field(name="안내", value="그림 생성에는 최대 2분이 소요될 수 있어요!(크돌이는 돈이 없어요...)", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def evalate(tags, rating) -> ChristmasEmbed:
|
||||
if tags == None:
|
||||
embed = ChristmasEmbed(name="**오류**", value="그림 분석에 실패했어요. 나중에 다시 시도해주세요", inline=False)
|
||||
return embed
|
||||
else:
|
||||
embed = ChristmasEmbed(title="**그림 분석 완료**", description="그림 분석이 완료되었어요!")
|
||||
embed.set_image(url="attachment://image.png")
|
||||
embed.add_field(name="**등급**", value=f"{rating}", inline=False)
|
||||
texts = ""
|
||||
for tag, score in tags:
|
||||
percentage = score * 100
|
||||
texts = texts + f"{tag} : {percentage:.1f}%\n"
|
||||
embed.add_field(name="**분석된 요소**", value=f"{texts}", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def gen_nsfw():
|
||||
embed = ChristmasEmbed(title="❌ 그림 생성 실패!", description="그림 생성에 실패했어요!")
|
||||
embed.add_field(name="안내", value="NSFW 채널이 아닌경우 NSFW 그림을 생성을 할수 없어요!", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
|
||||
class Music_Embed:
|
||||
|
||||
@staticmethod
|
||||
def music_notenable():
|
||||
embed = ChristmasEmbed(title="❌ 음악 재생 실패!", description="음악 재생에 실패했어요!")
|
||||
embed.add_field(name="안내", value="이 서버에서는 음악을 재생할수 없어요! \n만약 서버의 관리자라면 ``/설정`` 명령어로 음악 기능을 다시 활성화사킬수 있어요!",
|
||||
inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def author_not_voice():
|
||||
embed = ChristmasEmbed(title="❌ 음악 재생 실패!", description="음악 재생에 실패했어요!")
|
||||
embed.add_field(name="안내", value="음악을 재생하려면 음성채널에 들어가야 해요!", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@staticmethod
|
||||
def author_diffrent_voice():
|
||||
embed = ChristmasEmbed(title="❌ 음악 재생 실패!", description="음악 재생에 실패했어요!")
|
||||
embed.add_field(name="안내", value="이미 다른 채널에 접속되어있어요!", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@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
|
||||
|
||||
@staticmethod
|
||||
def music_setting(value: bool, settings: str):
|
||||
embed = ChristmasEmbed(title="✅ 음악 설정 변경!", description="음악 설정을 변경했어요!")
|
||||
if settings == "music":
|
||||
if value == True:
|
||||
embed.add_field(name="안내", value="이제 이 서버에서 음악을 재생할수 있어요!", inline=False)
|
||||
else:
|
||||
embed.add_field(name="안내", value="이제 이 서버에서 음악을 재생할수 없어요!", inline=False)
|
||||
elif settings == "admin_run":
|
||||
if value == False:
|
||||
embed.add_field(name="안내", value="이제 이 서버에서 관리자를 제외한 사람들도 음악을 재생할수 있어요!", inline=False)
|
||||
else:
|
||||
embed.add_field(name="안내", value="이제 이 서버에서 관리자를 제외한 사람은 음악을 재생할수 없어요!", inline=False)
|
||||
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)
|
||||
|
||||
@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
|
@ -1,86 +1,85 @@
|
||||
import re
|
||||
import base64
|
||||
from discord import InputTextStyle, Interaction, Member
|
||||
from discord.ui import Modal, InputText
|
||||
|
||||
#from Christmas.Module import check_curse
|
||||
|
||||
from Christmas.UI.Embed import Mail_Embed, Aiart_Embed
|
||||
from Christmas.UI.Buttons import Mail_Confirm_Button
|
||||
from Christmas.Module import process_prompt, post_gpu_server, base64_to_image
|
||||
from Christmas.config import ChristmasConfig
|
||||
from Christmas.Tagging import Tagging
|
||||
from Christmas.Cogs.Event import model
|
||||
|
||||
|
||||
class Send_Mail_Modal(Modal):
|
||||
def __init__(self, reciveuser: Member, editmode: bool, *args, **kwargs):
|
||||
self.reciveuser = reciveuser
|
||||
self.editmode = editmode
|
||||
|
||||
super().__init__(timeout=None, *args, **kwargs)
|
||||
|
||||
self.add_item(InputText(label="제목", placeholder="제목을 입력해주세요.", style=InputTextStyle.short, required=True, custom_id="mail_title"))
|
||||
self.add_item(InputText(label="내용", placeholder="내용을 입력해주세요.", style=InputTextStyle.long, required=True, custom_id="mail_content"))
|
||||
|
||||
|
||||
async def callback(self, interaction: Interaction):
|
||||
if self.editmode == False:
|
||||
await interaction.response.send_message(embed=Mail_Embed.mail_confirm(self.children[0].value, self.children[1].value, self.reciveuser), view=Mail_Confirm_Button(recive_user=self.reciveuser, title=self.children[0].value, description=self.children[1].value, editmode=False),ephemeral=True)
|
||||
else:
|
||||
await interaction.response.send_message(embed=Mail_Embed.mail_confirm_edit(self.children[0].value, self.children[1].value, self.reciveuser), view=Mail_Confirm_Button(recive_user=self.reciveuser, title=self.children[0].value, description=self.children[1].value, editmode=True),ephemeral=True)
|
||||
|
||||
class Aiart(Modal):
|
||||
def __init__(self, show: bool, allownsfw: bool, res: list, style1: float, style2: float, afterprocess: bool, *args, **kwargs):
|
||||
self.show = show
|
||||
self.allownsfw = allownsfw
|
||||
self.res = res
|
||||
self.style1 = style1
|
||||
self.style2 = style2
|
||||
self.config = ChristmasConfig()
|
||||
self.afterprocess = afterprocess
|
||||
super().__init__(timeout=None, *args, **kwargs)
|
||||
|
||||
self.add_item(InputText(label="그람에 포함시키고 싶은 태그를 입력해주세요.", placeholder="한글도 입력 가능해요! 태그는 문장형도 알아듣지만 ,를 통해 구별해요", style=InputTextStyle.long, required=True, custom_id="aiart_tag"))
|
||||
self.add_item(InputText(label="그림에서 제거하고 싶은 태그를 입력해주세요.", placeholder="한글도 입력 가능해요! 태그는 문장형도 알아듣지만 ,를 통해 구별해요", style=InputTextStyle.long, required=False, custom_id="aiart_remove_tag"))
|
||||
|
||||
async def callback(self, interaction: Interaction):
|
||||
prompt = self.children[0].value
|
||||
remove = self.children[1].value
|
||||
#255자까지 자름
|
||||
original_prompt = prompt
|
||||
original_remove = remove
|
||||
if len(prompt) > 255:
|
||||
original_prompt = original_prompt[:255]
|
||||
if len(remove) > 255:
|
||||
original_remove = original_remove[:255]
|
||||
await interaction.response.send_message(embed=Aiart_Embed.generating(), ephemeral=self.show)
|
||||
avatars = None
|
||||
if re.search(r"\{[0-9]{18}\}", prompt):
|
||||
user_id = re.search(r"\{[0-9]{18}\}", prompt).group()[1:-1]
|
||||
user = await interaction.guild.fetch_member(int(user_id))
|
||||
if user == None:
|
||||
avatars = None
|
||||
else:
|
||||
avatars = user.avatar
|
||||
config = ChristmasConfig()
|
||||
#prompt: str, remove: str, res: list, isnsfw: bool, style1: float, style2: float, afterprocess: float
|
||||
payload = await process_prompt(prompt, remove, self.res, self.allownsfw, self.style1, self.style2, self.afterprocess, avatars)
|
||||
config = ChristmasConfig()
|
||||
result = await post_gpu_server(f"{config.AI}/sdapi/v1/txt2img", payload)
|
||||
if result["status"] != True:
|
||||
return await interaction.edit_original_response(embed=Aiart_Embed.failed_generate())
|
||||
if self.allownsfw is False:
|
||||
tag = Tagging(model=model)
|
||||
result2 = await tag.predict(base64.b64decode(result["data"]["images"][0]))
|
||||
if result2 is None:
|
||||
return await interaction.edit_original_response(embed=Aiart_Embed.failed_generate())
|
||||
rating = max(result2[2], key=result2[2].get)
|
||||
if rating == "explicit" or rating == "questionable":
|
||||
return await interaction.edit_original_response(embed=Aiart_Embed.gen_nsfw())
|
||||
try:
|
||||
attachment = await base64_to_image(result["data"]["images"][0])
|
||||
except Exception as e:
|
||||
return await interaction.edit_original_response(embed=Aiart_Embed.failed_generate())
|
||||
await interaction.edit_original_response(embed=Aiart_Embed.sucess_generate(original_prompt,original_remove), file=attachment)
|
||||
import re
|
||||
import os
|
||||
import random
|
||||
import base64
|
||||
from discord import InputTextStyle, Interaction, Member
|
||||
from discord.ui import Modal, InputText
|
||||
|
||||
from dotenv import load_dotenv, find_dotenv
|
||||
#from RUNA.Module import check_curse
|
||||
|
||||
from RUNA.UI.Embed import Mail_Embed, Aiart_Embed
|
||||
from RUNA.UI.Buttons import Mail_Confirm_Button
|
||||
from RUNA.Module import process_prompt, post_gpu_server, base64_to_image
|
||||
from RUNA.Tagging import Tagging
|
||||
from RUNA.Cogs.Event import model
|
||||
|
||||
|
||||
class Send_Mail_Modal(Modal):
|
||||
def __init__(self, reciveuser: Member, editmode: bool, *args, **kwargs):
|
||||
self.reciveuser = reciveuser
|
||||
self.editmode = editmode
|
||||
|
||||
super().__init__(timeout=None, *args, **kwargs)
|
||||
|
||||
self.add_item(InputText(label="제목", placeholder="제목을 입력해주세요.", style=InputTextStyle.short, required=True, custom_id="mail_title"))
|
||||
self.add_item(InputText(label="내용", placeholder="내용을 입력해주세요.", style=InputTextStyle.long, required=True, custom_id="mail_content"))
|
||||
|
||||
|
||||
async def callback(self, interaction: Interaction):
|
||||
if self.editmode == False:
|
||||
await interaction.response.send_message(embed=Mail_Embed.mail_confirm(self.children[0].value, self.children[1].value, self.reciveuser), view=Mail_Confirm_Button(recive_user=self.reciveuser, title=self.children[0].value, description=self.children[1].value, editmode=False),ephemeral=True)
|
||||
else:
|
||||
await interaction.response.send_message(embed=Mail_Embed.mail_confirm_edit(self.children[0].value, self.children[1].value, self.reciveuser), view=Mail_Confirm_Button(recive_user=self.reciveuser, title=self.children[0].value, description=self.children[1].value, editmode=True),ephemeral=True)
|
||||
|
||||
class Aiart(Modal):
|
||||
def __init__(self, show: bool, allownsfw: bool, res: list, style1: float, style2: float, afterprocess: bool, *args, **kwargs):
|
||||
self.show = show
|
||||
self.allownsfw = allownsfw
|
||||
self.res = res
|
||||
self.style1 = style1
|
||||
self.style2 = style2
|
||||
self.afterprocess = afterprocess
|
||||
super().__init__(timeout=None, *args, **kwargs)
|
||||
|
||||
self.add_item(InputText(label="그람에 포함시키고 싶은 태그를 입력해주세요.", placeholder="한글도 입력 가능해요! 태그는 문장형도 알아듣지만 ,를 통해 구별해요", style=InputTextStyle.long, required=True, custom_id="aiart_tag"))
|
||||
self.add_item(InputText(label="그림에서 제거하고 싶은 태그를 입력해주세요.", placeholder="한글도 입력 가능해요! 태그는 문장형도 알아듣지만 ,를 통해 구별해요", style=InputTextStyle.long, required=False, custom_id="aiart_remove_tag"))
|
||||
|
||||
async def callback(self, interaction: Interaction):
|
||||
prompt = self.children[0].value
|
||||
remove = self.children[1].value
|
||||
#255자까지 자름
|
||||
original_prompt = prompt
|
||||
original_remove = remove
|
||||
if len(prompt) > 255:
|
||||
original_prompt = original_prompt[:255]
|
||||
if len(remove) > 255:
|
||||
original_remove = original_remove[:255]
|
||||
await interaction.response.send_message(embed=Aiart_Embed.generating(), ephemeral=self.show)
|
||||
avatars = None
|
||||
if re.search(r"\{[0-9]{18}\}", prompt):
|
||||
user_id = re.search(r"\{[0-9]{18}\}", prompt).group()[1:-1]
|
||||
user = await interaction.guild.fetch_member(int(user_id))
|
||||
if user == None:
|
||||
avatars = None
|
||||
else:
|
||||
avatars = user.avatar
|
||||
#prompt: str, remove: str, res: list, isnsfw: bool, style1: float, style2: float, afterprocess: float
|
||||
payload = await process_prompt(prompt, remove, self.res, self.allownsfw, self.style1, self.style2, self.afterprocess, avatars)
|
||||
result = await post_gpu_server(f"{random.choices(list(os.getenv("AI_GATEWAT")))}/sdapi/v1/txt2img", payload)
|
||||
if result["status"] != True:
|
||||
return await interaction.edit_original_response(embed=Aiart_Embed.failed_generate())
|
||||
if self.allownsfw is False:
|
||||
tag = Tagging()
|
||||
result2 = await tag.predict(base64.b64decode(result["data"]["images"][0]))
|
||||
if result2 is None:
|
||||
return await interaction.edit_original_response(embed=Aiart_Embed.failed_generate())
|
||||
rating = max(result2[2], key=result2[2].get)
|
||||
if rating == "explicit" or rating == "questionable":
|
||||
return await interaction.edit_original_response(embed=Aiart_Embed.gen_nsfw())
|
||||
try:
|
||||
attachment = await base64_to_image(result["data"]["images"][0])
|
||||
except Exception as e:
|
||||
return await interaction.edit_original_response(embed=Aiart_Embed.failed_generate())
|
||||
await interaction.edit_original_response(embed=Aiart_Embed.sucess_generate(original_prompt,original_remove), file=attachment)
|
||||
|
@ -1,62 +1,62 @@
|
||||
from functools import cached_property
|
||||
from typing import Any, Dict, List, Union
|
||||
|
||||
from discord.ui import button
|
||||
|
||||
from discord.enums import ButtonStyle
|
||||
from discord.interactions import Interaction
|
||||
from discord.ui import Button, View
|
||||
|
||||
from Christmas.UI.Embed import ChristmasEmbed
|
||||
|
||||
class Mail_Paginator(View):
|
||||
def __init__(
|
||||
self,
|
||||
senduser: int,
|
||||
embeds: list[ChristmasEmbed],
|
||||
timeout: int = 180,
|
||||
|
||||
):
|
||||
super().__init__(timeout=timeout)
|
||||
self.embeds = embeds
|
||||
self.index = 0
|
||||
self.senduser = senduser
|
||||
self.selected = False
|
||||
|
||||
@cached_property
|
||||
def total(self) -> int:
|
||||
return len(self.embeds)
|
||||
|
||||
async def interaction_check(self, interaction: Interaction) -> bool:
|
||||
if user := interaction.user:
|
||||
if user.id == self.senduser.id:
|
||||
return True
|
||||
|
||||
await interaction.response.send_message(
|
||||
"명령어 실행자만 상호작용이 가능합니다.", ephemeral=True
|
||||
)
|
||||
|
||||
return False
|
||||
|
||||
@button(label="이전", style=ButtonStyle.primary, emoji="◀")
|
||||
async def prev(self, button, interaction: Interaction) -> None:
|
||||
self.index -= 1
|
||||
|
||||
if self.index < 0:
|
||||
self.index = self.total - 1
|
||||
|
||||
await interaction.response.edit_message(embed=self.embeds[self.index])
|
||||
|
||||
@button(label="다음", style=ButtonStyle.primary, emoji="▶️")
|
||||
async def next(self, button, interaction: Interaction) -> None:
|
||||
self.index += 1
|
||||
|
||||
if self.index >= self.total:
|
||||
self.index = 0
|
||||
|
||||
await interaction.response.edit_message(embed=self.embeds[self.index])
|
||||
|
||||
@button(label="닫기", style=ButtonStyle.danger, emoji="✖️")
|
||||
async def close(self, button, interaction: Interaction) -> None:
|
||||
await interaction.response.defer()
|
||||
from functools import cached_property
|
||||
from typing import Any, Dict, List, Union
|
||||
|
||||
from discord.ui import button
|
||||
|
||||
from discord.enums import ButtonStyle
|
||||
from discord.interactions import Interaction
|
||||
from discord.ui import Button, View
|
||||
|
||||
from RUNA.UI.Embed import ChristmasEmbed
|
||||
|
||||
class Mail_Paginator(View):
|
||||
def __init__(
|
||||
self,
|
||||
senduser: int,
|
||||
embeds: list[ChristmasEmbed],
|
||||
timeout: int = 180,
|
||||
|
||||
):
|
||||
super().__init__(timeout=timeout)
|
||||
self.embeds = embeds
|
||||
self.index = 0
|
||||
self.senduser = senduser
|
||||
self.selected = False
|
||||
|
||||
@cached_property
|
||||
def total(self) -> int:
|
||||
return len(self.embeds)
|
||||
|
||||
async def interaction_check(self, interaction: Interaction) -> bool:
|
||||
if user := interaction.user:
|
||||
if user.id == self.senduser.id:
|
||||
return True
|
||||
|
||||
await interaction.response.send_message(
|
||||
"명령어 실행자만 상호작용이 가능합니다.", ephemeral=True
|
||||
)
|
||||
|
||||
return False
|
||||
|
||||
@button(label="이전", style=ButtonStyle.primary, emoji="◀")
|
||||
async def prev(self, button, interaction: Interaction) -> None:
|
||||
self.index -= 1
|
||||
|
||||
if self.index < 0:
|
||||
self.index = self.total - 1
|
||||
|
||||
await interaction.response.edit_message(embed=self.embeds[self.index])
|
||||
|
||||
@button(label="다음", style=ButtonStyle.primary, emoji="▶️")
|
||||
async def next(self, button, interaction: Interaction) -> None:
|
||||
self.index += 1
|
||||
|
||||
if self.index >= self.total:
|
||||
self.index = 0
|
||||
|
||||
await interaction.response.edit_message(embed=self.embeds[self.index])
|
||||
|
||||
@button(label="닫기", style=ButtonStyle.danger, emoji="✖️")
|
||||
async def close(self, button, interaction: Interaction) -> None:
|
||||
await interaction.response.defer()
|
||||
self.stop()
|
@ -1,4 +1,4 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
24
RUNA/__main__.py
Normal file
24
RUNA/__main__.py
Normal file
@ -0,0 +1,24 @@
|
||||
import os
|
||||
|
||||
from typing import Any, cast
|
||||
from dotenv import find_dotenv, load_dotenv
|
||||
|
||||
from discord import AutoShardedBot, Intents
|
||||
from discord.ext import commands, tasks
|
||||
|
||||
from RUNA.discord import Runa, load_cogs, apply_uvloop, init_sentry_sdk
|
||||
from koreanbots.integrations.discord import DiscordpyKoreanbots
|
||||
|
||||
load_dotenv(find_dotenv())
|
||||
|
||||
if __name__ == "__main__":
|
||||
bot = Runa(
|
||||
command_prefix=commands.when_mentioned_or("r!"),
|
||||
case_insensitive=True,
|
||||
intents=Intents.default()
|
||||
)
|
||||
DiscordpyKoreanbots(bot, os.getenv("KOREANBOT_TOKEN"), run_task=True)
|
||||
load_cogs(bot)
|
||||
apply_uvloop()
|
||||
init_sentry_sdk(os.getenv("SENTRY_DSN"))
|
||||
bot.run()
|
55
RUNA/discord.py
Normal file
55
RUNA/discord.py
Normal file
@ -0,0 +1,55 @@
|
||||
import os
|
||||
import sentry_sdk
|
||||
|
||||
from sentry_sdk.integrations.asyncio import AsyncioIntegration
|
||||
from sentry_sdk.integrations.pymongo import PyMongoIntegration
|
||||
from sentry_sdk.integrations.aiohttp import AioHttpIntegration
|
||||
from sentry_sdk.integrations.loguru import LoguruIntegration
|
||||
|
||||
from typing import Any, cast
|
||||
from dotenv import load_dotenv, find_dotenv
|
||||
from discord import AutoShardedBot
|
||||
from discord.ext import commands, tasks
|
||||
|
||||
from RUNA.Modules.Logging import Logging
|
||||
|
||||
load_dotenv(find_dotenv())
|
||||
|
||||
|
||||
class Runa(AutoShardedBot):
|
||||
def __init__(self, *args: Any, **kwargs: Any):
|
||||
super().__init__(*args, **kwargs)
|
||||
# self.debug_guilds = [1090621667778244638,1015236495910649926,957142859629342790,1125370139165081612,1170310470503247993]
|
||||
|
||||
def run(self, *args: Any, **kwargs: Any) -> None:
|
||||
kwargs.update({"token": os.getenv("TOKEN")})
|
||||
super().run(*args, **kwargs)
|
||||
|
||||
|
||||
def load_cogs(bot: AutoShardedBot) -> None:
|
||||
for filename in os.listdir("RUNA/Cogs"):
|
||||
if filename.endswith(".py"):
|
||||
bot.load_extension(f"RUNA.Cogs.{filename[:-3]}")
|
||||
|
||||
|
||||
def apply_uvloop() -> None:
|
||||
try:
|
||||
import uvloop
|
||||
import asyncio
|
||||
except ImportError:
|
||||
pass
|
||||
else:
|
||||
uvloop.install()
|
||||
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
|
||||
|
||||
|
||||
def init_sentry_sdk(dsn: str) -> None:
|
||||
sentry_sdk.init(
|
||||
dsn=dsn,
|
||||
integrations=[
|
||||
AsyncioIntegration(),
|
||||
PyMongoIntegration(),
|
||||
AioHttpIntegration(),
|
||||
LoguruIntegration()
|
||||
]
|
||||
)
|
33
pyproject.toml
Normal file
33
pyproject.toml
Normal file
@ -0,0 +1,33 @@
|
||||
[tool.poetry]
|
||||
name = "runabot"
|
||||
version = "0.1.0"
|
||||
description = ""
|
||||
authors = ["tmddn3070 <tmddn3070@gmail.com>"]
|
||||
readme = "README.md"
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = "^3.12"
|
||||
py-cord = {extras = ["speed"], version = "^2.5.0"}
|
||||
uvloop = "^0.19.0"
|
||||
nanoid = "^2.0.0"
|
||||
pendulum = "^3.0.0"
|
||||
onnxruntime = "^1.17.1"
|
||||
psutil = "^5.9.8"
|
||||
meilisearch-python-sdk = "^2.8.0"
|
||||
pillow = "^10.2.0"
|
||||
opencv-python = "^4.9.0.80"
|
||||
aiogoogletrans = "^3.3.3"
|
||||
koreanbots = "^2.1.0"
|
||||
joblib = "^1.3.2"
|
||||
pandas = "^2.2.1"
|
||||
numpy = "^1.26.4"
|
||||
sentry-sdk = "^1.42.0"
|
||||
loguru = "^0.7.2"
|
||||
orjson = "^3.9.15"
|
||||
motor = "^3.3.2"
|
||||
python-dotenv = "^1.0.1"
|
||||
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry-core"]
|
||||
build-backend = "poetry.core.masonry.api"
|
Loading…
Reference in New Issue
Block a user