Skip to content

Commit

Permalink
init send_report_by_keyword.
Browse files Browse the repository at this point in the history
  • Loading branch information
liante0904 committed Aug 22, 2024
1 parent 80e4d76 commit e52e15e
Show file tree
Hide file tree
Showing 2 changed files with 185 additions and 42 deletions.
124 changes: 122 additions & 2 deletions json_to_sqlite.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,133 @@
# JSON 파일 리스트와 대응되는 테이블 이름
json_files = {
"data_main_daily_send.json": "data_main_daily_send",
"hankyungconsen_research.json": "hankyungconsen",
"hankyungconsen_research.json": "hankyungconsen_research",
"naver_research.json": "naver_research"
}

# 명령행 인자 파서 설정
parser = argparse.ArgumentParser(description="SQLite Database Management Script")
parser.add_argument('action', nargs='?', choices=['table', 'insert', 'select', 'keyword_select'], help="Action to perform")
parser.add_argument('action', nargs='?', choices=['table', 'insert', 'select','fetch', 'keyword_select'], help="Action to perform")
parser.add_argument('name', nargs='?', help="Table name for the action")
args = parser.parse_args()

def fetch_data(date=None, keyword=None, user_id=None):
"""특정 테이블에서 데이터를 조회하고, 파라미터가 포함된 실제 쿼리를 출력합니다.
:param date: 조회일자. 'YYYYMMDD' 또는 'YYMMDD' 형식도 지원하며, 없을 경우 오늘 날짜를 사용합니다.
:param keyword: 필수 파라미터로, ARTICLE_TITLE을 검색합니다.
:param user_id: 조회 시 제외할 사용자 ID.
:return: 조회된 데이터의 리스트
"""
# 데이터베이스 연결
conn = sqlite3.connect(db_path)
cursor = conn.cursor()

if date is None:
date = datetime.now().strftime('%Y-%m-%d')
else:
# 날짜가 이미 'YYYY-MM-DD' 형식인지 확인
try:
datetime.strptime(date, '%Y-%m-%d')
except ValueError:
# 날짜 형식 변환 (YYYYMMDD 또는 YYMMDD → YYYY-MM-DD)
if len(date) == 8: # YYYYMMDD
date = datetime.strptime(date, '%Y%m%d').strftime('%Y-%m-%d')
elif len(date) == 6: # YYMMDD
date = datetime.strptime(date, '%y%m%d').strftime('%Y-%m-%d')
else:
raise ValueError("Invalid date format. Use 'YYYYMMDD', 'YYMMDD', or 'YYYY-MM-DD'.")

if keyword is None:
raise ValueError("keyword 파라미터는 필수입니다.")

# 조회할 테이블 목록
tables = ['data_main_daily_send', 'hankyungconsen_research', 'naver_research']
query_parts = []

for table in tables:
query_parts.append(f"""
SELECT FIRM_NM, ARTICLE_TITLE, ATTACH_URL AS ARTICLE_URL, SAVE_TIME, SEND_USER
FROM {table}
WHERE ARTICLE_TITLE LIKE '%{keyword}%'
AND DATE(SAVE_TIME) = '{date}'
AND (SEND_USER IS NULL OR SEND_USER NOT LIKE '%"{user_id}"%')
""")

# 전체 쿼리 조합
final_query = " UNION ".join(query_parts) + " ORDER BY SAVE_TIME ASC, FIRM_NM ASC"

# 쿼리 출력
print("Generated SQL Query:")
print(final_query)

cursor.execute(final_query)
results = cursor.fetchall()

# 조회된 데이터 출력
print("\nFetched Data:")
for row in results:
print(row)

conn.close()
return results



def update_data(date=None, keyword=None, user_ids=None):
"""특정 키워드와 날짜를 기준으로 여러 테이블의 데이터를 업데이트하며, 파라미터가 포함된 실제 쿼리를 출력합니다.
:param date: 조회일자. 'YYYYMMDD' 또는 'YYMMDD' 형식도 지원하며, 없을 경우 오늘 날짜를 사용합니다.
:param keyword: 필수 파라미터로, ARTICLE_TITLE을 검색합니다.
:param user_ids: 필수 파라미터로, SEND_USER 컬럼에 저장할 사용자 ID 리스트. 문자열 형태로 저장됩니다.
"""
if date is None:
date = datetime.now().strftime('%Y-%m-%d')
else:
# 날짜 형식 변환 (YYYYMMDD 또는 YYMMDD → YYYY-MM-DD)
if len(date) == 8: # YYYYMMDD
date = datetime.strptime(date, '%Y%m%d').strftime('%Y-%m-%d')
elif len(date) == 6: # YYMMDD
date = datetime.strptime(date, '%y%m%d').strftime('%Y-%m-%d')
else:
raise ValueError("Invalid date format. Use 'YYYYMMDD', 'YYMMDD', or 'YYYY-MM-DD'.")

if keyword is None:
raise ValueError("keyword 파라미터는 필수입니다.")

if user_ids is None:
raise ValueError("user_ids 파라미터는 필수입니다.")

# 사용자 ID를 JSON 문자열로 변환
user_ids_json = json.dumps(user_ids)

# 데이터베이스 연결
conn = sqlite3.connect(db_path)
cursor = conn.cursor()

# 업데이트할 테이블 목록
tables = ['data_main_daily_send', 'hankyungconsen_research', 'naver_research']

for table in tables:
# 데이터 업데이트 쿼리
update_query = f"""
UPDATE {table}
SET SEND_USER = '{user_ids_json}'
WHERE ARTICLE_TITLE LIKE '%{keyword}%' AND DATE(SAVE_TIME) = '{date}'
"""

# 쿼리 출력
print(f"Generated SQL Query for {table}:")
print(update_query)

cursor.execute(update_query)

# 업데이트된 행 수 출력
print(f"{cursor.rowcount} rows updated in {table}.")

conn.commit()
conn.close()

def print_tables():
"""데이터베이스에 존재하는 테이블 목록을 출력합니다."""
cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
Expand Down Expand Up @@ -179,6 +296,9 @@ def keyword_select(keyword):
insert_data()
elif args.action == 'select':
select_data(args.name)
elif args.action == 'fetch':
print(args.name)
fetch_data(date='2024-08-21', keyword=args.name)
elif args.action == 'keyword_select':
if args.name:
keyword_select(args.name)
Expand Down
103 changes: 63 additions & 40 deletions send_report_by_keyword_to_user.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,40 +4,37 @@
import telegram
import asyncio
from datetime import datetime

# 프로젝트 내부 모듈 경로 추가
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from package.json_util import format_message # import the function from json_util
from package.json_util import format_message, format_message_sql
from package.SecretKey import SecretKey
from package.json_to_sqlite import fetch_data, update_data

# 비밀키 불러오기
SECRET_KEY = SecretKey()
SECRET_KEY.load_secrets()

async def sendMessage(sendMessageText, chat_id=None): #실행시킬 함수명 임의지정
# chat_id가 제공되지 않으면 기본값 사용
# 텔레그램 메시지 발송 함수
async def sendMessage(sendMessageText, chat_id=None):
if chat_id is None:
return

bot = telegram.Bot(token = SECRET_KEY.TELEGRAM_BOT_TOKEN_REPORT_ALARM_SECRET)
return await bot.sendMessage(chat_id = chat_id, text = sendMessageText, disable_web_page_preview = True, parse_mode = "Markdown")

bot = telegram.Bot(token=SECRET_KEY.TELEGRAM_BOT_TOKEN_REPORT_ALARM_SECRET)
return await bot.sendMessage(chat_id=chat_id, text=sendMessageText, disable_web_page_preview=True, parse_mode="Markdown")

# 파일 경로를 현재 디렉토리 기준으로 얻는 함수
def get_file_path(relative_path):
"""
현재 작업 디렉토리를 기준으로 상위 폴더에서 파일 경로를 설정합니다.
:param relative_path: 상위 폴더를 기준으로 한 상대 경로
:return: 파일의 절대 경로
"""
current_dir = os.getcwd()
print(f"Current working directory: {current_dir}")
parent_dir = os.path.abspath(os.path.join(current_dir, os.pardir))
print(f"Parent directory: {parent_dir}")
file_path = os.path.join(parent_dir, relative_path)
return file_path
return os.path.join(parent_dir, relative_path)

# JSON 파일 읽기 함수
def read_json_file(filepath):
print(filepath)
with open(filepath, 'r', encoding='utf-8') as file:
return json.load(file)

# 중복 데이터 제거 및 병합 함수
def remove_duplicates(main_data, *other_data_sources):
unique_firm_names = set(item['FIRM_NM'] for item in main_data)
filtered_data = []
Expand All @@ -50,18 +47,22 @@ def remove_duplicates(main_data, *other_data_sources):

return main_data + filtered_data

# 오늘 날짜 데이터 필터링 함수
def filter_today_data(data):
today = datetime.now().strftime('%Y-%m-%d')
return [item for item in data if item['SAVE_TIME'].startswith(today)]

# 키워드로 데이터 필터링 함수
def filter_by_keyword(data, keyword):
if keyword:
return [item for item in data if keyword in item['ARTICLE_TITLE']]
return data

# SEND_USER로 데이터 필터링 함수
def filter_by_send_user(data, user_id):
return [item for item in data if user_id not in item.get('SEND_USER', [])]

# SEND_USER 업데이트 함수
def update_send_user(data, user_id):
for item in data:
if 'SEND_USER' in item:
Expand Down Expand Up @@ -102,30 +103,52 @@ def update_send_user(data, user_id):
for entry in keywords:
keyword = entry['keyword']
print(f"알림 키워드 : {keyword}")
r = fetch_data(keyword=keyword, user_id=user_id_str)
print('===>',r)

# 키워드로 필터링
keyword_filtered_data = filter_by_keyword(merged_data, keyword)

# 필터링 결과 출력(SEND_USER 필터 전)
print('======필터링 결과 출력(SEND_USER 필터 전)======')
print(keyword_filtered_data)
# # 전송할 메시지 생성 및 발송
if r:
message = f"=====알림 키워드 : {entry['keyword']}=====\n\n"
message += format_message_sql(r)
print('여기==>', message) # 메시지 발송 전에 출력 (디버깅 용도)

# SEND_USER로 필터링
send_user_filtered_data = filter_by_send_user(keyword_filtered_data, user_id_str)

# 필터링 결과 출력(SEND_USER 필터 후)
print('======필터링 결과 출력(SEND_USER 필터 후)======')
print(send_user_filtered_data)

message = f"=====알림 키워드 : {entry['keyword']}=====\n\n"
if send_user_filtered_data:
message += format_message(send_user_filtered_data)
print('여기==>',message) # 메시지 발송 전에 출력 (디버깅 용도)
# 발송 코드 여기에 추가 (예: send_message(user_id_str, message))
# 전송할 메시지 생성 및 발송
if message:
asyncio.run(sendMessage(message, user_id_str))
# SEND_USER에 user_id 추가
merged_data = update_send_user(merged_data, user_id_str)

# 수정된 데이터를 저장 (필요시)
with open(main_file, 'w', encoding='utf-8') as file:
json.dump(merged_data, file, ensure_ascii=False, indent=4)
update_data(keyword=keyword, user_ids= user_id_str)

# # 키워드로 필터링
# keyword_filtered_data = filter_by_keyword(merged_data, keyword)

# # 필터링 결과 출력(SEND_USER 필터 전)
# print('======필터링 결과 출력(SEND_USER 필터 전)======')
# print(keyword_filtered_data)

# # SEND_USER로 필터링
# send_user_filtered_data = filter_by_send_user(keyword_filtered_data, user_id_str)

# # 필터링 결과 출력(SEND_USER 필터 후)
# print('======필터링 결과 출력(SEND_USER 필터 후)======')
# print(send_user_filtered_data)

# # 전송할 메시지 생성 및 발송
# if send_user_filtered_data:
# message = f"=====알림 키워드 : {entry['keyword']}=====\n\n"
# message += format_message(send_user_filtered_data)
# print('여기==>', message) # 메시지 발송 전에 출력 (디버깅 용도)
# asyncio.run(sendMessage(message, user_id_str))

# # 발송된 항목에 대해서만 SEND_USER 업데이트
# for item in send_user_filtered_data:
# merged_data = update_send_user(merged_data, user_id_str)

# # 기존 main_data를 유지하면서 merged_data에서 SEND_USER 정보만 업데이트
# for item in main_data:
# for updated_item in merged_data:
# if item['FIRM_NM'] == updated_item['FIRM_NM']:
# if 'SEND_USER' in updated_item:
# item['SEND_USER'] = updated_item['SEND_USER']

# # 수정된 데이터를 저장
# with open(main_file, 'w', encoding='utf-8') as file:
# json.dump(main_data, file, ensure_ascii=False, indent=4)

0 comments on commit e52e15e

Please sign in to comment.