<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jerry Wen on Medium]]></title>
        <description><![CDATA[Stories by Jerry Wen on Medium]]></description>
        <link>https://medium.com/@chiehwen0926?source=rss-751994df6ff1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HJNxvd5-dXxnxEptdedIkw.jpeg</url>
            <title>Stories by Jerry Wen on Medium</title>
            <link>https://medium.com/@chiehwen0926?source=rss-751994df6ff1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 02:07:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chiehwen0926/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[透過LINE控制GCP VM開關機]]></title>
            <link>https://medium.com/@chiehwen0926/%E9%80%8F%E9%81%8Eline%E6%8E%A7%E5%88%B6gcp-vm%E9%96%8B%E9%97%9C%E6%A9%9F-79092ec9c0e4?source=rss-751994df6ff1------2</link>
            <guid isPermaLink="false">https://medium.com/p/79092ec9c0e4</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[line-bot]]></category>
            <category><![CDATA[pub-sub]]></category>
            <dc:creator><![CDATA[Jerry Wen]]></dc:creator>
            <pubDate>Mon, 15 May 2023 04:38:58 GMT</pubDate>
            <atom:updated>2023-05-15T04:38:58.604Z</atom:updated>
            <content:encoded><![CDATA[<h4>#LINE #GCP #VM #Cloud Functions #Compute Engine</h4><h4>GCP VM x Cloud Logging x Cloud Functions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vmvdr-h7KSdu2DP7i0Ko-w.png" /></figure><p>在本篇文章中，將透過 LINE BOT 去串接 GCP 上的服務，讓我們可以更快速的控制 VM 的開關機，去達到節流的目的。</p><blockquote>🔥 <strong>後記：</strong>使用 Pub/Sub 去 Push VM log 給 Cloud Functions，實現主動通知的功能！</blockquote><pre>Journey 🥾 :<br><br>    流程概觀 🔍<br><br> 1. 註冊LINE BOT，並設定 Rich Menu 圖文選單<br><br> 2. 建立一台 Compute Engine<br><br> 3. 取得VM相關資訊<br><br> 4. 建立 Cloud Functions<br><br> 5. 開開關關囉</pre><h4>流程概觀 🔍</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7r2jPHqGJt1xkbzxd5eVBw.png" /></figure><h4>步驟 1：註冊LINE BOT，並設定 Rich Menu 圖文選單</h4><p>可以參考前面兩篇文章，去設計自己的 Rich Menu</p><p><a href="https://medium.com/@chiehwen0926/line-%E5%9C%96%E6%96%87%E9%81%B8%E5%96%AE2-%E7%94%A8-postman-%E8%A8%AD%E8%A8%88-line-rich-menu-%E5%9C%96%E6%96%87%E9%81%B8%E5%96%AE-91d288d0f576">LINE 圖文選單2 - 用 Postman 設計 LINE Rich Menu 圖文選單</a></p><h4>步驟 2：建立一台 Compute Engine</h4><p>這部分就先不贅述，因為網路上有很多詳細資源可以參考，機器開最便宜的即可！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*HUxW8m_lmnA9y1vwPIquHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ccinLB7ZqxrqcaSmHXQeuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2sm83E2LOV01ysfuI93XJg.png" /></figure><h4>步驟 3：建立 取得VM相關資訊</h4><p><strong>3.1 ) — 開啟 Cloud Shell</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*EeGcLkG3Ui78m_PQTzBMmg.png" /></figure><p><strong>3.2 ) — 獲取這台 VM 的NAME and ZONE</strong></p><pre>gcloud compute instances list --filter=&quot;my-vm01&quot;</pre><p><strong>3.3 ) — 獲取這台 VM 的所屬的 Project ID</strong></p><pre>gcloud config get-value project</pre><p>記下VM的<strong>NAME, ZONE 與 Project ID，之後的Cloud Functions會要用到</strong></p><h4>步驟 4：建立 Cloud Functions</h4><p>記得將 LINE TOKEN 設置環境變數 (方法可參考前面的篇文章)</p><p><strong>4.1 ) — 部署程式碼1 (main.py) </strong>💻</p><p>引入需要的套件</p><pre>import json<br>import hmac<br>import hashlib<br>import base64<br>import os<br><br>from linebot import LineBotApi, WebhookHandler<br>from linebot.exceptions import InvalidSignatureError<br>from linebot.models import MessageEvent, TextMessage, TextSendMessage<br><br># Import all functions from vm_operations.py<br>from vm_operations import *<br><br>line_bot_api = LineBotApi(os.environ.get(&#39;CHANNEL_ACCESS_TOKEN&#39;))<br>channel_secret = os.environ.get(&#39;CHANNEL_SECRET&#39;)<br>handler = WebhookHandler(channel_secret)</pre><pre>def linebot(request):<br>    if request.method == &#39;POST&#39;:<br>        if &#39;X-Line-Signature&#39; not in request.headers:<br>            return &#39;Error: Invalid source&#39;, 403<br>        else:<br>            # get X-Line-Signature header value<br>            x_line_signature = request.headers[&#39;X-Line-Signature&#39;]<br>            # get body value<br>            body = request.get_data(as_text=True)<br>            # decode body<br>            hash = hmac.new(channel_secret.encode(&#39;utf-8&#39;),<br>                        body.encode(&#39;utf-8&#39;), hashlib.sha256).digest()<br>            signature = base64.b64encode(hash).decode(&#39;utf-8&#39;)<br>            # Compare x-line-signature request header and the signature<br>            if x_line_signature == signature:<br>                json_data = json.loads(body)<br>                handler.handle(body, x_line_signature)<br>                tk = json_data[&#39;events&#39;][0][&#39;replyToken&#39;]         # 取得 reply token<br>                msg = json_data[&#39;events&#39;][0][&#39;message&#39;][&#39;text&#39;]   # 取得 訊息 <br>                user_id = json_data[&#39;events&#39;][0][&#39;source&#39;][&#39;userId&#39;] # 取得 user ID<br><br>                #line_bot_api.reply_message(tk,TextSendMessage(msg))<br>                <br>                if msg == &#39;VM_OPEN&#39;:<br>                    vm_status = start_vm(request)<br>                    if vm_status == &#39;RUNNING&#39;:<br>                        line_bot_api.push_message(user_id, TextSendMessage(&#39;VM_已經是開機狀態!&#39;))<br>                    else:<br>                        line_bot_api.push_message(user_id, TextSendMessage(&#39;VM_開機中...&#39;))<br>                    return &#39;OK&#39;, 200<br>                elif msg == &#39;VM_CLOSE&#39;:<br>                    vm_status = stop_vm(request)<br>                    if vm_status == &#39;STOPPING&#39;:<br>                        line_bot_api.push_message(user_id, TextSendMessage(&#39;VM_目前正在關機&#39;))<br>                    elif vm_status == &#39;TERMINATED&#39;:<br>                        line_bot_api.push_message(user_id, TextSendMessage(&#39;VM_已經是關機狀態!&#39;))    <br>                    else:<br>                        line_bot_api.push_message(user_id, TextSendMessage(&#39;VM_關機中...&#39;))<br>                    return &#39;OK&#39;, 200<br>                elif msg == &#39;VM_STATUS&#39;:<br>                    vm_status = get_vm_status(request)<br>                    line_bot_api.push_message(user_id, TextSendMessage(f&#39;VM_狀態：{vm_status}&#39;))<br>                    # line_bot_api.push_message(user_id, TextSendMessage(&#39;user_id:&#39; + user_id))<br>                    return &#39;OK&#39;, 200<br>                else:<br>                    line_bot_api.push_message(user_id, TextSendMessage(&#39;Sorry_無法處理的請求&#39;))<br>                    return &#39;OK&#39;, 200<br>            else:<br>                return &#39;Invalid signature&#39;, 403<br>    else:<br>        return &#39;Method not allowed&#39;, 400</pre><p><strong>4.2 ) — 部署程式碼2 (requirements.txt) </strong>💻</p><pre>line-bot-sdk<br>google-cloud-compute</pre><p><strong>4.3 ) — 部署程式碼3 (vm_operations.txt) </strong>💻</p><p>這部分去撰寫控制VM開關機的func，然後再import到main.py</p><pre># vm_operations.py<br>import google.auth<br>from googleapiclient.discovery import build<br>from googleapiclient.errors import HttpError<br><br>project = &#39;YOUR PROJECT ID&#39;<br>zone = &#39;YOUR ZONE ID&#39;<br>instance = &#39;YOUR VM ID&#39;<br><br>def start_vm(request):<br>    try:<br>        # Check the current status of the VM<br>        current_status = get_vm_status(request)<br><br>        # If the VM is already running, return a message<br>        if &#39;Status: RUNNING&#39; in current_status:<br>            return &#39;RUNNING&#39;    <br>        credentials, _ = google.auth.default()<br>        service = build(&#39;compute&#39;, &#39;v1&#39;, credentials=credentials)<br>        request = service.instances().start(project=project, zone=zone, instance=instance)<br>        response = request.execute()<br>        return str(response)<br>    except HttpError as e:<br>        return f&quot;An error occurred: {e}&quot;<br><br><br>def stop_vm(request):<br>    try:<br>        # Check the current status of the VM<br>        current_status = get_vm_status(request)<br><br>        # If the VM is already stopped, return a message<br>        if &#39;Status: TERMINATED&#39; in current_status:<br>            return &#39;TERMINATED&#39;<br>        elif &#39;Status: STOPPING&#39; in current_status:<br>            return &#39;STOPPING&#39;<br>        credentials, _ = google.auth.default()<br>        service = build(&#39;compute&#39;, &#39;v1&#39;, credentials=credentials)<br>        request = service.instances().stop(project=project, zone=zone, instance=instance)<br>        response = request.execute()<br>        return str(response)<br>    except HttpError as e:<br>        return f&quot;An error occurred: {e}&quot;<br><br><br>def get_vm_status(request):<br>    try:<br>        credentials, _ = google.auth.default()<br>        service = build(&#39;compute&#39;, &#39;v1&#39;, credentials=credentials)<br>        request = service.instances().get(project=project, zone=zone, instance=instance)<br>        response = request.execute()<br><br>        # Extract the VM status and other information from the response<br>        vm_status = response[&#39;status&#39;]<br>        vm_name = response[&#39;name&#39;]<br><br>        # Format the VM information into a string<br>        vm_info = f&quot;\nProject: {project}\nZone: {zone}\nVM Name: {vm_name}\nStatus: {vm_status}&quot;<br>        return vm_info<br>    except HttpError as e:<br>        return f&quot;An error occurred: {e}&quot;</pre><blockquote>VM 生命週期狀態</blockquote><blockquote><a href="https://cloud.google.com/compute/docs/instances/instance-life-cycle?hl=zh-cn">https://cloud.google.com/compute/docs/instances/instance-life-cycle?hl=zh-cn</a></blockquote><h4>步驟 5：開開關關囉</h4><p>可以更快速的去控制 VM 囉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vmvdr-h7KSdu2DP7i0Ko-w.png" /></figure><p>在這步驟可以看到，當我不論是開關機成功後，都要再額外去點擊最右邊的按鈕，才能查看到 VM 目前的最新狀態…</p><h4>總結 👽</h4><p>在本篇文章中，我們成功地掌握了如何透過 LINE 去控制 GCP 上的 VM 開關機作業，可以讓我們更有效且彈性的去節省花費，畢竟在雲上機器沒用到一直開著可是要錢的啊～</p><p>📔 <strong>以上內容部分參考自網路，並整理成自已的實作筆記分享給大家 </strong>📔</p><p>今天就先這樣<br>掰掰 🏊🏼 🏊🏼 🏊🏼 🏊🏼 🏊🏼 🏊🏼</p><h4>後記 📖</h4><p>做到這一步，基本的開關機功能算是完成了，但我們要如何知道 VM 已經開機成功？最簡單的方法就是在現在的 Cloud Functions 上加上開完機後回傳訊息給 LINE，但我們又不可能讓程序涼在這等 VM 開好機吧？！所以在下一篇章節將使用 Pub/Sub 去 Push VM log 給 Cloud Functions，實現主動通知的功能！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79092ec9c0e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LINE 圖文選單2 - 用 Postman 設計 LINE Rich Menu 圖文選單]]></title>
            <link>https://medium.com/@chiehwen0926/line-%E5%9C%96%E6%96%87%E9%81%B8%E5%96%AE2-%E7%94%A8-postman-%E8%A8%AD%E8%A8%88-line-rich-menu-%E5%9C%96%E6%96%87%E9%81%B8%E5%96%AE-91d288d0f576?source=rss-751994df6ff1------2</link>
            <guid isPermaLink="false">https://medium.com/p/91d288d0f576</guid>
            <category><![CDATA[line-bot]]></category>
            <category><![CDATA[rich-menu]]></category>
            <category><![CDATA[postman]]></category>
            <category><![CDATA[line]]></category>
            <dc:creator><![CDATA[Jerry Wen]]></dc:creator>
            <pubDate>Fri, 12 May 2023 02:43:36 GMT</pubDate>
            <atom:updated>2023-05-12T15:33:50.776Z</atom:updated>
            <content:encoded><![CDATA[<h4>#LINE #Canva #Rich Menu #圖文選單 #Postman</h4><h4>設計屬於你自己的 LINE 圖文選單</h4><p>在前一篇文章中，我們透過了最簡單的方式（LINE官方後台）建立了LINE圖文選單，在這篇文章中，將來介紹另一個不同的方法，也可以去達成一樣的目的！</p><p><a href="https://medium.com/@chiehwen0926/line-%E5%9C%96%E6%96%87%E9%81%B8%E5%96%AE1-%E4%BD%BF%E7%94%A8-canva-%E8%A8%AD%E8%A8%88-line-rich-menu-%E5%9C%96%E6%96%87%E9%81%B8%E5%96%AE-53186e7c1490">LINE 圖文選單1 - 使用 Canva 設計 LINE Rich Menu 圖文選單</a></p><pre>Journey 🥾 :<br><br>    流程概觀 🔍<br><br> 1. 建立選單圖片<br><br> 2. 下載, 安裝 Postman<br><br> 3. 將 Rich Menu 透過 API 方式打入<br><br> 4. 展示！</pre><h4>步驟 1：建立你的 Rich Menu 圖片</h4><p><strong>因為這步驟內容與前一篇文章重複，如果還不了解這步驟的朋友，建議可以先參考前一篇文章呦</strong>👇</p><p><a href="https://medium.com/@chiehwen0926/line-%E5%9C%96%E6%96%87%E9%81%B8%E5%96%AE1-%E4%BD%BF%E7%94%A8-canva-%E8%A8%AD%E8%A8%88-line-rich-menu-%E5%9C%96%E6%96%87%E9%81%B8%E5%96%AE-53186e7c1490">LINE 圖文選單1 - 使用 Canva 設計 LINE Rich Menu 圖文選單</a></p><h4>步驟 2：下載, 安裝 Postman</h4><p><strong>2.1 ) — 下載 Postman</strong></p><p><a href="https://www.getpostman.com/downloads/">Download Postman | Get Started for Free</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZRRDKwQxY_IC1qRpsvGigg.png" /></figure><p><strong>2.2 ) — 安裝完成後，選擇自己喜歡的方式註冊即可</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wrRV7HHtyiGaOy09nfgFAQ.png" /></figure><h4>步驟 3：將 Rich Menu 透過 API 方式打入</h4><p><strong>3.1 ) — 新增一個 Collections</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eNxXeVmth6d0zRDtgNjp0g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*CVuICdeo1U7VQhvanVrdxg.png" /></figure><p><strong>3.2 ) — 新增 Post Rich Menu API</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*gzHUC3O8rdor7LYAaMa8eQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*NGJVA1zCCiqgvyBIlG_nNQ.png" /></figure><ul><li>選擇POST方式，貼上 API URL</li><li>貼上 LINE 的 Channel access token</li></ul><blockquote>POST: <a href="https://api.line.me/v2/bot/richmenu">https://api.line.me/v2/bot/richmenu</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IKDZCfGJXFu3byVty5gjkg.png" /></figure><ul><li>在Body貼上我們要打入的格式</li><li>按 Send 送出</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*N9kYiSqXv_ZToTWjxcFklw.png" /></figure><pre>{<br>  &quot;size&quot;: {<br>    &quot;width&quot;: 2500,<br>    &quot;height&quot;: 843<br>  },<br>  &quot;selected&quot;: true,<br>  &quot;name&quot;: &quot;Sample Rich Menu&quot;,<br>  &quot;chatBarText&quot;: &quot;Open Menu&quot;,<br>  &quot;areas&quot;: [<br>    {<br>      &quot;bounds&quot;: {<br>        &quot;x&quot;: 0,<br>        &quot;y&quot;: 0,<br>        &quot;width&quot;: 833,<br>        &quot;height&quot;: 843<br>      },<br>      &quot;action&quot;: {<br>        &quot;type&quot;: &quot;message&quot;,<br>        &quot;label&quot;: &quot;左側按鈕&quot;,<br>        &quot;text&quot;: &quot;VM_OPEN&quot;<br>      }<br>    },<br>    {<br>      &quot;bounds&quot;: {<br>        &quot;x&quot;: 833,<br>        &quot;y&quot;: 0,<br>        &quot;width&quot;: 834,<br>        &quot;height&quot;: 843<br>      },<br>      &quot;action&quot;: {<br>        &quot;type&quot;: &quot;message&quot;,<br>        &quot;label&quot;: &quot;中間按鈕&quot;,<br>        &quot;text&quot;: &quot;VM_CLOSE&quot;<br>      }<br>    },<br>    {<br>      &quot;bounds&quot;: {<br>        &quot;x&quot;: 1667,<br>        &quot;y&quot;: 0,<br>        &quot;width&quot;: 833,<br>        &quot;height&quot;: 843<br>      },<br>      &quot;action&quot;: {<br>        &quot;type&quot;: &quot;message&quot;,<br>        &quot;label&quot;: &quot;右側按鈕&quot;,<br>        &quot;text&quot;: &quot;VM_STATUS&quot;<br>      }<br>    }<br>  ]<br>}</pre><p><strong>3.3 ) — Get Rich Menu</strong></p><p>再新增一個 HTTP Request</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*gzHUC3O8rdor7LYAaMa8eQ.png" /></figure><ul><li>貼上 LINE 的 Channel access token</li><li>按 Send 送出 GET 請求，下方有得到 richMenuId ，就代表有設定上去了</li></ul><blockquote><a href="https://api.line.me/v2/bot/richmenu/list">https://api.line.me/v2/bot/richmenu/list</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*aYa6r99cv6B0PjHGEGxn2g.png" /></figure><p><strong>3.3 ) — Post Rich Menu Picture</strong></p><p>上面切好了版型，在這步驟就是要把我們的圖片設定上去了</p><blockquote><a href="https://api-data.line.me/v2/bot/richmenu/richmenu-108af0d6f38c808cc97bd1566a58aed7/content">https://api-data.line.me/v2/bot/richmenu/你的richMenuId/content</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*t92iB99s_FvdjOjAJbOSiA.png" /></figure><ul><li>切至Body，選擇binary，在選擇我們做好的選單圖片</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*0nUI58G3bv1s1lXx1NTFPw.png" /></figure><ul><li>Send 出去，如果沒錯的話會收到 200 的訊息，但因為我已經設定過了所以收到錯誤訊息</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*BQwlpVMpPwWcekfBKPANMA.png" /></figure><p><strong>3.4 ) — Default Rich Menu</strong></p><p>將這個 Rich Menu 設定成目前的預設</p><blockquote><a href="https://api.line.me/v2/bot/user/all/richmenu/richmenu-108af0d6f38c808cc97bd1566a58aed7">https://api.line.me/v2/bot/user/all/richmenu/</a><a href="https://api-data.line.me/v2/bot/richmenu/richmenu-108af0d6f38c808cc97bd1566a58aed7/content">你的richMenuId</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*xt7I09BBIknzYLHUhoy8kg.png" /></figure><p><strong>補充 )</strong></p><blockquote><strong>Cancel default rich menu</strong><br>https://api.line.me/v2/bot/user/all/richmenu</blockquote><blockquote><strong>Delete rich menu</strong><br>https://api.line.me/v2/bot/richmenu/<a href="https://api-data.line.me/v2/bot/richmenu/richmenu-108af0d6f38c808cc97bd1566a58aed7/content">你的richMenuId</a></blockquote><blockquote><strong>兩個的 HTTP Request 都是 DELETE</strong></blockquote><h4>步驟 4：展示</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7IFInS7SC0PmmdoiG0czqA.png" /></figure><p>📔 <strong>以上內容部分參考自網路，並整理成自已的實作筆記分享給大家 </strong>📔</p><p>今天就先這樣<br>掰掰 🏊🏼 🏊🏼 🏊🏼 🏊🏼 🏊🏼 🏊🏼</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91d288d0f576" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LINE 圖文選單1 - 使用 Canva 設計 LINE Rich Menu 圖文選單]]></title>
            <link>https://medium.com/@chiehwen0926/line-%E5%9C%96%E6%96%87%E9%81%B8%E5%96%AE1-%E4%BD%BF%E7%94%A8-canva-%E8%A8%AD%E8%A8%88-line-rich-menu-%E5%9C%96%E6%96%87%E9%81%B8%E5%96%AE-53186e7c1490?source=rss-751994df6ff1------2</link>
            <guid isPermaLink="false">https://medium.com/p/53186e7c1490</guid>
            <category><![CDATA[rich-menu]]></category>
            <category><![CDATA[line-bot]]></category>
            <category><![CDATA[line]]></category>
            <category><![CDATA[canvas]]></category>
            <dc:creator><![CDATA[Jerry Wen]]></dc:creator>
            <pubDate>Wed, 10 May 2023 06:53:25 GMT</pubDate>
            <atom:updated>2023-05-10T06:53:25.396Z</atom:updated>
            <content:encoded><![CDATA[<h4>#LINE #Canva #Rich Menu #圖文選單</h4><h4>設計屬於你自己的 LINE 圖文選單</h4><p>在本篇文章中，將學習如何設計一個自己的 LINE 圖文選單。當點下相對應的區塊就會觸發你設定好的事件！</p><blockquote>🦸 <strong>後記：LINE 圖文選單2 - 用 Postman 設計 LINE Rich Menu</strong></blockquote><pre>Journey 🥾 :<br><br> 1. 建立你的 Rich Menu 圖片<br><br> 2. 設定 LINE 圖文選單<br><br> 3. 展示！</pre><h4>步驟 1：建立你的 Rich Menu 圖片</h4><p>在這步驟我是用 <a href="https://www.canva.com/zh_tw/login/"><strong>Canva</strong></a> 去弄出我想要的樣子</p><p><strong>1.1 ) — 選擇自己喜歡的註冊登入方式即可</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l0PnGEUbva_UmCef0agMUw.png" /></figure><p><strong>1.2 ) — 建立你想要 Rich Menu 尺寸</strong></p><ul><li>建立自訂的尺寸</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-lDxS8fNcfuj-SF5d55nWg.png" /></figure><ul><li>圖文選單類型介紹</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WygXZS4tZJMTiperxrPmKA.png" /></figure><ul><li>因為這篇文章我要設計去控制VM開關機的圖，大概只需要三個按鈕，也不希望篇幅站太大，所以選擇 小型-高解析度：2500px × 843px</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XSMAIgMRQiWKbXicrLCnMQ.png" /></figure><p><strong>1.3 ) — </strong>為了方便排版，可以先拉出三個內建的方框，調整每個大小 833 x 833 px</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Nch3-A3f9FCmDRgu5_uzg.png" /></figure><p><strong>1.4 ) — </strong>用拖曳的方式插入圖片，再調整每個方框想要的背景色</p><blockquote><a href="https://www.flaticon.com/free-icon/switch-off_889758?term=off&amp;page=1&amp;position=1&amp;origin=search&amp;related_id=889758">OFF 圖片</a><br><a href="https://www.flaticon.com/free-icon/switch-on_889754?term=off&amp;page=1&amp;position=5&amp;origin=search&amp;related_id=889754">ON 圖片</a><br><a href="https://www.flaticon.com/free-icon/clipboard_839746?term=status&amp;related_id=839746">List 圖片</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nBfDP7HjHPEsEYcBCJvcKw.png" /></figure><p><strong>1.5 ) — 將圖片下載下來，稍後要匯入 LINE</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JDbr3be4VwhJr8BHrR-NsQ.png" /></figure><h4>步驟 2：設定LINE圖文選單</h4><p>首先至 LINE 官方帳號</p><p><a href="https://manager.line.biz/">LINE Business ID</a></p><p><strong>2.1 ) — 點擊圖文選單</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UgvKBlOW3_dLG47Ueb4Y8A.png" /></figure><p><strong>2.2 ) — 設定名稱與時間期限</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXK10LZLvnMJP_u-JhYO8Q.png" /></figure><p><strong>2.3 ) — 設定版型與圖片</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PB8bUheJR2eKHwFWdqy7iw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RFOcVM8is3O1AnGJ339-8A.png" /></figure><p><strong>2.3 ) — 設定點擊效果<br>我這邊是設定當點到Ａ會發出開機訊息，依此類推…</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3N1oSCD6mCeqfHHrFS7nKg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BD--sYTBY3kwE_Vt3_abEQ.png" /></figure><h4>步驟 3：展示</h4><p>現在只要分別按下對應的按鈕，就會自動發出訊息囉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PwMyeiBrXW0tEhRfJb_klQ.png" /></figure><p>📔 <strong>以上內容部分參考自網路，並整理成自已的實作筆記分享給大家 </strong>📔</p><p>今天就先這樣<br>掰掰 🏊🏼 🏊🏼 🏊🏼 🏊🏼 🏊🏼 🏊🏼</p><blockquote>🦸 <strong>後記：LINE 圖文選單2 — 用 Postman 設計 LINE Rich Menu</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53186e7c1490" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LINE 聊天機器人 - 懶人投資術，結合ChatGPT與爬蟲，即時掌握股市資訊]]></title>
            <link>https://medium.com/@chiehwen0926/line-%E8%81%8A%E5%A4%A9%E6%A9%9F%E5%99%A8%E4%BA%BA-%E6%87%B6%E4%BA%BA%E6%8A%95%E8%B3%87%E8%A1%93-%E7%B5%90%E5%90%88chatgpt%E8%88%87%E7%88%AC%E8%9F%B2-%E5%8D%B3%E6%99%82%E6%8E%8C%E6%8F%A1%E8%82%A1%E5%B8%82%E8%B3%87%E8%A8%8A-238b9e3e4025?source=rss-751994df6ff1------2</link>
            <guid isPermaLink="false">https://medium.com/p/238b9e3e4025</guid>
            <category><![CDATA[cloud-functions]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[line-bot]]></category>
            <dc:creator><![CDATA[Jerry Wen]]></dc:creator>
            <pubDate>Mon, 08 May 2023 02:58:06 GMT</pubDate>
            <atom:updated>2023-05-08T02:58:06.021Z</atom:updated>
            <content:encoded><![CDATA[<h4>#LINE #聊天機器人 #GCP #ChatGPT #LINE聊天機器人3 #番外篇</h4><h4>LINE聊天機器人3：建立個人股市的消息小幫手！</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8RiKe8CgVXedf_AUFOfvwQ.png" /></figure><p>消息對於投資者來說是非常重要的資訊之一，因為它們可能會影響股票價格的波動。然而，對於和我一樣懶又閱讀障礙的人來說，消息的搜集和整理是非常耗時與困難的一件事。這就是為什麼我們可以運用爬蟲和ChatGPT，來建立個人股市的消息小幫手！</p><blockquote>這樣一來啊～我們就可以省下大量的時間去閱讀，而且還可以馬上獲得熱騰騰的重點筆記！</blockquote><h4><strong>前傳 </strong>👇</h4><ul><li><a href="https://medium.com/@chiehwen0926/line-%E8%81%8A%E5%A4%A9%E6%A9%9F%E5%99%A8%E4%BA%BA-%E8%BC%95%E9%AC%86%E6%A8%A1%E4%BB%BF%E8%88%87%E4%BA%92%E5%8B%95%E7%9A%84%E7%B5%82%E6%A5%B5%E6%8C%87%E5%8D%97-gcp-cloud-functions-%E6%87%89%E7%94%A8%E5%AF%A6%E4%BE%8B-d4f43db3ca67">👋 LINE 聊天機器人 - 輕鬆模仿與互動的終極指南 ( GCP Cloud Functions 應用實例 )</a></li><li><a href="https://medium.com/@chienwen0926/chatgpt-%E8%88%87-line-%E7%B5%90%E5%90%88-%E4%BD%A0%E7%9A%84%E9%9A%A8%E8%BA%AB%E6%99%BA%E8%83%BD%E5%B0%8F%E5%B9%AB%E6%89%8B-gcp-cloud-functions-%E6%87%89%E7%94%A8%E5%AF%A6%E4%BE%8B-da87f3bd66">🧠 ChatGPT 與 LINE 結合：你的隨身智能小幫手 ( GCP Cloud Functions 應用實例 )</a></li></ul><pre>Journey 🥾 :<br><br>    流程概觀 🔍<br><br> 1. 來寫一個爬蟲程式吧！<br><br> 2. 建立一個新的 LINE Messaging API Channel 🍔<br><br> 3. 將爬蟲放上 GCP Cloud Functions <br><br> 4. 新聞吃飽飽囉 🍔</pre><h4>流程概觀 🔍</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ubMTv9wuIVClOZoHekUhHQ.png" /></figure><blockquote><strong>1. User 透過 LINE 發出想要爬取的新聞重點</strong></blockquote><blockquote><strong>2. Cloud Function 接獲 Request 後，向 GoogleNews 爬取新聞</strong></blockquote><blockquote><strong>3. GoogleNews 將爬取的新聞結果回傳給 Cloud Function 做處理</strong></blockquote><blockquote><strong>4. Cloud Function 將爬取新聞的結果整理列表，交給 ChatGPT 做重點整理</strong></blockquote><blockquote><strong>5. ChatGPT 回傳重點整理，最後由 Cloud Function 回傳給 LINE。</strong></blockquote><h4><strong>步驟 1：來寫一個爬蟲程式吧！</strong></h4><p>如果沒有Python開發環境，或是和我一樣是上班偷偷玩的研究 🤫，可以使用<strong> </strong><a href="https://anaconda.cloud/sign-in"><strong>Anaconda Cloud</strong></a><strong> </strong>上提供的 <strong>Jupyter Notebook</strong> 去編寫及測試自己的程式，雖然是免費的環境，但上面提供的RAM和CPU對這次的爬蟲算是綽綽有 🐟</p><p><a href="https://anaconda.cloud/">Anaconda Nucleus</a></p><p><strong>1.1 ) — 打開一個Notebook，等等會在這編輯程式</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bf3Sn2Po4AdF3BGn7d8CeA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Q37nA0oFB7FS2dnyQN_CQ.png" /></figure><p><strong>1.2 ) — 打開Terminal，安裝GoogleNews</strong><br>因為我們這次需要使用GoogleNews 的模組，透過爬蟲從 Google 新聞搜索結果中抓取新聞。<br>在Terminal中輸入以下語法：</p><pre>pip install GoogleNews</pre><p><strong>1.3 ) — 將套件引入</strong></p><pre>from GoogleNews import GoogleNews</pre><p><strong>1.4 ) — 來寫抓取新聞的Function吧！<br></strong>使用 GoogleNews 函式庫對指定的字詞進行搜索，並返回查詢結果。</p><ul><li><strong>google_news_crawler ：</strong> <br><em>這個函式用於抓取 Google 新聞上關於特定查詢字詞的新聞。接受兩個參數：查詢字詞（query）和要獲取的新聞數量（num_results），目前默認為 5，代表會爬取五筆新聞。<br>對於獲取到的新聞，它將新聞的標題和連結分別存儲在 titles 和 links 列表中。</em></li></ul><pre>def google_news_crawler(query, num_results=5):<br>    # 初始化兩個空列表，用於存儲新聞連結和標題<br>    links = []<br>    titles = []<br>    try:<br>        # 使用 GoogleNews 函式庫創建一個 GoogleNews 對象，設置語言為中文，搜索範圍為最近一天<br>        googlenews = GoogleNews(lang=&quot;zh&quot;, period=&quot;1d&quot;)<br>        # 使用 GoogleNews 對象對查詢字詞進行搜索<br>        googlenews.search(query)        <br>        # 獲取搜索結果<br>        results = googlenews.results()<br>        <br>        # 遍歷搜索結果，只保留前 num_results 個結果<br>        for result in results[:num_results]:<br>            # 將新聞連結加入到 links 列表中<br>            links.append(result[&quot;link&quot;])<br>            # 將新聞標題加入到 titles 列表中<br>            titles.append(result[&quot;title&quot;])<br>    except Exception as e:<br>        # 如果遇到異常，捕獲並打印異常信息<br>        print(f&quot;Error: {e}&quot;)<br>    <br>    return links, titles</pre><ul><li><strong>get_news ： <br></strong><em>這個函式主要用於處理用戶輸入的查詢字詞，然後調用google_news_crawler 抓取相關新聞。將查詢結果（標題和連結）格式化為特定的輸出格式。<br>最後，在列表後面添加一行</em><strong><em> “要求ChatGPT整理新聞重點的提示“</em></strong></li></ul><pre>def get_news(user_input):<br>    query = user_input<br>    links, titles = google_news_crawler(query)<br>    # 初始化一個空字串來存儲結果<br>    output = &quot;&quot;  <br>    <br>    for i, (link, title) in enumerate(zip(links, titles), start=1):<br>        # 將當前結果格式化為一個字串<br>        result = f&quot;{i}. 標題： {title}\n   連結： {link}\n&quot;  <br>        # 將當前結果追加到 output 變數中<br>        output += result  <br>    output += &quot;\n請幫我整理以上新聞的重點，並條列出來&quot;<br>    print (output)<br>    # return output</pre><p><strong>結果會如下顯示：</strong></p><pre>get_news(&#39;台積電&#39;)</pre><pre>1. 標題： 台積電進軍熊本上演「搶土地大戰」 農地被迫變工地！當地酪農業者哀號<br>   連結： https://www.mirrormedia.mg/story/20230501edi016/<br>2. 標題： 曝台積電不來設廠「因缺電」！ 郭台銘喊話：當選將「高科技治國」【CNEWS】<br>   連結： https://www.youtube.com/watch?v=l_96quR_ku4<br>3. 標題： 「台積電不來高雄因為沒有電」！郭台銘拋：半屏山設小型核能發電站<br>   連結： https://www.setn.com/News.aspx?NewsID=1288201&amp;utm_campaign=viewallnews<br>4. 標題： 新聞評論／蔡政府又雙標 要美別張揚台積電風險<br>   連結： https://www.worldjournal.com/wj/story/121220/7134426<br>5. 標題： 「飲食界台積電」起底！ 一圖掌握鼎泰豐楊家3代布局<br>   連結： https://www.ettoday.net/news/20230501/2489898.htm<br><br>請幫我整理以上新聞的重點，並條列出來</pre><h4>步驟2：建立一個新的 LINE Messaging API Channel 🍔</h4><p><strong>因為這步驟內容與前一篇文章重複，如果還不了解這步驟的朋友，建議可以先參考前一篇文章呦</strong>👇</p><p><a href="https://medium.com/@chiehwen0926/line-%E8%81%8A%E5%A4%A9%E6%A9%9F%E5%99%A8%E4%BA%BA-%E8%BC%95%E9%AC%86%E6%A8%A1%E4%BB%BF%E8%88%87%E4%BA%92%E5%8B%95%E7%9A%84%E7%B5%82%E6%A5%B5%E6%8C%87%E5%8D%97-gcp-cloud-functions-%E6%87%89%E7%94%A8%E5%AF%A6%E4%BE%8B-d4f43db3ca67">LINE 聊天機器人 - 手把手教學，輕鬆學會模仿與互動的功能 on GCP Cloud Functions</a></p><p><strong>2.1 ) — 直接在原來的Provider底下新增一個 Msg Channel 即可</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3x_i7Kz9hSQ3vSkootggtg.png" /></figure><p><strong>2.1 ) — 要記得收好你的 </strong>🔑</p><ol><li><strong><em>CHANNEL_ACCESS_TOKEN</em></strong></li><li><strong><em>CHANNEL_SECRET</em></strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zdoRpxGWTisC5NrENlGwvA.png" /><figcaption>Channel secret</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AvFtOOjfdCtB3605p_song.png" /><figcaption>Channel access token</figcaption></figure><h4>步驟3：將我們的Code放上GCP Cloud Function</h4><p><strong>因為這步驟內容與前一篇文章重複，這邊只會說明重點調整部分，如果還不了解這步驟的朋友，建議可以先參考前一篇文章呦</strong>👇</p><p><a href="https://medium.com/@chiehwen0926/line-%E8%81%8A%E5%A4%A9%E6%A9%9F%E5%99%A8%E4%BA%BA-%E8%BC%95%E9%AC%86%E6%A8%A1%E4%BB%BF%E8%88%87%E4%BA%92%E5%8B%95%E7%9A%84%E7%B5%82%E6%A5%B5%E6%8C%87%E5%8D%97-gcp-cloud-functions-%E6%87%89%E7%94%A8%E5%AF%A6%E4%BE%8B-d4f43db3ca67">LINE 聊天機器人 - 手把手教學，輕鬆學會模仿與互動的功能 on GCP Cloud Functions</a></p><p><strong>3.1 ) — 再新增一個函式吧</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UdN2_JQGlJz1WHnZYv1Xrg.png" /></figure><p><strong>3.2 ) — 建議使用 256MB 的記憶體，本來用 128 但發現好像不太夠</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EuKPwU8u-YvVW5MT_lhrkA.png" /></figure><p><strong>3.3 ) — 記得將 </strong>🔑 <strong>設定成環境變數</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*Mz0m62o28EqrPNhoz2g0VQ.png" /></figure><p><strong>3.4 ) — import GoogleNews 套件<br></strong>允許使用 Google 新聞搜索功能來獲取新聞文章</p><pre>import json<br>import hmac<br>import hashlib<br>import base64<br>import os<br>import openai<br><br>from linebot import LineBotApi, WebhookHandler<br>from linebot.exceptions import InvalidSignatureError<br>from linebot.models import MessageEvent, TextMessage, TextSendMessage<br>from GoogleNews import GoogleNews</pre><p><strong>3.5 ) —程式碼調整，改變回傳訊息的方法 -&gt; push_message</strong></p><ul><li>我們前面都適用 reply_message 這個方法去回傳訊息給User，每次接收到User發送的訊息，我們就會收到一個 <strong>reply token</strong>。<strong>這個 reply token 在一次回應中只能被使用一次。</strong></li><li>若想要再次向用戶發送訊息，可以使用<strong> Push Message API</strong>，這時需要用到 <strong>user ID </strong>來指定發送對象。</li></ul><pre># 取得 reply token<br># tk = json_data[&#39;events&#39;][0][&#39;replyToken&#39;] <br><br># 取得 user ID<br>user_id = json_data[&#39;events&#39;][0][&#39;source&#39;][&#39;userId&#39;]     <br># 取得 Line訊息  <br>user_input = json_data[&#39;events&#39;][0][&#39;message&#39;][&#39;text&#39;]</pre><p><strong>3.6 ) — 加入剛剛在 Anaconda Cloud 上寫的爬蟲</strong></p><pre># 爬取資料<br>def get_news(user_input):<br>    query = user_input<br>    links, titles = google_news_crawler(query)<br>    output = &quot;&quot;  # 初始化一個空字串來存儲結果<br>    <br>    for i, (link, title) in enumerate(zip(links, titles), start=1):<br>        # print(f&quot;{i}. 標題： {title}\n   連結： {link}\n&quot;)<br>        result = f&quot;{i}. 標題： {title}\n   連結： {link}\n&quot;  # 將當前結果格式化為一個字串<br>        output += result  # 將當前結果追加到 output 變數中<br>    <br>    # output += &quot;\n請幫我整理以上新聞的重點，並條列出來&quot;    <br>    return output<br><br>def google_news_crawler(query, num_results=3):<br>    links = []<br>    titles = []<br>    try:<br>        googlenews = GoogleNews(lang=&quot;zh&quot;, period=&quot;1d&quot;)<br>        googlenews.search(query)<br>        results = googlenews.results()<br>        <br>        for result in results[:num_results]:<br>            links.append(result[&quot;link&quot;])<br>            titles.append(result[&quot;title&quot;])<br>    except Exception as e:<br>        print(f&quot;Error: {e}&quot;)<br>    return links, titles    </pre><p><strong>3.7 ) — 調整 </strong>linebot 函式</p><pre># 處理Line Request<br>def linebot(request):<br>    if request.method != &#39;POST&#39; or &#39;X-Line-Signature&#39; not in request.headers:<br>        return &#39;Error: Invalid source&#39;, 403<br>    else:<br>        # get X-Line-Signature header value<br>        x_line_signature = request.headers[&#39;X-Line-Signature&#39;]<br>        # get body value<br>        body = request.get_data(as_text=True)<br>        hash = hmac.new(channel_secret.encode(&#39;utf-8&#39;),<br>                    body.encode(&#39;utf-8&#39;), hashlib.sha256).digest()<br>        signature = base64.b64encode(hash).decode(&#39;utf-8&#39;)<br><br>        # Compare x-line-signature request header and the signature<br>        if x_line_signature == signature:<br>            try:<br>                # 解析 JSON<br>                json_data = json.loads(body)<br>                handler.handle(body, x_line_signature)<br>                # 取得 reply token<br>                tk = json_data[&#39;events&#39;][0][&#39;replyToken&#39;] <br>                # 取得 user ID<br>                user_id = json_data[&#39;events&#39;][0][&#39;source&#39;][&#39;userId&#39;]     <br>                # 取得 Line訊息  <br>                user_input = json_data[&#39;events&#39;][0][&#39;message&#39;][&#39;text&#39;]<br><br>                # 回傳等待訊息<br>                line_bot_api.push_message(user_id, TextSendMessage(&#39;資料爬取中請稍後...&#39;))<br><br>                # 將Line訊息發給get_news去爬取資料<br>                search_output = get_news(user_input)<br>                # 回傳爬取結果<br>                line_bot_api.push_message(user_id, TextSendMessage(&#39;&lt;以下為爬取結果，ChatGPT處理中請稍候...&gt;\n&#39; + search_output))<br><br>                # 將爬取結果發給ChatGPT做整理<br>                gpt_unify = search_output + &quot;\n請幫我整理以上新聞的重點，並條列出各項重點&quot;<br>                GPT_output = chat_with_gpt(gpt_unify)<br>                # 回傳ChatGPT整理後的結果<br>                line_bot_api.push_message(user_id, TextSendMessage(&#39;&lt;以下為ChatGPT整理結果：&gt;\n&#39; + GPT_output))<br><br>                return &#39;OK&#39;, 200<br>            except:<br>                print(&#39;error&#39;)<br>        else:<br>            return &#39;Invalid signature&#39;, 403</pre><p><strong>3.8 ) — main.py完整的程式會長這樣</strong></p><pre>import json<br>import hmac<br>import hashlib<br>import base64<br>import os<br>import openai<br><br>from linebot import LineBotApi, WebhookHandler<br>from linebot.exceptions import InvalidSignatureError<br>from linebot.models import MessageEvent, TextMessage, TextSendMessage<br>from GoogleNews import GoogleNews<br><br># line<br>line_bot_api = LineBotApi(os.environ.get(&#39;CHANNEL_ACCESS_TOKEN&#39;))<br>channel_secret = os.environ.get(&#39;CHANNEL_SECRET&#39;)<br>handler = WebhookHandler(channel_secret)<br><br># ChatGPT<br>openai.api_key = os.environ.get(&#39;OPENAI_API_KEY&#39;)<br><br># 處理Line Request<br>def linebot(request):<br>    if request.method != &#39;POST&#39; or &#39;X-Line-Signature&#39; not in request.headers:<br>        return &#39;Error: Invalid source&#39;, 403<br>    else:<br>        # get X-Line-Signature header value<br>        x_line_signature = request.headers[&#39;X-Line-Signature&#39;]<br>        # get body value<br>        body = request.get_data(as_text=True)<br>        hash = hmac.new(channel_secret.encode(&#39;utf-8&#39;),<br>                    body.encode(&#39;utf-8&#39;), hashlib.sha256).digest()<br>        signature = base64.b64encode(hash).decode(&#39;utf-8&#39;)<br><br>        # Compare x-line-signature request header and the signature<br>        if x_line_signature == signature:<br>            try:<br>                # 解析 JSON<br>                json_data = json.loads(body)<br>                handler.handle(body, x_line_signature)<br>                # 取得 reply token<br>                tk = json_data[&#39;events&#39;][0][&#39;replyToken&#39;] <br>                # 取得 user ID<br>                user_id = json_data[&#39;events&#39;][0][&#39;source&#39;][&#39;userId&#39;]     <br>                # 取得 Line訊息  <br>                user_input = json_data[&#39;events&#39;][0][&#39;message&#39;][&#39;text&#39;]<br><br>                # 回傳等待訊息<br>                line_bot_api.push_message(user_id, TextSendMessage(&#39;資料爬取中請稍後...&#39;))<br><br>                # 將Line訊息發給get_news去爬取資料<br>                search_output = get_news(user_input)<br>                # 回傳爬取結果<br>                line_bot_api.push_message(user_id, TextSendMessage(&#39;&lt;以下為爬取結果，ChatGPT處理中請稍候...&gt;\n&#39; + search_output))<br><br>                # 將爬取結果發給ChatGPT做整理<br>                gpt_unify = search_output + &quot;\n請幫我整理以上新聞的重點，並條列出各項重點&quot;<br>                GPT_output = chat_with_gpt(gpt_unify)<br>                # 回傳ChatGPT整理後的結果<br>                line_bot_api.push_message(user_id, TextSendMessage(&#39;&lt;以下為ChatGPT整理結果：&gt;\n&#39; + GPT_output))<br><br>                return &#39;OK&#39;, 200<br>            except:<br>                print(&#39;error&#39;)<br>        else:<br>            return &#39;Invalid signature&#39;, 403<br><br># 回傳ChatGPT訊息<br># 將LINE 使用者訊息發給ChatGPT，ChatGPT處理後再回傳給 LINE 使用者<br>def chat_with_gpt(user_input):<br>    try:<br>        # 設定提示語句，將使用者輸入的訊息與回覆模板結合<br>        prompt = f&quot;{user_input}\n\nResponse:&quot;<br>        # 使用OpenAI API，傳遞模型名稱、訊息角色和內容，以生成機器人回覆<br>        response = openai.ChatCompletion.create(<br>            model=&quot;gpt-3.5-turbo&quot;,<br>            messages=[<br>                    {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful assistant.&quot;},<br>                    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}<br>                ]<br>        )<br>        # 從回覆中提取機器人的回覆訊息，並去除前後空白<br>        result = response[&#39;choices&#39;][0][&#39;message&#39;][&#39;content&#39;].strip()<br>        return result # 返回處理過的回覆給LINE使用者<br>    except openai.Error as e:<br>        return &quot;Error: OpenAI API&quot;<br>    except Exception as e:<br>        return &quot;Error: An unexpected error occurred&quot;<br><br># 爬取資料<br>def get_news(user_input):<br>    query = user_input<br>    links, titles = google_news_crawler(query)<br>    output = &quot;&quot;  # 初始化一個空字串來存儲結果<br>    <br>    for i, (link, title) in enumerate(zip(links, titles), start=1):<br>        # print(f&quot;{i}. 標題： {title}\n   連結： {link}\n&quot;)<br>        result = f&quot;{i}. 標題： {title}\n   連結： {link}\n&quot;  # 將當前結果格式化為一個字串<br>        output += result  # 將當前結果追加到 output 變數中<br>    <br>    # output += &quot;\n請幫我整理以上新聞的重點，並條列出來&quot;    <br>    return output<br><br>def google_news_crawler(query, num_results=3):<br>    links = []<br>    titles = []<br>    try:<br>        googlenews = GoogleNews(lang=&quot;zh&quot;, period=&quot;1d&quot;)<br>        googlenews.search(query)<br>        results = googlenews.results()<br>        <br>        for result in results[:num_results]:<br>            links.append(result[&quot;link&quot;])<br>            titles.append(result[&quot;title&quot;])<br>    except Exception as e:<br>        print(f&quot;Error: {e}&quot;)<br>    return links, titles            </pre><p><strong>3.9 ) — 調整 requirements.txt </strong>💻<br>加入 GoogleNews 套件</p><pre>line-bot-sdk<br>openai<br>GoogleNews</pre><h4>步驟4：新聞吃飽飽囉 🍔</h4><p><strong>4.1 ) — 至Messaging API頁籤，掃碼加入這個帳號</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Lq6zCtgxuPtRkzTSMOOJw.png" /></figure><p><strong>4.2 ) —來吧，展示！</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ldaANUzC_FVGX_84V2g-wQ.png" /></figure><h4>優化調整 -&gt; 短網址</h4><p>到這一步，不知道大家有沒有注意到，我們爬取後的新聞連結有時會是這樣落落長的一段，吃掉整條訊息的篇幅，除了排版上的美觀度不佳，也多少影響了閱讀上的體驗</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*4qfgFc7s3dfnWXUOPKp1rA.png" /></figure><p>在這一步，我們要做到將網址精簡的目標。</p><p>因為會使用到 bitly 這個網站所提供縮短網址的服務，所以我們要先去註冊會員，並取得它的 API Token</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-s35f613VIQ-4xbynx1nA.png" /><figcaption>前後比較圖</figcaption></figure><p><strong>opt 1 ) —註冊bitly</strong></p><p>挑選自己喜歡的方式去註冊即可</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tXUztV08uTwrG-as7CUXHA.png" /></figure><p><a href="https://bitly.com/">Bitly | Short URLs, QR Codes, and More</a></p><p><strong>opt 2 ) — 取得Access token</strong></p><ol><li>註冊完成後，點及左邊選單的 <strong><em>Settings</em></strong></li><li>接著點擊下層的 <em>API</em></li><li>輸入你的登入密碼，點擊 <strong><em>Generate</em> <em>token</em></strong></li><li>完成後下方會顯示你的 <strong><em>Access token</em></strong>，將它複製起來</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QdvNNNdbJWq1AJnTIyyfEA.png" /></figure><p><strong>opt 3 ) — 回到GCP上，設定 Cloud Functions 的環境變數</strong></p><p>新增變數：<strong><em>BITLY_ACCESS_TOKEN</em></strong>，並放入剛剛拿到的 Token</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Kf9045k3s3oJMQ48rtgCQ.png" /></figure><p><strong>opt 4 ) — 編輯 Cloud Functions 程式碼</strong></p><ul><li><strong>調整 main.py </strong>💻</li></ul><p>引入套件：</p><pre>import bitlyshortener</pre><p>設定 BITLY_ACCESS_TOKEN：</p><pre># 縮短網址Token<br>BITLY_ACCESS_TOKEN = os.environ.get(&#39;BITLY_ACCESS_TOKEN&#39;)</pre><p>編寫函數shorten_url使用 TinyURL API 來縮短網址：</p><pre>def shorten_https://medium.com/url(url):<br>    shortener = bitlyshortener.Shortener(tokens=[BITLY_ACCESS_TOKEN], max_cache_size=256)<br>    short_url = shortener.shorten_urls([url])[0]<br>    return short_url</pre><p>在 google_news_crawler 函數中使用 shorten_url 函數將長網址轉換為短網址：</p><pre>def google_news_crawler(query, num_results=3):<br>    links = []<br>    titles = []<br>    try:<br>        googlenews = GoogleNews(lang=&quot;zh&quot;, period=&quot;1d&quot;)<br>        googlenews.search(query)<br>        results = googlenews.results()<br>        <br>        for result in results[:num_results]:<br>            long_url = result[&quot;link&quot;]<br>            short_url = shorten_url(https://medium.com/long_url)  # 使用 shorten_url 函數縮短網址<br>            links.append(short_url)<br>            titles.append(result[&quot;title&quot;])<br>    except Exception as e:<br>        print(f&quot;Error: {e}&quot;)<br>    return links, titles</pre><ul><li><strong>調整 requirements.txt </strong>💻<br>加入 bitlyshortener 套件</li></ul><pre>line-bot-sdk<br>openai<br>GoogleNews<br>bitlyshortener</pre><ul><li>完成後重新 <strong>DEPLOY </strong>🚀</li></ul><blockquote><strong>其他補充：</strong></blockquote><blockquote>如果是想在 Anaconda 上先測試的話，要先安裝套件 👇</blockquote><blockquote>pip install bitlyshortener</blockquote><h4>總結 👽</h4><p>在本篇文章中，我們創建了一個可以隨時幫我爬取新聞，且透過 ChatGPT 重點整理的聊天機器人 。最後也優化了網址的長度，並增加排版面積與可讀性。<br>如此一來我們不但可以即時掌握最新指標新聞，還能擁有ChatGPT整理後重點後，減少自行閱讀與整理的時間，如果想要知道詳情的文章內容也可以透過網址直接獲得！</p><p>📔 <strong>以上內容部分參考自網路，並整理成自已的實作筆記分享給大家 </strong>📔</p><p>今天就先這樣<br>掰掰 🏊🏼 🏊🏼 🏊🏼 🏊🏼 🏊🏼 🏊🏼</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=238b9e3e4025" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LINE 聊天機器人 - 結合ChatGPT 打造你的隨身智能小幫手]]></title>
            <link>https://medium.com/@chiehwen0926/chatgpt-%E8%88%87-line-%E7%B5%90%E5%90%88-%E4%BD%A0%E7%9A%84%E9%9A%A8%E8%BA%AB%E6%99%BA%E8%83%BD%E5%B0%8F%E5%B9%AB%E6%89%8B-gcp-cloud-functions-%E6%87%89%E7%94%A8%E5%AF%A6%E4%BE%8B-da87f3bd66?source=rss-751994df6ff1------2</link>
            <guid isPermaLink="false">https://medium.com/p/da87f3bd66</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[cloud-functions]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[line-bot]]></category>
            <dc:creator><![CDATA[Jerry Wen]]></dc:creator>
            <pubDate>Thu, 04 May 2023 04:44:56 GMT</pubDate>
            <atom:updated>2023-05-05T09:21:34.677Z</atom:updated>
            <content:encoded><![CDATA[<h4>#LINE #聊天機器人 #GCP #ChatGPT #LINE聊天機器人2 #<strong>後記</strong></h4><h4><strong>LINE聊天機器人2：將 </strong><em>ChatGPT 與 LINE 結合，打造隨身的智能小幫手</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Jyc1SmUv29_xkmaDx11DA.png" /></figure><p>在前一篇文章中，講述了 LINE BOT 設定 &amp; Cloud Functions 部署，並做出了模仿你說話的聊天機器人，但總覺得還有更多好玩的…</p><p><a href="https://medium.com/@chiehwen0926/line-%E8%81%8A%E5%A4%A9%E6%A9%9F%E5%99%A8%E4%BA%BA-%E8%BC%95%E9%AC%86%E6%A8%A1%E4%BB%BF%E8%88%87%E4%BA%92%E5%8B%95%E7%9A%84%E7%B5%82%E6%A5%B5%E6%8C%87%E5%8D%97-gcp-cloud-functions-%E6%87%89%E7%94%A8%E5%AF%A6%E4%BE%8B-d4f43db3ca67">👋 LINE 聊天機器人 - 輕鬆模仿與互動的終極指南 ( GCP Cloud Functions 應用實例 )</a></p><p>不知道大家是不是和我一樣懶，身為一個 ChatGPT 的愛用者，當在使用手機的時候，總覺得要去開瀏覽器再去使用 ChatGPT 有點麻煩，所以這篇文章就登場了！</p><blockquote>️ ✍ <strong>番外篇：</strong>透過爬蟲與 <strong>ChatGPT ，</strong>打造個人股市的消息整理小幫手</blockquote><pre>Journey 🥾 :<br><br>    流程概觀 🔍<br><br> 1. LINE BOT 設定、GCP Cloud Functions 開發, 部署與串接<br><br> 2. 註冊 OpenAI API，獲取 Keys 🔑<br><br> 3. 設定 ChatGPT API Key 環境變數<br><br> 4. OpenAI API 調用<br><br> 5. 領域展開：ChatGPT-J 😎</pre><h4>流程概觀 🔍</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_9ajE_hxgTDag-izqbcNHA.png" /></figure><h4>步驟 1：LINE BOT 設定、GCP Cloud Functions 開發, 部署與串接</h4><p>我這邊列出要有的東西，如果是一步一步跟到這的朋友，當然也可以拿前一篇建好的 Channel &amp; Functions 去微調使用，但我偏好都建立新的去使用，也可以順便再熟悉下前一章的內容</p><ol><li>建立一個 Messaging Channel</li><li>建立一個 GCP Cloud Functions</li></ol><p><strong>因為這步驟內容與前一篇文章重複，如果還不了解這步驟的朋友，建議可以先參考前一篇文章呦</strong>👇</p><p><a href="https://medium.com/@chiehwen0926/line-%E8%81%8A%E5%A4%A9%E6%A9%9F%E5%99%A8%E4%BA%BA-%E8%BC%95%E9%AC%86%E6%A8%A1%E4%BB%BF%E8%88%87%E4%BA%92%E5%8B%95%E7%9A%84%E7%B5%82%E6%A5%B5%E6%8C%87%E5%8D%97-gcp-cloud-functions-%E6%87%89%E7%94%A8%E5%AF%A6%E4%BE%8B-d4f43db3ca67">👋 LINE 聊天機器人 - 輕鬆模仿與互動的終極指南 ( GCP Cloud Functions 應用實例 )</a></p><h4>步驟 2：註冊 OpenAI API，獲取 Keys 🔑</h4><p>再來，我們要註冊並取得一個 API Key</p><p><strong>2.1 ) - 登入註冊一個OpenAI帳戶</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*woL_z77R4iwzwiqem6qe7A.png" /></figure><p><strong>2.2 ) - 點擊 View API keys</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8gkY4LokXV6pAgLARVR1g.png" /></figure><p><strong>2.3 ) — 點擊 Create new secret key</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NBsUYJ21-JRohtytDTEHZw.png" /></figure><p><strong>2.4 ) — 自由輸入 key Name</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LOH5O3aCbLhUbm12EkTxHw.png" /></figure><p><strong>2.5 ) — 複製你的key，後面會用到</strong> 🔑</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kdiy-wJroljVCdNOU9wBSg.png" /></figure><h4>步驟 3：設定 ChatGPT API Key 環境變數</h4><p>如同前一篇文章所提到，基於安全性問題我們要將 Key 放在環境變數，在程式執行時再去讀取它</p><blockquote>💡 <strong>若覺得 步驟3 怎麼跳了一大段，可以參考前一篇文章的基本設定</strong></blockquote><p><a href="https://medium.com/@chiehwen0926/line-%E8%81%8A%E5%A4%A9%E6%A9%9F%E5%99%A8%E4%BA%BA-%E8%BC%95%E9%AC%86%E6%A8%A1%E4%BB%BF%E8%88%87%E4%BA%92%E5%8B%95%E7%9A%84%E7%B5%82%E6%A5%B5%E6%8C%87%E5%8D%97-gcp-cloud-functions-%E6%87%89%E7%94%A8%E5%AF%A6%E4%BE%8B-d4f43db3ca67">👋 LINE 聊天機器人 - 輕鬆模仿與互動的終極指南 ( GCP Cloud Functions 應用實例 )</a></p><p><strong>3.1 ) — 設定環境變數：OPENAI_API_KEY，將 “步驟1” 拿到的 Key 放這在 🔑</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*GukzaBj-3xcoCYw1cNDPqQ.png" /></figure><p><strong>3.2 ) — </strong><strong>import openai 讓我們可以和 ChatGPT 進行互動</strong></p><pre>import openai</pre><p><strong>3.3 ) — 將新的環境變數加進來</strong></p><pre># ChatGPT<br>openai.api_key = os.environ.get(&#39;OPENAI_API_KEY&#39;)</pre><p><strong>3.4) — 到目前為止，程式上半部會長這樣</strong></p><pre>import json<br>import hmac<br>import hashlib<br>import base64<br>import os<br>import openai<br><br>from linebot import LineBotApi, WebhookHandler<br>from linebot.exceptions import InvalidSignatureError<br>from linebot.models import MessageEvent, TextMessage, TextSendMessage<br><br># line<br>line_bot_api = LineBotApi(os.environ.get(&#39;CHANNEL_ACCESS_TOKEN&#39;))<br>channel_secret = os.environ.get(&#39;CHANNEL_SECRET&#39;)<br>handler = WebhookHandler(channel_secret)<br><br># ChatGPT<br>openai.api_key = os.environ.get(&#39;OPENAI_API_KEY&#39;)</pre><h4>步驟 4：OpenAI API 調用</h4><p><strong>4.1) — 定義函式：chat_with_gpt </strong><br>用於將 LINE 使用者訊息傳遞給 ChatGPT，並將處理後的回覆返回給 LINE 使用者</p><pre># 回傳ChatGPT訊息<br># 將LINE 使用者訊息發給ChatGPT，ChatGPT處理後再回傳給 LINE 使用者<br>def chat_with_gpt(user_input):<br>    try:<br>        # 設定提示語句，將使用者輸入的訊息與回覆模板結合<br>        prompt = f&quot;{user_input}\n\nResponse:&quot;<br>        # 使用OpenAI API，傳遞模型名稱、訊息角色和內容，以生成機器人回覆<br>        response = openai.ChatCompletion.create(<br>            model=&quot;gpt-3.5-turbo&quot;,<br>            messages=[<br>                    {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful assistant.&quot;},<br>                    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}<br>                ]<br>        )<br>        # 從回覆中提取機器人的回覆訊息，並去除前後空白<br>        result = response[&#39;choices&#39;][0][&#39;message&#39;][&#39;content&#39;].strip()<br>        return result # 返回處理過的回覆給LINE使用者<br>    except openai.Error as e:<br>        return &quot;Error: OpenAI API&quot;<br>    except Exception as e:<br>        return &quot;Error: An unexpected error occurred&quot;</pre><p><strong>4.2) — 呼叫 chat_with_gpt 函式，並回傳訊息給 LINE 使用者<br>將以下兩行 Code 加到我們的 linebot</strong> 函式中</p><pre># 將Line訊息發給ChatGPT<br>GPT_output = chat_with_gpt(user_input)   <br><br># 回傳ChatGPT訊息<br>line_bot_api.reply_message(tk, TextSendMessage(GPT_output))</pre><p><strong>4.3) — main.py完整的程式會長這樣</strong></p><pre>import json<br>import hmac<br>import hashlib<br>import base64<br>import os<br>import openai<br><br>from linebot import LineBotApi, WebhookHandler<br>from linebot.exceptions import InvalidSignatureError<br>from linebot.models import MessageEvent, TextMessage, TextSendMessage<br><br># line<br>line_bot_api = LineBotApi(os.environ.get(&#39;CHANNEL_ACCESS_TOKEN&#39;))<br>channel_secret = os.environ.get(&#39;CHANNEL_SECRET&#39;)<br>handler = WebhookHandler(channel_secret)<br><br># ChatGPT<br>openai.api_key = os.environ.get(&#39;OPENAI_API_KEY&#39;)<br><br># 處理Line Request<br>def linebot(request):<br>    if request.method != &#39;POST&#39; or &#39;X-Line-Signature&#39; not in request.headers:<br>        return &#39;Error: Invalid source&#39;, 403<br>    else:<br>        # get X-Line-Signature header value<br>        x_line_signature = request.headers[&#39;X-Line-Signature&#39;]<br>        # get body value<br>        body = request.get_data(as_text=True)<br>        hash = hmac.new(channel_secret.encode(&#39;utf-8&#39;),<br>                    body.encode(&#39;utf-8&#39;), hashlib.sha256).digest()<br>        signature = base64.b64encode(hash).decode(&#39;utf-8&#39;)<br><br>        # Compare x-line-signature request header and the signature<br>        if x_line_signature == signature:<br>            try:<br>                # 解析 JSON<br>                json_data = json.loads(body)<br>                handler.handle(body, x_line_signature)<br>                # 取得 reply token<br>                tk = json_data[&#39;events&#39;][0][&#39;replyToken&#39;]      <br>                # 取得 Line訊息  <br>                user_input = json_data[&#39;events&#39;][0][&#39;message&#39;][&#39;text&#39;]<br><br>                # 將Line訊息發給ChatGPT<br>                GPT_output = chat_with_gpt(user_input)   <br>                # 回傳ChatGPT訊息<br>                line_bot_api.reply_message(tk, TextSendMessage(GPT_output))<br><br>                return &#39;OK&#39;, 200<br>            except:<br>                print(&#39;error&#39;)<br>        else:<br>            return &#39;Invalid signature&#39;, 403<br><br># 回傳ChatGPT訊息<br># 將LINE 使用者訊息發給ChatGPT，ChatGPT處理後再回傳給 LINE 使用者<br>def chat_with_gpt(user_input):<br>    try:<br>        # 設定提示語句，將使用者輸入的訊息與回覆模板結合<br>        prompt = f&quot;{user_input}\n\nResponse:&quot;<br>        # 使用OpenAI API，傳遞模型名稱、訊息角色和內容，以生成機器人回覆<br>        response = openai.ChatCompletion.create(<br>            model=&quot;gpt-3.5-turbo&quot;,<br>            messages=[<br>                    {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful assistant.&quot;},<br>                    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}<br>                ]<br>        )<br>        # 從回覆中提取機器人的回覆訊息，並去除前後空白<br>        result = response[&#39;choices&#39;][0][&#39;message&#39;][&#39;content&#39;].strip()<br>        return result # 返回處理過的回覆給LINE使用者<br>    except openai.Error as e:<br>        return &quot;Error: OpenAI API&quot;<br>    except Exception as e:<br>        return &quot;Error: An unexpected error occurred&quot;</pre><p><strong>4.4 ) — 調整 requirements.txt </strong>💻<br>加入 openai</p><pre>openai</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*RJBXdenP0ET2_kIurgUMSw.png" /></figure><h4>步驟 5：領域展開 ChatGPT-J 😎</h4><p><strong>5.1 ) — 至Messaging API頁籤，掃碼加入這個帳號</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MjG5q8HuHNVMm93-M-oRPw.png" /></figure><p><strong>5.2 ) — 如假包換 ChatGPT</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TnIDTzP-GWD5hIbzcIF32w.png" /><figcaption>與ChatGPT對話截圖</figcaption></figure><h4>總結 👽</h4><p>在本篇文章中，成功地將原本的鸚鵡機器人蛻變為一隻展翅翱翔的鳳凰 🔥<br>透過 LINE BOT 與 ChatGPT 的結合，打造出一個無所不能的隨身 AI 機器人，當突然想要用 ChatGPT 時，終於不用一直去開瀏覽器了！</p><p>📔 <strong>以上內容部分參考自網路，並整理成自已的實作筆記分享給大家 </strong>📔</p><p>今天就先這樣<br>掰掰 🏊🏼 🏊🏼 🏊🏼 🏊🏼 🏊🏼 🏊🏼</p><h4>番外篇</h4><p>在下一篇的文章中，將延續本篇內容，再多應用一個 Google新聞的爬蟲，打造一個可以幫我們快速搜集和整理新聞的小幫手！✍</p><blockquote>身為一個股市投資者，消息面有時是確認自己想法與進攻訊號的步驟之一，但每天要追的新聞、消息、Twitter真的是多到數不清，更何況還要在時間內整理出重點分析…</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da87f3bd66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LINE 聊天機器人 - 手把手教學，輕鬆學會模仿與互動的功能 on GCP Cloud Functions]]></title>
            <link>https://medium.com/@chiehwen0926/line-%E8%81%8A%E5%A4%A9%E6%A9%9F%E5%99%A8%E4%BA%BA-%E8%BC%95%E9%AC%86%E6%A8%A1%E4%BB%BF%E8%88%87%E4%BA%92%E5%8B%95%E7%9A%84%E7%B5%82%E6%A5%B5%E6%8C%87%E5%8D%97-gcp-cloud-functions-%E6%87%89%E7%94%A8%E5%AF%A6%E4%BE%8B-d4f43db3ca67?source=rss-751994df6ff1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4f43db3ca67</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[line-bot]]></category>
            <category><![CDATA[cloud-functions]]></category>
            <category><![CDATA[gcp]]></category>
            <dc:creator><![CDATA[Jerry Wen]]></dc:creator>
            <pubDate>Thu, 04 May 2023 04:42:16 GMT</pubDate>
            <atom:updated>2023-05-05T08:53:28.339Z</atom:updated>
            <content:encoded><![CDATA[<h4>#LINE #聊天機器人 #GCP #ChatGPT #LINE聊天機器人1 #序</h4><h4>LINE聊天機器人1<strong>：</strong><em>創建一個模仿你說話的 LINE 聊天機器人</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ThfebLtmnv5_k20hKZ4uHg.png" /></figure><p>在本篇文章中，將學習到一個實用且有趣的 LINE 聊天機器人應用實例。<br>將ㄧ步一步 👣 的實作包括 LINE BOT 設定、GCP Cloud Functions 開發與部署功能、LINE Request 解碼與回覆訊息，最後將兩者串接在一起實現模仿說話的機器人。</p><p>學會了最基本的功能，我們後續就可以利用它延伸出其他更多元的功能！</p><blockquote>🔥 <strong>後記：</strong>將最近大受歡迎的 <strong>ChatGPT </strong>集成到我們的 LINE 聊天機器人中，讓這隻鸚鵡機器人蛻變為一隻展翅翱翔的鳳凰</blockquote><blockquote>✍️ <strong>番外篇：</strong>透過爬蟲與 <strong>ChatGPT ，</strong>打造個人股市的消息整理小幫手</blockquote><pre>Journey 🥾 :<br><br>    流程概觀 🔍<br><br> 1. 註冊成為 LINE 開發者，並設置 LINE Bot<br><br> 2. 學習如何使用 GCP Cloud Functions 服務部署程式碼<br><br> 3. 將 LINE 與 GCP Cloud Functions 連結在一起<br><br> 4. 和它說聲Hi吧 👋 （實現與機器人的互動）</pre><h4><strong>流程概觀 </strong>🔍</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WcRN6k-EXmIuKBKqYapd8Q.png" /></figure><h4>步驟 1：設置LINE Bot 🤖</h4><p>首先第一部份將會介紹如何成為 LINE 的開發者，並建立起一個自己的LINE BOT Channel。</p><blockquote>LINE Developers：<a href="https://developers.line.biz/zh-hant/">https://developers.line.biz/zh-hant/</a></blockquote><p><strong>1.1 ) - 註冊並登入 LINE Developer</strong><br>要開發一個 LINE BOT，需要先成為 LINE 的開發者。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*im-XOydMAnPtExfD_sX5sA.png" /><figcaption>LINE Developers Login</figcaption></figure><ul><li>我這邊是直接使用平常在用的 LINE 帳號去登入註冊</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fDhW1iwVGCFF5_zLZtMOg.png" /><figcaption>LINE Login</figcaption></figure><p><strong>1.2 ) - 在LINE Developers建立一個Provide</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JtsDVf4Gf_hdcaXhDI5Vzg.png" /><figcaption>建立一個你的Providers</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*2mCODT7KV14ZmsNgucOSHA.png" /><figcaption>自由輸入自己的Provider名稱</figcaption></figure><p><strong>1.3 ) - 建立一個Channel</strong></p><ul><li>選擇Messaging API的Channels形式</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yhYQ1LEeuxLLUizw6w8n3w.png" /><figcaption>選擇Messaging API</figcaption></figure><ul><li>填入這個Channel必要的欄位資訊</li></ul><blockquote>Hi圖片網址：<a href="https://www.flaticon.com/free-icon/hi_4666748?term=hi&amp;page=1&amp;position=8&amp;origin=search&amp;related_id=4666748">https://www.flaticon.com/free-icon/hi_4666748?term=hi&amp;page=1&amp;position=8&amp;origin=search&amp;related_id=4666748</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*36cEFmUAG7jrbOuwqaW6WQ.png" /><figcaption>填入必要欄位</figcaption></figure><p><strong>1.4 ) - 獲取Channel Secret<br> </strong>至Basic settings頁籤，取得Channel Secret</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*7ZVlzAofCDn2K8E46kdX7A.png" /><figcaption>Basic settings頁籤</figcaption></figure><ul><li>可以先將Channel Secret憑證紀錄下來，稍後程式會用到</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*TAkbBxduTt8sbrqNvjGL7A.png" /><figcaption>Channel secret</figcaption></figure><p><strong>1.5 ) - 獲取Access Token<br>至</strong>Messaging API頁籤，取得Channel Access Token</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*RUdRMGn0uAaydfD7Wn5Wug.png" /></figure><ul><li>點擊Issue，產生Channel Access Token</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E9rCQ2c9bNFxUKnWjUYtOA.png" /></figure><ul><li>可以先將Channel Access Token紀錄下來，稍後程式會用到</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*G-67WIsoABi6Qg4zNRnhDg.png" /></figure><p><strong>1.6 ) - Line官方帳號平台設定</strong></p><blockquote>LINE Official : <a href="https://manager.line.biz/">https://tw.linebiz.com/login/</a></blockquote><ul><li>關閉 聊天模式與自動回覆訊息</li><li>開啟 Webhook</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-NvGK8mhPU8FrpnF0CLR4g.png" /><figcaption>回應設定</figcaption></figure><ul><li>將LINE預設的自動回覆<strong><em>關閉</em></strong>，才不會一發訊息就一直收到自動回覆</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sdUxfPzCQIL_c5mhpVp74g.png" /><figcaption>關閉自動回覆</figcaption></figure><h4>步驟 2：設置 GCP Cloud Functions ☁️</h4><p><strong>為什麼要使用 GCP Cloud Functions</strong> ❓</p><ol><li>不用擔心伺服器的維護和管理工作，也不用在自己電腦上啟一個Flask環境 （雖然本次的小應用並不會用到什麼資源，就是懶…）</li><li>Cloud Functions 是按需求付費的，根據實際使用的資源付費。<br>這意味著不需要為未使用的伺服器或閒置的資源付費</li><li>沒有為什麼，純粹想試試看 Cloud Funcitons</li></ol><blockquote>Cloud Functions 是一個 Serverless 的服務，這種架構可讓我們更專注於應用程式的功能和邏輯，而<strong>無需擔心底層基礎設施的管理和維護。</strong></blockquote><blockquote>它允許在雲端環境中運行單一功能的程式碼片段<br>這種服務通常用於執行輕量的、事件驅動的任務，如處理 API 請求</blockquote><blockquote>GCP Login : <a href="https://console.cloud.google.com/?hl=en-AU">https://console.cloud.google.com</a></blockquote><p><strong>2.1 ) - 登入GCP，並至 Cloud Functions</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nJgMx7OgWNW9lj3byrVEBQ.png" /></figure><p><strong>2.2 ) - 建立一個函式</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vpd0jzZcEPS8shDZD1620g.png" /></figure><p><strong>2.3 ) - 填入函式必要欄位</strong></p><ul><li>自由輸入你的函式名稱</li><li>地區選擇：台灣</li><li>驗證：允許未經驗證的叫用</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dggZVa_ztctN54M37lqMXQ.png" /></figure><ul><li>Memory allocated：選擇最小的128MB即可 （夠用也比較便宜哈哈）</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*J8z0rTl7zgfi5d-fn0RH_A.png" /></figure><p><strong>2.4 ) -部署程式碼1 (main.py) </strong>💻</p><ul><li>選擇Python版本</li><li>確任目前是在編輯main.py</li><li>修改Entry point: linebot</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*uZkiofGkFEbQGwujsakyHg.png" /><figcaption>main.py 設定</figcaption></figure><p>在 <strong>main.py</strong>中引入以下套件</p><ul><li>這次會用到的套件：<br>包括 json，linebot（用於實現 Line Bot 相關功能）和加密模塊。</li></ul><pre># 這次會用到的套件<br>import json<br>import hmac<br>import hashlib<br>import base64<br>from linebot import LineBotApi, WebhookHandler<br>from linebot.exceptions import InvalidSignatureError<br>from linebot.models import MessageEvent, TextMessage, TextSendMessage</pre><p>在 <strong>main.py</strong>中填入以下Code</p><ul><li><strong>linebot函式：</strong><br>用於處理來自 Line 平台的請求<br><strong><em>將 CHANNEL_ACCESS_TOKEN , CHANNEL_SECRET_TOKEN 替換成上面設置 LINE BOT 所得到的值</em></strong></li></ul><blockquote>❌ <strong>這裡我們先偷懶，直接將 TOKEN Hard Code，但這樣不符合安全性，也缺乏彈性，最後會補充如何設置環境變數的方式</strong></blockquote><ul><li><strong>驗證請求：</strong><br>檢查請求頭中是否存在 ‘X-Line-Signature’，若不存在則返回錯誤。<br>接著將請求頭中的 ‘X-Line-Signature’ 與計算出的數字簽名進行對比，若不一致則返回錯誤。</li><li><strong>處理請求：</strong><br>將request內容轉換成 JSON 格式，並取得 reply Token 和訊息內容。</li><li><strong>回覆訊息：</strong><br>使用 push_message 方法，將取得的 reply Token，加上收到的訊息原樣推送回給用戶。</li></ul><p>這個程式碼主要實現了一個簡單的功能：當用戶向機器人發送訊息時，機器人會將訊息原樣返回給用戶</p><pre>line_bot_api = LineBotApi(&#39;YOUR CHANNEL_ACCESS_TOKEN&#39;)<br>channel_secret = &#39;YOUR CHANNEL_SECRET_TOKEN&#39;<br>handler = WebhookHandler(channel_secret)<br><br>def linebot(request):<br>    if request.method == &#39;POST&#39;:<br>        if &#39;X-Line-Signature&#39; not in request.headers:<br>            return &#39;Error: Invalid source&#39;, 403<br>        else:<br>            # get X-Line-Signature header value<br>            x_line_signature = request.headers[&#39;X-Line-Signature&#39;]<br>            # get body value<br>            body = request.get_data(as_text=True)<br>            # decode body<br>            hash = hmac.new(channel_secret.encode(&#39;utf-8&#39;),<br>                        body.encode(&#39;utf-8&#39;), hashlib.sha256).digest()<br>            signature = base64.b64encode(hash).decode(&#39;utf-8&#39;)<br>            # Compare x-line-signature request header and the signature<br>            if x_line_signature == signature:<br>                try:<br>                    json_data = json.loads(body)<br>                    handler.handle(body, x_line_signature)<br>                    tk = json_data[&#39;events&#39;][0][&#39;replyToken&#39;]         # 取得 reply token<br>                    msg = json_data[&#39;events&#39;][0][&#39;message&#39;][&#39;text&#39;]   # 取得 訊息 <br>                    line_bot_api.reply_message(tk,TextSendMessage(msg)) # 回傳 訊息<br>                    # print(msg, tk)<br>                    return &#39;OK&#39;, 200<br>                except:<br>                    print(&#39;error&#39;)<br>            else:<br>                return &#39;Invalid signature&#39;, 403<br>    else:<br>        return &#39;Method not allowed&#39;, 400<br></pre><ul><li>完成後的樣子，GCP 上的示意圖</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KLUIx1kaSLUFgH1dGG1HcA.png" /></figure><p><strong>2.5 ) -部署程式碼2 (requirements.txt) </strong>💻</p><p>在 requirements.txt 中填入以下套件</p><pre>line-bot-sdk</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*lYLcoP-ez9tmlBnozp01Og.png" /></figure><p><strong>2.6 ) - DEPLOY </strong>🚀</p><p>最後，確認以上步驟無誤，將程式碼部署上Cloud Functions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*gnXW-Bs7GAxcROP4vJAIyw.png" /><figcaption>DEPLOY</figcaption></figure><p><strong>2.7 ) - TRIGGER測試 </strong>🔫</p><ul><li>切換至TRIGGER頁籤，點擊觸發網址</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CrRc5-qrq7P-9NQHqvafcA.png" /><figcaption>點擊網址觸發程式</figcaption></figure><ul><li>因為在linebot的函式中，我們限制了Request的方法與格式（確認請求是從LINE發出的）<br>所以得到 Method not allowed 的結果是正確的</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*hOWDBmZVaSNdv-yKzfshww.png" /><figcaption>直接觸發網址的結果</figcaption></figure><p><strong>2.8 ) — 環境變數設定 (安全性優化) </strong>✅<strong><br></strong>不知道大家有沒有注意到，我們前面是將 <strong><em>CHANNEL_ACCESS_TOKEN , CHANNEL_SECRET_TOKEN </em></strong>直接放到程式碼內，但這樣會有安全性問題，所以這邊我們來調整一下</p><ul><li>先點進我們剛剛建立的函式</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*SuBqA3qT3MKfP1ErOL6t1A.png" /></figure><ul><li>點擊 編輯</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*dBv-1LD2ZyEhLtge3HVD3w.png" /></figure><ul><li>將隱藏的選單打開來</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*wt8x567YgNtrwTFcf9t5Gg.png" /></figure><ul><li>新增環境變數，變數名稱為大寫字母，並使用下劃線分隔單詞<br><strong><em>CHANNEL_ACCESS_TOKEN<br>CHANNEL_SECRET</em></strong></li><li>將你的 TOKEN 值填入對應的 Value 欄位</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*tfNFxIGYmMke4qTHzVIezg.png" /></figure><p><strong>2.8 ) — </strong>import os模塊，讓我們可以與系統進行交互。例：讀取環境變數</p><pre>import os</pre><ul><li>將原本 Hard Code 的 Key 調整成去讀取設定的環境變數</li></ul><pre># line_bot_api = LineBotApi(&#39;YOUR LINE_ACCESS_TOKEN&#39;)<br># channel_secret = &#39;YOUR CHANNEL_SECRET_TOKEN&#39;<br><br>line_bot_api = LineBotApi(os.environ.get(&#39;CHANNEL_ACCESS_TOKEN&#39;))<br>channel_secret = os.environ.get(&#39;CHANNEL_SECRET&#39;)</pre><p><strong>2.9 ) — </strong>調整完畢，重新 <strong>DEPLOY</strong> 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*R6Cy443vS9ePRwVSV-pmrw.png" /></figure><blockquote><a href="https://cloud.google.com/functions/docs/configuring/env-var?hl=zh-cn#functions-deploy-command-python">https://cloud.google.com/functions/docs/configuring/env-var?hl=zh-cn#functions-deploy-command-python</a></blockquote><h4>步驟 3：將LINE與GCP連結在一起吧！ 👉 👈</h4><p>在此步驟，我們將透過 LINE 去觸發 Cloud Functions 的網址，並得到Success的訊息！</p><p><strong>3.1 ) - 複製，Cloud Functions 的觸發網址</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CrRc5-qrq7P-9NQHqvafcA.png" /><figcaption>複製觸發網址</figcaption></figure><p><strong>3.2 ) - 回到LINE Developer平台，做Webhook設定</strong></p><blockquote>LINE Developers：<a href="https://developers.line.biz/zh-hant/">https://developers.line.biz/zh-hant/</a></blockquote><ul><li><strong>至</strong>Messaging API頁籤</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*RUdRMGn0uAaydfD7Wn5Wug.png" /><figcaption>Messaging API頁籤</figcaption></figure><ul><li>將剛剛複製的 Cloud Functions 觸發網址，貼至Webhook URL欄位</li><li>開啟 <strong>“Use webhook”</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K21vWgTHJjZBjWxq3U9KbA.png" /><figcaption>Webhook設定</figcaption></figure><p><strong>3.3 ) - 測試 Webhook </strong>🪝</p><ul><li>點擊 Verify 測試，<strong>確認收到 Success</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3XX1WDnEXkf__4QfrhlJxQ.png" /><figcaption>Verify</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xTo7xj9-cmPfwckQYsW0vQ.png" /><figcaption>Webhook Success</figcaption></figure><p>👏 做到這一步，你已經成功將 LINE Bot 與 GCP Cloud Functions 連接起來了！</p><h4>步驟 4：和它說聲Hi吧 👋</h4><p><strong>4.1 ) -至Messaging API頁籤，掃碼加入這個帳號</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B6hJ46NHRhv8h88N1ytaxQ.png" /></figure><p><strong>4.2 ) - 和它說聲Hi吧 </strong>👋</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*gG3F0Mbdn8-ydg0xgkwZ2w.jpeg" /><figcaption>Hi LINE Bot</figcaption></figure><h4>總結 👽</h4><p>在本篇文章中，我們成功地掌握了如何創建一個 <strong>LINE 鸚鵡機器人 </strong><br>我們讓這個機器人具備了<strong>模仿用戶語言的能力</strong>，讓它成為一個有趣的模仿達人。</p><p>📔 <strong>以上內容部分參考自網路，並整理成自已的實作筆記分享給大家 </strong>📔</p><p>今天就先這樣<br>掰掰 🏊🏼 🏊🏼 🏊🏼 🏊🏼 🏊🏼 🏊🏼</p><h4>後記 📖</h4><p>在下一篇的文章中，我們將嘗試將最近大受歡迎的 <strong>ChatGPT </strong>集成到我們的LINE機器人中，讓這隻鸚鵡機器人蛻變為一隻展翅翱翔的鳳凰 🔥</p><p><a href="https://medium.com/@chienwen0926/chatgpt-%E8%88%87-line-%E7%B5%90%E5%90%88-%E4%BD%A0%E7%9A%84%E9%9A%A8%E8%BA%AB%E6%99%BA%E8%83%BD%E5%B0%8F%E5%B9%AB%E6%89%8B-gcp-cloud-functions-%E6%87%89%E7%94%A8%E5%AF%A6%E4%BE%8B-da87f3bd66">🧠 ChatGPT 與 LINE 結合：你的隨身智能小幫手 ( GCP Cloud Functions 應用實例 )</a></p><blockquote>想像一下，隨時隨地擁有一個頂級的 AI 助理機器人 ( <strong>ChatGPT </strong>)，能回應你的問題，還能提供智能建議和實用的信息，讓日常的生活變得更加輕鬆、高效和有趣。</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4f43db3ca67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift 作品 — 可愛柴柴1A2B — 猜數字遊戲App]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/swift-%E4%BD%9C%E5%93%81-%E5%8F%AF%E6%84%9B%E6%9F%B4%E6%9F%B41a2b-%E7%8C%9C%E6%95%B8%E5%AD%97%E9%81%8A%E6%88%B2app-185c7e8e6441?source=rss-751994df6ff1------2</link>
            <guid isPermaLink="false">https://medium.com/p/185c7e8e6441</guid>
            <category><![CDATA[1a2b]]></category>
            <category><![CDATA[ios-apps]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios-games]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Jerry Wen]]></dc:creator>
            <pubDate>Sat, 09 Jun 2018 14:55:29 GMT</pubDate>
            <atom:updated>2018-06-09T14:58:19.008Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>一、首先來簡單介紹App操作流程</strong></p><p><strong>gif圖</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*TbQxGeQl2DmZSDio6fs8YA.gif" /></figure><ol><li>主頁面：</li></ol><p>按下ＧＯ便可開始遊戲！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*Jcx_32WmFtRuc0082j4uyg.png" /></figure><p>2.</p><p>進入畫面後便開始計時，</p><p>輸入四個數字後其他數字便無法點選。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*T7eHcBAfwETYZxJ4DBzTxA.png" /></figure><p>3.</p><p>按下ＯＫ送出答案，在黑板上顯示玩家猜的數字與幾Ａ幾Ｂ。</p><p>送出答案後，所有button便恢復成可點擊狀態，讓玩家繼續猜數字。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*KPmP4OE4_-VcdD6LdnneFw.png" /></figure><p>4.</p><p>點選黑板上方的柴柴，可以獲得一字提示！（因為阿柴都是很任性的，所以提示只會有一次！）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*d0yr1yycgp2qdYImfWbKfA.png" /></figure><p>5.</p><p>答對題目後，跳出Alert讓玩家輸入自己的姓名，並儲存起來。</p><p>若玩家未輸入姓名點選儲存，會以“noName”紀錄該筆過關秒數。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*97187q4ulkNObK9A_dPcjw.png" /></figure><p>6.</p><p>按下重新開始按鈕，重新一局遊戲。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*D0YZYZdemevrbvXjd4z0Hw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*5aPXzeHwtsVOBHiYbGlFRw.png" /></figure><p>7.</p><p>回到主畫面，點擊“記錄與排行”可以觀看自己的歷史破關秒數。</p><p>這部分是利用UserDefaults去儲存資料。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*aXo7DF7oRcYFF1eulpzPYw.png" /></figure><p>8.</p><p>未來希望增加線上排行功能，讓玩家可以上傳自己的成績，並且排名，讓玩家間可以相互較勁，增加遊戲趣味性。</p><p>（不過這部分我還在想要怎麼寫比較好）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*feV0CjdUmnIik489WIn5jA.png" /></figure><p><strong>二、部分程式碼解說</strong></p><ol><li>為 iOS App 加入客製字型</li></ol><p>黑板上的粉筆字體，我是參考彼得潘的這篇文章：</p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E7%82%BA-ios-app-%E5%8A%A0%E5%85%A5%E5%AE%A2%E8%A3%BD%E5%AD%97%E5%9E%8B-custom-font-d2b28b0269e0">為 iOS App 加入客製字型 (custom font)</a></p><p><strong>2. </strong>讓TextField不會彈跳出鍵盤</p><p>這個方法我也不知道正不正統，不過我用起來目前是沒什麼ＢＵＧ，也許可能有更好的方法。</p><p>在viewDidLoad()中把 TextField.inputView ＝ UIButton()</p><p><strong>3.</strong></p><p>在App一執行便在viewDidLoad()中呼叫func topic() 去產生隨機亂數題目：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b64f1ecc5d2ff11de046de6b9a658e4d/href">https://medium.com/media/b64f1ecc5d2ff11de046de6b9a658e4d/href</a></iframe><p><strong>4.</strong></p><p>給每一個數字button的Tag一個數字，數字1就給1，數字2就給2依此類推～</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*W53nrTC1s-_DSZptkcsu_A.png" /></figure><p>把每一個button的Action指到同一@IBAction func</p><p>然後利用 “ sender.tag ” 去得到目前點擊到的數字</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ou9pMxkLeOsd-9FjCP9lnA.png" /></figure><p><strong>5.</strong> 實現玩家點擊button，textField有數字填入，便自動跳下一個textField</p><p>在button點擊的func中呼叫 “ func switchField ” ，把數字與目前停留的textField傳入。</p><p>在 func switchField 中去做判斷，把number的值給到guessTextField.text，如果 guessTextField.text 不等於空，便呼叫下一個guessTextField： ” guessTextField2.becomeFirstResponder() “</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/933b5d8882ddf97fc166e4b6c0fbc4e9/href">https://medium.com/media/933b5d8882ddf97fc166e4b6c0fbc4e9/href</a></iframe><p>5. 限制textfield只能輸入一個數字</p><p>由於填入數字的textField</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63949d616960c5d5de2832ad13a5b203/href">https://medium.com/media/63949d616960c5d5de2832ad13a5b203/href</a></iframe><p><strong>三、最後附上GitHub</strong></p><p><a href="https://github.com/Wen0926/1A2B">Wen0926/1A2B</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=185c7e8e6441" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/swift-%E4%BD%9C%E5%93%81-%E5%8F%AF%E6%84%9B%E6%9F%B4%E6%9F%B41a2b-%E7%8C%9C%E6%95%B8%E5%AD%97%E9%81%8A%E6%88%B2app-185c7e8e6441">Swift 作品 — 可愛柴柴1A2B — 猜數字遊戲App</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift 作品 — 貓咪倒數・記事App— 練習UserDefaults儲存資料,protocol傳值,UIImagePickerController,tableView]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/swift%E4%BD%9C%E5%93%81-%E8%B2%93%E5%92%AA%E5%80%92%E6%95%B8-%E8%A8%98%E4%BA%8Bapp-%E7%B7%B4%E7%BF%92userdefaults%E5%84%B2%E5%AD%98%E8%B3%87%E6%96%99-protocol%E5%82%B3%E5%80%BC-uiimagepickercontroller-%E9%81%9E%E8%BF%B4-6d0aabba478b?source=rss-751994df6ff1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d0aabba478b</guid>
            <category><![CDATA[tableviews]]></category>
            <category><![CDATA[to-do-list-app]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Jerry Wen]]></dc:creator>
            <pubDate>Thu, 07 Jun 2018 05:08:19 GMT</pubDate>
            <atom:updated>2018-06-09T15:07:48.690Z</atom:updated>
            <content:encoded><![CDATA[<p>這個App應該可以說是把我在彼得潘的課程中學習到的都應用上了，tableView,pickerView,UserDefaults,protocol,UIImagePickerController,AutoLayout等等…我不是程式高手也沒什麼經驗，所以程式寫的有點雜亂，還請多見諒了！</p><p><strong>一、首先來簡單介紹App操作流程</strong></p><p><strong>gif圖</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*MEVgPDYfyNX_cZAuuymhGw.gif" /></figure><p>1.第一次執行App，會看到taleview上已經有一事項。（因為是貓咪記事，所以當然要提醒一下忘東忘西的主人買罐罐！）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*TieNgGtFYXtrcNHFlYTA3A.png" /></figure><p>2.在tableView的事項中往右滑可以進行刪除的動作</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*1cw1dXS-t00tl8-w3_UGYA.png" /></figure><p>3.刪除後，會看到頂置事項出現『傻眼貓咪，忘東忘西』</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*38-Dt-Kl1GD0QVWb40n8eA.png" /></figure><p>4.按右下角的貓咪腳掌，會跳到新增事件的頁面。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*sqYAiB6dU6TJuNQVQmqb3g.png" /></figure><p>5.第一個textField輸入事件。</p><p>第二個textField利用pickerview選擇日期時間。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*-EPjT-UB4c_hLmU4lElr7g.png" /></figure><p>6.點選右上角完成後，跳回主畫面，就可以看到我們剛剛新增的事件了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*qcNXZZYacmvbf0W5jOgHjg.png" /></figure><p>7.最上頭的頂置事項，會優先顯示“時間最短最緊急的事項”。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*3G7B5J808gZCLqcuuiR00Q.png" /></figure><p>8.點擊tableView中的任一事項便可進入完整顯示頁面</p><p>點擊右上角button便可進去編輯事項頁面。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*IbGgRbJ1NRghmirj4cU2TA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*m1LBuSQoxf34aDsavuCMHA.png" /></figure><p>9.修改待辦事項為“跑步”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*GkCDPZJ9ZPCv4RJItMVLBQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*eqHIoEtOkq9KtWBwjH8FBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*X-vfTmaMcdv_5zJPo8Z8Wg.png" /></figure><p>10.若已完成事項，又不想馬上刪除，可方便日後查看自己完成了哪些事項，可以點擊單一事件左邊的方匡，會出現一個貓咪掌印印在方匡上，並且將已完成事項的字劃上橫線。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*KKJIgSQXJNlM_Vc5FBF_Ww.png" /></figure><p>右上方本來顯示0個罐罐，變成顯示1，代表你完成了一個待辦事項。</p><p>（多虧了這個貓咪記事，才沒有讓各位貓奴們忘東忘西，是不是該買個罐罐獎賞一下你家的喵皇呢）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*1mWhhG6L_bAsE3JXNvyepA.png" /></figure><p>11.如果各位喵奴們不喜歡我家的阿胖怎辦？沒關西！點擊右上角的圖片button，就可以將封面更換成你家的貓咪了！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*eeKPOpSr4zcwRTcwkkQQhA.png" /></figure><p>12.最後的最後，如果今天事項很多，一個一個去刪除實在太麻煩費時了！這時左上角的垃圾桶button就派上用場了，給他用力的點擊下去，一次刪除所有完成事項！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*WZWfF1egMa0dLK8v-1QxGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*eIst_E6UUEEaP2miPnHelQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*KiLFQ1s3E3ivSv4Y7PAoTw.png" /></figure><p><strong>二、部分程式碼解說</strong></p><ol><li>宣告UserDefults儲存資料</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ee7fc703265c82be1af859f3e28e8d8/href">https://medium.com/media/7ee7fc703265c82be1af859f3e28e8d8/href</a></iframe><p>2.一鍵刪除已完成事項：</p><p>當使用者按下刪除button時，計算一下tableView有無事項可刪除，沒有事項的話跳出無事項的Alert。有事項可刪除的話跳出詢問是否刪除的Alert。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cuqe4erT_BD-dcXaNAwVyg.png" /></figure><p>按下OK後會執行delete funciton</p><p>這邊本來想說用“for迴圈”去寫出一鍵刪除，但怎麼寫都錯</p><p>後來試試用“遞迴”的寫法總算找到解答，不停地去呼叫func delete 直到每一筆事項都被檢查過</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9IwZd-LJr_ylCsvfWOEK8A.png" /></figure><p>3.利用protocol傳值，去判斷使用者點選哪一個待辦事項的完成方匡</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71e310dc57eac680733275970581c405/href">https://medium.com/media/71e310dc57eac680733275970581c405/href</a></iframe><p><strong>三、最後附上GitHub</strong></p><p><a href="https://github.com/Wen0926/-">Wen0926/-</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d0aabba478b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/swift%E4%BD%9C%E5%93%81-%E8%B2%93%E5%92%AA%E5%80%92%E6%95%B8-%E8%A8%98%E4%BA%8Bapp-%E7%B7%B4%E7%BF%92userdefaults%E5%84%B2%E5%AD%98%E8%B3%87%E6%96%99-protocol%E5%82%B3%E5%80%BC-uiimagepickercontroller-%E9%81%9E%E8%BF%B4-6d0aabba478b">Swift 作品 — 貓咪倒數・記事App— 練習UserDefaults儲存資料,protocol傳值,UIImagePickerController,tableView</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift 作品— 訂飲料App — 練習解析JSON資料 並且上傳— 使用SheetDB]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/swift-%E8%A8%82%E9%A3%B2%E6%96%99app-%E7%B7%B4%E7%BF%92%E8%A7%A3%E6%9E%90json%E8%B3%87%E6%96%99-%E4%BD%BF%E7%94%A8sheetdb-ddc2a1ff5841?source=rss-751994df6ff1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddc2a1ff5841</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[pickerview]]></category>
            <category><![CDATA[pickers]]></category>
            <dc:creator><![CDATA[Jerry Wen]]></dc:creator>
            <pubDate>Tue, 22 May 2018 14:07:27 GMT</pubDate>
            <atom:updated>2018-06-07T05:09:45.532Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/84/1*yZXJ5-A5t3l_DBSdNnu_QA@2x.png" /></figure><p><strong>1.放上GIF檔案 先來看看整體訂購流程</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*0Fxmcvf7J_E41VM_SipRHg.gif" /></figure><p><strong>讀取txt檔</strong></p><p>1.將txt檔拖曳到project底下</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*o-ZX7OOzP31XpQcuEN5M3Q.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e224212375111db07ad0700e1f98f30/href">https://medium.com/media/2e224212375111db07ad0700e1f98f30/href</a></iframe><p><strong>在viewDidLoad()中加入以下程式碼實現：</strong></p><p>1.讓選飲料的textField為picker選項</p><p>2.並且讓使用者無法更改價錢</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0e726401f261832415b90212bd70ed3/href">https://medium.com/media/f0e726401f261832415b90212bd70ed3/href</a></iframe><p><strong>建立pickerView</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be9caf784ebd5c04d7e3c8e9b4a1d0a4/href">https://medium.com/media/be9caf784ebd5c04d7e3c8e9b4a1d0a4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*s_cKKO3nRQ4CIl2BiXXpLw.png" /></figure><p><strong>將資料傳送到SheetDB</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ffd46f41422f096d494a345eb667a51/href">https://medium.com/media/7ffd46f41422f096d494a345eb667a51/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*tOAuG1I952_KBKbIIDVT9w.png" /></figure><p><a href="https://github.com/Wen0926/Drink">Wen0926/Drink</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddc2a1ff5841" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/swift-%E8%A8%82%E9%A3%B2%E6%96%99app-%E7%B7%B4%E7%BF%92%E8%A7%A3%E6%9E%90json%E8%B3%87%E6%96%99-%E4%BD%BF%E7%94%A8sheetdb-ddc2a1ff5841">Swift 作品— 訂飲料App — 練習解析JSON資料 並且上傳— 使用SheetDB</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift 小教學 — 將Navigation bar 變透明的方法]]></title>
            <link>https://medium.com/@chiehwen0926/swift-%E5%B0%87navigation-bar-%E8%AE%8A%E9%80%8F%E6%98%8E%E7%9A%84%E6%96%B9%E6%B3%95-5d7e77dc98e8?source=rss-751994df6ff1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d7e77dc98e8</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[transparency]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Jerry Wen]]></dc:creator>
            <pubDate>Fri, 18 May 2018 08:25:20 GMT</pubDate>
            <atom:updated>2018-06-09T14:56:11.753Z</atom:updated>
            <content:encoded><![CDATA[<p>當我們在設計APP時</p><p>有時需要將Navigation bar 設定成透明</p><p>讓整體ＵＩ設計與背景更具一致性</p><p>那要如何將Navigation bar變成透明呢？</p><p><strong>教學：</strong></p><p>要將Navigation bar變成透明其實非常簡單</p><p>只需要透過簡單的三行程式</p><p>在 func viewDidLoad() 中加入以下程式碼便可實現</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba0386096c5799886b01c590d817778f/href">https://medium.com/media/ba0386096c5799886b01c590d817778f/href</a></iframe><p><strong>成果：</strong></p><p>加入前：</p><p>我們可以看到上方的Navigation bar是呈現預設得透明白色</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*6c1fvMymgfwMvo26aElu7g.gif" /></figure><p>加入後：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*sbXs-Nj1sa1xhy8SQUyDSQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d7e77dc98e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>