Python

구글 스프레드 시트 데이터 카카오톡 오픈채팅으로 전송하기

Always-Try 2021. 10. 16. 10:46

본 포스팅에서는 파이썬을 이용하여 PC 카톡이 로그인 되어 있는 상태의 PC에서 구글 스프레드 시트에 있는 데이터를 카카오톡 오픈채팅으로 주기적으로 보내는 방법에 대해 설명한다. 

 

1. 구글 API 서비스 계정 만들기

https://console.developers.google.com/iam-admin/serviceaccounts/

 

Google Cloud Platform

하나의 계정으로 모든 Google 서비스를 Google Cloud Platform을 사용하려면 로그인하세요.

accounts.google.com

위 사이트에 접속하여 서비스 계정 > 프로젝트 만들기 클릭

생성된 프로젝트로 진입하여 서비스 계정 만들기

서비스 계정을 만들면 생성되는 크리덴셜 관련 json 파일을 PC에 저장

 

 

2. 공유할 구글 스프레드 시트 만들고 서비스 계정과 공유하기

공유 대상에는 1번 항목에서 생성했던 아래 형태의 서비스 ID를 입력하면 된다. (xxxxx@nodal-pod~~~~.iam.gserviceaccount.com)

 

 

3. 파이썬 코드 

 

import gspread
from oauth2client.service_account import ServiceAccountCredentials
import time, win32con, win32api, win32gui
import requests
from bs4 import BeautifulSoup
from apscheduler.schedulers.blocking import BlockingScheduler
import time, win32con, win32api, win32gui
from apscheduler.schedulers.background import BackgroundScheduler
import re
# # 카톡창 이름, (활성화 상태의 열려있는 창)
kakao_opentalk_name = '오픈채팅방이름'



values = []
scope = [
'https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive',
]

#서비스 계정 생성 시 발급 받은 json 파일 
json_file_name = 'D:/0.Download/nodal-pod-~~.json'
credentials = ServiceAccountCredentials.from_json_keyfile_name(json_file_name, scope)
gc = gspread.authorize(credentials)
#공유할 스프레드 시트의 URL 주소
spreadsheet_url = 'https://docs.google.com/spreadsheets/~~~~'
doc = gc.open_by_url(spreadsheet_url)
#공유할 시트 및 컬럼
worksheet = doc.worksheet('sheet1')
range_list = worksheet.range('A2:B1')
for cell in range_list:
    values.append(cell.value)
cell_data = worksheet.acell('A2').value
print(cell_data)





# # 채팅방에 메시지 전송
def kakao_sendtext(chatroom_name, text):
    # # 핸들 _ 채팅방
    hwndMain = win32gui.FindWindow( None, chatroom_name)
    hwndEdit = win32gui.FindWindowEx( hwndMain, None, "RICHEDIT50W", None)

    win32api.SendMessage(hwndEdit, win32con.WM_SETTEXT, 0, text)
    SendReturn(hwndEdit)


# # 엔터
def SendReturn(hwnd):
    win32api.PostMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
    time.sleep(0.01)
    win32api.PostMessage(hwnd, win32con.WM_KEYUP, win32con.VK_RETURN, 0)


# # 채팅방 열기

# # # 채팅방 목록 검색하는 Edit (채팅방이 열려있지 않아도 전송 가능하기 위하여)
def open_chatroom(chatroom_name):
    hwndkakao = win32gui.FindWindow(None, "카카오톡")
    hwndkakao_edit1 = win32gui.FindWindowEx( hwndkakao, None, "EVA_ChildWindow", None)
    hwndkakao_edit2_1 = win32gui.FindWindowEx( hwndkakao_edit1, None, "EVA_Window", None)
    hwndkakao_edit2_2 = win32gui.FindWindowEx( hwndkakao_edit1, hwndkakao_edit2_1, "EVA_Window", None)
    hwndkakao_edit3 = win32gui.FindWindowEx( hwndkakao_edit2_2, None, "Edit", None)

    # # Edit에 검색 _ 입력되어있는 텍스트가 있어도 덮어쓰기됨
    win32api.SendMessage(hwndkakao_edit3, win32con.WM_SETTEXT, 0, chatroom_name)
    time.sleep(1)   # 안정성 위해 필요
    SendReturn(hwndkakao_edit3)
    time.sleep(1)


def job_1():
    global old_links, count
    open_chatroom(kakao_opentalk_name)  # 채팅방 열기
    new_links = cell_data
    if new_links:
        for link in new_links:
            kakao_sendtext(kakao_opentalk_name, cell_data)
            time.sleep(1)
        print(link)
    else:
        print("Null is Message")

def main():
    global count
    sched = BackgroundScheduler()
    sched.start()
    # # 매 분 30초마다 job_1 실행
    sched.add_job(job_1, 'cron', second='*/30', id="test_1")
    while True:
        time.sleep(30)
        print("Running wait")


if __name__ == '__main__':
    main()