From 8fc98eabbe859297d9ce0f5276570a9deb3abd33 Mon Sep 17 00:00:00 2001 From: 9Hundred100Five1 <69020075+9Hundred100Five1@users.noreply.github.com> Date: Wed, 14 Sep 2022 00:00:06 +0900 Subject: [PATCH 01/11] feat: added rate per unit --- functions/currency.py | 1 + 1 file changed, 1 insertion(+) diff --git a/functions/currency.py b/functions/currency.py index c807d25..5547034 100644 --- a/functions/currency.py +++ b/functions/currency.py @@ -126,6 +126,7 @@ async def currency( color=Constants.EMBED_COLOR["default"], ) .add_field(name="입력한 값", value=f"`{start:,}`원", inline=False) + .add_field(name=f"1 `{unit}` 당 원 ", value=f"`{end:.2f}` 원", inline=True) .add_field(name="변환된 값", value=f"`{result:.2f}` `{unit}`", inline=False) ) return await ctx.followup.send(embed=embed) From ff3b9b9642bfd893aff197f4eefed4e7aead3031 Mon Sep 17 00:00:00 2001 From: 9Hundred100Five1 Date: Fri, 21 Oct 2022 22:44:15 +0900 Subject: [PATCH 02/11] fix: unnecessory using db --- functions/currency.py | 67 +++++++++++++++++++++---------------------- 1 file changed, 32 insertions(+), 35 deletions(-) diff --git a/functions/currency.py b/functions/currency.py index 5547034..96a8a0d 100644 --- a/functions/currency.py +++ b/functions/currency.py @@ -19,7 +19,6 @@ import requests from utils.commands import slash_command import os -from utils.database import CurrencyDatabase import utils.logging import logging from utils.utils import to_querystring @@ -89,7 +88,7 @@ def __init__(self, bot): logger.warning("API Key가 없습니다") @slash_command( - name="환율", + name="테스트_환율", description="현재 시간 기준 환율로 환전합니다.", ) async def currency( @@ -106,32 +105,11 @@ async def currency( color=Constants.EMBED_COLOR["default"], ) return await ctx.respond(embed=err) - + await ctx.defer() unit = units[to[4:]] - db_unit = units.get(to[4:]) - await self.db_update(unit) - - if await CurrencyDatabase.currency_find(db_unit): - found = await CurrencyDatabase.currency_find(db_unit) - - end = int(found[f"country_{db_unit}"]) - result = start / end - if unit == "IDR(100)" or unit == "JPY(100)": - unit = unit[:3] - embed = ( - discord.Embed( - title=f"{Constants.EMOJI['check']} 변환된 값 정보", - description="변환된 값의 정보를 반환했어요", - color=Constants.EMBED_COLOR["default"], - ) - .add_field(name="입력한 값", value=f"`{start:,}`원", inline=False) - .add_field(name=f"1 `{unit}` 당 원 ", value=f"`{end:.2f}` 원", inline=True) - .add_field(name="변환된 값", value=f"`{result:.2f}` `{unit}`", inline=False) - ) - return await ctx.followup.send(embed=embed) - - else: + found = await self.find(unit) + if found == False: err = discord.Embed( title="주말/ 공휴일, 또는 밤 11시 이후에는 환율 조회가 불가능해요", description="나중에 다시 시도해주세요\n[Team White 디스코드 서버](https://discord.gg/aebSVBgzuG)", @@ -139,22 +117,41 @@ async def currency( ) return await ctx.followup.send(embed=err) + + found = int(found) # 환율 불러오는 함수 리턴값 + result = start / found # 환율로 입력한값 나눠서 환전 - async def db_update(self, unit): + + embed = ( + discord.Embed( + title=f"{Constants.EMOJI['check']} 변환된 값 정보", + description="변환된 값의 정보를 반환했어요", + color=Constants.EMBED_COLOR["default"], + ) + .add_field(name=f"1 `{unit}` 당 원 ", value=f"`{found:.2f}` 원", inline=False) + .add_field(name="입력한 값", value=f"`{start:,}`원", inline=False) + .add_field(name="변환된 값", value=f"`{result:.2f}` `{unit}`", inline=False) + ) + + await ctx.followup.send(embed=embed) + + async def find(self, unit): base_url = "https://www.koreaexim.go.kr/site/program/financial/exchangeJSON?" headers = {"authkey": os.getenv("CURRENCY"), "data": "AP01", "cur_unit": unit} req = requests.get(base_url + to_querystring(headers)) - data = req.json() + res = req.json() + + status = res[0]["result"] + + if status != "1": + return False + + value = res[0]["bkpr"].replace(",", "") # json에서 환율 값 추출 - await CurrencyDatabase.currency_reset() - for i in data: - dol = i["bkpr"] - re = dol.replace(",", "") - name = i["cur_unit"] - await CurrencyDatabase.currency_add(name, re) + return value def setup(bot): - bot.add_cog(Currency(bot)) + bot.add_cog(Currency(bot)) \ No newline at end of file From 60578220a45a347efc5f2bb976f118a1c4939a4c Mon Sep 17 00:00:00 2001 From: 9Hundred100Five1 Date: Fri, 21 Oct 2022 22:49:43 +0900 Subject: [PATCH 03/11] refactor: fix code quality --- functions/currency.py | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/functions/currency.py b/functions/currency.py index 96a8a0d..6c11ee9 100644 --- a/functions/currency.py +++ b/functions/currency.py @@ -105,11 +105,11 @@ async def currency( color=Constants.EMBED_COLOR["default"], ) return await ctx.respond(embed=err) - + await ctx.defer() unit = units[to[4:]] found = await self.find(unit) - if found == False: + if found is False: err = discord.Embed( title="주말/ 공휴일, 또는 밤 11시 이후에는 환율 조회가 불가능해요", description="나중에 다시 시도해주세요\n[Team White 디스코드 서버](https://discord.gg/aebSVBgzuG)", @@ -117,13 +117,12 @@ async def currency( ) return await ctx.followup.send(embed=err) - - found = int(found) # 환율 불러오는 함수 리턴값 - result = start / found # 환율로 입력한값 나눠서 환전 + found = int(found) # 환율 불러오는 함수 리턴값 + result = start / found # 환율로 입력한값 나눠서 환전 embed = ( - discord.Embed( + discord.Embed( title=f"{Constants.EMOJI['check']} 변환된 값 정보", description="변환된 값의 정보를 반환했어요", color=Constants.EMBED_COLOR["default"], @@ -148,10 +147,10 @@ async def find(self, unit): if status != "1": return False - value = res[0]["bkpr"].replace(",", "") # json에서 환율 값 추출 + value = res[0]["bkpr"].replace(",", "") # json에서 환율 값 추출 return value def setup(bot): - bot.add_cog(Currency(bot)) \ No newline at end of file + bot.add_cog(Currency(bot)) From e9e31a4c657ee43212b0701dca7756d0fe353908 Mon Sep 17 00:00:00 2001 From: 9Hundred100Five1 Date: Fri, 27 Jan 2023 00:41:25 +0900 Subject: [PATCH 04/11] =?UTF-8?q?db=20=EC=A0=91=EA=B7=BC=ED=82=A4=20?= =?UTF-8?q?=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.env.example b/.env.example index 7a71638..38ef2bd 100644 --- a/.env.example +++ b/.env.example @@ -13,5 +13,4 @@ WEATHER_KEY= # 날씨 API ID DATABASE_PATH= # DB 경로 # 환율 기능 -CURRENCY= # 환율 API ID -MONGO_URI= # MONGO DB \ No newline at end of file +CURRENCY= # 환율 API ID \ No newline at end of file From 9131744eb5e7c49ad4a238e643964df51003753c Mon Sep 17 00:00:00 2001 From: 9Hundred100Five1 Date: Fri, 27 Jan 2023 00:42:01 +0900 Subject: [PATCH 05/11] =?UTF-8?q?=EC=A0=84=EC=9D=BC=EC=9E=90=20=ED=98=B8?= =?UTF-8?q?=EC=B6=9C=20=EA=B8=B0=EB=8A=A5=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- functions/currency.py | 58 +++++++++++++++++++++++++++++++++---------- 1 file changed, 45 insertions(+), 13 deletions(-) diff --git a/functions/currency.py b/functions/currency.py index 6c11ee9..b2a56ad 100644 --- a/functions/currency.py +++ b/functions/currency.py @@ -23,7 +23,8 @@ import logging from utils.utils import to_querystring from constants import Constants - +from datetime import datetime, date, timedelta +from pytz import timezone utils.logging.setup_logging() logger = logging.getLogger(__name__) @@ -95,7 +96,7 @@ async def currency( self, ctx: ApplicationContext, start: Option(int, "변환할 값(KRW)를 입력하세요. ex) 100000"), - to: Option(str, "변환할 통화를 선택해주세요. ex)USD", choices=choice), + to: Option(str, "변환할 통화를 선택해주세요. ex) USD", choices=choice), ): if self.api_key is None: @@ -109,22 +110,27 @@ async def currency( await ctx.defer() unit = units[to[4:]] found = await self.find(unit) - if found is False: - err = discord.Embed( - title="주말/ 공휴일, 또는 밤 11시 이후에는 환율 조회가 불가능해요", - description="나중에 다시 시도해주세요\n[Team White 디스코드 서버](https://discord.gg/aebSVBgzuG)", - color=Constants.EMBED_COLOR["default"], - ) - - return await ctx.followup.send(embed=err) + if found == False: # 현재일자가 영업일이 아닐시 전일자 호출 + i = 1 + while True: # 조회 가능한 날짜가 나올때까지 계속 호출 + search_again = await self.prev_find(unit, i) + if search_again != False: + search_again = int(search_again) + found = search_again # 재검색한값 + break + i += 1 found = int(found) # 환율 불러오는 함수 리턴값 result = start / found # 환율로 입력한값 나눠서 환전 + formatted_date = ( + datetime.now().astimezone(timezone("Asia/Seoul")) - timedelta(days=i) + ).strftime("%Y년 %m월 %d일") + embed = ( discord.Embed( - title=f"{Constants.EMOJI['check']} 변환된 값 정보", - description="변환된 값의 정보를 반환했어요", + title=f"{Constants.EMOJI['check']} 변환된 값", + description=f"기준일: {formatted_date}", color=Constants.EMBED_COLOR["default"], ) .add_field(name=f"1 `{unit}` 당 원 ", value=f"`{found:.2f}` 원", inline=False) @@ -142,9 +148,35 @@ async def find(self, unit): req = requests.get(base_url + to_querystring(headers)) res = req.json() + if str(res) == "[]": + return False + + status = res[0]["result"] + if status != 1: + return False + + value = res[0]["bkpr"].replace(",", "") # json에서 환율 값 추출 + + return value + + async def prev_find(self, unit, i): # 호출날짜가 영업일이 아닐시 전일자 호출용으로 사용 + base_url = "https://www.koreaexim.go.kr/site/program/financial/exchangeJSON?" + previous_day = ( + datetime.now().astimezone(timezone("Asia/Seoul")) - timedelta(days=i) + ).strftime("%Y%m%d") + headers = { + "authkey": os.getenv("CURRENCY"), + "data": "AP01", + "cur_unit": unit, + "searchdate": previous_day, + } + + req = requests.get(base_url + to_querystring(headers)) + res = req.json() + status = res[0]["result"] - if status != "1": + if status != 1: return False value = res[0]["bkpr"].replace(",", "") # json에서 환율 값 추출 From a0fc502d8a79991e30291fb8db332ce8a8069a04 Mon Sep 17 00:00:00 2001 From: 9Hundred100Five1 Date: Fri, 27 Jan 2023 00:56:25 +0900 Subject: [PATCH 06/11] =?UTF-8?q?=EC=82=AC=EC=9A=A9=ED=95=98=EC=A7=80=20?= =?UTF-8?q?=EC=95=8A=EB=8A=94=20import=20=EC=A0=9C=EA=B1=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- functions/currency.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/functions/currency.py b/functions/currency.py index b2a56ad..806e88e 100644 --- a/functions/currency.py +++ b/functions/currency.py @@ -23,7 +23,7 @@ import logging from utils.utils import to_querystring from constants import Constants -from datetime import datetime, date, timedelta +from datetime import datetime, timedelta from pytz import timezone utils.logging.setup_logging() @@ -110,11 +110,11 @@ async def currency( await ctx.defer() unit = units[to[4:]] found = await self.find(unit) - if found == False: # 현재일자가 영업일이 아닐시 전일자 호출 + if found is False: # 현재일자가 영업일이 아닐시 전일자 호출 i = 1 while True: # 조회 가능한 날짜가 나올때까지 계속 호출 search_again = await self.prev_find(unit, i) - if search_again != False: + if search_again is not False: search_again = int(search_again) found = search_again # 재검색한값 break From 0cf7226653d289b19578473649deb71d967f9f14 Mon Sep 17 00:00:00 2001 From: 910051 <69020075+9Hundred100Five1@users.noreply.github.com> Date: Fri, 27 Jan 2023 16:18:07 +0900 Subject: [PATCH 07/11] =?UTF-8?q?db=20=EC=BD=94=EB=93=9C=20=EC=82=AD?= =?UTF-8?q?=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- functions/currency.py | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/functions/currency.py b/functions/currency.py index d845007..7ae50bc 100644 --- a/functions/currency.py +++ b/functions/currency.py @@ -83,22 +83,6 @@ ] -async def db_update(unit): - base_url = "https://www.koreaexim.go.kr/site/program/financial/exchangeJSON?" - - headers = {"authkey": os.getenv("CURRENCY"), "data": "AP01", "cur_unit": unit} - - req = requests.get(base_url + to_querystring(headers)) - data = req.json() - - await currency_reset() - for i in data: - dol = i["bkpr"] - re = dol.replace(",", "") - name = i["cur_unit"] - await currency_add(name, re) - - class Currency(commands.Cog): def __init__(self, bot): self.bot = bot From 04c962b99fabe1a609e1b286eeb299cff91c4df5 Mon Sep 17 00:00:00 2001 From: 9Hundred100Five1 Date: Fri, 27 Jan 2023 16:21:36 +0900 Subject: [PATCH 08/11] =?UTF-8?q?import=20=EC=9D=B4=EB=A6=84=20=EB=B3=80?= =?UTF-8?q?=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- functions/currency.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/functions/currency.py b/functions/currency.py index 7ae50bc..618d74d 100644 --- a/functions/currency.py +++ b/functions/currency.py @@ -22,7 +22,7 @@ from constants import Constants from utils.commands import slash_command import os -import utils.logging +import utils.logger import logging from utils.utils import to_querystring from constants import Constants From 6c468f788b3f3ca161a870b2f7ce8e781508bfdd Mon Sep 17 00:00:00 2001 From: 9Hundred100Five1 Date: Fri, 27 Jan 2023 16:23:45 +0900 Subject: [PATCH 09/11] =?UTF-8?q?import=20=EC=9D=B4=EB=A6=84=20=EB=B3=80?= =?UTF-8?q?=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- functions/currency.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/functions/currency.py b/functions/currency.py index 618d74d..609ac7d 100644 --- a/functions/currency.py +++ b/functions/currency.py @@ -29,7 +29,7 @@ from datetime import datetime, timedelta from pytz import timezone -utils.logging.setup_logging() +utils.logger.setup_logging() logger = logging.getLogger(__name__) units = { From 1b97892240ba1b5f99b92f0f80d7ad129cce49ae Mon Sep 17 00:00:00 2001 From: 9Hundred100Five1 Date: Fri, 27 Jan 2023 16:30:23 +0900 Subject: [PATCH 10/11] =?UTF-8?q?=EC=8A=AC=EB=9E=98=EC=8B=9C=20=EC=BB=A4?= =?UTF-8?q?=EB=A7=A8=EB=93=9C=20=EC=9D=B4=EB=A6=84=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- functions/currency.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/functions/currency.py b/functions/currency.py index 609ac7d..b7de2df 100644 --- a/functions/currency.py +++ b/functions/currency.py @@ -92,7 +92,7 @@ def __init__(self, bot): logger.warning("API Key가 없습니다") @slash_command( - name="테스트_환율", + name="환율", description="현재 시간 기준 환율로 환전합니다.", ) async def currency( From 5ef7962875212c613ff99a68c5f2d07f671ec0bf Mon Sep 17 00:00:00 2001 From: 9Hundred100Five1 Date: Fri, 27 Jan 2023 16:34:10 +0900 Subject: [PATCH 11/11] =?UTF-8?q?=EB=B3=80=EC=88=98=20=EC=9C=84=EC=B9=98?= =?UTF-8?q?=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- functions/currency.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/functions/currency.py b/functions/currency.py index b7de2df..cb5e92e 100644 --- a/functions/currency.py +++ b/functions/currency.py @@ -112,8 +112,8 @@ async def currency( await ctx.defer() unit = units[to[4:]] found = await self.find(unit) + i = 1 if found is False: # 현재일자가 영업일이 아닐시 전일자 호출 - i = 1 while True: # 조회 가능한 날짜가 나올때까지 계속 호출 search_again = await self.prev_find(unit, i) if search_again is not False: