Compare commits
10 Commits
8bed6ca308
...
84f2e3f3a7
Author | SHA1 | Date | |
---|---|---|---|
|
84f2e3f3a7 | ||
|
f6979086d0 | ||
|
cfdfe8b4a6 | ||
|
37333d89df | ||
|
a187a23153 | ||
|
0048e81666 | ||
|
6693186d40 | ||
|
3941a13df5 | ||
|
c53420b164 | ||
|
d793cb2930 |
24
.github/workflows/docker-build.yml
vendored
Normal file
24
.github/workflows/docker-build.yml
vendored
Normal file
@ -0,0 +1,24 @@
|
||||
jobs:
|
||||
docker_build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Docker Build
|
||||
run: docker build -t git.runa.pw/tmddn3070/runabot:latest .
|
||||
- name: Docker Registry
|
||||
run: echo ${{ secrets.DOCKER_PASSWORD }} | docker login git.runa.pw -u ${{ secrets.DOCKER_USERNAME }} --password-stdin
|
||||
- name: Docker Push
|
||||
run: docker push git.runa.pw/tmddn3070/runabot:latest
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
pull_request:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
# skip-build가 커밋 메시지에 있으면 빌드를 건너뛴다.
|
||||
paths-ignore:
|
||||
- 'skip-build'
|
19
.github/workflows/qodana_code_quality.yml
vendored
Normal file
19
.github/workflows/qodana_code_quality.yml
vendored
Normal file
@ -0,0 +1,19 @@
|
||||
name: Qodana
|
||||
on:
|
||||
workflow_dispatch:
|
||||
pull_request:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
qodana:
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: 'Qodana Scan'
|
||||
uses: JetBrains/qodana-action@v2023.3
|
||||
env:
|
||||
QODANA_TOKEN: ${{ secrets.QODANA_TOKEN }}
|
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,134 +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 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.all()
|
||||
)
|
||||
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,12 +1,12 @@
|
||||
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):
|
||||
from RUNA.UI.Embed import Default_Embed, RunaEmbed
|
||||
from RUNA.UI.Buttons import Recommanded
|
||||
from RUNA.Module import get_gpuserver_status, Get_Backend_latency
|
||||
from RUNA.Database.Mongo.guild import MongoGuild
|
||||
|
||||
class CogUtil(Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
|
||||
@ -15,9 +15,11 @@ class CUtil(Cog):
|
||||
@cooldown(1, 10, BucketType.user)
|
||||
@slash_command(name="서버가입", description="서버에 가입합니다.")
|
||||
async def _join(self, ctx: Context):
|
||||
pma_babo = True
|
||||
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)
|
||||
if await MongoGuild().get_guild(ctx.guild.id): return await ctx.respond(embed=Default_Embed.already_register(),
|
||||
ephemeral=True)
|
||||
await MongoGuild().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())
|
||||
@ -27,19 +29,18 @@ class CUtil(Cog):
|
||||
@cooldown(1, 10, BucketType.user)
|
||||
@slash_command(name="서버탈퇴", description="서버에서 탈퇴합니다.")
|
||||
async def _leave(self, ctx: Context):
|
||||
try:
|
||||
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())
|
||||
except Exception as e:
|
||||
await ctx.respond(embed=Default_Embed.leave_failed())
|
||||
|
||||
if not await MongoGuild.get_guild(ctx.guild.id): return await ctx.respond(embed=Default_Embed.not_register(),
|
||||
ephemeral=True)
|
||||
await MongoGuild().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)
|
||||
if not await database.get_guild(ctx.guild.id): return await ctx.respond(
|
||||
embed=RunaEmbed(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))
|
||||
|
||||
@ -50,9 +51,10 @@ class CUtil(Cog):
|
||||
|
||||
@cooldown(1, 10, BucketType.user)
|
||||
@guild_only()
|
||||
@slash_command(name="추천", description="한디리의 추천링크를 표시해요! 추천 갯수는 추후 크돌이를 통해 오픈될 게임에 영향을 줘요!")
|
||||
async def _recommand(self, ctx: Context):
|
||||
@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(CUtil(bot))
|
||||
bot.add_cog(CogUtil(bot))
|
@ -1,5 +1,4 @@
|
||||
import random
|
||||
import wavelink
|
||||
import pendulum
|
||||
|
||||
import onnxruntime as rt
|
||||
@ -9,16 +8,14 @@ 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
|
||||
from RUNA.UI.Embed import Default_Embed, Music_Embed, RunaEmbed
|
||||
from RUNA.Database import database
|
||||
|
||||
model = rt.InferenceSession("Christmas/Tagging/model.onnx", provider_options="CPUExecutionProvider")
|
||||
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:
|
||||
@ -28,23 +25,16 @@ class Event(Cog):
|
||||
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)
|
||||
await ctx.respond(embed=RunaEmbed(title="❌ 에러!", description=f"권한이 부족해요! 필요한 권한: {need_permissions}", color=Color.red()),ephemeral=True)
|
||||
else:
|
||||
await ctx.respond(embed=ChristmasEmbed(title="❌ 에러!", description=f"알수 없는 에러가 발생했어요! 봇 소유자에게 연락해주세요.", color=Color.red()),ephemeral=True)
|
||||
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="크리스마스에 함께!"))
|
||||
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:
|
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):
|
||||
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")]
|
||||
|
||||
def connect(self):
|
||||
return self.client()
|
||||
|
34
RUNA/Database/Mongo/guild.py
Normal file
34
RUNA/Database/Mongo/guild.py
Normal file
@ -0,0 +1,34 @@
|
||||
from RUNA.Database.Mongo import MongoDBClient
|
||||
|
||||
|
||||
class MongoGuild:
|
||||
def __init__(self):
|
||||
self.client = MongoDBClient().connect()
|
||||
self.guild = self.client["guild"]
|
||||
|
||||
async def get_guild(self, guild_id):
|
||||
return await self.guild.find_one({"_id": guild_id})
|
||||
|
||||
async def register_guild(self, guild_id, guild_name):
|
||||
return await self.guild.insert_one(
|
||||
{"_id": guild_id, "name": guild_name, "art_point": 0, "use_art": 0, "settings": {}})
|
||||
|
||||
async def leave_guild(self, guild_id):
|
||||
return await self.guild.delete_one({"_id": guild_id})
|
||||
|
||||
async def update_guild_name(self, guild_id, guild_name):
|
||||
return await self.guild.update_one({"_id": guild_id}, {"$set": {"name": guild_name}})
|
||||
|
||||
async def update_guild_art_point(self, guild_id, art_point):
|
||||
return await self.guild.update_one({"_id": guild_id}, {"$set": {"art_point": art_point}})
|
||||
|
||||
async def decrease_art_point(self, guild_id: int):
|
||||
guild = await self.get_guild(guild_id)
|
||||
art_point = guild["art_point"]
|
||||
return await self.update_guild_art_point(guild_id, art_point - 1)
|
||||
|
||||
async def increase_art_point(self, guild_id: int):
|
||||
guild = await self.get_guild(guild_id)
|
||||
art_point = guild["art_point"]
|
||||
return await self.update_guild_art_point(guild_id, art_point + 1)
|
||||
|
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)
|
||||
|
||||
|
||||
|
@ -10,8 +10,8 @@ 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
|
||||
from RUNA.Tagging import Tagging
|
||||
from RUNA.Cogs.Event import model
|
||||
translator = Translator()
|
||||
BLOCKTAG = [
|
||||
"nsfw",
|
||||
@ -82,7 +82,7 @@ async def process_prompt(prompt: str, remove: str, res: list, isnsfw: bool, styl
|
||||
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"""
|
||||
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:
|
||||
@ -109,7 +109,6 @@ async def process_prompt(prompt: str, remove: str, res: list, isnsfw: bool, styl
|
||||
"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,
|
186
RUNA/Modules/ART_Generate.py
Normal file
186
RUNA/Modules/ART_Generate.py
Normal file
@ -0,0 +1,186 @@
|
||||
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.Modules.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 is_korean(string):
|
||||
pattern = re.compile(r"[ㄱ-ㅎㅏ-ㅣ가-힣]")
|
||||
match = pattern.search(string)
|
||||
return bool(match)
|
||||
|
||||
|
||||
async def process_prompt(positive: str, negative: str, res: list, isnsfw: bool, style: list, after_process: bool, avatar):
|
||||
tags = None
|
||||
if avatar is not None:
|
||||
try:
|
||||
if avatar.url.endswith(".gif"):
|
||||
avatar = avatar.replace(format="png")
|
||||
avatar = await avatar.read()
|
||||
tags = (await Tagging().predict(avatar))[0]
|
||||
except Exception:
|
||||
tags = None
|
||||
if is_korean(positive):
|
||||
positive = (await translator.translate(positive, dest="en")).text
|
||||
if is_korean(negative):
|
||||
negative = (await translator.translate(negative, dest="en")).text
|
||||
if not isnsfw:
|
||||
for tag in BLOCKTAG:
|
||||
if tag in positive:
|
||||
positive = positive.replace(tag, "")
|
||||
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"
|
||||
for styles in style:
|
||||
positive += f" <lora:{styles["style"]}:{styles["weight"]}>"
|
||||
if negative is not None:
|
||||
negative = default_negative + "," + negative
|
||||
if tags is not None:
|
||||
positive += "," + tags
|
||||
payload = {
|
||||
"prompt": positive,
|
||||
"negative": negative,
|
||||
"seed": random.randint(0, 1000000000),
|
||||
"width": res[0],
|
||||
"height": res[1],
|
||||
"cfg_scale": random.choice(cfg),
|
||||
"steps": random.randint(20, 25),
|
||||
"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
|
||||
}]
|
||||
},
|
||||
"sonar": {
|
||||
'args': [
|
||||
{
|
||||
'sampler': 'Euler a',
|
||||
'momentum': 0.95,
|
||||
'momentum_hist': 0.75
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
if after_process:
|
||||
additional = {
|
||||
"enable_hr": True,
|
||||
"hr_scale": 1.3,
|
||||
"hr_upscaler": "R-ESRGAN 4x+ Anime6B",
|
||||
"denoising_strength": 0.6
|
||||
}
|
||||
payload.update(additional)
|
||||
return payload
|
||||
|
||||
|
||||
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,29 +1,23 @@
|
||||
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
|
||||
|
||||
|
||||
model = rt.InferenceSession("RUNA/Tagging/model.onnx", provider_options=["CPUExecutionProvider"])
|
||||
|
||||
|
||||
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"
|
||||
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)
|
||||
@ -40,7 +34,6 @@ class Tagging:
|
||||
)
|
||||
return new_im
|
||||
|
||||
|
||||
def smart_resize(self, img, size):
|
||||
# Assumes the image has already gone through make_square
|
||||
if img.shape[0] > size:
|
||||
@ -67,12 +60,10 @@ class Tagging:
|
||||
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
|
||||
_, height, width, _ = self.model.get_inputs()[0].shape
|
||||
|
||||
image = self.preprocess_image(image)
|
||||
image = self.make_square(image, height)
|
||||
@ -101,8 +92,8 @@ class Tagging:
|
||||
|
||||
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):
|
||||
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:
|
@ -1,6 +1,6 @@
|
||||
from discord import AutocompleteContext
|
||||
|
||||
from Christmas.SearchEngine.Snowball import Snowball
|
||||
from RUNA.Database.MeiliSearch import Snowball
|
||||
|
||||
|
||||
async def Guild_Autocomplete(ctx: AutocompleteContext):
|
@ -1,14 +1,16 @@
|
||||
import random
|
||||
import os
|
||||
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 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 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
|
||||
@ -60,14 +62,14 @@ class Arcade_Register_Agree(View):
|
||||
|
||||
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)
|
||||
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)
|
@ -7,10 +7,10 @@ from discord.types.embed import EmbedType
|
||||
from datetime import datetime
|
||||
from korcen import korcen
|
||||
|
||||
|
||||
start_time = datetime.now()
|
||||
|
||||
class ChristmasEmbed(Embed):
|
||||
|
||||
class RunaEmbed(Embed):
|
||||
def __init__(self, *,
|
||||
color: int | Colour | None = 0xf4f9ff,
|
||||
title: Any | None = None,
|
||||
@ -18,7 +18,7 @@ class ChristmasEmbed(Embed):
|
||||
url: Any | None = None,
|
||||
description: Any | None = None,
|
||||
timestamp: datetime | None = None,
|
||||
):
|
||||
):
|
||||
super().__init__(
|
||||
color=color,
|
||||
title=title,
|
||||
@ -28,22 +28,24 @@ class ChristmasEmbed(Embed):
|
||||
timestamp=timestamp,
|
||||
)
|
||||
|
||||
def set_footer(self, *, text: Any | None = "크돌이⛄", icon_url: Any | None = "https://discord.com/assets/6dbfff5aae6b1de2b83f.svg") -> None:
|
||||
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="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="서버가입을 성공했어요!")
|
||||
@ -69,6 +71,13 @@ class Default_Embed:
|
||||
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="크리스마스를 즐겨보세요!")
|
||||
@ -77,14 +86,17 @@ class Default_Embed:
|
||||
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.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="크돌이를 추천해주시면 크돌이가 더욱더 발전할 수 있어요!\n 아래의 추천링크를 통해 크돌이를 추천하였다면 ``추천완료``버튼을 눌러주세요",
|
||||
inline=False)
|
||||
embed.add_field(name="추천 링크", value="https://koreanbots.dev/bots/974665354573930507", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
@ -98,31 +110,41 @@ class Default_Embed:
|
||||
gpuserver: [system_memory_usage,cuda_memory_usage,oom_count]
|
||||
"""
|
||||
embed = Embed(title="**봇 정보**", description="크돌이의 정보에요!")
|
||||
embed.add_field(name="**봇 개요**", value=f"봇 ID: {bot.user.id}\n봇 버전: 1.3.0\n가동시간: {str(uptime)}\n개발자: RunaLab,PvPConnect", inline=True)
|
||||
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)
|
||||
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(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:
|
||||
# if APIlatency is None:
|
||||
# embed.add_field(name="**봇 핑**", value=f"🏓 **디스코드 게이트웨이 핑**: {round(bot.latency * 1000)}ms\n🏓 **AI 게이트웨이 핑**: 오류", inline=False)
|
||||
#else:
|
||||
# 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="편지는 한 번 전송하면 한번의 수정 기회 이후에는 취소할 수 없어요!\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)
|
||||
@ -132,7 +154,8 @@ class Mail_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="이번에 편지를 수정하면 다시는 수정할 수 없게 되요!\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)
|
||||
@ -146,7 +169,6 @@ class Mail_Embed:
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
|
||||
@staticmethod
|
||||
def mail_sended(receive_user: Member) -> Embed:
|
||||
embed = ChristmasEmbed(title="✅ 전송완료!", description="편지 전송을 완료했어요!")
|
||||
@ -192,6 +214,7 @@ class Mail_Embed:
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
|
||||
class Aiart_Embed:
|
||||
|
||||
@staticmethod
|
||||
@ -241,12 +264,14 @@ class Aiart_Embed:
|
||||
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.add_field(name="안내", value="이 서버에서는 음악을 재생할수 없어요! \n만약 서버의 관리자라면 ``/설정`` 명령어로 음악 기능을 다시 활성화사킬수 있어요!",
|
||||
inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@ -278,7 +303,8 @@ class Music_Embed:
|
||||
|
||||
@staticmethod
|
||||
def changed_christmas():
|
||||
embed = ChristmasEmbed(title="✅ 크리스마스 모드 변경!", description="크리스마스 모드를 변경했어요! 이 시간부터 25일 11시 59분까지 크리스마스 모드가 적용되요!")
|
||||
embed = ChristmasEmbed(title="✅ 크리스마스 모드 변경!",
|
||||
description="크리스마스 모드를 변경했어요! 이 시간부터 25일 11시 59분까지 크리스마스 모드가 적용되요!")
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
@ -298,18 +324,19 @@ class Music_Embed:
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
||||
class Arcade_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="크돌이의 눈싸움은 서버대 서버로 경쟁하며 그 안의 유저들이 서로 협동하여 이뤄지는 게임이에요!\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="눈싸움 등록을 성공했어요!")
|
||||
@ -350,7 +377,6 @@ class Arcade_Embed:
|
||||
embed.add_field(name="진영", value=f"{region}", inline=False)
|
||||
embed.add_field(name="상대진영", value=f"{region}", inline=False)
|
||||
|
||||
|
||||
@staticmethod
|
||||
def recommend_sucess():
|
||||
embed = ChristmasEmbed(title="🎉 추천 완료!", description="크돌이를 추천해주셔서 감사해요!")
|
||||
@ -364,4 +390,3 @@ class Arcade_Embed:
|
||||
embed.add_field(name="안내", value="크돌이의 추천을 확인하는데 실패했어요! 이 현상이 지속된다면 서비스 서버에 문의해주세요!", inline=False)
|
||||
embed.set_footer()
|
||||
return embed
|
||||
|
@ -1,16 +1,18 @@
|
||||
import re
|
||||
import os
|
||||
import random
|
||||
import base64
|
||||
from discord import InputTextStyle, Interaction, Member
|
||||
from discord.ui import Modal, InputText
|
||||
|
||||
#from Christmas.Module import check_curse
|
||||
from dotenv import load_dotenv, find_dotenv
|
||||
#from RUNA.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
|
||||
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.Modules.Tagging import Tagging
|
||||
from RUNA.Cogs.Event import model
|
||||
|
||||
|
||||
class Send_Mail_Modal(Modal):
|
||||
@ -37,7 +39,6 @@ class Aiart(Modal):
|
||||
self.res = res
|
||||
self.style1 = style1
|
||||
self.style2 = style2
|
||||
self.config = ChristmasConfig()
|
||||
self.afterprocess = afterprocess
|
||||
super().__init__(timeout=None, *args, **kwargs)
|
||||
|
||||
@ -63,15 +64,13 @@ class Aiart(Modal):
|
||||
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)
|
||||
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(model=model)
|
||||
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())
|
@ -7,7 +7,7 @@ from discord.enums import ButtonStyle
|
||||
from discord.interactions import Interaction
|
||||
from discord.ui import Button, View
|
||||
|
||||
from Christmas.UI.Embed import ChristmasEmbed
|
||||
from RUNA.UI.Embed import ChristmasEmbed
|
||||
|
||||
class Mail_Paginator(View):
|
||||
def __init__(
|
25
RUNA/__main__.py
Normal file
25
RUNA/__main__.py
Normal file
@ -0,0 +1,25 @@
|
||||
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()
|
57
RUNA/discord.py
Normal file
57
RUNA/discord.py
Normal file
@ -0,0 +1,57 @@
|
||||
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()
|
||||
]
|
||||
)
|
36
RUNAAPI/__init__.py
Normal file
36
RUNAAPI/__init__.py
Normal file
@ -0,0 +1,36 @@
|
||||
from fastapi import FastAPI, Request, Response, HTTPException
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.middleware import Middleware
|
||||
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
from fastapi.openapi.models import APIKey
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
origins = [
|
||||
"*"
|
||||
]
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=origins,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content=jsonable_encoder({"detail": exc.errors(), "body": exc.body}),
|
||||
)
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return {"message": "RUNABOT API"}
|
||||
|
7
main.py
Normal file
7
main.py
Normal file
@ -0,0 +1,7 @@
|
||||
class tmddn3070:
|
||||
def __init__(self):
|
||||
self.기만강도 = 100,
|
||||
self.재력 = 100
|
||||
|
||||
tmddn = tmddn3070()
|
||||
|
2745
poetry.lock
generated
Normal file
2745
poetry.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
38
pyproject.toml
Normal file
38
pyproject.toml
Normal file
@ -0,0 +1,38 @@
|
||||
[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"
|
||||
fastapi = "^0.110.0"
|
||||
uvicorn = {extras = ["standard"], version = "^0.28.0"}
|
||||
jinja2 = "^3.1.3"
|
||||
redis = {extras = ["hiredis"], version = "^5.0.3"}
|
||||
coverage = "^7.4.4"
|
||||
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry-core"]
|
||||
build-backend = "poetry.core.masonry.api"
|
29
qodana.yaml
Normal file
29
qodana.yaml
Normal file
@ -0,0 +1,29 @@
|
||||
#-------------------------------------------------------------------------------#
|
||||
# Qodana analysis is configured by qodana.yaml file #
|
||||
# https://www.jetbrains.com/help/qodana/qodana-yaml.html #
|
||||
#-------------------------------------------------------------------------------#
|
||||
version: "1.0"
|
||||
|
||||
#Specify inspection profile for code analysis
|
||||
profile:
|
||||
name: qodana.starter
|
||||
|
||||
#Enable inspections
|
||||
#include:
|
||||
# - name: <SomeEnabledInspectionId>
|
||||
|
||||
#Disable inspections
|
||||
#exclude:
|
||||
# - name: <SomeDisabledInspectionId>
|
||||
# paths:
|
||||
# - <path/where/not/run/inspection>
|
||||
|
||||
#Execute shell command before Qodana execution (Applied in CI/CD pipeline)
|
||||
#bootstrap: sh ./prepare-qodana.sh
|
||||
|
||||
#Install IDE plugins before Qodana execution (Applied in CI/CD pipeline)
|
||||
#plugins:
|
||||
# - id: <plugin.id> #(plugin id can be found at https://plugins.jetbrains.com)
|
||||
|
||||
#Specify Qodana linter for analysis (Applied in CI/CD pipeline)
|
||||
linter: jetbrains/qodana-python:latest
|
Loading…
Reference in New Issue
Block a user