파이썬 프로그래밍으로 지루한 작업 자동화하기 학습중..



import logging
# logging.basicConfig(level = logging.DEBUG, format = '%(asctime)s s %(levelname)s - %(message)s')
# logging.basicConfig(filename = 'myPGMlog.txt', level = logging.INFO, format = '%(asctime)s s %(levelname)s - %(message)s')
logging.basicConfig(filename = 'myPGMlog.txt', level = logging.DEBUG, format = '%(asctime)s s %(levelname)s - %(message)s')
logging.debug('Start of program')
# logging.disable(logging.CRITICAL) ## logging on/off 명령어

def factorial(n) :
logging.debug('Start of factorial(%s%%)' %(n))
total = 1
for i in range(n + 1) :
total *= i
logging.debug('i is ' + str(i) + ', total is ' + str(total))
logging.debug('End of factorial(%s%%)' % (n))
return total

print(factorial(5))
logging.debug('End of program')

## 수준 로깅 함수 설명
## DEBUG logging.debug() 가장 낮은 수준이다. 사소한 세부 사항에 사용된다. 보통은 문제를 진달할 때만 이러한 메시지에 관심있을 것이다.
## INFO logging.info() 프로그램의 일반적인 이벤트에 관한 정보를 기록하거나 프로그램이 그 지점에서 제대로 동작하는지 확인하기 위해 사용된다.
## WARNING logging.warning() 프로그램의 동작까지는 막지 않지만 앞으로 그럴 가능성이 있는 문제를 가리키는데 사용된다.
## ERROR logging.error() 프로그램이 무엇인가 실패한 원인이 된 오류를 기록하는데 사용된다.
## CRITICAL logging.critical 가장 높은 수준의 로깅함수로 프로그램의 실행을 완전히 중단시킨 원인이 되었거다 원인이 되려하는 치명적인 오류를 표시하는데 사용

logging.basicConfig(level = logging.INFO, format = '%(asctime)s s %(levelname)s - %(message)s')
logging.critical('Critical error! Critical error!')
# logging.disable(logging.CRITICAL)
logging.error('Error~ Error~')



파이썬으로 open api를 하다보니 카카오톡도  open api가 가능할 것 같다는 생각이 문득 드는 것입니다. 물론 텔레그램도 마찬가지고.. 그래서 검색해보니 왠걸.. 역시 있었네요. 이미 많은 분들이 활용하고 있었습니다. 카톡을 통한 수많은 광고성 메시지들이 다 이것을 활용한 것이었군요. 너무 늦게 알아버렸네요. 부랴부랴 회원가입부터 합니다.


https://developers.kakao.com/



카카오톡 이메일 계정이 있다면 로그인 하시면 됩니다.


도구탭 > REST API 테스트에 들어가서 토큰 신청합니다.


메시지 > 나에게 메시지 보내기에 들어가서 토큰 발급을 받습니다. 아래 Params는 저두 뭐하는건진 아직 모르겠습니다.


발급받은 토큰을 저장한 후 아래와 같이 코드를 구현하니 신기하게도 정말 저에게 메시지를 보냅니다. 다만 자기에게서 온 메시지는 당연하겠지만 알림음이 없습니다. 해볼수록 신기합니다. Python으로 쉽게 할 수 있는 일이 엄청 많습니다.



#!/usr/bin/python
# -*- coding: utf-8 -*-

import requests
import urllib
import json

def getAccessToken(refreshToken) :
url = "https://kauth.kakao.com/oauth/token"
payload = "grant_type=refresh_token&client_id=************************************&refresh_token=" + refreshToken
headers = {'Content-Type' : "application/x-www-form-urlencoded", 'Cache-Control' : "no-cache",}
reponse = requests.request("POST", url, data=payload, headers=headers)
access_token = json.loads(((reponse.text).encode('utf-8')))
return access_token

def sendText(accessToken) :
url = 'https://kapi.kakao.com/v2/api/talk/memo/default/send'
payloadDict = dict({
"object_type" : "text",
"text" : u"테스트",
"link" : {
"web_url" : "https://www.daum.net",
"mobile_web_url" : "https://m.daum.net"
},
"button_title" : u"초대",})
payload = 'template_object=' + str(json.dumps(payloadDict))
print('payload : ', payload)
headers = {'Content-Type' : "application/x-www-form-urlencoded", 'Cache-Control' : "no-cache",
'Authorization' : "Bearer " + accessToken,}
response = requests.post(url, data = payload, headers = headers)
if response.json().get('result_code') == 0:
print('메시지를 성공적으로 보냈습니다.')
else:
print('메시지를 성공적으로 보내지 못했습니다. 오류메시지 : ' + str(response.json()))
access_token = json.loads((response.text).encode('utf-8'))
return access_token

result = getAccessToken("**************************************************") # 메세지 받을 사람의 REFRESH TOKEN 이용
print(result)
print(result['access_token'])
sendText(result['access_token'])



'파이썬(PYTHON)' 카테고리의 다른 글

웹 스크랩 모듈 활용 연습  (0) 2020.08.15
logging 모듈 활용 연습  (0) 2020.08.15
os 모듈 파일 읽고 쓰기 활용 연습  (0) 2020.08.14
pyautogui 모듈 활용 연습  (0) 2020.08.08
subprocess 모듈 활용 연습  (0) 2020.08.08

파이썬 프로그래밍으로 지루한 작업 자동화하기 학습중..



import os

os.chdir('C:\\Windows\\System32') ## 폴더 변경
print(os.getcwd()) ## 현재 작업 폴더명 얻기 - Current Working Directory

# relative paths absolute path
# ..\ C:\
# .\ C:\beacon
# .\fizz C:\beacon\fizz
# ..\eggs C:\eggs

os.makedirs('C:\\PythonProject\\autobuy\\OS_TEST') ## 폴더 만들기

print(os.path.abspath('.')) ## 절대 경로를 알려주는 명령어

print(os.path.abspath('.\\OS_TEST')) ## 절대 경로

print(os.path.isabs('.'))
print(os.path.isabs(os.path.abspath('.\\OS_TEST')))

print(os.path.relpath('C:\\Windows', 'C:\\'))
print(os.path.relpath('C:\\Windows', 'C:\PythonProject\autobuy\OS_TEST\OS_TEST'))
print(os.getcwd())
PATH = 'C:\\Windows\\System32\\calc.exe'
print(os.path.basename(PATH)) ## 실행 파일명
print(os.path.dirname(PATH))

calcFilePath = 'C:\\Windows\\System32\\calc.exe'
print(os.path.split(calcFilePath)) ## 경로와 폴더명으로 나누어 주는 명령어
print(calcFilePath.split(os.path.sep)) ## 경로명까지도 분리해주는 명령어
print(os.path.getsize(calcFilePath)) ## FILE 사이즈를 바이트 단위로 알려준다.

print(os.path.exists('C:\\Windows')) ## 경로 유효성 확인
print(os.path.isdir('C:\\Windows\\System32'))
print(os.path.isfile('C:\\Windows\\System32'))
print(os.path.isdir('C:\\Windows\\System32\\calc.exe'))
print(os.path.isfile('C:\\Windows\\System32\\calc.exe'))

helloFile = open('C:\\PythonProject\\autobuy\\hello.txt') ## 파일에 내용을 읽고 쓰기
helloContent = helloFile.read()
print(helloContent)
sonnetFile = open('sonnet.txt')
print(sonnetFile.readlines())
beanFile = open('bacon.txt', 'w')
beanFile.write('Hello World!\n')
beanFile.write('Bean is not a meat.')
beanFile.close()

import shelve
shelveFile = shelve.open('myData')
dog = ['Zophie', 'Pooka', 'Simon']
shelveFile['dog'] = dog
shelveFile.close()
shelveFile = shelve.open('myData')
print(type(shelveFile))
print(shelveFile['dog'])
shelveFile.close()
shelveFile = shelve.open('myData')
print(list(shelveFile.keys()))
print(list(shelveFile.values()))
shelveFile.close()

import pprint ## pprint, pformat() 함수로 변수 저장하기
cats = [{'name' : 'zombie', 'desc' : 'chubby'}, {'name' : 'pokka', 'desc' : 'fluffy'}]
print(pprint.pformat(cats))
fileObject = open('myCats.py', 'w')
fileObject.write('cats = ' + pprint.pformat(cats) + '\n')
fileObject.close()
import myCats
print(myCats.cats)
print(myCats.cats[0])
print(myCats.cats[0]['name'])



+ Recent posts