메뉴 건너뛰기

infra

[Gdata] API v4 사용 for Python

lispro062017.10.09 22:30조회 수 688댓글 1

  • 1
    • 글자 크기
slackclien와 gdata-api-python-client 를 이용해 슬랙으로 챗봇 계정에 말을 걸었을 때, 응답하는 코드를 짜집기(?) 했다.
추후, 언어처리만 되면 미리 정의한 스프레드시트의 응답 메시지를 슬랙 챗봇이 응답하도록 응용할 수 있다.

ai.png

ifttt 로 모든 알림을 스프레드시트로 저장시켰으며, 해당 스프레드 시트의 내용의 일부를 가져오는 코드이다.


from __future__ import print_function
import os
import datetime
import time
from slackclient import SlackClient
import httplib2

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# starterbot's ID as an environment variable
BOT_ID = os.environ.get("BOT_ID")

# constants
AT_BOT = "<@" + BOT_ID + ">"
EXAMPLE_COMMAND = "날짜"

# instantiate Slack & Twilio clients
slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))


SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
CLIENT_SECRET_FILE = '/var/www/html/gdata/client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'

def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'sheets.googleapis.com-python-quickstart.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def handle_command(command, channel):
    """
        Receives commands directed at the bot and determines if they
        are valid commands. If so, then acts on the commands. If not,
        returns back what it needs for clarification.
    """
    response = "Not sure what you mean. Use the *" + EXAMPLE_COMMAND +
               "* command with numbers, delimited by spaces."
    if command.find(EXAMPLE_COMMAND) >= 0:
        now = time.localtime()
        s = "%04d-%02d-%02d" % (now.tm_year, now.tm_mon, now.tm_mday)
        response = "날짜는 "+s
    elif command.find("시간") >= 0:
        now = time.localtime()
        s = "%02d:%02d:%02d" % (now.tm_hour, now.tm_min, now.tm_sec)
        response = "시간은 "+s
    else:
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                    'version=v4')
    service = discovery.build('sheets', 'v4', http=http,
                              discoveryServiceUrl=discoveryUrl)
    spreadsheetId = '시트ID'
    rangeName = '_시트이름_!A2:D'
    result = service.spreadsheets().values().get(
        spreadsheetId=spreadsheetId, range=rangeName).execute()
    values = result.get('values', [])
    if not values:
        print('No data found.')
    else:
        printval='col1, col2, col3, col4'
        for row in values:
            printval=printval+'n'+row[0]+', '+row[1]+', '+row[2]+', '+row[3]
        response=printval

    slack_client.api_call("chat.postMessage", channel=channel,
                          text=response, as_user=True)


def parse_slack_output(slack_rtm_output):
    """
        The Slack Real Time Messaging API is an events firehose.
        this parsing function returns None unless a message is
        directed at the Bot, based on its ID.
    """
    output_list = slack_rtm_output
    if output_list and len(output_list) > 0:
        for output in output_list:
            if output and 'text' in output and AT_BOT in output['text']:
                # return text after the @ mention, whitespace removed
                return output['text'].split(AT_BOT)[1].strip().lower(),
                       output['channel']
    return None, None


if __name__ == "__main__":
    READ_WEBSOCKET_DELAY = 1 # 1 second delay between reading from firehose
    if slack_client.rtm_connect():
        print("StarterBot connected and running!")
        while True:
            command, channel = parse_slack_output(slack_client.rtm_read())
            if command and channel:
                handle_command(command, channel)
            time.sleep(READ_WEBSOCKET_DELAY)
    else:
        print("Connection failed. Invalid Slack token or bot ID?")

lispro06 (비회원)
  • 1
    • 글자 크기

댓글 달기

댓글 1
  • 1) 쓰기 위해서는 SCOPE 에서 readonly를 제거하고, 새로 생성한 json 을 다운 받아 위치를 수정해 준다.

    SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
    CLIENT_SECRET_FILE = '/home/lispro06/ai/write_secret.json'
    APPLICATION_NAME = 'writetest'
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    2) oAuth 로 쓰기 권한이 있는 크레덴셜 패스도 수정해야 재인증 한다.
    credential_path = os.path.join(credential_dir,
                                       'sheets.googleapis.com-python-write.json')
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    3) https://developers.google.com/sheets/samples/writing 레퍼런스 문서를 참고하여 작성하면, 수식도 별 문제 없이 적용 가능하다! 
        query = "=(1+1)"
        body = {'values' : [[query]]}
        result = service.spreadsheets().values().update(
            spreadsheetId=spreadsheetId, range=rangeName, valueInputOption="USER_ENTERED", body=body).execute()
suritam9
2022.10.26 조회 21
lispro06
2017.07.08 조회 1529
박영식
2009.08.01 조회 5409
lispro06
2017.08.13 조회 1997
suritam9
2024.03.10 조회 0
lispro06
2017.10.01 조회 536
첨부 (1)
ai.png
18.4KB / Download 59
위로