Browse Source

kakao talk push

tobby48 4 years ago
parent
commit
77595fbcd3

+ 43
- 0
src/kr/co/swh/lecture/python/scene5/kakao/dummy_sample.py View File

1
+import requests
2
+import urllib
3
+import json
4
+
5
+def getAccessToken(refreshToken) :
6
+    url = "https://kauth.kakao.com/oauth/token"
7
+    payload = "grant_type=refresh_token&client_id=1fd8d72c840797ca81faeedb8abdfcfb&refresh_token=" + refreshToken
8
+    headers = {
9
+        'Content-Type' : "application/x-www-form-urlencoded",
10
+        'Cache-Control' : "no-cache",
11
+    }
12
+
13
+    reponse = requests.request("POST",url,data=payload, headers=headers)
14
+    access_token = json.loads(((reponse.text).encode('utf-8')))
15
+    return access_token
16
+
17
+def sendText(accessToken) :
18
+    url = 'https://kapi.kakao.com/v2/api/talk/memo/default/send'
19
+    payloadDict = dict({
20
+            "object_type" : "text",
21
+            "text" :"sample text",
22
+            "link" : {
23
+                "web_url" : "http://localhost:5000",
24
+                "mobile_web_url" : "http://localhost:5000.mobile"
25
+             },
26
+            "button_title" : "button-title"
27
+            })
28
+#     payload = 'template_object=' + str(json.dumps(payloadDict))
29
+    payload = 'template_object=' + str(payloadDict)
30
+    print(payload)
31
+    headers = {
32
+        'Content-Type' : "application/x-www-form-urlencoded",
33
+        'Cache-Control' : "no-cache",
34
+        'Authorization' : "Bearer " + accessToken,
35
+    }
36
+
37
+    reponse = requests.request("POST",url,data=payload, headers=headers)
38
+    access_token = json.loads(((reponse.text).encode('utf-8')))
39
+    return access_token
40
+
41
+result =  getAccessToken("hliBdT6lOqCFUlPzcdXVWEkHlDy3jE24_omX3gopb9QAAAFzPCUkJA")   # 메세지 받을 사람의 REFRESH TOKEN 이용
42
+print(result['access_token'])
43
+print(sendText(result['access_token']))

+ 30
- 0
src/kr/co/swh/lecture/python/scene5/kakao/kakao_auth_request.py View File

1
+from flask import Flask, render_template, redirect, url_for, request
2
+import requests
3
+import json
4
+app = Flask(__name__)
5
+
6
+@app.route('/')
7
+def index() :
8
+    return render_template('index.html')
9
+
10
+@app.route('/oauth')
11
+def oauth():
12
+    code = str(request.args.get('code'))
13
+    resToken = getAccessToken("1fd8d72c840797ca81faeedb8abdfcfb",str(code))  #XXXXXXXXX 자리에 RESET API KEY값을 사용
14
+    return 'code=' + str(code) + '<br/>response for token=' + str(resToken)
15
+
16
+def getAccessToken(clientId, code) :  # 세션 코드값 code 를 이용해서 ACESS TOKEN과 REFRESH TOKEN을 발급 받음
17
+    url = "https://kauth.kakao.com/oauth/token"
18
+    payload = "grant_type=authorization_code"
19
+    payload += "&client_id=" + clientId
20
+    payload += "&redirect_url=http%3A%2F%2Flocalhost%3A5000%2Foauth&code=" + code
21
+    headers = {
22
+        'Content-Type' : "application/x-www-form-urlencoded",
23
+        'Cache-Control' : "no-cache",
24
+    }
25
+    reponse = requests.request("POST",url,data=payload, headers=headers)
26
+    access_token = json.loads(((reponse.text).encode('utf-8')))
27
+    return access_token
28
+
29
+if __name__ == '__main__' :
30
+    app.run(debug = True)

+ 196
- 0
src/kr/co/swh/lecture/python/scene5/kakao/kakaotalk.ipynb View File

1
+{
2
+ "cells": [
3
+  {
4
+   "cell_type": "code",
5
+   "execution_count": null,
6
+   "metadata": {
7
+    "collapsed": true
8
+   },
9
+   "outputs": [],
10
+   "source": [
11
+    "import requests"
12
+   ]
13
+  },
14
+  {
15
+   "cell_type": "code",
16
+   "execution_count": null,
17
+   "metadata": {
18
+    "collapsed": true
19
+   },
20
+   "outputs": [],
21
+   "source": [
22
+    "# 기본 템플릿(피드, 리스트, 위치, 커머스, 텍스트) : https://kapi.kakao.com/v2/api/talk/memo/default/send\n",
23
+    "# 스크랩 템플릿 : https://kapi.kakao.com/v2/api/talk/memo/scrap/send\n",
24
+    "# 커스텀 템플릿 : https://kapi.kakao.com/v2/api/talk/memo/send\n",
25
+    "default_talk_url = \"https://kapi.kakao.com/v2/api/talk/memo/default/send\"\n",
26
+    "custom_talk_url = \"https://kapi.kakao.com/v2/api/talk/memo/send\""
27
+   ]
28
+  },
29
+  {
30
+   "cell_type": "code",
31
+   "execution_count": null,
32
+   "metadata": {
33
+    "collapsed": false
34
+   },
35
+   "outputs": [],
36
+   "source": [
37
+    "# 사용자 토큰\n",
38
+    "token = '<본인의 API키 넣기>'\n",
39
+    "header = {\n",
40
+    "    \"Authorization\": \"Bearer {본인의 사용자 토큰 넣기}\".format(\n",
41
+    "        token=token\n",
42
+    "    )\n",
43
+    "}"
44
+   ]
45
+  },
46
+  {
47
+   "cell_type": "code",
48
+   "execution_count": null,
49
+   "metadata": {
50
+    "collapsed": true
51
+   },
52
+   "outputs": [],
53
+   "source": [
54
+    "# 1. 기본 템플릿 보내기"
55
+   ]
56
+  },
57
+  {
58
+   "cell_type": "code",
59
+   "execution_count": null,
60
+   "metadata": {
61
+    "collapsed": false
62
+   },
63
+   "outputs": [],
64
+   "source": [
65
+    "# 리스트 템플릿 파일\n",
66
+    "list_template = \"template/list_template.json\"\n",
67
+    "# feed_template = \"template/feed_template.json\"\n",
68
+    "# location_template = \"template/location_template.json\"\n",
69
+    "# commerce_template = \"template/commerce_template.json\"\n",
70
+    "# text_template = \"template/text_template.json\"\n",
71
+    "\n",
72
+    "template_file = list_template\n",
73
+    "with open(template_file, 'r', encoding='utf-8') as f:\n",
74
+    "    payload = {'template_object' : f.read()}"
75
+   ]
76
+  },
77
+  {
78
+   "cell_type": "code",
79
+   "execution_count": null,
80
+   "metadata": {
81
+    "collapsed": false
82
+   },
83
+   "outputs": [],
84
+   "source": [
85
+    "print(payload)"
86
+   ]
87
+  },
88
+  {
89
+   "cell_type": "code",
90
+   "execution_count": null,
91
+   "metadata": {
92
+    "collapsed": true
93
+   },
94
+   "outputs": [],
95
+   "source": [
96
+    "# 리스트 템플릿 카카오톡 메시지 전송\n",
97
+    "res = requests.post(default_talk_url, data=payload, headers=header)"
98
+   ]
99
+  },
100
+  {
101
+   "cell_type": "code",
102
+   "execution_count": null,
103
+   "metadata": {
104
+    "collapsed": false
105
+   },
106
+   "outputs": [],
107
+   "source": [
108
+    "if res.json().get('result_code') == 0:\n",
109
+    "    print('메시지를 성공적으로 보냈습니다.')\n",
110
+    "else:\n",
111
+    "    print('메시지를 성공적으로 보내지 못했습니다. 오류메시지 : ' + str(res.json()))"
112
+   ]
113
+  },
114
+  {
115
+   "cell_type": "code",
116
+   "execution_count": null,
117
+   "metadata": {
118
+    "collapsed": true
119
+   },
120
+   "outputs": [],
121
+   "source": [
122
+    "# 2. 커스텀 템플릿 보내기"
123
+   ]
124
+  },
125
+  {
126
+   "cell_type": "code",
127
+   "execution_count": null,
128
+   "metadata": {
129
+    "collapsed": true
130
+   },
131
+   "outputs": [],
132
+   "source": [
133
+    "payload = {\n",
134
+    "    'template_id' : {본인의 templete id 넣기},\n",
135
+    "    'template_args' : '{\"name\": \"테스트 제목\"}'\n",
136
+    "}"
137
+   ]
138
+  },
139
+  {
140
+   "cell_type": "code",
141
+   "execution_count": null,
142
+   "metadata": {
143
+    "collapsed": false
144
+   },
145
+   "outputs": [],
146
+   "source": [
147
+    "# 커스텀 템플릿 카카오톡 메시지 전송\n",
148
+    "res = requests.post(custom_talk_url, data=payload, headers=header)"
149
+   ]
150
+  },
151
+  {
152
+   "cell_type": "code",
153
+   "execution_count": null,
154
+   "metadata": {
155
+    "collapsed": false
156
+   },
157
+   "outputs": [],
158
+   "source": [
159
+    "if res.json().get('result_code') == 0:\n",
160
+    "    print('메시지를 성공적으로 보냈습니다.')\n",
161
+    "else:\n",
162
+    "    print('메시지를 성공적으로 보내지 못했습니다. 오류메시지 : ' + str(res.json()))"
163
+   ]
164
+  },
165
+  {
166
+   "cell_type": "code",
167
+   "execution_count": null,
168
+   "metadata": {
169
+    "collapsed": true
170
+   },
171
+   "outputs": [],
172
+   "source": []
173
+  }
174
+ ],
175
+ "metadata": {
176
+  "kernelspec": {
177
+   "display_name": "Python 3",
178
+   "language": "python",
179
+   "name": "python3"
180
+  },
181
+  "language_info": {
182
+   "codemirror_mode": {
183
+    "name": "ipython",
184
+    "version": 3
185
+   },
186
+   "file_extension": ".py",
187
+   "mimetype": "text/x-python",
188
+   "name": "python",
189
+   "nbconvert_exporter": "python",
190
+   "pygments_lexer": "ipython3",
191
+   "version": "3.5.1"
192
+  }
193
+ },
194
+ "nbformat": 4,
195
+ "nbformat_minor": 4
196
+}

+ 34
- 0
src/kr/co/swh/lecture/python/scene5/kakao/message_send_to_me.py View File

1
+import json
2
+import requests
3
+
4
+# 기본 템플릿(피드, 리스트, 위치, 커머스, 텍스트) : https://kapi.kakao.com/v2/api/talk/memo/default/send
5
+# 스크랩 템플릿 : https://kapi.kakao.com/v2/api/talk/memo/scrap/send
6
+# 커스텀 템플릿 : https://kapi.kakao.com/v2/api/talk/memo/send
7
+default_talk_url = "https://kapi.kakao.com/v2/api/talk/memo/default/send"
8
+custom_talk_url = "https://kapi.kakao.com/v2/api/talk/memo/send"
9
+
10
+# token = "305sfgmbszYwrTCl6ytOo40kAMqmRcdc4gGVZwo9dZsAAAFzPCnqgQ"
11
+token = "ndRMXUzFVkjEDXikm7bDmRhW0yL8DpCl54uSKQo9dZwAAAFzPDj8Cg"
12
+# header = {
13
+#     "Authorization": "Bearer {본인의 사용자 토큰 넣기}".format(
14
+#         token=token
15
+#     )
16
+# }
17
+header = {"Authorization": "Bearer " + token}
18
+
19
+# 리스트 템플릿 파일
20
+# template_file = "template/list_template.json"
21
+# template_file = "template/feed_template.json"
22
+# template_file = "template/location_template.json"
23
+# template_file = "template/commerce_template.json"
24
+template_file = "template/text_template.json"
25
+
26
+with open(template_file, 'r', encoding='utf-8') as f:
27
+    payload = {'template_object' : f.read()}
28
+print(payload)
29
+# 리스트 템플릿 카카오톡 메시지 전송
30
+res = requests.post(default_talk_url, data=payload, headers=header)
31
+if res.json().get('result_code') == 0:
32
+    print('메시지를 성공적으로 보냈습니다.')
33
+else:
34
+    print('메시지를 성공적으로 보내지 못했습니다. 오류메시지 : ' + str(res.json()))

+ 40
- 0
src/kr/co/swh/lecture/python/scene5/kakao/template/commerce_template.json View File

1
+{
2
+  "object_type": "commerce",
3
+  "content": {
4
+    "title": "Ivory long dress (4 Color)",
5
+    "image_url": "http://mud-kage.kakao.co.kr/dn/RY8ZN/btqgOGzITp3/uCM1x2xu7GNfr7NS9QvEs0/kakaolink40_original.png",
6
+    "image_width": 640,
7
+    "image_height": 640,
8
+    "link": {
9
+      "web_url": "https://style.kakao.com/main/women/contentId=100",
10
+      "mobile_web_url": "https://style.kakao.com/main/women/contentId=100",
11
+      "android_execution_params": "contentId=100",
12
+      "ios_execution_params": "contentId=100"
13
+    }
14
+  },
15
+  "commerce": {
16
+    "regular_price": 208800,
17
+    "discount_price": 146160,
18
+    "discount_rate": 30
19
+  },
20
+  "buttons": [
21
+    {
22
+      "title": "구매하기",
23
+      "link": {
24
+        "web_url": "https://style.kakao.com/main/women/contentId=100/buy",
25
+        "mobile_web_url": "https://style.kakao.com/main/women/contentId=100/buy",
26
+        "android_execution_params": "contentId=100&buy=true",
27
+        "ios_execution_params": "contentId=100&buy=true"
28
+      }
29
+    },
30
+    {
31
+      "title": "공유하기",
32
+      "link": {
33
+        "web_url": "https://style.kakao.com/main/women/contentId=100/share",
34
+        "mobile_web_url": "https://style.kakao.com/main/women/contentId=100/share",
35
+        "android_execution_params": "contentId=100&share=true",
36
+        "ios_execution_params": "contentId=100&share=true"
37
+      }
38
+    }
39
+  ]
40
+}

+ 39
- 0
src/kr/co/swh/lecture/python/scene5/kakao/template/feed_template.json View File

1
+{
2
+  "object_type": "feed",
3
+  "content": {
4
+    "title": "디저트 사진",
5
+    "description": "아메리카노, 빵, 케익",
6
+    "image_url": "http://mud-kage.kakao.co.kr/dn/NTmhS/btqfEUdFAUf/FjKzkZsnoeE4o19klTOVI1/openlink_640x640s.jpg",
7
+    "image_width": 640,
8
+    "image_height": 640,
9
+    "link": {
10
+      "web_url": "http://www.daum.net",
11
+      "mobile_web_url": "http://m.daum.net",
12
+      "android_execution_params": "contentId=100",
13
+      "ios_execution_params": "contentId=100"
14
+    }
15
+  },
16
+  "social": {
17
+    "like_count": 100,
18
+    "comment_count": 200,
19
+    "shared_count": 300,
20
+    "view_count": 400,
21
+    "subscriber_count": 500
22
+  },
23
+  "buttons": [
24
+    {
25
+      "title": "웹으로 이동",
26
+      "link": {
27
+        "web_url": "http://www.daum.net",
28
+        "mobile_web_url": "http://m.daum.net"
29
+      }
30
+    },
31
+    {
32
+      "title": "앱으로 이동",
33
+      "link": {
34
+        "android_execution_params": "contentId=100",
35
+        "ios_execution_params": "contentId=100"
36
+      }
37
+    }
38
+  ]
39
+}

+ 67
- 0
src/kr/co/swh/lecture/python/scene5/kakao/template/list_template.json View File

1
+{
2
+  "object_type": "list",
3
+  "header_title": "WEEKELY MAGAZINE",
4
+  "header_link": {
5
+    "web_url": "http://www.daum.net",
6
+    "mobile_web_url": "http://m.daum.net",
7
+    "android_execution_params": "main",
8
+    "ios_execution_params": "main"
9
+  },
10
+  "contents": [
11
+    {
12
+      "title": "자전거 라이더를 위한 공간",
13
+      "description": "매거진",
14
+      "image_url": "http://mud-kage.kakao.co.kr/dn/QNvGY/btqfD0SKT9m/k4KUlb1m0dKPHxGV8WbIK1/openlink_640x640s.jpg",
15
+      "image_width": 640,
16
+      "image_height": 640,
17
+      "link": {
18
+        "web_url": "http://www.daum.net/contents/1",
19
+        "mobile_web_url": "http://m.daum.net/contents/1",
20
+        "android_execution_params": "/contents/1",
21
+        "ios_execution_params": "/contents/1"
22
+      }
23
+    },
24
+    {
25
+      "title": "비쥬얼이 끝내주는 오레오 카푸치노",
26
+      "description": "매거진",
27
+      "image_url": "http://mud-kage.kakao.co.kr/dn/boVWEm/btqfFGlOpJB/mKsq9z6U2Xpms3NztZgiD1/openlink_640x640s.jpg",
28
+      "image_width": 640,
29
+      "image_height": 640,
30
+      "link": {
31
+        "web_url": "http://www.daum.net/contents/2",
32
+        "mobile_web_url": "http://m.daum.net/contents/2",
33
+        "android_execution_params": "/contents/2",
34
+        "ios_execution_params": "/contents/2"
35
+      }
36
+    },
37
+    {
38
+      "title": "감성이 가득한 분위기",
39
+      "description": "매거진",
40
+      "image_url": "http://mud-kage.kakao.co.kr/dn/NTmhS/btqfEUdFAUf/FjKzkZsnoeE4o19klTOVI1/openlink_640x640s.jpg",
41
+      "image_width": 640,
42
+      "image_height": 640,
43
+      "link": {
44
+        "web_url": "http://www.daum.net/contents/3",
45
+        "mobile_web_url": "http://m.daum.net/contents/3",
46
+        "android_execution_params": "/contents/3",
47
+        "ios_execution_params": "/contents/3"
48
+      }
49
+    }
50
+  ],
51
+  "buttons": [
52
+    {
53
+      "title": "웹으로 이동",
54
+      "link": {
55
+        "web_url": "http://www.daum.net",
56
+        "mobile_web_url": "http://m.daum.net"
57
+      }
58
+    },
59
+    {
60
+      "title": "앱으로 이동",
61
+      "link": {
62
+        "android_execution_params": "main",
63
+        "ios_execution_params": "main"
64
+      }
65
+    }
66
+  ]
67
+}

+ 27
- 0
src/kr/co/swh/lecture/python/scene5/kakao/template/location_template.json View File

1
+{
2
+  "object_type": "location",
3
+  "content": {
4
+    "title": "SWH 코딩학원",
5
+    "description": "SWH 코딩학원 위치입니다.",
6
+    "image_url": "https://lh5.googleusercontent.com/p/AF1QipN-zUBwHDojbwokx8Utlx5nw1i2367idSpoqhUV=w480-h240-k-no",
7
+    "image_width": 800,
8
+    "image_height": 800,
9
+    "link": {
10
+      "web_url": "http://swhcoding.com",
11
+      "mobile_web_url": "http://swhcoding.com",
12
+      "android_execution_params": "platform=android",
13
+      "ios_execution_params": "platform=ios"
14
+    }
15
+  },
16
+  "buttons": [
17
+    {
18
+      "title": "웹으로 보기",
19
+      "link": {
20
+        "web_url": "http://swhcoding.com",
21
+        "mobile_web_url": "http://swhcoding.com"
22
+      }
23
+    }
24
+  ],
25
+  "address": "경기도 이천시 증포동 이섭대천로 1411 KR 흥인프라자 405호",
26
+  "address_title": "SWH 코딩학원"
27
+}

+ 9
- 0
src/kr/co/swh/lecture/python/scene5/kakao/template/text_template.json View File

1
+{
2
+  "object_type": "text",
3
+  "text": "텍스트 영역입니다. 최대 200자 표시 가능합니다.",
4
+  "link": {
5
+    "web_url": "https://developers.kakao.com",
6
+    "mobile_web_url": "https://developers.kakao.com"
7
+  },
8
+  "button_title": "바로 확인"
9
+}

+ 10
- 0
src/kr/co/swh/lecture/python/scene5/kakao/templates/index.html View File

1
+<html>
2
+<head>
3
+<meta charset="utf-8">
4
+</head>
5
+<body>
6
+<a href="https://kauth.kakao.com/oauth/authorize?client_id=1fd8d72c840797ca81faeedb8abdfcfb&redirect_uri=http://localhost:5000/oauth&response_type=code&scope=talk_message">
7
+    Kakao login
8
+</a>
9
+</body>
10
+</html>