From 4abdb9b0cf220561277f93ef1fc94faa91954a70 Mon Sep 17 00:00:00 2001 From: pikokr Date: Mon, 4 Jul 2022 16:18:17 +0900 Subject: [PATCH] chore: format code --- Legacy_Codes/admin.py | 4 +- Legacy_Codes/censorship.py | 2 +- cogs/admin.py | 69 ++++++++++---- cogs/censorship.py | 21 +++-- cogs/etc.py | 8 +- cogs/fishing/admin.py | 27 ++++-- cogs/fishing/cycle.py | 4 +- cogs/fishing/fishing.py | 16 +++- cogs/fishing/game.py | 8 +- cogs/fishing/unit.py | 3 +- config.example.py | 2 +- db/seta_json.py | 20 ++--- db/seta_pgsql.py | 57 ++++++------ db/seta_sqlite.py | 37 ++++---- main.py | 4 +- scripts/gensecret.py | 4 +- static/hanspell/__init__.py | 2 +- static/hanspell/constants.py | 3 +- static/hanspell/response.py | 26 +++--- static/hanspell/spell_checker.py | 70 +++++++-------- utils/fish_card/fish_card.py | 58 ++++++------ utils/fish_card/utils/fish_card/fishcard.py | 90 +++++++++++++++---- utils/fish_card/utils/fish_card_new/editor.py | 12 +-- .../utils/fish_card_new/fish_card.py | 47 +++++----- utils/fish_card/utils/logger.py | 63 ++++++------- utils/fish_card/utils/on_working.py | 57 +++++++----- utils/fish_card/utils/seta_josa.py | 28 +++--- utils/fish_card/utils/seta_json.py | 20 ++--- utils/fish_card/utils/seta_sqlite_class.py | 41 +++++---- utils/fish_card/utils/tag.py | 50 +++++------ utils/fish_card/utils/util_box.py | 36 ++++---- utils/on_working.py | 8 +- utils/seta_josa.py | 28 +++--- utils/util_box.py | 36 ++++---- 34 files changed, 572 insertions(+), 389 deletions(-) diff --git a/Legacy_Codes/admin.py b/Legacy_Codes/admin.py index 62cfe7d..a3a567e 100644 --- a/Legacy_Codes/admin.py +++ b/Legacy_Codes/admin.py @@ -1,6 +1,6 @@ # 디스코드 메세지 인텐트로 인한 검열 기능 사용 제한. # From cogs/admin.py -''' +""" class DBManagerCog(commands.Cog): def __init__(self, bot): self.bot = bot @@ -157,4 +157,4 @@ async def 목록(self, ctx, *args): else: await ctx.send("`이프야 목록 <야한말/정치언급/욕설/변태/나쁜말/관리자>`") return None -''' \ No newline at end of file +""" diff --git a/Legacy_Codes/censorship.py b/Legacy_Codes/censorship.py index 0f96cdc..be8ac24 100644 --- a/Legacy_Codes/censorship.py +++ b/Legacy_Codes/censorship.py @@ -125,4 +125,4 @@ async def gumyol(message): # 검열에 안 걸린 경우 return True -''' \ No newline at end of file +''' diff --git a/cogs/admin.py b/cogs/admin.py index 76045fe..682eb2d 100644 --- a/cogs/admin.py +++ b/cogs/admin.py @@ -30,7 +30,11 @@ def __init__(self, bot): self.bot = bot @on_working.administrator() - @slash_command(name = "계란", guild_ids = config.ADMIN_COMMAND_GUILD, decription = "관리자 디버그용 도구입니다. (관리자 전용)") + @slash_command( + name="계란", + guild_ids=config.ADMIN_COMMAND_GUILD, + decription="관리자 디버그용 도구입니다. (관리자 전용)", + ) async def 계란(self, ctx, args: str): here = Room(ctx.channel) me = User(ctx.author) @@ -55,13 +59,17 @@ async def 계란(self, ctx, args: str): ) embed.set_footer( text=f"{ctx.author.name} • 달걀", - #작동하지 않음 - #icon_url=str(ctx.author.avatar_url_as(static_format="png", size=128)), + # 작동하지 않음 + # icon_url=str(ctx.author.avatar_url_as(static_format="png", size=128)), ) await ctx.respond(embed=embed) @on_working.administrator() - @slash_command(name = "달걀", guild_ids = config.ADMIN_COMMAND_GUILD, description = "관리자 디버그용 도구입니다. (관리자 전용)") + @slash_command( + name="달걀", + guild_ids=config.ADMIN_COMMAND_GUILD, + description="관리자 디버그용 도구입니다. (관리자 전용)", + ) async def 달걀(self, ctx, args: str): here = Room(ctx.channel) me = User(ctx.author) @@ -88,27 +96,39 @@ async def 달걀(self, ctx, args: str): ) embed.set_footer( text=f"{ctx.author.name} • 달걀", - #작동하지 않음 - #icon_url=str(ctx.author.avatar_url_as(static_format="png", size=128)), + # 작동하지 않음 + # icon_url=str(ctx.author.avatar_url_as(static_format="png", size=128)), ) await ctx.respond(embed=embed) # 팡 하면 펑 하고 터짐 @on_working.administrator() - @slash_command(name = "팡", guild_ids = config.ADMIN_COMMAND_GUILD, description = "관리자 디버그용 도구입니다. (관리자 전용)") + @slash_command( + name="팡", + guild_ids=config.ADMIN_COMMAND_GUILD, + description="관리자 디버그용 도구입니다. (관리자 전용)", + ) async def 팡(self, ctx): await ctx.respond(f"펑! 💥\n`지연 시간 : {int(self.bot.latency * 1000)}ms`") raise Exception # 팡 하면 펑 하고 터짐 @on_working.administrator() - @slash_command(name = "핑핑", guild_ids = config.ADMIN_COMMAND_GUILD, description = "관리자 디버그용 도구입니다. (관리자 전용)") + @slash_command( + name="핑핑", + guild_ids=config.ADMIN_COMMAND_GUILD, + description="관리자 디버그용 도구입니다. (관리자 전용)", + ) async def 핑핑(self, ctx): ping = [f"#shard_{i[0]} ({int(i[1] * 1000)}ms)" for i in self.bot.latencies] text = "\n".join(ping) await ctx.respond(f"퐁퐁! 🏓🏓\n```css\n[ 지연 시간 ]\n{text}```") - @slash_command(name = "공지", guild_ids = config.ADMIN_COMMAND_GUILD, description = "관리자 공지용 도구입니다. (관리자 전용)") + @slash_command( + name="공지", + guild_ids=config.ADMIN_COMMAND_GUILD, + description="관리자 공지용 도구입니다. (관리자 전용)", + ) @on_working.administrator() async def 공지(self, ctx: discord.commands.context.ApplicationContext): old = await ctx.respond( @@ -134,8 +154,8 @@ async def 공지(self, ctx: discord.commands.context.ApplicationContext): ) news_embed.set_footer( text=f"{ctx.author.name} • #공지", - #작동하지 않음 - #icon_url=str(ctx.author.avatar_url_as(static_format="png", size=128)), + # 작동하지 않음 + # icon_url=str(ctx.author.avatar_url_as(static_format="png", size=128)), ) """ news_embed.set_thumbnail( @@ -206,17 +226,21 @@ async def progress(): ) await window.edit(embed=embed) - @slash_command(name = "업데이트공지", guild_ids = config.ADMIN_COMMAND_GUILD, description = "관리자 공지용 도구입니다. (관리자 전용)") + @slash_command( + name="업데이트공지", + guild_ids=config.ADMIN_COMMAND_GUILD, + description="관리자 공지용 도구입니다. (관리자 전용)", + ) @on_working.administrator() async def 업데이트공지(self, ctx, arg): embed = discord.Embed( title="**공지사항**", color=0x00A495, timestamp=datetime.datetime.now() ) - ''' + """ embed.set_thumbnail( url=str(self.bot.user.avatar_url_as(static_format="png", size=256)) ) - ''' + """ embed.add_field( name="**<이프 업데이트 공지>**", value=f"이프가 **`{arg}`**동안 업데이트 될 예정입니다.\n업데이트 중에는 이프를 사용하실수 없습니다.\n\n감사합니다.", @@ -224,7 +248,7 @@ async def 업데이트공지(self, ctx, arg): ) embed.set_footer( text=f"{ctx.author.name} • #공지", - #icon_url=str(ctx.author.avatar_url_as(static_format="png", size=128)), + # icon_url=str(ctx.author.avatar_url_as(static_format="png", size=128)), ) end = [] for guild in self.bot.guilds: # 서버 리스트 @@ -257,7 +281,11 @@ class LogManagerCog(commands.Cog): def __init__(self, bot): self.bot = bot - @slash_command(name = "로그", guild_ids = config.ADMIN_COMMAND_GUILD, description = "관리자 디버그용 도구입니다. (관리자 전용)") + @slash_command( + name="로그", + guild_ids=config.ADMIN_COMMAND_GUILD, + description="관리자 디버그용 도구입니다. (관리자 전용)", + ) @on_working.administrator() async def 로그(self, ctx, args: str): arg = ( @@ -273,7 +301,11 @@ async def 로그(self, ctx, args: str): else: await ctx.respond(f"'logs/log_{arg}.txt'는 없는 파일입니다.") - @slash_command(name = "에러로그", guild_ids = config.ADMIN_COMMAND_GUILD, description = "관리자 디버그용 도구입니다. (관리자 전용)") + @slash_command( + name="에러로그", + guild_ids=config.ADMIN_COMMAND_GUILD, + description="관리자 디버그용 도구입니다. (관리자 전용)", + ) @on_working.administrator() async def 에러로그(self, ctx, args: str): arg = ( @@ -290,9 +322,8 @@ async def 에러로그(self, ctx, args: str): await ctx.send(f"'logs/error_log_{arg}.txt'는 없는 파일입니다.") - def setup(bot): logger.info(f"{os.path.abspath(__file__)} 로드 완료") bot.add_cog(AdminCog(bot)) bot.add_cog(LogManagerCog(bot)) - #bot.add_cog(DBManagerCog(bot)) # Legacy Code + # bot.add_cog(DBManagerCog(bot)) # Legacy Code diff --git a/cogs/censorship.py b/cogs/censorship.py index 7b555b5..58fa1a0 100644 --- a/cogs/censorship.py +++ b/cogs/censorship.py @@ -16,14 +16,22 @@ class CensorshipCog(commands.Cog): def __init__(self, bot): self.bot = bot - @slash_command(name = "검열", description = "검열 기능에 대한 설명입니다!", guild_ids=SCRS) + @slash_command(name="검열", description="검열 기능에 대한 설명입니다!", guild_ids=SCRS) async def 검열(self, ctx): - embed = discord.Embed(title = "검열 기능은 어디로 갔나요?", colour = 0x4BC59F) - embed.add_field(name = "왜 없어졌나요?", value = "디스코드의 메세지 인텐트 정책에 의거해, 2022.09.01 부터는 검열 기능이 정상적으로 작동하지 않을 예정입니다.", inline = False) - embed.add_field(name = "그럼 검열은 어디에서 해야 하나요?", value = "키뮤소프트가 새롭게 개발중인 봇 `위브`는 검열을 위한 봇입니다! 검열 기능은 위브로 이관될 예정이니 많은 관심 부탁드릴게요!", inline = False) - await ctx.respond(embed = embed) + embed = discord.Embed(title="검열 기능은 어디로 갔나요?", colour=0x4BC59F) + embed.add_field( + name="왜 없어졌나요?", + value="디스코드의 메세지 인텐트 정책에 의거해, 2022.09.01 부터는 검열 기능이 정상적으로 작동하지 않을 예정입니다.", + inline=False, + ) + embed.add_field( + name="그럼 검열은 어디에서 해야 하나요?", + value="키뮤소프트가 새롭게 개발중인 봇 `위브`는 검열을 위한 봇입니다! 검열 기능은 위브로 이관될 예정이니 많은 관심 부탁드릴게요!", + inline=False, + ) + await ctx.respond(embed=embed) - @slash_command(name = "태그", description="이 채널의 태그를 확인하세요!", guild_ids=SCRS) + @slash_command(name="태그", description="이 채널의 태그를 확인하세요!", guild_ids=SCRS) async def 태그(self, ctx): tags = eptag.tag_to_korean(eptag.get_tags(ctx.channel)) @@ -34,7 +42,6 @@ async def 태그(self, ctx): await ctx.respond(embed=embed) - def setup(bot): logger.info(f"{os.path.abspath(__file__)} 로드 완료") bot.add_cog(CensorshipCog(bot)) # 꼭 이렇게 위의 클래스를 이렇게 add_cog해 줘야 작동해요! diff --git a/cogs/etc.py b/cogs/etc.py index b94a880..0ad95d1 100644 --- a/cogs/etc.py +++ b/cogs/etc.py @@ -38,11 +38,15 @@ async def 핑(self, ctx: discord.commands.context.ApplicationContext): now = datetime.datetime.now() latency = int(self.bot.latency * 1000) - i = await ctx.respond(f"퐁! 🏓\n`지연 시간 : {latency}ms (실제 지연시간 계산 중...)`", ) + i = await ctx.respond( + f"퐁! 🏓\n`지연 시간 : {latency}ms (실제 지연시간 계산 중...)`", + ) wd = await i.original_message() - real_latency = int((wd.created_at.replace(tzinfo=None) - now).microseconds / 1000) + real_latency = int( + (wd.created_at.replace(tzinfo=None) - now).microseconds / 1000 + ) await ctx.edit( content=f"퐁! 🏓\n`지연 시간 : {latency}ms (실제 지연시간 {real_latency}ms)`" ) diff --git a/cogs/fishing/admin.py b/cogs/fishing/admin.py index 7f0a1ae..5852d23 100644 --- a/cogs/fishing/admin.py +++ b/cogs/fishing/admin.py @@ -19,11 +19,21 @@ class FishAdminCog(commands.Cog): def __init__(self, bot): self.bot = bot - @slash_command(name = "디버그", guild_ids = config.ADMIN_COMMAND_GUILD, description="관리자 디버그용 도구입니다. (관리자 전용)") + @slash_command( + name="디버그", + guild_ids=config.ADMIN_COMMAND_GUILD, + description="관리자 디버그용 도구입니다. (관리자 전용)", + ) @administrator() - async def 테스트(self, ctx, command_type: - Option(str, "관리자 명령어 종류", choices = ["지형변경", "명성설정", "명성부여", "돈부여", "기타"]), - num: int = None, user: discord.Member = None): + async def 테스트( + self, + ctx, + command_type: Option( + str, "관리자 명령어 종류", choices=["지형변경", "명성설정", "명성부여", "돈부여", "기타"] + ), + num: int = None, + user: discord.Member = None, + ): if command_type == "지형변경": Room(ctx.channel).biome = num @@ -34,23 +44,24 @@ async def 테스트(self, ctx, command_type: origin_exp = room.exp room.exp = num await ctx.respond(content=f"여기의 명성을 `{origin_exp}`에서 `{num}`(으)로 바꿔써!") - + elif command_type == "명성부여": room = Room(ctx.channel) origin_exp = room.exp room.exp += num - await ctx.respond(content=f"여기의 명성을 `{origin_exp}`에서 `{room.exp:,}`(으)로 바꿔써!") + await ctx.respond( + content=f"여기의 명성을 `{origin_exp}`에서 `{room.exp:,}`(으)로 바꿔써!" + ) elif command_type == "돈부여": user = User(user) user.give_money(num) await ctx.respond(f"<@!{user.id}>가 `{user.money:,}💰` 가 됐어!") - else: + else: await ctx.respond("Hello, This is KOI3125 test command!") - def setup(bot): logger.info(f"{os.path.abspath(__file__)} 로드 완료") bot.add_cog(FishAdminCog(bot)) diff --git a/cogs/fishing/cycle.py b/cogs/fishing/cycle.py index 7732edf..3b55325 100644 --- a/cogs/fishing/cycle.py +++ b/cogs/fishing/cycle.py @@ -38,7 +38,7 @@ def __init__(self, bot): logger.info("AsyncIOScheduler 스케쥴 시작") self.sched = AsyncIOScheduler() - #self.sched.add_job(self.day_end_schedule, "cron", hour="23", minute="55") + # self.sched.add_job(self.day_end_schedule, "cron", hour="23", minute="55") # self.sched.add_job(self.day_end_schedule, 'cron', minute='*/5') self.sched.start() @@ -56,6 +56,7 @@ async def cleaner(self): if len(self.bot.guilds) != 0: logger.info(f"통계 : 현재 서버 수 {len(self.bot.guilds)}곳") + """ 사용하지 않음 @commands.command() @administrator() @@ -166,6 +167,7 @@ async def day_end_schedule(self): db.update_sql("users", "biggest_size=0, biggest_name=''") # 최고 기록 초기화 """ + def setup(bot): logger.info(f"{os.path.abspath(__file__)} 로드 완료") bot.add_cog(CycleCog(bot)) # 꼭 이렇게 위의 클래스를 이렇게 add_cog해 줘야 작동해요! diff --git a/cogs/fishing/fishing.py b/cogs/fishing/fishing.py index 043d188..608363a 100644 --- a/cogs/fishing/fishing.py +++ b/cogs/fishing/fishing.py @@ -100,7 +100,9 @@ async def 여기(self, ctx: discord.commands.context.ApplicationContext): @slash_command(name="랭킹", description="이프의 랭킹을 보여줘요!", guild_ids=SCRS) @on_working(prohibition=True) async def 랭킹( - self, ctx: discord.commands.context.ApplicationContext, type: Option(str, "보고 싶으신 랭킹의 종류를 고르세요!", choices=["개인", "낚시터"]) + self, + ctx: discord.commands.context.ApplicationContext, + type: Option(str, "보고 싶으신 랭킹의 종류를 고르세요!", choices=["개인", "낚시터"]), ): await ctx.defer() @@ -195,7 +197,11 @@ async def 낚시중지(self, ctx: discord.commands.context.ApplicationContext): @slash_command(name="도감", description="물고기의 정보 or 도감을 보여드려요!", guild_ids=SCRS) @on_working(prohibition=True) - async def 도감(self, ctx: discord.commands.context.ApplicationContext, fish_name: Option(str, "검색하고 싶은 물고기 이름") = None): + async def 도감( + self, + ctx: discord.commands.context.ApplicationContext, + fish_name: Option(str, "검색하고 싶은 물고기 이름") = None, + ): await ctx.defer() # 물고기가 낚인 이후 @@ -248,7 +254,11 @@ async def 도감(self, ctx: discord.commands.context.ApplicationContext, fish_na @slash_command(name="분석", description="물고기가 낚이는 확률을 보여드려요!", guild_ids=SCRS) @commands.cooldown(3, 30) - async def 분석(self, ctx: discord.commands.context.ApplicationContext, type: Option(str, "분석 결과의 종류", choices=["일반", "단순 표현"])): + async def 분석( + self, + ctx: discord.commands.context.ApplicationContext, + type: Option(str, "분석 결과의 종류", choices=["일반", "단순 표현"]), + ): await ctx.defer() accuracy = 20 diff --git a/cogs/fishing/game.py b/cogs/fishing/game.py index 1e0f785..6ac8f00 100644 --- a/cogs/fishing/game.py +++ b/cogs/fishing/game.py @@ -51,13 +51,17 @@ def __init__(self, ctx): @discord.ui.button( label="낚싯줄 당기기", style=discord.ButtonStyle.blurple, emoji="🎣" ) - async def button1_callback(self, button: discord.ui.Button, interaction: discord.Interaction): + async def button1_callback( + self, button: discord.ui.Button, interaction: discord.Interaction + ): self.button_value = "당김" self.stop() await interaction.response.defer() @discord.ui.button(label="그만하기", style=discord.ButtonStyle.red, emoji="🚫") - async def button2_callback(self, button: discord.ui.Button, interaction: discord.Interaction): + async def button2_callback( + self, button: discord.ui.Button, interaction: discord.Interaction + ): self.button_value = "그만둠" self.stop() diff --git a/cogs/fishing/unit.py b/cogs/fishing/unit.py index 878786e..deb35b1 100644 --- a/cogs/fishing/unit.py +++ b/cogs/fishing/unit.py @@ -384,8 +384,7 @@ async def interaction_check(self, interaction) -> bool: @slash_command(name="시설", description="특정 티어의 시설중 낚시터에 알려드려요!", guild_ids=SCRS) @on_working(fishing=True, prohibition=True, landwork=True, twoball=False) - async def 시설(self, ctx, - tier: Option(int, "시설 목록을 알고 싶은 특정 티어를 입력해주세요!") = 1): + async def 시설(self, ctx, tier: Option(int, "시설 목록을 알고 싶은 특정 티어를 입력해주세요!") = 1): room = Room(ctx.channel) if room.tier < int(tier): diff --git a/config.example.py b/config.example.py index 9394a88..23ab35e 100644 --- a/config.example.py +++ b/config.example.py @@ -23,7 +23,7 @@ """ FishCard Server Setting""" CARD_SERVER = "http://localhost:3000" # 슬래시로 끝내지 말아주세요 -CARD_TOKEN = os.getenv('IMAGE_GENERATOR_TOKEN', '') # python scripts/genscript.py +CARD_TOKEN = os.getenv("IMAGE_GENERATOR_TOKEN", "") # python scripts/genscript.py """ Discord Bot Configuration """ TOKEN = "" diff --git a/db/seta_json.py b/db/seta_json.py index 81cc7b0..aec0428 100644 --- a/db/seta_json.py +++ b/db/seta_json.py @@ -1,4 +1,4 @@ -'''seta_JSON 1.0 +"""seta_JSON 1.0 제작 : 키뮤소프트 파이썬 초보자 분들의 JSON 사용을 더욱 편리하게 만들어 드리는 모듈입니다. @@ -8,7 +8,7 @@ 이 모듈을 사용하는 py 파일과 같은 경로에 놓은 뒤 코드 맨 윗 줄에 import seta_json as sj ...이라고 적어 주세요. (뒤의 'as sj'는 그냥 추천) -''' +""" import json import os @@ -16,16 +16,16 @@ def set_json(exist: str, content: dict): - '''content를 json 형식으로 exist 경로에 저장합니다. - 예) sj.set_json('키뮤귀여워.json', {'키뮤':1004})''' - logger.query(f'{exist} 작성') + """content를 json 형식으로 exist 경로에 저장합니다. + 예) sj.set_json('키뮤귀여워.json', {'키뮤':1004})""" + logger.query(f"{exist} 작성") - with open(exist, 'w', encoding="utf-8") as make_file: + with open(exist, "w", encoding="utf-8") as make_file: json.dump(content, make_file, ensure_ascii=False, indent="\t") def get_json(exist: str, default_content=False): - '''exist 경로의 json 파일을 불러옵니다. + """exist 경로의 json 파일을 불러옵니다. 예) my_dict = sj.get_json('키뮤귀여워.json') 파일이 없는 경우 None을 반환합니다. @@ -33,11 +33,11 @@ def get_json(exist: str, default_content=False): 예) my_dict = sj.get_json('키뮤귀여워.json', default_content={'키뮤':1004}) → 키뮤귀여워.json을 불러오지만 파일이 없을 경우 {'키뮤':1004} 내용으로 키뮤귀여워.json을 만듦. - ※ 이 경우 반환값은 default_content ({'키뮤':1004})임.''' - logger.query(f'{exist} 로드') + ※ 이 경우 반환값은 default_content ({'키뮤':1004})임.""" + logger.query(f"{exist} 로드") if not os.path.isfile(exist): if not default_content: - print('[SETA_Module/ERROR] ' + exist + ' 파일은 존재하지 않습니다.') + print("[SETA_Module/ERROR] " + exist + " 파일은 존재하지 않습니다.") return None else: set_json(exist, default_content) diff --git a/db/seta_pgsql.py b/db/seta_pgsql.py index 21c7224..10d22bf 100644 --- a/db/seta_pgsql.py +++ b/db/seta_pgsql.py @@ -6,12 +6,14 @@ class S_PgSQL: def __init__(self): - if (config.HOST == 'localhost' or config.HOST == '127.0.0.1') and not config.debug: + if ( + config.HOST == "localhost" or config.HOST == "127.0.0.1" + ) and not config.debug: self.conn = psycopg2.connect( dbname=config.DBNAME, user=config.USER, password=config.PASSWORD, - port=config.PORT + port=config.PORT, ) else: self.conn = psycopg2.connect( @@ -19,11 +21,11 @@ def __init__(self): dbname=config.DBNAME, user=config.USER, password=config.PASSWORD, - port=config.PORT + port=config.PORT, ) self.cur = self.conn.cursor() - def update_sql(self, table: str, rec: str, where: str = '', commit=True): + def update_sql(self, table: str, rec: str, where: str = "", commit=True): """ 설명 : 조건에 맞는 행의 내용을 수정함 update_sql(테이블명, 수정할 열의 이름과 값, 수정할 행의 조건, DB 경로) @@ -34,8 +36,8 @@ def update_sql(self, table: str, rec: str, where: str = '', commit=True): > seta_sqlite.update_sql('테이블', "kimu=3", "kawaii=1", '키뮤.sql') """ - if where != '' and not where.startswith('WHERE'): - where = 'WHERE ' + where + if where != "" and not where.startswith("WHERE"): + where = "WHERE " + where self.sql(f"UPDATE {table} SET {rec} {where}", commit=commit) return True @@ -49,19 +51,22 @@ def insert_sql(self, table: str, rec: str, val: str, commit=True): > seta_sqlite.insert_sql('테이블', "kimu, seta", "'kawaii', 4", '키뮤.sql') → 테이블의 kimu 열에 kawaii, seta 열에 4 값이 들어간 행이 추가됨 """ - self.sql("INSERT INTO " + table + " (" + rec + ") VALUES (" + val + ")", commit=commit) + self.sql( + "INSERT INTO " + table + " (" + rec + ") VALUES (" + val + ")", + commit=commit, + ) def insert_dict(self, table: str, dictionary: dict): - columns = ', '.join(dictionary.keys()) + columns = ", ".join(dictionary.keys()) values = [self.autoquotes(i) for i in dictionary.values()] - values = ', '.join(values) + values = ", ".join(values) statement = "INSERT INTO " + table + f" ({columns}) VALUES ({values})" logger.query(statement) self.cur.execute(statement) self.commit() - def select_sql(self, table: str, rec: str, rule: str = ''): - ''' + def select_sql(self, table: str, rec: str, rule: str = ""): + """ 설명 : (조건에 맞는) 행의 내용을 불러옴 selectsql(테이블명, 불러올 열의 이름, 불러올 행의 조건, DB 경로) ※ 파일이 없는 경우 False 반환 @@ -70,46 +75,48 @@ def select_sql(self, table: str, rec: str, rule: str = ''): ---- EXAMPLE ---- > seta_sqlite.select_sql('테이블', "kimu, seta", "kimu=1", '키뮤.sql') → 테이블에서 kimu 값이 1인 행에서 kimu, seta열 값을 모두 받아옴. - ''' - if rule != '' and not rule.startswith('WHERE') and not rule.startswith('ORDER'): - rule = 'WHERE ' + rule - return self.sql("SELECT " + rec + " FROM " + table + ' ' + rule, True) + """ + if rule != "" and not rule.startswith("WHERE") and not rule.startswith("ORDER"): + rule = "WHERE " + rule + return self.sql("SELECT " + rec + " FROM " + table + " " + rule, True) def delete_sql(self, table: str, rule: str): - ''' + """ 설명 : 조건에 맞는 행을 삭제함 delete_sql(테이블명, 삭제할 행의 조건, DB 경로) ---- EXAMPLE ---- > seta_sqlite.delete_sql('테이블', "WHERE kimu=1", '키뮤.sql') - ''' + """ self.sql("DELETE FROM " + table + " " + rule) - def is_sql(self, table: str, rule: str = ''): - ''' + def is_sql(self, table: str, rule: str = ""): + """ 설명 : 조건에 맞는 행이 있는 지의 여부(True, False)를 반환함 is_sql(테이블명, 조건, DB 경로) ---- EXAMPLE ---- > seta_sqlite.is_sql('테이블', "WHERE kimu=1", '키뮤.sql') - ''' - result = self.sql("select exists(select * from " + table + ' ' + rule + ")", True) + """ + result = self.sql( + "select exists(select * from " + table + " " + rule + ")", True + ) return result[0][0] def sql(self, qur, reading=False, commit=True): - ''' + """ 설명 : SQL문을 사용함 sql(SQL쿼리, DB 경로, writing) ※ rt 설명 reading True이면 fetchall로 결과를 반환 reading False이면 결과를 반환하지 않고 commit함. - ''' + """ logger.query(qur) try: self.cur.execute(qur) except Exception as e: - print(f'[오류] {e}') + print(f"[오류] {e}") if reading: return self.cur.fetchall() @@ -123,7 +130,7 @@ def autoquotes(self, value): if isinstance(value, int): return str(value) else: - value = "'" + str(value).replace('\"', "\\'") + "'" + value = "'" + str(value).replace('"', "\\'") + "'" return value def json_convert(self, val): diff --git a/db/seta_sqlite.py b/db/seta_sqlite.py index 14e139f..53e19a1 100644 --- a/db/seta_sqlite.py +++ b/db/seta_sqlite.py @@ -7,7 +7,7 @@ def __init__(self, path: str): self.conn = sqlite3.connect(path, check_same_thread=False) self.cur = self.conn.cursor() - def update_sql(self, table: str, rec: str, where: str = '', commit=True): + def update_sql(self, table: str, rec: str, where: str = "", commit=True): """ 설명 : 조건에 맞는 행의 내용을 수정함 update_sql(테이블명, 수정할 열의 이름과 값, 수정할 행의 조건, DB 경로) @@ -18,8 +18,8 @@ def update_sql(self, table: str, rec: str, where: str = '', commit=True): > seta_sqlite.update_sql('테이블', "kimu=3", "kawaii=1", '키뮤.sql') """ - if not where == '': - where = ' WHERE ' + where + if not where == "": + where = " WHERE " + where self.sql("UPDATE " + table + " SET " + rec + where, commit=commit) return True @@ -33,11 +33,14 @@ def insert_sql(self, table: str, rec: str, val: str, commit=True): > seta_sqlite.insert_sql('테이블', "kimu, seta", "'kawaii', 4", '키뮤.sql') → 테이블의 kimu 열에 kawaii, seta 열에 4 값이 들어간 행이 추가됨 """ - self.sql("INSERT into " + table + " (" + rec + ") VALUES (" + val + ")", commit=commit) + self.sql( + "INSERT into " + table + " (" + rec + ") VALUES (" + val + ")", + commit=commit, + ) return True - def select_sql(self, table: str, rec: str, rule: str = ''): - ''' + def select_sql(self, table: str, rec: str, rule: str = ""): + """ 설명 : (조건에 맞는) 행의 내용을 불러옴 selectsql(테이블명, 불러올 열의 이름, 불러올 행의 조건, DB 경로) ※ 파일이 없는 경우 False 반환 @@ -46,39 +49,41 @@ def select_sql(self, table: str, rec: str, rule: str = ''): ---- EXAMPLE ---- > seta_sqlite.select_sql('테이블', "kimu, seta", "WHERE kimu=1", '키뮤.sql') → 테이블에서 kimu 값이 1인 행에서 kimu, seta열 값을 모두 받아옴. - ''' - return self.sql("SELECT " + rec + " FROM " + table + ' ' + rule, True) + """ + return self.sql("SELECT " + rec + " FROM " + table + " " + rule, True) def delete_sql(self, table: str, rule: str): - ''' + """ 설명 : 조건에 맞는 행을 삭제함 delete_sql(테이블명, 삭제할 행의 조건, DB 경로) ---- EXAMPLE ---- > seta_sqlite.delete_sql('테이블', "WHERE kimu=1", '키뮤.sql') - ''' + """ self.sql("DELETE FROM " + table + " " + rule) - def is_sql(self, table: str, rule: str = ''): - ''' + def is_sql(self, table: str, rule: str = ""): + """ 설명 : 조건에 맞는 행이 있는 지의 여부(True, False)를 반환함 is_sql(테이블명, 조건, DB 경로) ---- EXAMPLE ---- > seta_sqlite.is_sql('테이블', "WHERE kimu=1", '키뮤.sql') - ''' - result = self.sql("select exists(select * from " + table + ' ' + rule + ")", True) + """ + result = self.sql( + "select exists(select * from " + table + " " + rule + ")", True + ) return result[0][0] def sql(self, qur, reading=False, commit=True): - ''' + """ 설명 : SQL문을 사용함 sql(SQL쿼리, DB 경로, writing) ※ rt 설명 reading True이면 fetchall로 결과를 반환 reading False이면 결과를 반환하지 않고 commit함. - ''' + """ logger.query(qur) try: self.cur.execute(qur) diff --git a/main.py b/main.py index 2726aa8..2bf4e56 100644 --- a/main.py +++ b/main.py @@ -101,7 +101,9 @@ async def on_command(self, ctx): logger.msg(ctx.message) @commands.Cog.listener() - async def on_application_command_error(self, ctx: discord.commands.context.ApplicationContext, error: Exception): + async def on_application_command_error( + self, ctx: discord.commands.context.ApplicationContext, error: Exception + ): """명령어 내부에서 오류 발생 시 작동하는 코드 부분""" channel = ctx.channel User(ctx.author).fishing_now = False diff --git a/scripts/gensecret.py b/scripts/gensecret.py index 94069d1..2fcc12f 100644 --- a/scripts/gensecret.py +++ b/scripts/gensecret.py @@ -1,4 +1,4 @@ import secrets -with open('.env', 'a') as f: - f.writelines([f'IMAGE_GENERATOR_TOKEN={secrets.token_hex(24)}', '\n']) +with open(".env", "a") as f: + f.writelines([f"IMAGE_GENERATOR_TOKEN={secrets.token_hex(24)}", "\n"]) diff --git a/static/hanspell/__init__.py b/static/hanspell/__init__.py index 21569bf..f901408 100644 --- a/static/hanspell/__init__.py +++ b/static/hanspell/__init__.py @@ -1 +1 @@ -__version__ = '1.1' \ No newline at end of file +__version__ = "1.1" diff --git a/static/hanspell/constants.py b/static/hanspell/constants.py index a76663f..ccddfbc 100644 --- a/static/hanspell/constants.py +++ b/static/hanspell/constants.py @@ -1,4 +1,5 @@ -base_url = 'https://m.search.naver.com/p/csearch/ocontent/spellchecker.nhn' +base_url = "https://m.search.naver.com/p/csearch/ocontent/spellchecker.nhn" + class CheckResult: PASSED = 0 diff --git a/static/hanspell/response.py b/static/hanspell/response.py index 699bead..9501d12 100644 --- a/static/hanspell/response.py +++ b/static/hanspell/response.py @@ -2,20 +2,26 @@ from collections import namedtuple # 조사와 어미도 단어로 처리함. 마땅한 영단어가 생각이 안 나서.. -_checked = namedtuple('Checked', - ['result', 'original', 'checked', 'errors', 'words', 'time']) +_checked = namedtuple( + "Checked", ["result", "original", "checked", "errors", "words", "time"] +) + + class Checked(_checked): - def __new__(cls, result=False, original='', checked='', errors=0, words=[], time=0.0): + def __new__( + cls, result=False, original="", checked="", errors=0, words=[], time=0.0 + ): return super(Checked, cls).__new__( - cls, result, original, checked, errors, words, time) + cls, result, original, checked, errors, words, time + ) def as_dict(self): d = { - 'result': self.result, - 'original': self.original, - 'checked': self.checked, - 'errors': self.errors, - 'words': self.words, - 'time': self.time, + "result": self.result, + "original": self.original, + "checked": self.checked, + "errors": self.errors, + "words": self.words, + "time": self.time, } return d diff --git a/static/hanspell/spell_checker.py b/static/hanspell/spell_checker.py index 2eeab21..6973ec2 100644 --- a/static/hanspell/spell_checker.py +++ b/static/hanspell/spell_checker.py @@ -21,11 +21,11 @@ def _remove_tags(text): - text = u'{}'.format(text).replace('
', '') + text = "{}".format(text).replace("
", "") if not PY3: - text = text.encode('utf-8') + text = text.encode("utf-8") - result = ''.join(ET.fromstring(text).itertext()) + result = "".join(ET.fromstring(text).itertext()) return result @@ -45,13 +45,11 @@ def check(text): if len(text) > 500: return Checked(result=False) - payload = { - '_callback': 'window.__jindo2_callback._spellingCheck_0', - 'q': text - } + payload = {"_callback": "window.__jindo2_callback._spellingCheck_0", "q": text} headers = { - 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36', 'referer': 'https://search.naver.com/' + "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36", + "referer": "https://search.naver.com/", } start_time = time.time() @@ -61,52 +59,54 @@ def check(text): r = r.text[42:-2] data = json.loads(r) - html = data['message']['result']['html'] + html = data["message"]["result"]["html"] result = { - 'result': True, - 'original': text, - 'checked': _remove_tags(html), - 'errors': data['message']['result']['errata_count'], - 'time': passed_time, - 'words': OrderedDict(), + "result": True, + "original": text, + "checked": _remove_tags(html), + "errors": data["message"]["result"]["errata_count"], + "time": passed_time, + "words": OrderedDict(), } # 띄어쓰기로 구분하기 위해 태그는 일단 보기 쉽게 바꿔둠. # ElementTree의 iter()를 써서 더 좋게 할 수 있는 방법이 있지만 # 이 짧은 코드에 굳이 그렇게 할 필요성이 없으므로 일단 문자열을 치환하는 방법으로 작성. - html = html.replace('', '') \ - .replace('', '') \ - .replace('', '') \ - .replace('', '') - items = html.split(' ') + html = ( + html.replace("", "") + .replace("", "") + .replace("", "") + .replace("", "") + ) + items = html.split(" ") words = [] - tmp = '' + tmp = "" for word in items: - if tmp == '' and word[:1] == '<': - pos = word.find('>') + 1 + if tmp == "" and word[:1] == "<": + pos = word.find(">") + 1 tmp = word[:pos] - elif tmp != '': - word = u'{}{}'.format(tmp, word) + elif tmp != "": + word = "{}{}".format(tmp, word) - if word[-5:] == '': - word = word.replace('', '') - tmp = '' + if word[-5:] == "": + word = word.replace("", "") + tmp = "" words.append(word) for word in words: check_result = CheckResult.PASSED - if word[:5] == '': + if word[:5] == "": check_result = CheckResult.WRONG_SPELLING - word = word.replace('', '') - elif word[:7] == '': + word = word.replace("", "") + elif word[:7] == "": check_result = CheckResult.WRONG_SPACING - word = word.replace('', '') - elif word[:8] == '': + word = word.replace("", "") + elif word[:8] == "": check_result = CheckResult.AMBIGUOUS - word = word.replace('', '') + word = word.replace("", "") - result['words'][word] = check_result + result["words"][word] = check_result result = Checked(**result) diff --git a/utils/fish_card/fish_card.py b/utils/fish_card/fish_card.py index 563b610..3092574 100644 --- a/utils/fish_card/fish_card.py +++ b/utils/fish_card/fish_card.py @@ -17,25 +17,33 @@ font12 = ImageFont.truetype(font_exist, 12) font8 = ImageFont.truetype(font_exist, 8) -default_fontset = {8: font8, 12: font12, 14: font14, 16: font16, 20: font20, 24: font24, 28: font28} +default_fontset = { + 8: font8, + 12: font12, + 14: font14, + 16: font16, + 20: font20, + 24: font24, + 28: font28, +} async def get_card(fish=None, room=None, user=None): theme = user.theme - theme_exist = f"{here}/theme/{theme}".replace('\\', '/') - theme = seta_json.get_json(f'{theme_exist}/theme.json') + theme_exist = f"{here}/theme/{theme}".replace("\\", "/") + theme = seta_json.get_json(f"{theme_exist}/theme.json") # 레이아웃 - if f'rank-{fish.rarity}' not in theme.keys(): - layout = theme['default'] + if f"rank-{fish.rarity}" not in theme.keys(): + layout = theme["default"] else: - layout = theme[f'rank-{fish.rarity}'] + layout = theme[f"rank-{fish.rarity}"] # 카드 배경 불러오기 - if os.path.isfile(f'{theme_exist}/rank-{fish.rarity}.png'): - img = Image.open(f'{theme_exist}/rank-{fish.rarity}.png') + if os.path.isfile(f"{theme_exist}/rank-{fish.rarity}.png"): + img = Image.open(f"{theme_exist}/rank-{fish.rarity}.png") else: - img = Image.open(f'{theme_exist}/default.png') + img = Image.open(f"{theme_exist}/default.png") # font 불러오기 if "font" not in theme.keys(): @@ -60,46 +68,42 @@ async def get_card(fish=None, room=None, user=None): "length": f"{fish.length:,}", # 물고기 크기 "average_cost": f"{fish.average_cost:,}", # 평균 물고기 크기 "average_length": f"{fish.average_length}", # 물고기 평균가 - "fees_p": f"{-1 * (room.fee + room.maintenance):+}", # 수수료 + 유지비 (%) "fee_p": f"{room.fee:+}", # 수수료 (%) "maintenance_p": f"{room.maintenance:+}", # 유지비 (%) "bonus_p": f"{room.bonus:+}", # 보너스 (%) - "fees": f"{fish.fee(user, room) + fish.maintenance(room):+,}", # 수수료 + 유지비 "fee": f"{fish.fee(user, room):+,}", # 수수료 "maintenance": f"{fish.maintenance(room):+,}", # 유지비 "bonus": f"{fish.bonus(room):+,}", # 보너스 - - "time": time.strftime('%Y-%m-%d %H'), # 현재 시간 + "time": time.strftime("%Y-%m-%d %H"), # 현재 시간 "roomname": deEmojify(room.name), # 낚은 낚시터 이름 "username": deEmojify(user.name), # 낚은 유저의 이름 - - "profit": f"{fish.cost() + fish.fee(user, room) + fish.maintenance(room) + fish.bonus(room):,}" + "profit": f"{fish.cost() + fish.fee(user, room) + fish.maintenance(room) + fish.bonus(room):,}", } OWNER = room.owner_id == user.id for object in layout: - if 'owner' in object.keys() and object['owner'] != OWNER: + if "owner" in object.keys() and object["owner"] != OWNER: continue - elif 'rarity' in object.keys() and object['rarity'] != fish.rarity: + elif "rarity" in object.keys() and object["rarity"] != fish.rarity: continue color = (0, 0, 0) - if 'color' in object.keys(): - color = tuple(object['color']) + if "color" in object.keys(): + color = tuple(object["color"]) draw.text( - tuple(object['position']), - Josa().convert(object['text'].format(**format_dict)), - font=fontset[object['size']], - fill=color - ) + tuple(object["position"]), + Josa().convert(object["text"].format(**format_dict)), + font=fontset[object["size"]], + fill=color, + ) return img def deEmojify(inputString): - result = inputString.encode('euc-kr', 'ignore').decode('euc-kr') - if result == '': - return '알 수 없는 이름' + result = inputString.encode("euc-kr", "ignore").decode("euc-kr") + if result == "": + return "알 수 없는 이름" else: return result diff --git a/utils/fish_card/utils/fish_card/fishcard.py b/utils/fish_card/utils/fish_card/fishcard.py index 645ef94..de9fa8a 100644 --- a/utils/fish_card/utils/fish_card/fishcard.py +++ b/utils/fish_card/utils/fish_card/fishcard.py @@ -14,14 +14,23 @@ def getCard(fish=None, room=None, user=None): - img = Image.open(f'utils/fish_card/card_type_{fish.rarity}.png') # 일단 기본배경폼 이미지를 open 합니다. + img = Image.open( + f"utils/fish_card/card_type_{fish.rarity}.png" + ) # 일단 기본배경폼 이미지를 open 합니다. draw = ImageDraw.Draw(img) cost = fish.cost() fee = fish.fee(user, room) + fish.maintenance(room) bonus = fish.bonus(room) - text_up = {0: '{}을(를) 낚아 버렸다;;;', 1: '{}이(가) 낚였다!', 2: '와! {}을(를) 낚았다!!!', 3: '월척이야!!! {}을 낚다니!', 4: '이건... {}?!?!', 5: '{}(이)라고?!?! 가능한 거야???'} + text_up = { + 0: "{}을(를) 낚아 버렸다;;;", + 1: "{}이(가) 낚였다!", + 2: "와! {}을(를) 낚았다!!!", + 3: "월척이야!!! {}을 낚다니!", + 4: "이건... {}?!?!", + 5: "{}(이)라고?!?! 가능한 거야???", + } text = Josa().convert(text_up[fish.rarity].format(fish.name)) if len(text) < 13: @@ -32,11 +41,23 @@ def getCard(fish=None, room=None, user=None): if fish.rarity != 0: if room.owner_id == user.id: - draw.text((72, 85), f"{fee:+,}$ ({-1 * room.maintenance:+}%)", font=font16, fill=(50, 0, 0)) + draw.text( + (72, 85), + f"{fee:+,}$ ({-1 * room.maintenance:+}%)", + font=font16, + fill=(50, 0, 0), + ) draw.text((72, 38), "낚시터 주인", font=font8) else: - draw.text((72, 85), f"{fee:+,}$ ({-1 * (room.fee + room.maintenance):+}%)", font=font16, fill=(50, 0, 0)) - draw.text((72, 105), f"{bonus:+,}$ ({room.bonus:+}%)", font=font16, fill=(0, 50, 0)) + draw.text( + (72, 85), + f"{fee:+,}$ ({-1 * (room.fee + room.maintenance):+}%)", + font=font16, + fill=(50, 0, 0), + ) + draw.text( + (72, 105), f"{bonus:+,}$ ({room.bonus:+}%)", font=font16, fill=(0, 50, 0) + ) draw.text((85, 145), f"{(cost + fee + bonus):,}$", font=font24, fill=(0, 0, 0)) if len(fish.name) < 6: @@ -50,21 +71,35 @@ def getCard(fish=None, room=None, user=None): time = datetime.today() draw.text((290, 160), f"『{deEmojify(user.name)}』", font=font8, fill=(0, 0, 0)) - draw.text((280, 170), f"{time.strftime('%Y-%m-%d %H')}시에 '{deEmojify(room.name)}'에서", font=font8, fill=(0, 0, 0)) + draw.text( + (280, 170), + f"{time.strftime('%Y-%m-%d %H')}시에 '{deEmojify(room.name)}'에서", + font=font8, + fill=(0, 0, 0), + ) # img.show() return img def getCard_eng(fish=None, room=None, user=None): - img = Image.open(f'utils/fish_card/en_card_{fish.rarity}.png') # 일단 기본배경폼 이미지를 open 합니다. + img = Image.open( + f"utils/fish_card/en_card_{fish.rarity}.png" + ) # 일단 기본배경폼 이미지를 open 합니다. draw = ImageDraw.Draw(img) cost = fish.cost() fee = fish.fee(user, room) + fish.maintenance(room) bonus = fish.bonus(room) - text_up = {0: 'I caught the {} ...', 1: 'I caught a {}!', 2: 'WOW! I caught the a {}!!!', 3: "I caught a {}! I can't belive it!!!", 4: 'This is... {}?!?!', 5: '{}?! Is it possible?!?!'} + text_up = { + 0: "I caught the {} ...", + 1: "I caught a {}!", + 2: "WOW! I caught the a {}!!!", + 3: "I caught a {}! I can't belive it!!!", + 4: "This is... {}?!?!", + 5: "{}?! Is it possible?!?!", + } text = text_up[fish.rarity].format(fish.eng_name) if len(text) < 13: @@ -75,10 +110,22 @@ def getCard_eng(fish=None, room=None, user=None): if fish.rarity != 0: if room.owner_id == user.id: - draw.text((72, 85), f"{fee:,}$ (OWNER {room.maintenance}%)", font=font16, fill=(50, 0, 0)) + draw.text( + (72, 85), + f"{fee:,}$ (OWNER {room.maintenance}%)", + font=font16, + fill=(50, 0, 0), + ) else: - draw.text((72, 85), f"{fee:,}$ ({room.fee + room.maintenance}%)", font=font16, fill=(50, 0, 0)) - draw.text((72, 105), f"+{bonus:,}$ ({room.bonus}%)", font=font16, fill=(0, 50, 0)) + draw.text( + (72, 85), + f"{fee:,}$ ({room.fee + room.maintenance}%)", + font=font16, + fill=(50, 0, 0), + ) + draw.text( + (72, 105), f"+{bonus:,}$ ({room.bonus}%)", font=font16, fill=(0, 50, 0) + ) draw.text((85, 145), f"{(cost + fee + bonus):,}$", font=font24, fill=(0, 0, 0)) if len(fish.name) < 6: @@ -86,22 +133,31 @@ def getCard_eng(fish=None, room=None, user=None): else: draw.text((350, 60), f"{fish.eng_name}", font=font20, fill=(0, 0, 0)) draw.text((350, 90), f"{fish.length}cm", font=font20, fill=(0, 0, 0)) - draw.text((350, 115), f"(Average {fish.average_length}cm)", font=font12, fill=(0, 0, 0)) + draw.text( + (350, 115), f"(Average {fish.average_length}cm)", font=font12, fill=(0, 0, 0) + ) draw.text((350, 130), f"{fish.cost():,}$", font=font20, fill=(0, 0, 0)) - draw.text((350, 155), f"(Average {fish.average_cost:,}$)", font=font12, fill=(0, 0, 0)) + draw.text( + (350, 155), f"(Average {fish.average_cost:,}$)", font=font12, fill=(0, 0, 0) + ) time = datetime.today() draw.text((290, 160), f"『{deEmojify(user.name)}』", font=font8, fill=(0, 0, 0)) - draw.text((280, 170), f"In the '{deEmojify(room.name)}' at {time.strftime('%Y-%m-%d %H')}", font=font8, fill=(0, 0, 0)) + draw.text( + (280, 170), + f"In the '{deEmojify(room.name)}' at {time.strftime('%Y-%m-%d %H')}", + font=font8, + fill=(0, 0, 0), + ) # img.show() return img def deEmojify(inputString): - fifinal = inputString.encode('euc-kr', 'ignore').decode('euc-kr') - if fifinal == '': - return '알 수 없는 이름' + fifinal = inputString.encode("euc-kr", "ignore").decode("euc-kr") + if fifinal == "": + return "알 수 없는 이름" else: return fifinal diff --git a/utils/fish_card/utils/fish_card_new/editor.py b/utils/fish_card/utils/fish_card_new/editor.py index 321af06..4bb1d1f 100644 --- a/utils/fish_card/utils/fish_card_new/editor.py +++ b/utils/fish_card/utils/fish_card_new/editor.py @@ -2,9 +2,9 @@ from utils.fish_card_new.fish_card import get_card -class ExampleFish(): +class ExampleFish: id = 123 - name = '물고기' + name = "물고기" cost = 1234 def fee(self, *args): @@ -14,14 +14,14 @@ def maintenance(self, *args): return 5 -class ExampleUser(): +class ExampleUser: id = 123456789 - name = '유저 이름' + name = "유저 이름" -class ExampleRoom(): +class ExampleRoom: id = 123456789 - name = '낚시터 이름' + name = "낚시터 이름" fish = ExampleFish() diff --git a/utils/fish_card/utils/fish_card_new/fish_card.py b/utils/fish_card/utils/fish_card_new/fish_card.py index 7ff9001..1c1653e 100644 --- a/utils/fish_card/utils/fish_card_new/fish_card.py +++ b/utils/fish_card/utils/fish_card_new/fish_card.py @@ -16,17 +16,17 @@ fonts = {8: font8, 12: font12, 16: font16, 20: font20, 24: font24} -def get_card(fish=None, room=None, user=None, theme='default'): +def get_card(fish=None, room=None, user=None, theme="default"): here = os.path.dirname(os.path.realpath(__file__)) theme_exist = f"{here}/theme/{theme}" - theme = seta_json.get_json(f'{theme_exist}/theme.json') + theme = seta_json.get_json(f"{theme_exist}/theme.json") - if f'rank-{fish.rarity}' not in theme.keys(): - img = Image.open(f'{theme_exist}/default.png') - layout = theme['default'] + if f"rank-{fish.rarity}" not in theme.keys(): + img = Image.open(f"{theme_exist}/default.png") + layout = theme["default"] else: - img = Image.open(f'{theme_exist}/rank-{fish.rarity}.png') - layout = theme[f'rank-{fish.rarity}'] + img = Image.open(f"{theme_exist}/rank-{fish.rarity}.png") + layout = theme[f"rank-{fish.rarity}"] draw = ImageDraw.Draw(img) time = datetime.today() @@ -37,38 +37,37 @@ def get_card(fish=None, room=None, user=None, theme='default'): "length": f"{fish.length:,}", # 물고기 크기 "average_cost": f"{fish.average_cost:,}", # 평균 물고기 크기 "average_length": f"{fish.average_length}", # 물고기 평균가 - "fees_p": room.fee + room.maintenance, # 수수료 + 유지비 (%) "fee_p": room.fee, # 수수료 (%) - "maintenance_p": room.maintenance, #유지비 (%) + "maintenance_p": room.maintenance, # 유지비 (%) "bonus_p": room.bonus, # 보너스 (%) - "fees": fish.fee(user, room) + fish.maintenance(room), # 수수료 + 유지비 - "fee": fish.fee(user, room), # 수수료 - "maintenance": fish.maintenance(room), #유지비 + "fee": fish.fee(user, room), # 수수료 + "maintenance": fish.maintenance(room), # 유지비 "bonus": fish.bonus(room), # 보너스 - - "time": time.strftime('%Y-%m-%d %H'), # 현재 시간 + "time": time.strftime("%Y-%m-%d %H"), # 현재 시간 "roomname": room.name, # 낚은 낚시터 이름 "username": deEmojify(user.name), # 낚은 유저의 이름 - - "profit": fish.cost() + fish.fee(user, room) + fish.maintenance(room) + fish.bonus(room) + "profit": fish.cost() + + fish.fee(user, room) + + fish.maintenance(room) + + fish.bonus(room), } for object in layout: draw.text( - tuple(object['position']), - Josa().convert(object['text']).format(format_dict), - font=fonts[object['size']], - fill=(0, 0, 0) - ) + tuple(object["position"]), + Josa().convert(object["text"]).format(format_dict), + font=fonts[object["size"]], + fill=(0, 0, 0), + ) return img def deEmojify(inputString): - result = inputString.encode('euc-kr', 'ignore').decode('euc-kr') - if result == '': - return '알 수 없는 이름' + result = inputString.encode("euc-kr", "ignore").decode("euc-kr") + if result == "": + return "알 수 없는 이름" else: return result diff --git a/utils/fish_card/utils/logger.py b/utils/fish_card/utils/logger.py index 7a04663..783ed1a 100644 --- a/utils/fish_card/utils/logger.py +++ b/utils/fish_card/utils/logger.py @@ -1,11 +1,11 @@ -''' +""" 기록을 쉽게 남길 수 있게 해 주는 모듈이에요! print()보다는 logger.info()를 추천드려요! logger.py를 통해서 기록을 남기면 logs 폴더 안에 날짜 별로 기록이 자동으로 정리되니까 편할 거예요! ※ 파이썬 초심자라면 이 파일을 수정하지 않는 것을 추천드려요! - 키뮤 제작(0127 버전) -''' +""" from datetime import datetime from discord import DMChannel @@ -14,59 +14,60 @@ def err(error): - ''' + """ 오류 기록을 남길 때 사용해요! - ''' + """ try: raise error except Exception: error_message = traceback.format_exc() - log('[오류] {}\n\n'.format(error_message), True) + log("[오류] {}\n\n".format(error_message), True) return error_message def warn(msg: str): - ''' + """ 경고 기록을 남길 때 사용해요! - ''' - log('[경고] {}'.format(msg)) + """ + log("[경고] {}".format(msg)) def info(msg: str): - ''' + """ 일반적인 기록을 남길 때 사용해요! - ''' - log('[정보] {}'.format(msg)) + """ + log("[정보] {}".format(msg)) def debug(msg: str): - ''' + """ 디버그 모드를 켰을 때만 기록해 줘요! - ''' + """ pass def msg(message): - ''' + """ 디스코드 메시지를 깔끔하게 정리해 기록해 줘요! - ''' - if message.content == '': + """ + if message.content == "": return None author = message.author - '''message를 넣으면 로그를 씀''' + """message를 넣으면 로그를 씀""" if isinstance(message.channel, DMChannel): - log_msg = 'DM <{}> {}'.format(author.name, message.content) + log_msg = "DM <{}> {}".format(author.name, message.content) else: guild = message.guild channel = message.channel - log_msg = '{server} <{channel} | {user} | {id}> {text}'.format( + log_msg = "{server} <{channel} | {user} | {id}> {text}".format( server=guild.name, channel=channel.name, user=author.name, text=message.content, - id=author.id) + id=author.id, + ) log(log_msg) @@ -75,7 +76,7 @@ def log(msg: str, iserror=False): now = datetime.now() hour = now.strftime("%H") minute = now.strftime("%M") - log_msg = '{}시 {}분 / {}'.format(hour, minute, msg) + log_msg = "{}시 {}분 / {}".format(hour, minute, msg) print(log_msg) save(log_msg) if iserror: @@ -83,24 +84,24 @@ def log(msg: str, iserror=False): def save(msg): - if not(os.path.isdir('logs')): - os.makedirs(os.path.join('logs')) + if not (os.path.isdir("logs")): + os.makedirs(os.path.join("logs")) now = datetime.now() - time_text = now.strftime('%Y-%m-%d') + time_text = now.strftime("%Y-%m-%d") if not os.path.isfile("logs/log_" + time_text + ".txt"): - f = open("logs/log_" + time_text + ".txt", 'w', encoding='utf-8') + f = open("logs/log_" + time_text + ".txt", "w", encoding="utf-8") else: - f = open("logs/log_" + time_text + ".txt", 'a', encoding='utf-8') - f.write(msg + '\n') + f = open("logs/log_" + time_text + ".txt", "a", encoding="utf-8") + f.write(msg + "\n") f.close() def save_error(msg): now = datetime.now() - time_text = now.strftime('%Y-%m-%d') + time_text = now.strftime("%Y-%m-%d") if not os.path.isfile("logs/error_log_" + time_text + ".txt"): - f = open("logs/error_log_" + time_text + ".txt", 'w', encoding='utf-8') + f = open("logs/error_log_" + time_text + ".txt", "w", encoding="utf-8") else: - f = open("logs/error_log_" + time_text + ".txt", 'a', encoding='utf-8') - f.write(msg + '\n') + f = open("logs/error_log_" + time_text + ".txt", "a", encoding="utf-8") + f.write(msg + "\n") f.close() diff --git a/utils/fish_card/utils/on_working.py b/utils/fish_card/utils/on_working.py index 227d42c..5f8e1b8 100644 --- a/utils/fish_card/utils/on_working.py +++ b/utils/fish_card/utils/on_working.py @@ -7,23 +7,24 @@ def on_working(fishing=False, landwork=False, prohibition=False, owner_only=False): - ''' - fishing : 낚시와 동시에 불가능 - landwork : 낚시터 작업 중이면 불가능 - prohibition : #낚시금지 태그가 있으면 불가능 - owner_only : 낚시터 주인만 작업 가능 - ''' + """ + fishing : 낚시와 동시에 불가능 + landwork : 낚시터 작업 중이면 불가능 + prohibition : #낚시금지 태그가 있으면 불가능 + owner_only : 낚시터 주인만 작업 가능 + """ + async def predicate(ctx: discord.commands.context.ApplicationContext): channel = ctx.channel if isinstance(channel, DMChannel): - await ctx.send(f'으에, 이프는 DM은 안 받고 이써!\n`❗ 이프와는 개인 메시지로 놀 수 없습니다.`') + await ctx.send(f"으에, 이프는 DM은 안 받고 이써!\n`❗ 이프와는 개인 메시지로 놀 수 없습니다.`") return False if fishing: # 낚시 중에는 금지 if on_fishing(ctx.author.id): try: - await ctx.respond('낚시 중에는 낚시에 집중하자...!\n`❗ 이미 낚시가 진행 중이다.`') + await ctx.respond("낚시 중에는 낚시에 집중하자...!\n`❗ 이미 낚시가 진행 중이다.`") except Exception: pass return False @@ -31,22 +32,26 @@ async def predicate(ctx: discord.commands.context.ApplicationContext): if landwork: # 땅 작업 중에는 금지 if working_now(ctx.channel.id): try: - await ctx.respond('흐음... 여기 뭔가 하고 있는 거 같은데 조금 이따가 와 보자!\n`❗ 누군가 이미 땅에서 매입/매각/건설/철거 등의 작업을 하는 중이다.`') + await ctx.respond( + "흐음... 여기 뭔가 하고 있는 거 같은데 조금 이따가 와 보자!\n`❗ 누군가 이미 땅에서 매입/매각/건설/철거 등의 작업을 하는 중이다.`" + ) except Exception: pass return False if prohibition: # 낚시금지를 했다면 금지 - if channel.topic is not None and '#낚시금지' in channel.topic: + if channel.topic is not None and "#낚시금지" in channel.topic: try: await ctx.respond("여긴 낚시터가 아니야...\n`❗ 낚시 금지 태그가 설정된 채널입니다.`") except Exception: pass return False - if channel.topic is not None and '#no_fishing' in channel.topic: + if channel.topic is not None and "#no_fishing" in channel.topic: try: - await ctx.respond("You can't fish here! >ㅅ<\n`❗ This channel is tagged with no fishing.`") + await ctx.respond( + "You can't fish here! >ㅅ<\n`❗ This channel is tagged with no fishing.`" + ) except Exception: pass return False @@ -55,17 +60,19 @@ async def predicate(ctx: discord.commands.context.ApplicationContext): room = Room(channel) if room.owner_id != ctx.author.id: try: - await ctx.respond('다른 사람 땅은 건들 수 없어...!\n`❗ 자신의 땅에서만 할 수 있는 작업이다.`') + await ctx.respond("다른 사람 땅은 건들 수 없어...!\n`❗ 자신의 땅에서만 할 수 있는 작업이다.`") except Exception: pass return False return True + return check(predicate) def administrator(): - '''이프 관리자만 사용 가능하게 설정할 경우''' + """이프 관리자만 사용 가능하게 설정할 경우""" + async def predicate(ctx: discord.commands.context.ApplicationContext): if not User(ctx.author).admin: try: @@ -74,29 +81,39 @@ async def predicate(ctx: discord.commands.context.ApplicationContext): pass return False return True + return check(predicate) def p_requirements(manage_messages=False): - '''이프의 권한이 있어야 사용 가능한 명령어''' + """이프의 권한이 있어야 사용 가능한 명령어""" + async def predicate(ctx: discord.commands.context.ApplicationContext): if isinstance(ctx.channel, DMChannel): return False per = ctx.channel.guild.me.permissions_in(ctx.channel) if not per.send_messages: # 애초에 보내지도 못하면 할 수가 없지 - logger.warn(f'{ctx.channel.name}({ctx.channel.id})에서 메시지 보내기 권한이 없음') + logger.warn(f"{ctx.channel.name}({ctx.channel.id})에서 메시지 보내기 권한이 없음") return False - perdict = {'메시지 기록 보기': per.read_message_history, '반응 추가하기': per.add_reactions, '링크 첨부하기': per.embed_links, '파일 첨부하기': per.attach_files} + perdict = { + "메시지 기록 보기": per.read_message_history, + "반응 추가하기": per.add_reactions, + "링크 첨부하기": per.embed_links, + "파일 첨부하기": per.attach_files, + } if manage_messages: - perdict['메시지 관리하기'] = per.manage_messages + perdict["메시지 관리하기"] = per.manage_messages if False in perdict.values(): - text = '✔️ 메시지 읽기\n✔️ 메시지 보내기' + text = "✔️ 메시지 읽기\n✔️ 메시지 보내기" for i in perdict.keys(): text += f"\n{'✔️' if perdict[i] else '❌'} {i}" - await ctx.respond(f"으우... 마력이 부족해!\n`❗ 아래에 '❌'로 뜨는 권한을 이프에게 주세요!`\n```css\n{text}```") + await ctx.respond( + f"으우... 마력이 부족해!\n`❗ 아래에 '❌'로 뜨는 권한을 이프에게 주세요!`\n```css\n{text}```" + ) return False return True + return check(predicate) diff --git a/utils/fish_card/utils/seta_josa.py b/utils/fish_card/utils/seta_josa.py index 7dc0a17..a7e617f 100644 --- a/utils/fish_card/utils/seta_josa.py +++ b/utils/fish_card/utils/seta_josa.py @@ -1,29 +1,29 @@ -''' +""" 한국어 조사 변환 자체 라이브러리입니다. -''' +""" import hgtk import re class Josa: def convert(self, string: str): - string = string.replace('(이)랑', '랑(이랑)') - string = string.replace('(으)로', '로(으로)') - string = string.replace('(이)다', '다(이다)') - string = string.replace('(이)잖', '잖(이잖)') - string = string.replace('(이)자', '자(이자)') - string = string.replace('(이)라', '라(이라)') + string = string.replace("(이)랑", "랑(이랑)") + string = string.replace("(으)로", "로(으로)") + string = string.replace("(이)다", "다(이다)") + string = string.replace("(이)잖", "잖(이잖)") + string = string.replace("(이)자", "자(이자)") + string = string.replace("(이)라", "라(이라)") - ls = string.split(' ') + ls = string.split(" ") for k in ls: - p = re.compile(r'..\(.+\)') + p = re.compile(r"..\(.+\)") r = p.findall(k) for i in r: - p = re.compile(r'(.).\(.+\)') - josa_list = i[1:].replace(')', '').split('(') - if '잖' in i or '자' in i: + p = re.compile(r"(.).\(.+\)") + josa_list = i[1:].replace(")", "").split("(") + if "잖" in i or "자" in i: josa_list.sort(reverse=True) else: josa_list.sort() @@ -34,7 +34,7 @@ def convert(self, string: str): string = string.replace(i, i[0] + josa_list[0]) continue - if dec[2] == '': + if dec[2] == "": string = string.replace(i, i[0] + josa_list[0]) else: string = string.replace(i, i[0] + josa_list[1]) diff --git a/utils/fish_card/utils/seta_json.py b/utils/fish_card/utils/seta_json.py index c399dc8..87117ef 100644 --- a/utils/fish_card/utils/seta_json.py +++ b/utils/fish_card/utils/seta_json.py @@ -1,4 +1,4 @@ -'''seta_JSON 1.0 +"""seta_JSON 1.0 제작 : 키뮤소프트 파이썬 초보자 분들의 JSON 사용을 더욱 편리하게 만들어 드리는 모듈입니다. @@ -8,7 +8,7 @@ 이 모듈을 사용하는 py 파일과 같은 경로에 놓은 뒤 코드 맨 윗 줄에 import seta_json as sj ...이라고 적어 주세요. (뒤의 'as sj'는 그냥 추천) -''' +""" import json import os @@ -16,16 +16,16 @@ def set_json(exist: str, content: dict): - '''content를 json 형식으로 exist 경로에 저장합니다. - 예) sj.set_json('키뮤귀여워.json', {'키뮤':1004})''' - logger.debug(f'{exist} 작성') + """content를 json 형식으로 exist 경로에 저장합니다. + 예) sj.set_json('키뮤귀여워.json', {'키뮤':1004})""" + logger.debug(f"{exist} 작성") - with open(exist, 'w', encoding="utf-8") as make_file: + with open(exist, "w", encoding="utf-8") as make_file: json.dump(content, make_file, ensure_ascii=False, indent="\t") def get_json(exist: str, default_content=False): - '''exist 경로의 json 파일을 불러옵니다. + """exist 경로의 json 파일을 불러옵니다. 예) my_dict = sj.get_json('키뮤귀여워.json') 파일이 없는 경우 None을 반환합니다. @@ -33,11 +33,11 @@ def get_json(exist: str, default_content=False): 예) my_dict = sj.get_json('키뮤귀여워.json', default_content={'키뮤':1004}) → 키뮤귀여워.json을 불러오지만 파일이 없을 경우 {'키뮤':1004} 내용으로 키뮤귀여워.json을 만듦. - ※ 이 경우 반환값은 default_content ({'키뮤':1004})임.''' - logger.debug(f'{exist} 로드') + ※ 이 경우 반환값은 default_content ({'키뮤':1004})임.""" + logger.debug(f"{exist} 로드") if not os.path.isfile(exist): if not default_content: - print('[SETA_Module/ERROR] ' + exist + ' 파일은 존재하지 않습니다.') + print("[SETA_Module/ERROR] " + exist + " 파일은 존재하지 않습니다.") return None else: set_json(exist, default_content) diff --git a/utils/fish_card/utils/seta_sqlite_class.py b/utils/fish_card/utils/seta_sqlite_class.py index 9438570..fd2754b 100644 --- a/utils/fish_card/utils/seta_sqlite_class.py +++ b/utils/fish_card/utils/seta_sqlite_class.py @@ -1,4 +1,4 @@ -''' +""" seta_SQLite 1.0 제작 : 키뮤소프트, 녹스 @@ -9,7 +9,7 @@ 이 모듈을 사용하는 py 파일과 같은 경로에 놓은 뒤 코드 맨 윗 줄에 import seta_sqlite ...이라고 적어 주세요! -''' +""" import sqlite3 import os @@ -21,7 +21,7 @@ def __init__(self, path: str): self.conn = sqlite3.connect(path, check_same_thread=False) self.cur = self.conn.cursor() - def update_sql(self, table: str, rec: str, where: str = '', commit=True): + def update_sql(self, table: str, rec: str, where: str = "", commit=True): """ 설명 : 조건에 맞는 행의 내용을 수정함 update_sql(테이블명, 수정할 열의 이름과 값, 수정할 행의 조건, DB 경로) @@ -32,8 +32,8 @@ def update_sql(self, table: str, rec: str, where: str = '', commit=True): > seta_sqlite.update_sql('테이블', "kimu=3", "kawaii=1", '키뮤.sql') """ - if not where == '': - where = ' WHERE ' + where + if not where == "": + where = " WHERE " + where self.sql("UPDATE " + table + " SET " + rec + where, commit=commit) return True @@ -47,11 +47,14 @@ def insert_sql(self, table: str, rec: str, val: str, commit=True): > seta_sqlite.insert_sql('테이블', "kimu, seta", "'kawaii', 4", '키뮤.sql') → 테이블의 kimu 열에 kawaii, seta 열에 4 값이 들어간 행이 추가됨 """ - self.sql("INSERT into " + table + " (" + rec + ") VALUES (" + val + ")", commit=commit) + self.sql( + "INSERT into " + table + " (" + rec + ") VALUES (" + val + ")", + commit=commit, + ) return True - def select_sql(self, table: str, rec: str, rule: str = ''): - ''' + def select_sql(self, table: str, rec: str, rule: str = ""): + """ 설명 : (조건에 맞는) 행의 내용을 불러옴 selectsql(테이블명, 불러올 열의 이름, 불러올 행의 조건, DB 경로) ※ 파일이 없는 경우 False 반환 @@ -60,39 +63,41 @@ def select_sql(self, table: str, rec: str, rule: str = ''): ---- EXAMPLE ---- > seta_sqlite.select_sql('테이블', "kimu, seta", "WHERE kimu=1", '키뮤.sql') → 테이블에서 kimu 값이 1인 행에서 kimu, seta열 값을 모두 받아옴. - ''' - return self.sql("SELECT " + rec + " FROM " + table + ' ' + rule, True) + """ + return self.sql("SELECT " + rec + " FROM " + table + " " + rule, True) def delete_sql(self, table: str, rule: str): - ''' + """ 설명 : 조건에 맞는 행을 삭제함 delete_sql(테이블명, 삭제할 행의 조건, DB 경로) ---- EXAMPLE ---- > seta_sqlite.delete_sql('테이블', "WHERE kimu=1", '키뮤.sql') - ''' + """ self.sql("DELETE FROM " + table + " " + rule) - def is_sql(self, table: str, rule: str = ''): - ''' + def is_sql(self, table: str, rule: str = ""): + """ 설명 : 조건에 맞는 행이 있는 지의 여부(True, False)를 반환함 is_sql(테이블명, 조건, DB 경로) ---- EXAMPLE ---- > seta_sqlite.is_sql('테이블', "WHERE kimu=1", '키뮤.sql') - ''' - result = self.sql("select exists(select * from " + table + ' ' + rule + ")", True) + """ + result = self.sql( + "select exists(select * from " + table + " " + rule + ")", True + ) return result[0][0] def sql(self, qur, reading=False, commit=True): - ''' + """ 설명 : SQL문을 사용함 sql(SQL쿼리, DB 경로, writing) ※ rt 설명 reading True이면 fetchall로 결과를 반환 reading False이면 결과를 반환하지 않고 commit함. - ''' + """ logger.debug(qur) try: self.cur.execute(qur) diff --git a/utils/fish_card/utils/tag.py b/utils/fish_card/utils/tag.py index 4d75131..b61b88c 100644 --- a/utils/fish_card/utils/tag.py +++ b/utils/fish_card/utils/tag.py @@ -1,39 +1,39 @@ -'''이프의 태그 관련 기능이 모인 모듈''' +"""이프의 태그 관련 기능이 모인 모듈""" from utils import logger from utils import seta_json as sj # 문자열 -> 태그, 혹은 복합태그 tagdict = { - '욕설금지': 'yok', - '야한말금지': 'emr', - '정치언급금지': 'jci', - '정치발언금지': 'jci', - '거친말금지': ['yok', 'gcm'], - '변태금지': ['emr', 'bta'], - '건전': ['yok', 'emr', 'jci'], - '존댓말': ['예요체', 'ㅂ니다체'], - '고운말': ['yok', 'emr', 'jci', 'gcm', 'bta'], - '반말': '반말' - } + "욕설금지": "yok", + "야한말금지": "emr", + "정치언급금지": "jci", + "정치발언금지": "jci", + "거친말금지": ["yok", "gcm"], + "변태금지": ["emr", "bta"], + "건전": ["yok", "emr", "jci"], + "존댓말": ["예요체", "ㅂ니다체"], + "고운말": ["yok", "emr", "jci", "gcm", "bta"], + "반말": "반말", +} # 태그코드 -> 문자열 tagtostr = { - 'yok': '욕설 금지', - 'emr': '야한 말 금지', - 'bta': '변태 금지', - 'gcm': '거친 말 금지', - 'jci': '정치 발언 금지' - } + "yok": "욕설 금지", + "emr": "야한 말 금지", + "bta": "변태 금지", + "gcm": "거친 말 금지", + "jci": "정치 발언 금지", +} # 금칙어 관련 태그 -prohibit_tags = sj.get_json('db/bad_words.json').keys() +prohibit_tags = sj.get_json("db/bad_words.json").keys() def get_log_channel(message): log_channel = None for i in message.guild.text_channels: - if '#기록' in str(i.topic): + if "#기록" in str(i.topic): log_channel = i if log_channel is None: log_channel = message.channel @@ -53,15 +53,15 @@ def tag_to_korean(tags: list): def get_tags(channel): # 태그의 형태로 존재하는 것을 리스트에 담음 topic = channel.topic - if topic is None or '#' not in topic: + if topic is None or "#" not in topic: return [] - topic = topic.replace('_', '').replace(',', '') + topic = topic.replace("_", "").replace(",", "") - p = str(topic).split(' ') + p = str(topic).split(" ") tags = [] for i in p: - if i.startswith('#'): - tags.append(i.replace('#', '')) + if i.startswith("#"): + tags.append(i.replace("#", "")) for i in tagdict.keys(): if i in tags: diff --git a/utils/fish_card/utils/util_box.py b/utils/fish_card/utils/util_box.py index df0ce44..20c27c8 100644 --- a/utils/fish_card/utils/util_box.py +++ b/utils/fish_card/utils/util_box.py @@ -1,10 +1,10 @@ -''' +""" 자잘하지만 있으면 편한 함수들이 많이 있답니다. 제가 쓰던 거 그대로여서 지저분해요. 나중에 정리해서 업데이트할게요. ※ 봇 개발 초심자라면 이 파일을 수정하지 않는 것을 추천드려요! - 키뮤 제작(0127 버전) -''' +""" import asyncio import random @@ -14,14 +14,14 @@ async def ox(bot, message, ctx, auto_delete=True): - ''' + """ 🅾️❎ 이모지 선택지를 만들어 줘요! 🅾️를 누르면 0를 반환해요(True) ❎를 누르면 1를 반환하고(False) 만약 시간이 초과되면 2를 반환해요(False) ※ 헷갈림 주의 - ''' - result = await wait_for_reaction(bot, message, ['🅾️', '❎'], 10, ctx) + """ + result = await wait_for_reaction(bot, message, ["🅾️", "❎"], 10, ctx) if auto_delete: try: await message.clear_reactions() @@ -29,21 +29,27 @@ async def ox(bot, message, ctx, auto_delete=True): logger.warn(f"'{ctx.guild.name}'에서 이프에게 메시지 관리 권한을 주지 않음") if not result: return 2 - elif result.emoji == '❎': + elif result.emoji == "❎": return 1 else: return 0 -async def wait_for_reaction(bot, window, canpress, timeout, ctx, event='reaction_add', add_react=True): - '''지정한 이모지가 눌릴 때까지 기다린 후 눌림 여부에 따라 Bool 방식 반환 - - 시간 초과는 False 반환''' +async def wait_for_reaction( + bot, window, canpress, timeout, ctx, event="reaction_add", add_react=True +): + """지정한 이모지가 눌릴 때까지 기다린 후 눌림 여부에 따라 Bool 방식 반환 + - 시간 초과는 False 반환""" if add_react: for i in list(canpress): await window.add_reaction(i) def check(reaction, user): - if user == ctx.author and str(reaction.emoji) in canpress and reaction.message.id == window.id: + if ( + user == ctx.author + and str(reaction.emoji) in canpress + and reaction.message.id == window.id + ): return True else: return False @@ -58,7 +64,7 @@ def check(reaction, user): return reaction[0] -async def wait_for_saying(bot, timeout, ctx, keyword='', user=None): +async def wait_for_saying(bot, timeout, ctx, keyword="", user=None): if user is None: for_user = ctx.author else: @@ -71,7 +77,7 @@ def check(m): return False try: - msg = await bot.wait_for('message', timeout=timeout, check=check) + msg = await bot.wait_for("message", timeout=timeout, check=check) except asyncio.TimeoutError: return False @@ -81,9 +87,9 @@ def check(m): def rdpc(percentage: float): - '''RanDom PerCents - 퍼센트를 넣으면 그 확률로 Bool 뱉음''' - if random.random() <= percentage/100: + """RanDom PerCents + 퍼센트를 넣으면 그 확률로 Bool 뱉음""" + if random.random() <= percentage / 100: return True else: return False diff --git a/utils/on_working.py b/utils/on_working.py index 2cd0e37..83bc8de 100644 --- a/utils/on_working.py +++ b/utils/on_working.py @@ -13,7 +13,7 @@ def on_working( - fishing=False, landwork=False, prohibition=False, owner_only=False, twoball=True + fishing=False, landwork=False, prohibition=False, owner_only=False, twoball=True ): """ fishing : 낚시와 동시에 불가능 @@ -52,9 +52,9 @@ async def predicate(ctx): if prohibition: # 낚시금지를 했다면 금지 if ( - not isinstance(channel, Thread) - and channel.topic is not None - and "#낚시금지" in channel.topic + not isinstance(channel, Thread) + and channel.topic is not None + and "#낚시금지" in channel.topic ): try: await ctx.respond( diff --git a/utils/seta_josa.py b/utils/seta_josa.py index 7dc0a17..a7e617f 100644 --- a/utils/seta_josa.py +++ b/utils/seta_josa.py @@ -1,29 +1,29 @@ -''' +""" 한국어 조사 변환 자체 라이브러리입니다. -''' +""" import hgtk import re class Josa: def convert(self, string: str): - string = string.replace('(이)랑', '랑(이랑)') - string = string.replace('(으)로', '로(으로)') - string = string.replace('(이)다', '다(이다)') - string = string.replace('(이)잖', '잖(이잖)') - string = string.replace('(이)자', '자(이자)') - string = string.replace('(이)라', '라(이라)') + string = string.replace("(이)랑", "랑(이랑)") + string = string.replace("(으)로", "로(으로)") + string = string.replace("(이)다", "다(이다)") + string = string.replace("(이)잖", "잖(이잖)") + string = string.replace("(이)자", "자(이자)") + string = string.replace("(이)라", "라(이라)") - ls = string.split(' ') + ls = string.split(" ") for k in ls: - p = re.compile(r'..\(.+\)') + p = re.compile(r"..\(.+\)") r = p.findall(k) for i in r: - p = re.compile(r'(.).\(.+\)') - josa_list = i[1:].replace(')', '').split('(') - if '잖' in i or '자' in i: + p = re.compile(r"(.).\(.+\)") + josa_list = i[1:].replace(")", "").split("(") + if "잖" in i or "자" in i: josa_list.sort(reverse=True) else: josa_list.sort() @@ -34,7 +34,7 @@ def convert(self, string: str): string = string.replace(i, i[0] + josa_list[0]) continue - if dec[2] == '': + if dec[2] == "": string = string.replace(i, i[0] + josa_list[0]) else: string = string.replace(i, i[0] + josa_list[1]) diff --git a/utils/util_box.py b/utils/util_box.py index 4e44ab8..8b4dc93 100644 --- a/utils/util_box.py +++ b/utils/util_box.py @@ -1,10 +1,10 @@ -''' +""" 자잘하지만 있으면 편한 함수들이 많이 있답니다. 제가 쓰던 거 그대로여서 지저분해요. 나중에 정리해서 업데이트할게요. ※ 봇 개발 초심자라면 이 파일을 수정하지 않는 것을 추천드려요! - 키뮤 제작(0127 버전) -''' +""" import asyncio import random @@ -13,14 +13,14 @@ async def ox(bot, message, ctx, auto_delete=True): - ''' + """ 🅾️❎ 이모지 선택지를 만들어 줘요! 🅾️를 누르면 0를 반환해요(False) ❎를 누르면 1를 반환하고(True) 만약 시간이 초과되면 2를 반환해요(True) ※ 헷갈림 주의 - ''' - result = await wait_for_reaction(bot, message, ['🅾️', '❎'], 10, ctx) + """ + result = await wait_for_reaction(bot, message, ["🅾️", "❎"], 10, ctx) if auto_delete: try: await message.clear_reactions() @@ -28,21 +28,27 @@ async def ox(bot, message, ctx, auto_delete=True): logger.warn(f"'{ctx.guild.name}'에서 이프에게 메시지 관리 권한을 주지 않음") if not result: return 2 - elif result.emoji == '❎': + elif result.emoji == "❎": return 1 else: return 0 -async def wait_for_reaction(bot, window, canpress, timeout, ctx, event='reaction_add', add_react=True): - '''지정한 이모지가 눌릴 때까지 기다린 후 눌림 여부에 따라 Bool 방식 반환 - - 시간 초과는 False 반환''' +async def wait_for_reaction( + bot, window, canpress, timeout, ctx, event="reaction_add", add_react=True +): + """지정한 이모지가 눌릴 때까지 기다린 후 눌림 여부에 따라 Bool 방식 반환 + - 시간 초과는 False 반환""" if add_react: for i in list(canpress): await window.add_reaction(i) def check(reaction, user): - if user == ctx.author and str(reaction.emoji) in canpress and reaction.message.id == window.id: + if ( + user == ctx.author + and str(reaction.emoji) in canpress + and reaction.message.id == window.id + ): return True else: return False @@ -57,7 +63,7 @@ def check(reaction, user): return reaction[0] -async def wait_for_saying(bot, timeout, ctx, keyword='', user=None): +async def wait_for_saying(bot, timeout, ctx, keyword="", user=None): if user is None: for_user = ctx.author else: @@ -70,7 +76,7 @@ def check(m): return False try: - msg = await bot.wait_for('message', timeout=timeout, check=check) + msg = await bot.wait_for("message", timeout=timeout, check=check) except asyncio.TimeoutError: return False @@ -80,9 +86,9 @@ def check(m): def rdpc(percentage: float): - '''RanDom PerCents - 퍼센트를 넣으면 그 확률로 Bool 뱉음''' - if random.random() <= percentage/100: + """RanDom PerCents + 퍼센트를 넣으면 그 확률로 Bool 뱉음""" + if random.random() <= percentage / 100: return True else: return False