<?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 PamornT on Medium]]></title>
        <description><![CDATA[Stories by PamornT on Medium]]></description>
        <link>https://medium.com/@pamornt?source=rss-655fb7ee2ef3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*lahgaVuX6OH2F3lvnZfIAw.jpeg</url>
            <title>Stories by PamornT on Medium</title>
            <link>https://medium.com/@pamornt?source=rss-655fb7ee2ef3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 02:06:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pamornt/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 Chatbot และ AI Agent สำหรับองค์กรด้วย Google ADK #3— เชื่อมต่อ LINE Chatbot กับ Agent…]]></title>
            <link>https://medium.com/linedevth/line-chatbot-with-google-adk-connect-with-line-ba8fa9bdab52?source=rss-655fb7ee2ef3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba8fa9bdab52</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[google-adk]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[linedevth]]></category>
            <category><![CDATA[line-bot]]></category>
            <dc:creator><![CDATA[PamornT]]></dc:creator>
            <pubDate>Mon, 02 Feb 2026 02:31:01 GMT</pubDate>
            <atom:updated>2026-02-02T02:43:35.264Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MmsUBV6D1juWDLL7qNwULw.png" /></figure><h3>สร้าง LINE Chatbot และ AI Agent สำหรับองค์กรด้วย Google ADK #3— เชื่อมต่อ LINE Chatbot กับ Agent Google ADK</h3><p>สำหรับบทความนี้เกิดจากการลองออกแบบและคิดระบบ <strong>LINE Chatbot สำหรับองค์กร </strong>โดยใช้แนวคิดของ <strong>AI Agent</strong> และ <strong>Google Agent Development Kit (ADK) </strong>เพื่อสร้างระบบที่ <strong>มีโครงสร้าง, มีขอบเขต และนำไปใช้จริงได้ในระดับองค์กร</strong></p><h3>เตรียมความพร้อม</h3><p>บทความนี้มีทั้งหมด 3 ตอน ด้วยกัน ตอนที่ท่านกำลังอ่านอยู่จะเป็นตอนสุดท้ายที่จะทำการเชื่อมต่อ LINE Chatbot เข้ากับ Agent ที่สร้างบน Google ADK</p><p>ถ้าท่านยังไม่ได้อ่านตอนที่ 1 และยังมีคำถามเหล่านี้</p><ul><li>Agent คืออะไร?</li><li>Agent แตกต่างจาก Chatbot อย่างไร?</li><li>Google ADK คืออะไร?</li></ul><p>ผมแนะนำให้เข้าไปอ่านที่บทความตอนแรกได้ที่ลิงก์ด้านล่างนี้ได้เลยครับ</p><p><a href="https://medium.com/linedevth/line-chatbot-with-google-adk-concept-5c3b884ba057">สร้าง LINE Chatbot และ AI Agent สำหรับองค์กรด้วย Google ADK #1 — แนวคิดและโครงสร้าง Google ADK</a></p><p>หรือ ถ้าท่านยังไม่ได้สร้าง Agent บน Google ADK ผมแนะนำให้ไปสร้างก่อนจากบทความนี้ได้เลยครับ</p><p><a href="https://medium.com/linedevth/line-chatbot-with-google-adk-workshop-527f69dad16a">สร้าง LINE Chatbot และ AI Agent สำหรับองค์กรด้วย Google ADK #2 — เริ่มสร้าง LINE Chatbot + Google…</a></p><p>เอาละ ถ้าพร้อมแล้ว ก็มาเริ่มลงมือทำกันได้เลยย 😆</p><h3>เริ่มเชื่อมต่อ LINE Chatbot กับ Google ADK</h3><h3>สร้าง LINE Webhook</h3><p>จาก Project เดิมที่เราสร้างไว้ตั้งแต่บทความตอนที่ 2 เราจะสร้าง LINE Webhook ภายใต้ Project นี้ ขั้นตอนแรกเราต้อง Install dependency ที่จำเป็นต้องใช้ก่อนครับ</p><h4>Install dependency ที่จำเป็น</h4><pre>pip install flask uvicorn line-bot-sdk python-dotenv</pre><h4>สร้างไฟล์ Webhook</h4><p>สร้างไฟล์ line_webhook.py ที่ root project folder โครงสร้างไฟล์จะเป็นแบบนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C7oz1iS3SJnP7X1gixzCuw.png" /></figure><p>แก้ไขไฟล์ line_webhook.py ตาม code ด้านล่างนี้ <br>โดยในไฟล์ webhook ตัวอย่างนี้จะ handle แค่ข้อความประเภท text เท่านั้น</p><pre>import asyncio<br>import base64<br>import os<br>from dotenv import load_dotenv<br>from flask import Flask, request, abort<br>from linebot.v3 import WebhookHandler<br>from linebot.v3.exceptions import InvalidSignatureError<br>from linebot.v3.messaging import (<br>    Configuration,<br>    ApiClient,<br>    MessagingApi,<br>    MessagingApiBlob,<br>    ReplyMessageRequest,<br>    TextMessage<br>)<br>from linebot.v3.webhooks import (<br>    MessageEvent,<br>    TextMessageContent,<br>    ImageMessageContent<br>)<br># 🔥 base_agent (entry point ของ agent ทั้งระบบ)<br>from my_agent.agent import get_agent_response</pre><pre>load_dotenv()</pre><pre>app = Flask(__name__)</pre><pre>CHANNEL_ACCESS_TOKEN = os.getenv(&#39;CHANNEL_ACCESS_TOKEN&#39;)<br>CHANNEL_SECRET = os.getenv(&#39;CHANNEL_SECRET&#39;)</pre><pre>if not CHANNEL_ACCESS_TOKEN or not CHANNEL_SECRET:<br>    raise ValueError(&quot;CHANNEL_ACCESS_TOKEN and CHANNEL_SECRET must be set in .env file&quot;)</pre><pre>configuration = Configuration(access_token=CHANNEL_ACCESS_TOKEN)<br>handler = WebhookHandler(CHANNEL_SECRET)</pre><pre>api_client = ApiClient(configuration)<br>messaging_api = MessagingApi(api_client)</pre><pre>@app.route(&quot;/&quot;, methods=[&#39;GET&#39;])<br>def root():<br>    return {&quot;status&quot;: &quot;ok&quot;, &quot;message&quot;: &quot;LINE Bot with ADK is running&quot;}</pre><pre>@app.route(&quot;/webhook&quot;, methods=[&#39;POST&#39;])<br>def webhook():<br>    signature = request.headers.get(&#39;X-Line-Signature&#39;, &#39;&#39;)<br>    <br>    if not signature:<br>        abort(400, description=&quot;Missing X-Line-Signature header&quot;)<br>    <br>    body = request.get_data(as_text=True)<br>    try:<br>        handler.handle(body, signature)<br>    except InvalidSignatureError:<br>        abort(400)<br>    except Exception as e:<br>        app.logger.error(f&quot;Error handling webhook: {e}&quot;)<br>        abort(500)<br>    <br>    return &#39;OK&#39;</pre><pre>@handler.add(MessageEvent, message=TextMessageContent)<br>def handle_text_message(event):<br>    line_user_id = event.source.user_id<br>    user_message = event.message.text<br>    try:<br>        reply_text = get_agent_response(<br>            user_message=user_message, <br>            user_id=line_user_id<br>        )<br>    except Exception as e:<br>        print(f&quot;Error: {e}&quot;)<br>        reply_text = &quot;เกิดข้อผิดพลาดในการประมวลผลครับ&quot;</pre><pre>messaging_api.reply_message(<br>        ReplyMessageRequest(<br>            reply_token=event.reply_token,<br>            messages=[TextMessage(text=reply_text)]<br>        )<br>    )</pre><pre>if __name__ == &quot;__main__&quot;:<br>    app.run(host=&quot;0.0.0.0&quot;, port=8000, debug=True)</pre><p>เสร็จแล้วทำการกำหนดค่า config ต่างๆ ของ LINE ด้วยคำสั่งนี้ครับ</p><pre>export CHANNEL_SECRET=&quot;YOUR_CHANNEL_SECRET&quot;<br>export CHANNEL_ACCESS_TOKEN=&quot;YOUR_ACCESS_TOKEN&quot;</pre><p>ให้เราตรวจสอบในไฟล์ .env ต้องมีกำหนดค่าครบตามนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JElBfTLDyYg5JP8ZWwb_hA.png" /></figure><p>จากนั้นแก้ไข code ในไฟล์ agent.py ตามด้านล่างนี้ครับ</p><pre>import asyncio<br>from google.adk.agents import Agent<br>from agents.hr_agent import hr_agent<br>from agents.operation_agent import operation_agent<br>from google.adk.runners import Runner<br>from google.adk.sessions import InMemorySessionService<br>from google.genai.types import Content, Part<br>from dotenv import load_dotenv<br>load_dotenv()</pre><pre>APP_NAME = &quot;memory_example_app&quot;</pre><pre>session_service = InMemorySessionService()</pre><pre># Create parent agent and assign children via sub_agents<br>root_agent = Agent(<br>    name=&quot;Base_Agent&quot;,<br>    model=&quot;gemini-2.0-flash&quot;,<br>    description=&quot;I coordinate greetings and tasks.&quot;,<br>    sub_agents=[ # Assign sub_agents here<br>        hr_agent, operation_agent<br>    ]<br>)</pre><pre>runner = Runner(<br>    agent=root_agent,<br>    app_name=APP_NAME,<br>    session_service=session_service,<br>)</pre><pre>user_sessions = {}</pre><pre>def get_agent_response(user_message=None, user_id=None):<br>    if user_id not in user_sessions:<br>        session = asyncio.run(session_service.create_session(app_name=APP_NAME, user_id=user_id))<br>        user_sessions[user_id] = session.id<br>    <br>    session_id = user_sessions[user_id]<br>    <br>    parts = [Part(text=user_message)] if user_message else []<br>    content = Content(role=&quot;user&quot;, parts=parts)<br>    events = runner.run(user_id=user_id, session_id=session_id, new_message=content)<br>    <br>    for event in events:<br>        if event.is_final_response():<br>            return event.content.parts[0].text<br>    <br>    return &quot;ขออภัย ระบบขัดข้อง&quot;</pre><p>หลักๆ การแก้ไข agent.py คือการเพิ่มเติม 2 สิ่งดังนี้</p><ul><li>เพิ่ม runner ที่ทำหน้าที่เหมือน Execution Engine ของระบบ Agent ครับ คือเป็นตัว เรียก run ตัว agent นั่นเอง</li><li>เพิ่ม functions get_agent_response ที่ทำหน้าที่ จัดการ session และ เรียก runner ทำงาน</li></ul><p>หลังจากนั้นให้เราทดสอบ run ตัว Webhook ด้วยคำสั่งนี้ครับ</p><pre>python line_webhook.py</pre><p>เมื่อ run เสร็จแล้วตอนนี้เราจะสามารถเรียกใช้ webhook บน local ได้แล้วผ่าน localhost port 8000</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vPbQUH7HVNP8_6CxtrXXUg.png" /></figure><p>แต่การจะใช้งานบน LINE เราต้องทำให้คนภายนอกเข้าใช้งานได้ด้วยโดยการเปิด Tunnel ทำได้หลากหลายวิธีครับ ในที่นี้ผมเปิด Tunnel ผ่าน VSCode โดยให้คลิกเลือกที่ Port ตรงส่วน Terminal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XKMHt-UHNPEH-zqymUy4dg.png" /></figure><p>คลิก Forward a Port แล้วกำหนด port เท่ากับ 8000 แล้ว enter จะเป็นการสร้าง forward port หน้าตาแบบนี้ครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x22u3rfPua0x8u45oMdZXA.png" /></figure><p>จากนั้นให้เราสังเกตุตรง Visibility จะเป็น Private อยู่ บุคคลภายนอกเข้าใช้งานไม่ได้ ตรงนี้เราต้องเปลี่ยนเป็น Public โดยการ Click ขวา เลือก Port Visiblility แล้วเปลี่ยนเป็น Public</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PjgMPwUru1_oZrvP2MhWvw.png" /></figure><h3>ติดตั้ง LINE Webhook</h3><p>เสร็จเรียบร้อยตอนนี้ Webhook เราพร้อมใช้งานแล้ว ถัดไปให้เรา Copy link ที่ได้ จากการเปิด Forward port ไปตั้งค่า Webhook URL ที่ LINE Developer Console ตามขั้นตอนนี้</p><ul><li>ไปที่ <a href="https://developers.line.biz/">LINE Developer Console</a></li><li>เข้าไปที่ Channel Messaging API ที่ต้องการ</li><li>เข้าไปที่ Tab Messaging API</li><li>แล้วนำ URL ที่ copy ไว้ paste ที่ช่อง Webhook URL โดยให้เติม /webhook ต่อท้าย link ด้วย</li><li>คลิกเปิด Use webhook</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-ZJ5FX-2wkJThCTiVCosA.png" /></figure><p>เท่านี้ก็พร้อมใช้งานแล้ว โดยการทำงานจะเป็นเหมือนรูปด้านล่างเลยค้าบ ถัดไปเราจะไปทดสอบกันครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fzSvlw0Fg7kVyXAOkB_Few.png" /></figure><h3>ทดสอบใช้งาน</h3><p>ผมลองทดสอบใช้งาน จะเห็นว่าตัว Agent สามารถตอบคำถามได้ ไม่ว่าจะเป็นคำถามเกี่ยวกับ Operation หรือ เกี่ยวกับงาน HR Policy ถือว่าทำงานได้สมบูรณ์เลยครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QePPnSvroVQGi-VR8xmeOw.png" /></figure><h3>บทส่งท้าย</h3><p>หวังว่าบทความนี้จะช่วยให้ทุกคนเห็นภาพการนำ <strong>Google ADK</strong> มาออกแบบระบบ <strong>Multi-Agent</strong> ได้ชัดเจนขึ้น ตั้งแต่การแยกบทบาทของ Agent แต่ละตัว การใช้ Tool และ Data ร่วมกัน ไปจนถึงการมี <strong>Router / Orchestrator Agent</strong> คอยจัดการ intent และกระจายงานอย่างเป็นระบบ</p><p>สิ่งที่ผมได้เรียนรู้จากการลงมือทำจริงคือ</p><blockquote><em>Multi-Agent ไม่ได้ทำให้ระบบซับซ้อนขึ้น แต่ช่วย “จัดระเบียบความซับซ้อน” ให้คิดง่าย ดูแลง่าย และต่อยอดได้ไกลกว่าเดิม</em></blockquote><p>ไม่ว่าคุณจะเริ่มจาก HR Agent ตัวเล็ก ๆ หรือกำลังวางระบบองค์กรที่มีหลายฝ่าย การออกแบบให้ Agent ทำหน้าที่ชัดเจนตั้งแต่แรก จะช่วยให้ระบบโตได้อย่างมั่นคงในระยะยาว</p><p>หวังว่าประสบการณ์และตัวอย่างในบทความนี้จะเป็นประโยชน์กับทุกคนไม่มากก็น้อย<br> ถ้ามีไอเดีย คำถาม หรืออยากแลกเปลี่ยน use case เพิ่มเติม สามารถคุยกันต่อได้เลยครับ 😁</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba8fa9bdab52" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linedevth/line-chatbot-with-google-adk-connect-with-line-ba8fa9bdab52">สร้าง LINE Chatbot และ AI Agent สำหรับองค์กรด้วย Google ADK #3— เชื่อมต่อ LINE Chatbot กับ Agent…</a> was originally published in <a href="https://medium.com/linedevth">LINE Developers Thailand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[สร้าง LINE Chatbot และ AI Agent สำหรับองค์กรด้วย Google ADK #2 — เริ่มสร้าง LINE Chatbot + Google…]]></title>
            <link>https://medium.com/linedevth/line-chatbot-with-google-adk-workshop-527f69dad16a?source=rss-655fb7ee2ef3------2</link>
            <guid isPermaLink="false">https://medium.com/p/527f69dad16a</guid>
            <category><![CDATA[linedevth]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[line-chatbot]]></category>
            <category><![CDATA[google-adk]]></category>
            <category><![CDATA[chatbots]]></category>
            <dc:creator><![CDATA[PamornT]]></dc:creator>
            <pubDate>Thu, 29 Jan 2026 07:07:42 GMT</pubDate>
            <atom:updated>2026-02-02T02:41:14.771Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T2fHoessBNUwX9xUXp4zZg.png" /></figure><h3>สร้าง LINE Chatbot และ AI Agent สำหรับองค์กรด้วย Google ADK #2 — เริ่มสร้าง Google ADK Multi-Agent</h3><p>สำหรับบทความนี้เกิดจากการลองออกแบบและคิดระบบ <strong>LINE Chatbot สำหรับองค์กร </strong>โดยใช้แนวคิดของ <strong>AI Agent</strong> และ <strong>Google Agent Development Kit (ADK) </strong>เพื่อสร้างระบบที่ <strong>มีโครงสร้าง, มีขอบเขต และนำไปใช้จริงได้ในระดับองค์กร</strong></p><p>ถ้าใครยังมีคำถามเหล่านี้</p><ul><li>Agent คืออะไร?</li><li>Agent แตกต่างจาก Chatbot อย่างไร?</li><li>Google ADK คืออะไร?</li></ul><p>ผมแนะนำให้เข้าไปอ่านที่บทความตอนแรกได้ที่ลิงก์ด้านล่างนี้ได้เลยครับ ส่วนใครที่เข้าใจแล้ว ก็มาเริ่มลงมือทำกันได้เลยย 😆</p><p><a href="https://medium.com/linedevth/line-chatbot-with-google-adk-concept-5c3b884ba057">สร้าง LINE Chatbot และ AI Agent สำหรับองค์กรด้วย Google ADK #1 — แนวคิดและโครงสร้าง Google ADK</a></p><h3>เริ่มสร้าง LINE Chatbot — Google ADK</h3><h4>ติดตั้ง Google AdK และเริ่มสร้าง Project</h4><p>เราจะทำการเริ่มสร้าง Project จากศูนย์กันเลย ก่อนอื่นเราต้องติดตั้ง google-adk ก่อนตามคำสั่งด้านล่างนี้</p><pre>python -m venv venv<br>source venv/bin/activate</pre><pre>pip install google-adk</pre><p>จากนั้นเราจะเริ่มสร้าง Project ด้วยคำสั่งด้านล่างนี้</p><pre>adk create my_agent</pre><p>เลือก model <em>“gemini-2.5-flash” </em>โดยการกรอกเลข 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ECN5M0womKdmFLFZbUS3GA.png" /></figure><p>เลือก model <em>“Google AI” </em>โดยการกรอกเลข 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z2Ifpyks5UPsvuLryfqRug.png" /></figure><p>ถัดไปเราต้องใช้ Google API Key ถ้าใครยังไม่มีให้ทำตามขั้นถัดไปได้เลยครับ</p><h3>Get Google API key</h3><ul><li>เข้าไปที่ <a href="https://aistudio.google.com/">Google AI Studio</a></li><li>คลิกที่เมนู Get API key</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NNFEJ_myvM7mDdVfUAKMLw.png" /></figure><ul><li>คลิกที่ปุ่ม Create API Key จะเจอ Dialog Create a new key</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BaS2dWc7sU8Ya_N8VrKS_w.png" /></figure><ul><li>กรอกชื่อ Key และ เลือก Project ที่ต้องการ แล้วกดปุ่ม Create key ได้เลย</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y0ICacAWGW-rWiQ0eRQCcQ.png" /></figure><ul><li>สร้าง API Key เสร็จแล้ว ให้คลิกที่ Key เพื่อเปิด Dialog API key details</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ji08VT4BcAisnlIsQQF08A.png" /></figure><ul><li>คลิกตรงไอคอนด้านหลังเพื่อ Copy ได้เลย</li></ul><p>เอา API Key ที่ Copy มาวางที่ Terminal ต่อก็จะเสร็จกระบวนการสร้าง Project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQvxMpAvBOaMU-ifIWF7gw.png" /></figure><h3>ทดสอบลอง Run</h3><p>ให้ลองทดสอบ Run ADKโดยใช้คำสั่งตามด้านล่างนี้ใน Terminal ครับ ซึ่งเป็นคำสั่ง คือให้ <strong>Google ADK เปิด Web Server สำหรับพัฒนา (Development Web UI)</strong><br>เพื่อให้เราสามารถ <strong>ทดสอบและดูการทำงานของ Agent แบบ Interactive ผ่าน Browser ได้</strong></p><pre>adk web --port 8000</pre><p>ถ้า run สำเร็จตรง Terminal จะขึ้นแบบนี้ครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SiEo7x2j8tHNsRB222IGBA.png" /></figure><p>ให้ทดลองเปิด chat interface ด้วย url <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000</a> ดูครับ จะเจอหน้าตาแบบในรูปภาพครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*24L5dTohzmkQVmV7U2X6OA.png" /></figure><p>ลองทดสอบ chat คุยกับ Agent ดูครับ จะพบว่า Agent ยังตอบคำถามทั่วๆ ไปอยู่เพราะเรายังไม่ได้กำหนด role และ ขอบเขต การทำงานของ agent</p><p>ต่อไปเราจะเริ่มสร้าง Tool ที่เป็นเครื่องมือให้ Agent เรียกใช้ครับ</p><h3>เริ่มต้นสร้าง Tool ให้ Agent</h3><p>เราจะเริ่มทดลองสร้าง Tool สำหรับให้ Agent เรียกใช้งานกันครับ โดยเราจะทดสอบโดยใช้รายละเอียดตามนี้ครับ</p><ul><li>Agent : เป็น HR Agent</li><li>Tool : เป็น Tool สำหรับดึงข้อมูล Policy ของบริษัท</li></ul><h4>เตรียมไฟล์ Policy เพื่อเก็บข้อมูล Policy</h4><p>สร้าง folder ใหม่ชื่อว่า data และสร้างไฟล์ใหม่ชื่อ policy.md</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7W21ZGU2B851MDyqTC4uQ.png" /></figure><p>ใส่ข้อมูลในไฟล์ policy.md โดยเป็นข้อมูล policy ของบริษัท</p><pre># นโยบายลางาน</pre><pre>- ลาป่วย: ไม่เกิน 30 วัน/ปี<br>- ลากิจ: ไม่เกิน 6 วัน/ปี<br>- ลาพักร้อน: ตามอายุงาน</pre><h4>สร้าง Policy Tool</h4><p>สร้าง folder ใหม่ชื่อว่า tools และสร้างไฟล์ใหม่ชื่อ policy_tool.py</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bnWixJn4dn51gu1_zZm-yw.png" /></figure><p>นำโค้ดด้านล่าง ใส่ในไฟล์ policy_tool.py โดยการทำงานของโค้ดชุดนี้คือการอ่านข้อมูลจากไฟล์ data/policy.md เพื่อใช้ในการตอบ user</p><pre>from google.adk.tools import FunctionTool</pre><pre>def load_policy() -&gt; str:<br>    &quot;&quot;&quot;<br>    อ่านไฟล์ policy ขององค์กร<br>    &quot;&quot;&quot;<br>    with open(&quot;data/policy.md&quot;, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>        return f.read()</pre><pre>policy_tool = FunctionTool(func=load_policy)</pre><h4>แก้ไข Agent เรียกใช้ Policy Tool</h4><p>แก้ไขไฟล์ my_agent/agent.py ตามโค้ดด้านล่างเพื่อเปลี่ยน Agent ให้เป็น HR Agent และเรียกใช้ Policy Tool</p><pre>from google.adk.agents import Agent<br>from tools.policy_tool import policy_tool<br></pre><pre>root_agent = Agent(<br>    name=&quot;hr_policy_agent&quot;,<br>    model=&quot;gemini-2.0-flash&quot;,<br>    description=&quot;ตอบคำถามเกี่ยวกับนโยบายและสวัสดิการพนักงาน&quot;,<br>    instruction=&quot;&quot;&quot;<br>คุณคือ AI Agent ฝ่ายบุคคล<br>ให้ตอบคำถามจากนโยบายบริษัทเท่านั้น<br>ห้ามเดา<br>&quot;&quot;&quot;,<br>    tools=[policy_tool]<br>)</pre><p>ลองทดสอบ Run Adk ดูใหม่ แล้วลองทดสอบ chat กับ Agent ดูครับจะพบว่า Agent เริ่มรู้ Role ของตนเอง และสามารถเรียกใช้ Tool ที่เราสร้างได้แล้ว</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pG--ahjCQ-973IfNbr1FYw.png" /></figure><p>สังเกตุดูตรงช่อง chat ตอนที่เราถามเกี่ยวกับนโยบายของบริษัท (ในที่นี้คือวันลาป่วย) Agent จะทำการเรียกใช้ Tool ชื่อ load_policy เพื่อดึงลาป่วยเลย</p><p>ถ้าลองคลิกที่ tab Events ที่กล่องด้านซ้าย จะเห็นว่ามีการ call load_policy ถ้าคลิกดูจะเห็นรายละเอียดต่างๆ ในการ call load_policy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*woTVBXufgxjSCmO26s8YcQ.png" /></figure><p>การทำงานตอนนี้ก็จะเป็นเหมือนในรูปนี้ด้านล่าง คือ มี HR Agent และมี Tool 1 ตัวสำหรับดึงข้อมูล policy ของบริษัท</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ldi6mLGpdACmy-Y_t5VzLg.png" /></figure><p>ถัดไปเราจะทดลองสร้าง Tool หลายๆ ตัวให้ Agent เนื่องจากตอนทำงานจริงข้อมูลที่ต้องใช้ในการตอบคำถาม จะใช้ข้อมูลหลากหลายประเภท</p><h3>ทดลองเรียกใช้ Multi Tool</h3><p>เราจะเพิ่ม Tool ให้ HR โดย Tool ที่เพิ่มใหม่ คือ attendance_tool สำหรับตอบคำถามเรื่อง <strong>การเข้า–ออกงาน / มาสาย / ลา / สรุปผล</strong></p><h4>เพิ่มข้อมูล employee</h4><p>สร้างไฟล์ data/employees.md แล้ว copy ข้อมูลด้านล่างไปใส่ ซึ่งเป็นข้อมูลของพนักงาน ประกอบไปด้วย รหัสพนักงาน ชื่อ ตำแหน่ง และ แผนก</p><pre># Employee Master Data</pre><pre>## 👥 Employee List</pre><pre>| Employee ID | Name            | Position            | Department        |<br>|------------|-----------------|---------------------|-------------------|<br>| EMP001     | สมชาย ใจดี        | Sales               | Sales             |<br>| EMP002     | สมหญิง พราวใจ     | Accounting          | Finance           |<br>| EMP003     | อนุชา มั่นคง       | Engineer            | Engineering       |<br>| EMP004     | ปวีณา แสงทอง      | HR                  | Human Resource    |<br>| EMP005     | กิตติพงศ์ รุ่งเรือง | Customer Support    | Support           |<br>| EMP006     | วราภรณ์ สุขใจ      | Marketing           | Marketing         |<br>| EMP007     | ณัฐวุฒิ ศรีสุข     | Engineer            | Engineering       |<br>| EMP008     | ชลธิชา นิ่มนวล     | Admin               | Administration   |<br>| EMP009     | ภาคิน นพคุณ       | Operations          | Operations        |<br>| EMP010     | ศิริพร อรุณรุ่ง    | Customer Support    | Support           |</pre><pre>## 📌 Notes<br>- ใช้เป็น master data สำหรับอ้างอิงชื่อ ตำแหน่ง และแผนก<br>- Employee ID ใช้เป็น key เชื่อมกับ attendance data</pre><h4>เพิ่มข้อมูล attendance</h4><p>สร้างไฟล์ data/attendance.md แล้ว copy ข้อมูลด้านล่างไปใส่ ซึ่งเป็นข้อมูลประวัติการเข้าออกงานของพนักงาน โดยมีระบุวันที่ รหัสพนักงาน เวลาเข้า เวลาออก และหมายเหตุ</p><pre># Employee Attendance Records</pre><pre>ช่วงเวลา: 6–10 มกราคม 2025  <br>เวลาทำงานปกติ: 09:00 – 18:00  <br>รูปแบบวันที่: YYYY-MM-DD</pre><pre>---</pre><pre>## 🕒 Attendance Log</pre><pre>| Date       | Employee ID | Check-in | Check-out | Remark |<br>|------------|-------------|----------|-----------|--------|<br>| 2025-01-06 | EMP001 | 08:55 | 18:02 | On time |<br>| 2025-01-06 | EMP002 | 09:10 | 18:00 | Late |<br>| 2025-01-06 | EMP003 | 09:00 | 18:10 | On time |<br>| 2025-01-06 | EMP004 | 08:50 | 17:55 | On time |<br>| 2025-01-06 | EMP005 | 09:05 | 18:00 | Late |<br>| 2025-01-06 | EMP006 | 09:00 | 18:00 | On time |<br>| 2025-01-06 | EMP007 | 09:20 | 18:05 | Late |<br>| 2025-01-06 | EMP008 | 08:58 | 18:00 | On time |<br>| 2025-01-06 | EMP009 | 09:00 | 18:00 | On time |<br>| 2025-01-06 | EMP010 | 09:15 | 18:00 | Late |<br>| 2025-01-07 | EMP001 | 09:00 | 18:00 | On time |<br>| 2025-01-07 | EMP002 | 08:55 | 18:05 | On time |<br>| 2025-01-07 | EMP003 | 09:05 | 18:00 | Late |<br>| 2025-01-07 | EMP004 | 09:00 | 18:00 | On time |<br>| 2025-01-07 | EMP005 | 09:00 | 17:45 | Leave early |<br>| 2025-01-07 | EMP006 | 09:10 | 18:00 | Late |<br>| 2025-01-07 | EMP007 | 09:00 | 18:00 | On time |<br>| 2025-01-07 | EMP008 | 08:50 | 18:00 | On time |<br>| 2025-01-07 | EMP009 | 09:05 | 18:00 | Late |<br>| 2025-01-07 | EMP010 | 09:00 | 18:10 | On time |<br>| 2025-01-08 | EMP001 | 09:05 | 18:00 | Late |<br>| 2025-01-08 | EMP002 | 09:00 | 18:00 | On time |<br>| 2025-01-08 | EMP003 | 08:50 | 18:00 | On time |<br>| 2025-01-08 | EMP004 | 09:00 | 18:00 | On time |<br>| 2025-01-08 | EMP005 | - | - | Sick leave |<br>| 2025-01-08 | EMP006 | 09:00 | 18:00 | On time |<br>| 2025-01-08 | EMP007 | 09:10 | 18:05 | Late |<br>| 2025-01-08 | EMP008 | 09:00 | 18:00 | On time |<br>| 2025-01-08 | EMP009 | 08:55 | 18:00 | On time |<br>| 2025-01-08 | EMP010 | 09:00 | 18:00 | On time |<br>| 2025-01-09 | EMP001 | 09:00 | 18:00 | On time |<br>| 2025-01-09 | EMP002 | 09:20 | 18:00 | Late |<br>| 2025-01-09 | EMP003 | 09:00 | 18:00 | On time |<br>| 2025-01-09 | EMP004 | 08:55 | 18:00 | On time |<br>| 2025-01-09 | EMP005 | 09:00 | 18:00 | On time |<br>| 2025-01-09 | EMP006 | 09:00 | 17:50 | Leave early |<br>| 2025-01-09 | EMP007 | 09:00 | 18:00 | On time |<br>| 2025-01-09 | EMP008 | 09:05 | 18:00 | Late |<br>| 2025-01-09 | EMP009 | 09:00 | 18:10 | On time |<br>| 2025-01-09 | EMP010 | 09:00 | 18:00 | On time |<br>| 2025-01-10 | EMP001 | 08:50 | 17:30 | Leave early |<br>| 2025-01-10 | EMP002 | 09:00 | 17:45 | Leave early |<br>| 2025-01-10 | EMP003 | 09:00 | 18:00 | On time |<br>| 2025-01-10 | EMP004 | 09:05 | 18:00 | Late |<br>| 2025-01-10 | EMP005 | 09:00 | 18:00 | On time |<br>| 2025-01-10 | EMP006 | 09:00 | 18:00 | On time |<br>| 2025-01-10 | EMP007 | 09:10 | 18:00 | Late |<br>| 2025-01-10 | EMP008 | 08:55 | 18:00 | On time |<br>| 2025-01-10 | EMP009 | 09:00 | 18:00 | On time |<br>| 2025-01-10 | EMP010 | 09:00 | 18:00 | On time |</pre><pre>---</pre><pre>## 📌 Notes<br>- Late = Check-in หลัง 09:00  <br>- Leave early = Check-out ก่อน 18:00  <br>- Sick leave = ไม่มี Check-in / Check-out  <br>- โครงสร้างนี้เหมาะกับการ filter ด้วย Date + Employee ID มากที่สุด</pre><h4>สร้าง attendance_tool</h4><p>สร้างไฟล์ใหม่ภายใน folder tools ชื่อ attendance_tool.py และนำโค้ดด้านล่างไปใช้ โดยการทำงานของโค้ดชุดนี้คือการอ่านข้อมูลจากไฟล์ data/attendance.md และทำการสรุปการ เข้า-ออก งานของพนักงาน โดยรับ query-type หรือหัวข้อข้อมูลตามรายการนี้</p><ul><li>daily_record สำหรับ ดูการ เข้า-ออก งานรายวัน</li><li>late_count สำหรับ นับจำนวนครั้งที่มาสาย</li><li>leave_count สำหรับ นับจำนวนครั้งที่ลา</li><li>leave_by_date สำหรับ หาพนักงานที่ลาในวันนั้นๆ</li><li>late_by_date สำหรับ หาพนกังานที่มาสายในวันนั้นๆ</li></ul><pre>from google.adk.tools import FunctionTool<br>from typing import Optional<br>import re<br>from pathlib import Path<br></pre><pre>DATA_DIR = Path(__file__).parent / &quot;../data&quot;<br>ATTENDANCE_FILE = DATA_DIR / &quot;attendance.md&quot;</pre><pre>def load_rows():<br>    &quot;&quot;&quot;<br>    โหลด attendance.md แล้ว parse เป็น list ของ dict<br>    &quot;&quot;&quot;<br>    text = ATTENDANCE_FILE.read_text(encoding=&quot;utf-8&quot;)</pre><pre>    rows = []<br>    for line in text.splitlines():<br>        if not line.startswith(&quot;| 2025&quot;):<br>            continue</pre><pre>        cols = [c.strip() for c in line.strip(&quot;|&quot;).split(&quot;|&quot;)]<br>        if len(cols) != 5:<br>            continue</pre><pre>        rows.append({<br>            &quot;date&quot;: cols[0],<br>            &quot;employee_id&quot;: cols[1],<br>            &quot;check_in&quot;: cols[2],<br>            &quot;check_out&quot;: cols[3],<br>            &quot;remark&quot;: cols[4],<br>        })</pre><pre>    return rows</pre><pre>def attendance_tool(<br>    query_type: str,<br>    employee_id: Optional[str] = None,<br>    date: Optional[str] = None,<br>):<br>    &quot;&quot;&quot;<br>    Tool สำหรับตอบข้อมูลการเข้า-ออกงานพนักงาน</pre><pre>    query_type:<br>    - late_count        : นับจำนวนมาสายของพนักงาน<br>    - daily_record      : ดูข้อมูลเข้า-ออกงานรายวัน<br>    - leave_by_date     : ดูว่าใครลางานในวันนั้น<br>    &quot;&quot;&quot;</pre><pre>    rows = load_rows()</pre><pre>    # -------------------------<br>    # นับจำนวนมาสาย<br>    # -------------------------<br>    if query_type == &quot;late_count&quot; and employee_id:<br>        late_days = [<br>            r for r in rows<br>            if r[&quot;employee_id&quot;] == employee_id and r[&quot;remark&quot;] == &quot;Late&quot;<br>        ]<br>        return f&quot;{employee_id} มาสายทั้งหมด {len(late_days)} ครั้ง&quot;</pre><pre>    # -------------------------<br>    # ดูข้อมูลรายวันของพนักงาน<br>    # -------------------------<br>    if query_type == &quot;daily_record&quot; and employee_id and date:<br>        for r in rows:<br>            if r[&quot;employee_id&quot;] == employee_id and r[&quot;date&quot;] == date:<br>                return (<br>                    f&quot;{employee_id} วันที่ {date} &quot;<br>                    f&quot;เข้า {r[&#39;check_in&#39;]} &quot;<br>                    f&quot;ออก {r[&#39;check_out&#39;]} &quot;<br>                    f&quot;สถานะ: {r[&#39;remark&#39;]}&quot;<br>                )<br>        return f&quot;ไม่พบข้อมูลของ {employee_id} วันที่ {date}&quot;</pre><pre>    # -------------------------<br>    # ดูพนักงานที่ลางานในวันนั้น<br>    # -------------------------<br>    if query_type == &quot;leave_by_date&quot; and date:<br>        leaves = [<br>            r[&quot;employee_id&quot;]<br>            for r in rows<br>            if r[&quot;date&quot;] == date and r[&quot;remark&quot;] == &quot;Sick leave&quot;<br>        ]</pre><pre>        if not leaves:<br>            return f&quot;ไม่มีพนักงานลางานในวันที่ {date}&quot;</pre><pre>        return f&quot;พนักงานที่ลางานวันที่ {date}: {&#39;, &#39;.join(leaves)}&quot;<br>    <br>    # -------------------------<br>    # นับจำนวนมาลางาน<br>    # -------------------------<br>    if query_type == &quot;leave_count&quot; and employee_id:<br>        leave_days = [<br>            r for r in rows<br>            if r[&quot;employee_id&quot;] == employee_id<br>            and r[&quot;remark&quot;] == &quot;Sick leave&quot;<br>        ]</pre><pre>        return f&quot;{employee_id} ลางานทั้งหมด {len(leave_days)} วัน&quot;<br>    <br>    # -------------------------<br>    # ดูพนักงานที่มาสายในวันนั้น<br>    # -------------------------<br>    if query_type == &quot;late_by_date&quot; and date:<br>        lates = [<br>            r[&quot;employee_id&quot;]<br>            for r in rows<br>            if r[&quot;date&quot;] == date and r[&quot;remark&quot;] == &quot;Late&quot;<br>        ]</pre><pre>        if not lates:<br>            return f&quot;วันที่ {date} ไม่มีพนักงานมาสาย&quot;</pre><pre>        return f&quot;วันที่ {date} พนักงานที่มาสาย: {&#39;, &#39;.join(lates)}&quot;</pre><pre>    return &quot;กรุณาระบุ query_type และ parameters ให้ครบ&quot;<br></pre><pre>attendance_tool = FunctionTool(func=attendance_tool)</pre><h4>แก้ไข Agent เพิ่มการเรียกใช้ Attendance Tool</h4><p>แก้ไขไฟล์ my_agent/agent.py ตามโค้ดด้านล่างเพื่อปรับให้ Agent เรียกใช้ Attendance Tool เพิ่ม</p><pre>from google.adk.agents import Agent<br>from tools.policy_tool import policy_tool<br>from tools.attendance_tool import attendance_tool<br></pre><pre>root_agent = Agent(<br>    name=&quot;hr_policy_agent&quot;,<br>    model=&quot;gemini-2.0-flash&quot;,<br>    description=&quot;ตอบคำถามเกี่ยวกับนโยบายและสวัสดิการพนักงาน&quot;,<br>    instruction=&quot;&quot;&quot;<br>คุณเป็น HR assistant<br>- ห้ามเดาข้อมูลการลา / มาสายเอง<br>- ถ้าถามจำนวนวันลา ให้เรียก attendance_tool ด้วย query_type=leave_count<br>- ถ้าถามพนักงานที่มาสาย ในแต่ละวัน ให้เรียก attendance_tool ด้วย query_type=late_by_date<br>&quot;&quot;&quot;,<br>    tools=[policy_tool, attendance_tool]<br>)</pre><p>ลองทดสอบ Run ADK ดูใหม่แล้วลองคุยเรื่องข้อมูลการ เข้า-ออก งาน แล้วลองเข้าไปดูใน Events จะเห็นว่ามี 2 Tool แล้ว (Policy, Attendance)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C3m6wNLE98L6JgrgIWAc_A.png" /></figure><p>การทำงานตอนนี้ก็จะเป็นเหมือนในรูปนี้ด้านล่าง คือ มี HR Agent และมี Tool 2 ตัวสำหรับดึงข้อมูล policy และ time attendance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wumvhaFAskpVVaHs68i-ag.png" /></figure><p>ต่อไปเราจะสร้าง Multi-Agent เพื่อรองรับการทำงานหลายแผนกกันครับ</p><h3>เตรียมตัวก่อนสร้าง Multi-Agent</h3><p>ก่อนเริ่มสร้างเรามาวางโครงสร้าง Agent กันก่อนนะครับ ว่าเราจะสร้าง Agent อะไรเพิ่มและ Agent ทำงานอะไรบ้าง ต้องมี Tool อะไรบ้าง</p><p>โดยในตัวอย่างนี้ ผมจะสร้างเพิ่มอีก 1 Agent รายละเอียดดังนี้</p><h4>Operations Agent</h4><ul><li>Role: ผู้ช่วยผู้จัดการ</li><li>หน้าที่: “ตอบ + วิเคราะห์ + เตือน” เรื่องการปฏิบัติงานประจำวัน</li><li>Tool: <br> — task / job_status_tool = สำหรับดึงข้อมูลสถานะงาน <br> — policy_SLA_tool (SLA / threshold) = สำหรับดึงนโยบาย SLA</li></ul><p>และเราต้องสร้าง Base Agent ด้วย เพื่อทำหน้าที่เป็นตัวกลางในการเลือกว่าจะเรียกใช้ Agent ไหนเพื่อตอบ user</p><p>เราจะเริ่มจากการสร้าง Base Agent และปรับโครงสร้างให้พร้อมสำหรับ Multi-Agent ก่อน</p><h3>สร้าง Base Agent และ ปรับโครงสร้างสำหรับ Multi-Agent</h3><h4>ปรับโครงสร้างสำหรับ Multi Agent</h4><ul><li>สร้าง Folder agents ใน root folderเพื่อไว้เก็บ agent ทั้งหมด แล้วสร้างไฟล์ hr_agent.py</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4PL2AHJ0W3YJWACp2O-PA.png" /></figure><p>นำ code ด้านล่างใส่ในไฟล์ hr_agent.py</p><pre>from google.adk.agents import Agent<br>from tools.policy_tool import policy_tool<br>from tools.attendance_tool import attendance_tool</pre><pre>print(&#39;---- start hr_agent -----&#39;)<br>hr_agent = Agent(<br>    name=&quot;hr_policy_agent&quot;,<br>    description=&quot;ตอบคำถามเกี่ยวกับนโยบายและสวัสดิการพนักงาน&quot;,<br>    instruction=&quot;&quot;&quot;<br>คุณเป็น HR assistant</pre><pre>ขั้นตอนแรกของทุกคำตอบ:<br>1) เรียก tool ที่เหมาะสม<br>2) ใช้ผลลัพธ์จาก tool เท่านั้นในการตอบ<br>3) ถ้า tool ไม่คืนข้อมูล ให้ตอบว่า &quot;ไม่พบข้อมูล&quot;</pre><pre>ข้อบังคับ (สำคัญมาก):<br>- ห้ามตอบคำถามเกี่ยวกับการลา การมาสาย การเข้างาน<br>  ด้วยความรู้ของตัวเองโดยเด็ดขาด<br>- ทุกคำถามในหมวดนี้ ต้องเรียก tool ก่อนเสมอ<br>- ถ้าไม่เรียก tool ถือว่าผิดพลาด</pre><pre>การตัดสินใจเรียก tool:<br>- ถ้ามีคำว่า &quot;มาสาย&quot; → เรียก attendance_tool<br>- ถ้ามีวันที่ หรือรหัสพนักงาน → เรียก attendance_tool</pre><pre>การใข้งาน policy_tool:<br>- ถามนโยบายบริษัท → ใช้ policy_tool<br>- ถามสวัสดิการ → ใช้ policy_tool<br>- ถามจำนวนวันลาของพนักงาน → ใช้ policy_tool</pre><pre>การใช้งาน attendance_tool:<br>- ถามใครลาในวันใด → query_type=leave_by_date<br>- ถามใครมาสายในวันใด → query_type=late_by_date<br>- ถามข้อมูลรายวัน → query_type=daily_record</pre><pre>&quot;&quot;&quot;,<br>    tools=[policy_tool, attendance_tool]<br>)</pre><h4>สร้าง Base Agent</h4><p>แก้ไขไฟล์ my_agent/agent.py ให้เป็น Base_Agent โดยแก้ไขเป็นตาม code ด้านล่าง</p><pre>from google.adk.agents import Agent<br>from agents.hr_agent import hr_agent</pre><pre># Create parent agent and assign children via sub_agents<br>root_agent = Agent(<br>    name=&quot;Base_Agent&quot;,<br>    model=&quot;gemini-2.0-flash&quot;,<br>    description=&quot;I coordinate greetings and tasks.&quot;,<br>    sub_agents=[ # Assign sub_agents here<br>        hr_agent<br>    ]<br>)</pre><p>จาก code เราทำการ import hr_agent และ ทำการสร้าง Agent Base_Agent แล้วกำหนด hr_agent เป็น sub_agents</p><p>หลังจากแก้เสร็จแล้ว ลอง run แล้วพิมพ์ข้อความถามว่า “พนักงาน ลาป่วย ได้กี่วัน” จะพบว่า การทำงานจะเริ่มจาก Base_Agent แล้วส่งต่อไปที่ hr_agent หลังจากนั้น hr_agent ทำการเรียก Tool load_policy เพื่อดึงเรื่องนโยบาย วันหยุดของพนักงาน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2NUna05xJEU08ZqVvouhAA.png" /></figure><p>ต่อไปเราจะทำการสร้าง <strong>Operations Agent </strong>เป็นผู้ช่วยผู้จัดการกันครับ</p><h3>สร้าง Operations Agent</h3><p>เรากำลังสร้าง Operation Agent สำหรับเป็นผู้ช่วยผู้จัดการ <strong>โดย Agent นี้จะตอบคำถามเกี่ยวกับเรื่อง Performance การทำงานในแต่ละ Process</strong> ตัวอย่างคำถาม</p><blockquote>วันที่ 2025–01–08 มี process ไหนเกิน SLA ?<br>process P003 ทำงานช้าแค่ไหน ?<br>งานส่วนไหนเป็นคอขวดของระบบ ?</blockquote><p>โดยส่วนของข้อมูลจะแบ่งเป็น 2 ส่วนคือ</p><ol><li><strong>Process SLA</strong> — สำหรับเก็บข้อมูล ข้อกำหนดกระบวนการทำงาน</li><li><strong>Operation log </strong>— สำหรับเก็บข้อมูล Log การทำงานแต่ละกระบวนการ</li></ol><p>เราจะเริ่มสร้างข้อมูล และ Tool กันครับ</p><h4>สร้างข้อมูล Process SLA</h4><p>สร้างไฟล์ process_sla.md แล้วแก้ไขไฟล์ตามข้อมูลด้านล่างนี้ โดยจะเป็นข้อมูลข้อกำหนดระยะเวลาการทำงานของแต่ละกระบวนการ</p><pre>| process_id | process_name        | owner_dept | sla_minutes |<br>|------------|---------------------|------------|-------------|<br>| P001       | รับคำสั่งซื้อ       | Sales      | 30          |<br>| P002       | ตรวจสอบสต๊อก        | Warehouse  | 20          |<br>| P003       | แพ็กสินค้า           | Warehouse  | 45          |<br>| P004       | จัดส่งสินค้า         | Logistics  | 120         |<br>| P005       | ปิดงานและออกบิล     | Finance    | 15          |</pre><h4>สร้างข้อมูล Operation log</h4><p>สร้างไฟล์ operation_log.md แล้วแก้ไขไฟล์ตามข้อมูลด้านล่างนี้ โดยจะเป็นข้อมูลประวัติการทำงานของแต่ละกระบวนการทำงาน</p><pre>| date       | process_id | order_id | start_time | end_time | status     |<br>|------------|------------|----------|------------|----------|------------|<br>| 2025-01-08 | P001       | ORD001   | 09:00      | 09:40    | Completed  |<br>| 2025-01-08 | P002       | ORD001   | 09:45      | 10:05    | Completed  |<br>| 2025-01-08 | P003       | ORD001   | 10:10      | 11:10    | Completed  |<br>| 2025-01-08 | P004       | ORD001   | 11:30      | 14:00    | Completed  |<br>| 2025-01-08 | P001       | ORD002   | 10:00      | 10:20    | Completed  |<br>| 2025-01-08 | P003       | ORD002   | 10:30      | 11:45    | Delayed    |</pre><h4>สร้าง Tool สำหรับ Operation Agent</h4><p>สร้างไฟล์ tools/operations_tool.py แล้วแก้ไขข้อมูลตาม code ด้านล่างนี้</p><p>โดยหลักๆ จะเป็นการอ่านข้อมูลจาก operation log และ process sla แล้วจัดเตรียมข้อมูลตาม query type ตามนี้</p><blockquote><strong>“sla_breach_by_date”</strong> : ดู process ที่เกิน SLA ในวันนั้น</blockquote><blockquote><strong>“process_summary”</strong> : สรุป performance ของ process</blockquote><pre>from google.adk.tools import FunctionTool<br>from pathlib import Path<br>from datetime import datetime</pre><pre>BASE_DIR = Path(__file__).resolve().parent.parent<br>PROCESS_PATH = BASE_DIR / &quot;data&quot; / &quot;process_sla.md&quot;<br>LOG_PATH = BASE_DIR / &quot;data&quot; / &quot;operation_log.md&quot;<br></pre><pre>def parse_md_table(path):<br>    rows = []<br>    with open(path, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>        lines = [l.strip() for l in f.readlines() if &quot;|&quot; in l]</pre><pre>    headers = [h.strip() for h in lines[0].split(&quot;|&quot;)[1:-1]]</pre><pre>    for line in lines[2:]:<br>        values = [v.strip() for v in line.split(&quot;|&quot;)[1:-1]]<br>        rows.append(dict(zip(headers, values)))</pre><pre>    return rows<br></pre><pre>def minutes_diff(start, end):<br>    s = datetime.strptime(start, &quot;%H:%M&quot;)<br>    e = datetime.strptime(end, &quot;%H:%M&quot;)<br>    return int((e - s).total_seconds() / 60)<br></pre><pre>def operations_tool(<br>    query_type: str,<br>    date: str = None,<br>    process_id: str = None<br>) -&gt; str:<br>    &quot;&quot;&quot;<br>    query_type:<br>    - sla_breach_by_date : ดู process ที่เกิน SLA ในวันนั้น<br>    - process_summary   : สรุป performance ของ process<br>    &quot;&quot;&quot;</pre><pre>    processes = parse_md_table(PROCESS_PATH)<br>    logs = parse_md_table(LOG_PATH)</pre><pre>    process_map = {p[&quot;process_id&quot;]: p for p in processes}</pre><pre>    # -------------------------<br>    # SLA breach by date<br>    # -------------------------<br>    if query_type == &quot;sla_breach_by_date&quot; and date:<br>        breached = []</pre><pre>        for log in logs:<br>            if log[&quot;date&quot;] != date:<br>                continue</pre><pre>            pid = log[&quot;process_id&quot;]<br>            sla = int(process_map[pid][&quot;sla_minutes&quot;])<br>            duration = minutes_diff(log[&quot;start_time&quot;], log[&quot;end_time&quot;])</pre><pre>            if duration &gt; sla:<br>                breached.append(<br>                    f&quot;{pid} ({duration} นาที / SLA {sla} นาที)&quot;<br>                )</pre><pre>        if not breached:<br>            return f&quot;วันที่ {date} ไม่มี process ที่เกิน SLA&quot;</pre><pre>        return f&quot;วันที่ {date} process ที่เกิน SLA: &quot; + &quot;, &quot;.join(breached)</pre><pre>    # -------------------------<br>    # Process summary<br>    # -------------------------<br>    if query_type == &quot;process_summary&quot; and process_id:<br>        related = [l for l in logs if l[&quot;process_id&quot;] == process_id]</pre><pre>        if not related:<br>            return f&quot;ไม่พบข้อมูลของ process {process_id}&quot;</pre><pre>        avg_time = sum(<br>            minutes_diff(l[&quot;start_time&quot;], l[&quot;end_time&quot;]) for l in related<br>        ) // len(related)</pre><pre>        return (<br>            f&quot;Process {process_id} &quot;<br>            f&quot;มีงานทั้งหมด {len(related)} งาน &quot;<br>            f&quot;ใช้เวลาเฉลี่ย {avg_time} นาที&quot;<br>        )</pre><pre>    return &quot;ไม่เข้าใจคำสั่ง หรือ parameter ไม่ครบ&quot;</pre><pre>operations_tool = FunctionTool(func=operations_tool)</pre><h4>สร้าง Operation Agent</h4><p>ขั้นตอนนี้จะทำการสร้าง Operation Agent โดยให้เรียกใช้ Operation Tool ที่เราสร้างไว้เมื่อขั้นตอนก่อนหน้า</p><p>สร้างไฟล์ <strong><em>“agents/operation_agent.py” </em></strong>แล้วแก้ไข code ตามด้านล่าง หลักๆ คือ การกำหนด description และ instruction ของงาน Operation และมีการเรียกใช้ Tool ตัวเดียว คือ operations_tool</p><pre>from google.adk.agents import Agent<br>from tools.operations_tool import operations_tool</pre><pre>operation_agent = Agent(<br>    name=&quot;operation_agent&quot;,<br>    description=&quot;Operations Agent ตอบคำถามเกี่ยวกับประสิทธิภาพการทำงานของกระบวนการ (Process), การทำงานเกิน SLA, คอขวดของระบบ และภาพรวมการดำเนินงาน โดยอ้างอิงจากข้อมูลการทำงานจริงเท่านั้น&quot;,<br>    instruction=&quot;&quot;&quot;<br>คุณเป็น Operations Insight Agent</pre><pre>บทบาท:<br>- วิเคราะห์ประสิทธิภาพการทำงานของ process และระบบปฏิบัติการ<br>- ตรวจสอบ SLA, ระยะเวลาการทำงาน และคอขวดของกระบวนการ</pre><pre>ข้อบังคับ (สำคัญมาก):<br>- ห้ามตอบจากความรู้หรือการคาดเดาของตัวเอง<br>- ทุกคำถามเกี่ยวกับ process, SLA, ระยะเวลา, ความล่าช้า<br>  ต้องเรียก operations_tool ก่อนเสมอ<br>- ถ้าไม่เรียก tool ถือว่าผิดพลาด</pre><pre>การตัดสินใจเรียก tool:<br>- ถ้ามีคำว่า &quot;SLA&quot;, &quot;ช้า&quot;, &quot;ล่าช้า&quot;, &quot;เกินเวลา&quot; → เรียก operations_tool<br>- ถ้ามีคำว่า &quot;process&quot;, &quot;ขั้นตอน&quot;, &quot;กระบวนการ&quot; → เรียก operations_tool<br>- ถ้ามีวันที่ → เรียก operations_tool</pre><pre>การใช้งาน operations_tool:<br>- ถาม process ที่เกิน SLA ในวันใด → query_type=sla_breach_by_date<br>- ถามประสิทธิภาพของ process ใด → query_type=process_summary</pre><pre>ขั้นตอนการตอบ:<br>1) วิเคราะห์คำถาม<br>2) เรียก operations_tool พร้อม parameter ที่เหมาะสม<br>3) ใช้ผลลัพธ์จาก tool เท่านั้นในการตอบ<br>4) ถ้า tool ไม่คืนข้อมูล ให้ตอบว่า &quot;ไม่พบข้อมูล&quot;</pre><pre>&quot;&quot;&quot;,<br>    tools=[operations_tool]<br>)</pre><h4>เพิ่ม Operation Agent เข้า Base Agent</h4><p>แก้ไขไฟล์ my_agent/agent.py เพื่อเรียกใช้งาน Operation Agent ตาม code ด้านล่างนี้</p><pre>from google.adk.agents import Agent<br>from agents.hr_agent import hr_agent<br>from agents.operation_agent import operation_agent</pre><pre># Create parent agent and assign children via sub_agents<br>root_agent = Agent(<br>    name=&quot;Base_Agent&quot;,<br>    model=&quot;gemini-2.0-flash&quot;,<br>    description=&quot;I coordinate greetings and tasks.&quot;,<br>    sub_agents=[ # Assign sub_agents here<br>        hr_agent, operation_agent<br>    ]<br>)</pre><p>ทดสอบ run ADK และลอง chat คุย คำถามว่า “วันที่ 2025–01–08 มี process ไหนเกิน SLA” แล้วเปิด Event ดู จะเห็นว่ามี Sub Agent สองตัว แล้ว และ ทำการเรียกใช้งาน Operation Agent</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l0sQy2L7jYfZDMqzU95kbw.png" /></figure><p>การทำงานตอนนี้ก็จะเป็นเหมือนในรูปนี้ด้านล่าง คือ มี Base Agent เป็นตัวรับ คำถามจาก User และ คอย เรียกใช้ HR Agent และ Operation Agent</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47gqli0iM5mB1gEQY28jCA.png" /></figure><h3>ส่งท้ายไปตอนที่ 3</h3><p>ตอนนี้เราก็ได้ทำการสร้าง Agent แบบ Multi Agent + Multi Tool เรียบร้อยแล้ว สามารถตอบคำถาม user ได้แล้ว</p><p>ขั้นตอนต่อไปเราจะทำการเชื่อม Agent ตัวนี้ให้ใช้งานกับ LINE OA ไปต่อตอน 3 กันที่ลิงก์ด้านล่างได้เลยค้าบบ 🚀</p><p><a href="https://medium.com/linedevth/line-chatbot-with-google-adk-connect-with-line-ba8fa9bdab52">สร้าง LINE Chatbot และ AI Agent สำหรับองค์กรด้วย Google ADK #3— เชื่อมต่อ LINE Chatbot กับ Agent…</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=527f69dad16a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linedevth/line-chatbot-with-google-adk-workshop-527f69dad16a">สร้าง LINE Chatbot และ AI Agent สำหรับองค์กรด้วย Google ADK #2 — เริ่มสร้าง LINE Chatbot + Google…</a> was originally published in <a href="https://medium.com/linedevth">LINE Developers Thailand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[สร้าง LINE Chatbot และ AI Agent สำหรับองค์กรด้วย Google ADK #1 — แนวคิดและโครงสร้าง Google ADK]]></title>
            <link>https://medium.com/linedevth/line-chatbot-with-google-adk-concept-5c3b884ba057?source=rss-655fb7ee2ef3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c3b884ba057</guid>
            <category><![CDATA[line-bot]]></category>
            <category><![CDATA[google-adk]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[linedevth]]></category>
            <dc:creator><![CDATA[PamornT]]></dc:creator>
            <pubDate>Wed, 28 Jan 2026 06:37:38 GMT</pubDate>
            <atom:updated>2026-01-30T08:17:11.343Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6nzgF46U9hoa5ab4ke4ogA.png" /></figure><h3>สร้าง LINE Chatbot และ AI Agent สำหรับองค์กรด้วย Google ADK #1 — แนวคิดและโครงสร้าง Google ADK</h3><p>สำหรับบทความนี้เกิดจากการลองออกแบบและคิดระบบ <strong>LINE Chatbot สำหรับองค์กร </strong>โดยใช้แนวคิดของ <strong>AI Agent</strong> และ <strong>Google Agent Development Kit (ADK) </strong>เพื่อสร้างระบบที่ <strong>มีโครงสร้าง, มีขอบเขต และนำไปใช้จริงได้ในระดับองค์กร</strong></p><p>ก่อนจะไปเริ่มลงมือทำ เรามาทำความเข้าใจแนวคิดของ Agent และโครงสร้าง Google ADK กันก่อน เพราะการตั้งกรอบความคิดให้ถูกต้องก่อนเป็นสิ่งที่สำคัญมาก</p><h3>Chatbot ไม่ใช่ Agent</h3><p>ก่อนจะพูดถึง AI Agent สำหรับองค์กร <br>ผมอยากชวนกลับมาทำความเข้าใจพื้นฐานก่อนว่า</p><blockquote><strong><em>Chatbot กับ Agent แตกต่างกันอย่างไร</em></strong></blockquote><p>ในทางปฏิบัติ Chatbot แบบดั้งเดิมที่เราใช้งานกัน มักอยู่ใน 2 รูปแบบหลัก</p><h4>1. Rule-based Chatbot</h4><p>เป็น Chatbot ที่ทำงานตามเส้นทางที่กำหนดไว้ล่วงหน้า โดยอาศัยการกำหนด Input และ Response อย่างชัดเจน เช่น</p><pre>ผู้ใช้ → พิมพ์ข้อความ  <br>→ Input (Training / Matching Rule)  <br>→ Response ที่กำหนดไว้</pre><p>แนวทางนี้:</p><ul><li>ควบคุมง่าย</li><li>พฤติกรรมคาดเดาได้</li><li>แต่ขยายยาก และไม่ยืดหยุ่น</li></ul><p>เหมาะกับ use case ง่าย ๆ เช่น FAQ หรือ flow คงที่</p><h4>2. LLM-based Chatbot</h4><p>จะเป็นการใช้ความสามารถของ LLM ช่วย ทำให้ Chatbot “ฉลาดขึ้น” รูปแบบการทำงานจะกลายเป็น</p><pre>ผู้ใช้ → Prompt  <br>→ LLM (ตาม Instruction ที่กำหนด)  <br>→ Response</pre><p>Chatbot ประเภทนี้:</p><ul><li>เข้าใจภาษามนุษย์ได้ดีขึ้น</li><li>ตอบได้หลากหลายและยืดหยุ่น</li><li>ปรับตัวตามบริบทได้ดี</li></ul><p>ในแง่นี้ เราสามารถเรียกมันได้ว่า <strong>Agent เชิงพฤติกรรม (Behavioral Agent)<br></strong>แต่ปัญหาคือยังมีหลายสิ่งที่ยังขาดไปสำหรับทำ <strong>Agent เชิงระบบ (Architectural / Enterprise Agent)</strong></p><h3>สิ่งที่ยังขาดสำหรับการเป็น Agent เชิงระบบ</h3><p>แม้ LLM-based Chatbot จะตอบเก่งขึ้นมาก<br> แต่มันยังขาดองค์ประกอบสำคัญสำหรับการใช้งานในระดับองค์กร เช่น</p><ul><li>ไม่มีบทบาทที่ชัดเจน (Role)</li><li>ไม่มีขอบเขตความรับผิดชอบ (Responsibility)</li><li>ไม่สามารถบังคับ boundary ได้จากระดับระบบ</li><li>แยกหน้าที่ตามแผนกไม่ได้</li><li>ควบคุมความเสี่ยงได้ยาก</li></ul><p>ทั้งหมดนี้ทำให้ LLM-based Chatbot ยัง <strong>ไม่ใช่ Agent เชิงระบบ (Architectural / Enterprise Agent)</strong></p><blockquote><em>Agent สำหรับองค์กร ไม่ได้เกิดจาก prompt ที่ฉลาดขึ้น<br>แต่เกิดจากโครงสร้างระบบที่บังคับบทบาทและขอบเขตของมันได้</em></blockquote><p>เราจะเห็นว่า:</p><ul><li>Chatbot แบบดั้งเดิม ไม่ว่าจะเป็น rule-based หรือ LLM-based ยังขาดโครงสร้างที่เหมาะกับการใช้งานในระดับองค์กร</li><li>LLM ทำให้ chatbot “ฉลาดขึ้น” แต่ความฉลาดเพียงอย่างเดียว ไม่เพียงพอสำหรับระบบที่ต้องควบคุมได้</li><li>Agent สำหรับองค์กร ไม่ได้ถูกนิยามจากความสามารถในการสนทนา แต่จาก <strong>บทบาท ความรับผิดชอบ และขอบเขตที่ระบบบังคับใช้ได้</strong></li></ul><p>เมื่อเราเริ่มมอง AI เป็น “พนักงานดิจิทัล” คำถามสำคัญจึงเปลี่ยนจาก</p><blockquote>มันตอบเก่งแค่ไหน</blockquote><p>เป็น</p><blockquote>มันควรถูกอนุญาตให้ทำอะไรบ้าง</blockquote><h3>Google ADK แก้ปัญหานี้อย่างไร</h3><p>Google ADK ถูกออกแบบมาเพื่อจัดการ AI Agent ในฐานะองค์ประกอบหนึ่งของระบบ software</p><p>แทนที่จะมี AI ตัวเดียวตอบทุกอย่าง ADK เปิดโอกาสให้เราออกแบบ:</p><ul><li>Agent หลายตัว</li><li>แยกตามบทบาท</li><li>มีขอบเขตชัดเจน</li><li>ใช้ tool ต่างกัน</li><li>ทำงานร่วมกันผ่าน orchestration</li></ul><h3>โครงสร้างการทำงานของ Google ADK — Multi Agent</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6K5sEhk6E9gYZYhaHBcYKA.png" /></figure><h3>Router Agent: จุดเริ่มต้นของทุกคำถาม</h3><p>ในระบบ Multi-Agent Router Agent คือด่านแรกที่ทุกข้อความต้องผ่าน</p><p>Router Agent ทำหน้าที่:</p><ul><li>รับข้อความจาก LINE</li><li>วิเคราะห์ intent ระดับแผนก</li><li>ส่งต่อไป Agent ที่เหมาะสม</li></ul><p>Router ไม่ควรตอบผู้ใช้เอง และไม่ควรมี business logic</p><h3>ตัวอย่างการออกแบบ Agent ตามแผนก</h3><ul><li><strong>HR Agent <br></strong>รับผิดชอบเรื่อง policy และข้อมูลพนักงาน</li><li><strong>Sales Agent</strong><br>รับผิดชอบข้อมูลสินค้า ราคา และ promotion</li><li><strong>Support Agent</strong><br>รับผิดชอบปัญหาการใช้งาน และการเปิด ticket</li></ul><p>การแยกแบบนี้:</p><ul><li>ลดความเสี่ยง</li><li>เพิ่มความชัดเจน</li><li>ทำให้ระบบขยายได้ง่าย</li></ul><h3>ส่งท้ายไปตอนที่ 2</h3><p>สำหรับบทความนี้ เราก็ทำความเข้าใจถึง แนวความคิดของ Agent และ โครงสร้างของ Google ADK กันแล้ว ต่อไปเราจะไปลงมือสร้าง Agent บน Google ADK แบบ Multi Agent + Multi Tool พร้อมทำตามได้ทีละขั้นตอนเลย ไปต่อกันที่ตอนที่ 2 ที่ลิงก์ด้านล่างได้เลยค้าบ 🚀</p><p><a href="https://medium.com/linedevth/line-chatbot-with-google-adk-workshop-527f69dad16a">สร้าง LINE Chatbot และ AI Agent สำหรับองค์กรด้วย Google ADK #2 — เริ่มสร้าง LINE Chatbot + Google…</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c3b884ba057" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linedevth/line-chatbot-with-google-adk-concept-5c3b884ba057">สร้าง LINE Chatbot และ AI Agent สำหรับองค์กรด้วย Google ADK #1 — แนวคิดและโครงสร้าง Google ADK</a> was originally published in <a href="https://medium.com/linedevth">LINE Developers Thailand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tuning Firebase Storage ให้เร็วขึ้น ⚡ และค่าใช้จ่ายลดลง ]]></title>
            <link>https://medium.com/firebasethailand/tuning-firebase-storage-%E0%B9%83%E0%B8%AB%E0%B9%89%E0%B9%80%E0%B8%A3%E0%B9%87%E0%B8%A7%E0%B8%82%E0%B8%B6%E0%B9%89%E0%B8%99-%E0%B9%81%E0%B8%A5%E0%B8%B0%E0%B8%84%E0%B9%88%E0%B8%B2%E0%B9%83%E0%B8%8A%E0%B9%89%E0%B8%88%E0%B9%88%E0%B8%B2%E0%B8%A2%E0%B8%A5%E0%B8%94%E0%B8%A5%E0%B8%87-29d053a85da2?source=rss-655fb7ee2ef3------2</link>
            <guid isPermaLink="false">https://medium.com/p/29d053a85da2</guid>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[storage]]></category>
            <dc:creator><![CDATA[PamornT]]></dc:creator>
            <pubDate>Mon, 19 Jan 2026 04:03:07 GMT</pubDate>
            <atom:updated>2026-01-19T07:37:02.959Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ga2lTT2b0M9fYYIT3R2JVA.png" /></figure><p>เมื่อเดือนก่อนจู่ๆ ก็พบว่าค่าใช้จ่าย <strong>Google Cloud เพิ่มขึ้นจากเดือนก่อนค่อนข้างมาก </strong>ทั้งที่ feature ใหม่ก็ไม่ได้ปล่อย ระบบก็ไม่ได้ scale ผู้ใช้แบบก้าวกระโดด</p><p>พอเปิด <strong>Billing Report</strong> ดูแบบจริงจัง ก็เริ่มเห็นตัวเลขแปลกๆ โผล่ขึ้นมาในหมวด <strong>Cloud Storage</strong></p><p>ไล่ breakdown ต่อไปเรื่อยๆ จนสุดท้ายเจอต้นตอว่า…</p><blockquote>ค่าใช้จ่ายส่วนใหญ่เกิดจาก <strong>Traffic การเรียกไฟล์ Video</strong><br> ที่ User upload ไว้บน <strong>Firebase Storage</strong> <em>😫</em></blockquote><p>ทั้งที่ video เหล่านี้:</p><ul><li>ไม่ได้เปลี่ยนไฟล์</li><li>ไม่ได้ถูกแก้ไข</li><li>แต่ถูกเปิดดูซ้ำๆ จากหลายหน้า หลาย session</li></ul><p>และนี่แหละครับ คือที่มาของบทความนี้ เพื่อมาเล่าสิ่งที่ผมเจอ + สิ่งที่แก้ เผื่อใครกำลังเจอสถานการณ์คล้ายๆ กันจะได้ไม่ต้องเสียค่าเรียนเหมือนเรา 😅</p><h3>มาทำความเข้าใจก่อนว่า ค่าใช้จ่ายของ Cloud Storage มาจากไหน</h3><p>หลายคน (รวมถึงผมในตอนแรก) มักจะเข้าใจว่า <strong>Cloud Storage = ค่าฝากไฟล์<br></strong>แต่จริงๆ แล้ว ค่าใช้จ่ายหลักๆ ของ Cloud Storage มีอยู่ <strong>3 ส่วน</strong></p><h3>1. Storage (ค่าฝากไฟล์)</h3><p>อันนี้เข้าใจง่ายที่สุด</p><ul><li>เก็บไฟล์กี่ GB</li><li>เก็บนานแค่ไหน</li></ul><p>ส่วนนี้มัก <strong>ไม่ใช่ตัวปัญหา </strong>เพราะไฟล์ video ต่อให้หลาย GB ถ้า user ไม่เยอะ ก็ยังไม่แรงมาก</p><h3>2. Operations (ค่าการอ่าน / เขียน)</h3><p>เช่น:</p><ul><li>Upload</li><li>Download</li><li>List file</li></ul><p>โดยปกติค่าใช้จ่ายส่วนนี้ก็ยังไม่สูงมาก ถ้าเทียบกับสิ่งถัดไป 👇</p><h3>3. Network Data Transfer (ตัวร้ายเงียบ 😈)</h3><p>นี่แหละครับ… ตัวที่ทำให้บิลพุ่งแบบไม่รู้ตัว</p><p>เพราะทุกครั้งที่ User เรียกไฟล์จากหน้าเว็บ จะเกิด:</p><blockquote>Data transfer ออกจาก Cloud โดย มัน คิดเงินตามปริมาณข้อมูลที่ส่งออกไป</blockquote><p>โดยสิ่งที่สำคัญคือมัน</p><p>⚠️ <strong>ไม่สนใจว่าไฟล์นั้นจะเคยโหลดไปแล้วหรือยัง</strong><br>⚠️ <strong>ไม่สนใจว่าเป็นไฟล์เดิมหรือไฟล์ใหม่</strong></p><p>เรียกได้ว่า โหลด = จ่าย, refresh ที ก็จ่ายที ไม่จบไม่สิ้น 😢</p><p>ลองนึกภาพง่ายๆ ถ้าเรามี:</p><ul><li>Video ขนาด 20 MB</li><li>User เปิดดู 1 video</li><li>เปิดซ้ำ 5 ครั้ง</li></ul><p>เท่ากับ โหลด ไป = 20MB x 5 = 100MB นี่แค่ 1 user ถ้าเป็น 1,000 user จะเท่ากับ 100,000MB หรือ 100GB กันเลยทีเดียว<br>โดยค่าใช้จ่ายในส่วน data transfer จะประมาณ $0.08–$0.12 / GB ถ้าเอา 100 GB มาคำนวณ จะเสียค่าใช้จ่ายประมาณ $8 เลยทีเดียว</p><blockquote>การใช้งานจริงจะมากกว่า 1,000 user ไปอีกเยอะ ทำให้ค่าใช้จ่ายบานตะไท <em>🤢</em></blockquote><h3>เริ่ม Tuning Firebase Storage</h3><p>โดยโจทย์ของผมคือ “User ยังต้องสามารถเรียกดูไฟล์ Video ใน Storage ซ้ำๆ ได้” และ “ยังไม่อยากรื้อระบบ” เพราะจะกระทบกับหลาย service</p><p>ซึ่งพอเราดูแล้ว “ปัญหาเกิดจาก User เรียกดูไฟล์ Video เดิมๆ และ ถูกเปิดซ้ำจากหลายหน้า” ถ้าเราให้ User Cache ไฟล์ Video ไว้ที่ Client เอง จะแก้ปัญหาตรงนี้ไปได้เลย เราจึงเลือกทำในสิ่งที่เรียกว่า Cache-Control</p><h3>Cache-Control</h3><p>Cache-Control คือ HTTP Header ที่ใช้บอก browser, CDN และ proxy ว่า <em>“ไฟล์นี้ cache ได้ไหม cache ได้นานแค่ไหน และต้องโหลดใหม่ตอนไหน</em>” ซึ่งไม่ได้เป็นความรู้ใหม่เลย เป็นสิ่งที่เราเคยทำมานมนานแล้ว แต่เราอาจจะลืมสิ่งนี้ไป <br>และพอไปค้นมาแล้วพบว่า <strong>Firebase Storage สามารถกำหนด Cache Control</strong> ได้หลายวิธีเลย</p><h4>วิธีที่ 1 : ปรับ Metadata บน Google Cloud Console</h4><p>วิธีเป็นการแก้ไขแบบ Manual ทีละไฟล์ วิธีการคือ</p><ol><li>เข้าไปที่ Cloud Storage</li><li>เข้าไปที่ Bucket ที่เก็บไฟล์ที่ต้องการแก้ไข</li><li>คลิกที่เมนู 3 dots ด้านหลังไฟล์ แล้วเลือก Edit metadata</li><li>แก้ไขตรงส่วน Cache-Control โดยโครงสร้างการกำหนดค่าจะเป็นประมาณนี้</li></ol><pre>Cache-Control: public,max-age=31536000,immutable</pre><p>แบ่งเป็นส่วนๆ แบบนี้</p><ol><li>public vs private</li></ol><p>คือการกำหนดสิทธในการ cache ไฟล์นั้นๆ มี 2 ประเภท<br>public : ไฟล์นี้ใช้กับทุกคนเหมือนกัน<br>private: ไฟล์นี้เฉพาะบุคคล เช่น หลังจาก login</p><p>2. max-age — อายุของ cache</p><p>ตัวนี้จะเป็นการกำหนดว่า สามารถใช้ไฟล์จาก cache ได้ โดยไม่ต้องถาม server ใหม่นานขนาดไหน โดยหน่วยที่กำหนดเป็น วินาที เช่น max-age=31536000 ก็คือเป็นนาน 1 ปีเลย</p><p>3. immutable vs must-revalidate</p><p>คือการกำหนดว่า ถ้า max-age หมดอายุแล้ว จะต้องทำอย่างไรต่อ โดย<br><strong>immutable</strong> : คือ การบอก browser ว่าไฟล์นี้ “ไม่มีทางเปลี่ยน” ประเภทนี้จะเหมาะกับไฟล์ที่ไม่เปลี่ยนแน่ๆ หรือ ถ้าเปลี่ยนก็จะเปลี่ยนชื่อไฟล์ไปเลย<br><strong>must-revalidate </strong>: คือ การบอก browser ว่าให้กลับมาโหลดไฟล์ใหม่ที่ server</p><h4>วิธีที่ 2 : ตั้งค่า Cache-Control ตอน Upload</h4><p>วิธีนี้เป็นวิธีที่แนะนำที่สุด เพราะกำหนดตั้งแต่ตอน Upload ไฟล์เลย เราสามารถกำหนดได้เลยว่าไฟล์ประเภทไหนควรจะตั้ง Cache Control แบบไหน โดยใส่ metadata ตอน upload file ได้เลยครับ ตัวอย่าง</p><pre>await bucket.upload(filePath, {<br>  destination: destinationPath,<br>  metadata: {<br>    contentType: &#39;video/mp4&#39;,<br>    cacheControl: &#39;public, max-age=86400&#39;<br>  }<br>})</pre><h4>วิธีที่ 3: แก้ไข Cache-Control ด้วย gsutil</h4><p>วิธีนี้จะเหมาะกับกรณีที่เรามีไฟล์เก่าๆ อยู่เยอะ และต้องการแก้ไขในทีเดียว โดยไม่กระทบไฟล์ และไม่ต้องอัปโหลดใหม่</p><p>โดยเจ้า gsutil คือ CLI สำหรับจัดการ Google Cloud Storage นั่นเองครับ โดยให้เราเปิด shell ใน Google Cloud Console แล้วใช้คำสั่งประมาณนี้ครับ</p><pre>gsutil -m setmeta \<br>  -h &quot;Cache-Control:public,max-age=86400&quot; \<br>  gs://your-bucket/videos/**</pre><p>อธิบาย:</p><ul><li>-m → ทำงานแบบ parallel (เร็วขึ้น)</li><li>setmeta → แก้ metadata</li><li>Cache-Control → header ที่ต้องการ</li><li>gs://your-bucket/videos/** → ครอบคลุมไฟล์ทั้งหมดใน path videos ใน bucket นี้</li></ul><h3>ส่งท้าย</h3><p>การใช้ Cloud ทำให้เราสร้างระบบได้เร็ว scale ได้ง่าย และไม่ต้องปวดหัวกับ infrastructure เหมือนสมัยก่อน แต่สิ่งหนึ่งที่ต้องระวังเสมอคือ <strong>ค่าใช้จ่าย </strong>เพราะ Cloud ส่วนใหญ่ คิดเงินตามการใช้งานจริง</p><p>หวังว่าบทความนี้จะช่วยให้ใครที่ใช้ Firebase Storage ลองกลับไปดูระบบของตัวเอง แล้วลดค่าใช้จ่ายที่ไม่จำเป็นลงได้บ้างนะครับ 🙂</p><p>ขอบคุณที่อ่านจนจบครับ 🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29d053a85da2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/firebasethailand/tuning-firebase-storage-%E0%B9%83%E0%B8%AB%E0%B9%89%E0%B9%80%E0%B8%A3%E0%B9%87%E0%B8%A7%E0%B8%82%E0%B8%B6%E0%B9%89%E0%B8%99-%E0%B9%81%E0%B8%A5%E0%B8%B0%E0%B8%84%E0%B9%88%E0%B8%B2%E0%B9%83%E0%B8%8A%E0%B9%89%E0%B8%88%E0%B9%88%E0%B8%B2%E0%B8%A2%E0%B8%A5%E0%B8%94%E0%B8%A5%E0%B8%87-29d053a85da2">Tuning Firebase Storage ให้เร็วขึ้น ⚡ และค่าใช้จ่ายลดลง 💸</a> was originally published in <a href="https://medium.com/firebasethailand">Firebase Thailand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Firestore เปิด Region ใหม่ Bangkok แล้ว! ถึงเวลาย้ายระบบมาใกล้ผู้ใช้ไทย]]></title>
            <link>https://medium.com/firebasethailand/firestore-%E0%B9%80%E0%B8%9B%E0%B8%B4%E0%B8%94-region-%E0%B9%83%E0%B8%AB%E0%B8%A1%E0%B9%88-bangkok-%E0%B9%81%E0%B8%A5%E0%B9%89%E0%B8%A7-%E0%B8%96%E0%B8%B6%E0%B8%87%E0%B9%80%E0%B8%A7%E0%B8%A5%E0%B8%B2%E0%B8%A2%E0%B9%89%E0%B8%B2%E0%B8%A2%E0%B8%A3%E0%B8%B0%E0%B8%9A%E0%B8%9A%E0%B8%A1%E0%B8%B2%E0%B9%83%E0%B8%81%E0%B8%A5%E0%B9%89%E0%B8%9C%E0%B8%B9%E0%B9%89%E0%B9%83%E0%B8%8A%E0%B9%89%E0%B9%84%E0%B8%97%E0%B8%A2-6e38959776bf?source=rss-655fb7ee2ef3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e38959776bf</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[firestore]]></category>
            <category><![CDATA[regions]]></category>
            <category><![CDATA[bangkok]]></category>
            <dc:creator><![CDATA[PamornT]]></dc:creator>
            <pubDate>Thu, 15 Jan 2026 05:28:42 GMT</pubDate>
            <atom:updated>2026-01-19T07:37:11.434Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oyp1Y9DKu-q4zGy7WOrQiw.png" /></figure><p>Google Firestore เปิดตัว <strong>region ใหม่ asia-southeast3 (Bangkok)</strong> อย่างเป็นทางการแล้ว 🎉 <br>บอกเลยว่างานนี้ถูกใจคนทำแอปในประเทศไทยสุดๆ เพราะ data อยู่ใกล้ผู้ใช้มากขึ้นกว่าเดิม</p><p>ลองไปไล่ดูรายละเอียดมา พบว่ามี <strong>ข้อดีหลักๆ อยู่ 2 เรื่องที่เห็นผลชัดมาก</strong></p><p>อย่างแรกคือ <strong>ความเร็ว</strong> — สำหรับผู้ใช้งานในไทย latency ลดลงอย่างเห็นได้ชัด แอปตอบสนองไวขึ้นแบบรู้สึกได้ทันที</p><p>อย่างที่สองคือ <strong>เรื่องราคา</strong> — ค่าใช้จ่ายถูกลงกว่าการใช้ region <strong>asia-southeast1 (Singapore)</strong> พอสมควร โดยเฉพาะสำหรับระบบที่มี traffic เยอะหรือใช้งาน Firestore หนักๆ ลองดูราคาเปรียบเทียบที่ด้านล่างนี้ได้เลยครับ</p><p><strong>asia-southeast1 (Singapore)<br></strong>Document reads² $0.0369 per 100,000 documents<br>Document writes $0.1107 per 100,000 documents<br>Document deletes $0.0123 per 100,000 documents<br>Stored data $0.1846 GiB/month</p><p><strong>asia-southeast3 (Bangkok)<br></strong>Document reads² $0.0315 per 100,000 documents<br>Document writes $0.0945 per 100,000 documents<br>Document deletes $0.0105 per 100,000 documents<br>Stored data $0.1575 GiB/month</p><p>เจอข้อดีขนาดนี้แล้ว จะรออะไรอยู่ล่ะค้าบ 😄<br>ถึงเวลาย้าย Firestore มาใช้ <strong>region ใหม่ Bangkok (asia-southeast3)</strong> กันได้แล้ว</p><p>การย้ายครั้งนี้ต้องทำผ่าน <strong>Google Cloud Console</strong> โดยตรงนะครับ เพราะ Firestore ยังไม่สามารถเปลี่ยน region ของ database เดิมได้แบบคลิกเดียว จำเป็นต้องมีขั้นตอนวางแผนและย้ายข้อมูลอย่างถูกวิธี แต่ข่าวดีคือ <strong>ทำได้ไม่ยาก</strong> และสามารถจัดการให้ downtime ต่ำมาก หรือแทบไม่มีเลย</p><h3>เริ่มกันเลย</h3><ol><li>เข้าไปที่ <a href="https://console.cloud.google.com/">Google Cloud Console</a></li><li>ก่อนอื่น เราต้องเตรียม <strong>ที่เก็บไฟล์สำหรับ export ข้อมูล</strong> ก่อนนะครับ ให้เข้าไปที่ <strong>Google Cloud Storage</strong> แล้วสร้าง <strong>Bucket ใหม่</strong> ขึ้นมา <br>ในขั้นตอนการสร้าง Bucket ให้ตั้งค่า <strong>Location type เป็นแบบ Multi-region</strong> และเลือก <strong>region เป็น Asia <br></strong>เหตุผลที่ต้องเลือกแบบนี้ เพราะเราจะทำการย้ายข้อมูล <strong>ข้าม region</strong> (จาก Singapore ไป Bangkok) ซึ่ง Cloud Storage แบบ Multi-region จะรองรับการ export/import ข้อมูลได้ไม่มีปัญหา</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*ncoJeWxlBEammtJeHqHGAA.png" /></figure><p>เมื่อสร้าง Bucket เสร็จเรียบร้อยแล้ว เราก็พร้อมสำหรับขั้นตอนถัดไปในการย้าย Firestore ข้อมูลครับ 🚀</p><p>3. ต่อมาให้เข้าไปที่ product firestore ถ้าหาเมนูไม่เจอให้ search เอาได้เลยค้าบ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s-fef-J21EEiXrC0sgRuqg.png" /></figure><p>4. เข้ามาแล้วจะเจอ database firestore ตัว default ที่เรามีอยู่แล้ว จะสามารถดูได้เลยว่า database เดิมเรา อยู่ที่ region ไหน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xWvDyx-icS24EN9txLwzAg.png" /></figure><p>5. สร้าง Firestore database ใหม่ โดยการคลิกปุ่ม Create Firestore database ทำการกำหนด database-id ตั้งชื่อตามใจเราเลย แล้วเลือก region เป็น asia-southeast3 (Bangkok)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*NfKzHgsn6fd_TojIH7tO3g.png" /></figure><p>6. สร้าง database เสร็จแล้ว ก็จะได้ database มา 2 database แล้วค้าบ ลองตรวจสอบ region ให้เรียบร้อยว่าถูกต้องแล้ว</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7NR6JxgFz42XTy0ohcApcQ.png" /></figure><p>7. ต่อมาให้เราคลิกเลือกที่ database ตัวหลักที่เราต้องการ export data ออกมา ในที่นี้คือ database (default)</p><p>8. เมื่อเข้ามาที่ database ตัวหลักแล้วให้เข้าไปที่เมนู Import/Export</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*rvPgPqT2VgL9s04xUA6L9w.png" /></figure><p>9. คลิกที่ปุ่ม Export แล้วทำการเลือก Bucket ที่เราสร้างไว้ในขั้นตอนที่ 2 แล้วคลิกปุ่ม Select แล้วคลิก Export เพื่อเริ่มทำงานได้เลย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fnfgsfufg914cWoOYlyFKw.png" /></figure><p>10. เมื่อ export เสร็จเรียบร้อยแล้ว ก็จะมีรายการขึ้นมาให้เห็นบนหน้า Import/Export ครับ โดยจะมีการบอกด้วยว่า export นี้มี Collection อะไรบ้าง ในที่นี้คือ All Collections</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rzRxxZu-j0jFQnkWID4-_A.png" /></figure><p>11. จากนั้นให้เรากลับไปที่ All database แล้วเข้าไปที่ database ตัวที่เราสร้างใหม่ ที่อยู่ region asia-southeast3 จะพบ database เปล่าๆ แบบนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i5of0Ndhtz3HEVazWQzhQw.png" /></figure><p>12. ให้คลิกเข้าไปที่เมนู Import/Export แล้วคลิกที่ปุ่ม Import</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*nOHnwbIMeW2Cos4TXN0_LQ.png" /></figure><p>13. กดปุ่ม Browse แล้วทำการเลือกไฟล์ที่เรา export ไว้จากขั้นตอนก่อนหน้า แล้วทำการกดปุ่ม Select แล้ว กดปุ่ม Import เพื่อเริ่ม Import database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VuoBhfQRkGiT4k-BWa3HdA.png" /></figure><p>14. เมื่อ import เสร็จแล้วก็จะขึ้นหน้าตาแบบนี้ครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypNyjS-CyZLxPM415-ZlwA.png" /></figure><p>15. ทดสอบเข้าที่เมนู Firestore Studio ก็จะพบข้อมูลทั้งหมดได้ถูก import เรียบร้อยแล้ววว \(^o^)/</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I0f2ScsCowakrDPcomAi1A.png" /></figure><p>เพียงเท่านี้ก็สามารถย้าย <strong>Firestore Database</strong> มาใช้งานใน <strong>Region ใหม่ (Bangkok)</strong> ได้เรียบร้อยแล้วครับ<br>ขั้นตอนไม่ได้ยุ่งยากอย่างที่หลายคนคิด แค่เตรียม <strong>Cloud Storage Bucket</strong> สำหรับรองรับไฟล์ จากนั้นทำการ <strong>export และ import ข้อมูล</strong> ก็จบกระบวนการย้ายได้เลย</p><p>ขอฝากข้อมูลเพิ่มเติมเรื่อง <strong>ค่าใช้จ่าย</strong> นิดหนึ่งนะครับ<br>ในการ import/export ข้อมูล Google จะคิดค่าใช้จ่ายตาม <strong>rates เดียวกับการอ่านและเขียนเอกสาร (document reads &amp; writes)</strong> ดังนั้นก่อนย้าย แนะนำให้ประเมินปริมาณข้อมูลคร่าวๆ เพื่อคุมงบประมาณให้เหมาะสม</p><p>หวังว่าบทความนี้จะช่วยให้การย้าย Firestore มาใช้ <strong>Bangkok Region</strong> เป็นเรื่องที่ง่ายและตัดสินใจได้เร็วขึ้น ขอบคุณมากครับ 🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e38959776bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/firebasethailand/firestore-%E0%B9%80%E0%B8%9B%E0%B8%B4%E0%B8%94-region-%E0%B9%83%E0%B8%AB%E0%B8%A1%E0%B9%88-bangkok-%E0%B9%81%E0%B8%A5%E0%B9%89%E0%B8%A7-%E0%B8%96%E0%B8%B6%E0%B8%87%E0%B9%80%E0%B8%A7%E0%B8%A5%E0%B8%B2%E0%B8%A2%E0%B9%89%E0%B8%B2%E0%B8%A2%E0%B8%A3%E0%B8%B0%E0%B8%9A%E0%B8%9A%E0%B8%A1%E0%B8%B2%E0%B9%83%E0%B8%81%E0%B8%A5%E0%B9%89%E0%B8%9C%E0%B8%B9%E0%B9%89%E0%B9%83%E0%B8%8A%E0%B9%89%E0%B9%84%E0%B8%97%E0%B8%A2-6e38959776bf">Firestore เปิด Region ใหม่ Bangkok แล้ว! ถึงเวลาย้ายระบบมาใกล้ผู้ใช้ไทย</a> was originally published in <a href="https://medium.com/firebasethailand">Firebase Thailand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LINE Chatbot x Gemini API สร้างนักโภชนาการเอาใจสาย Healthy ep1.]]></title>
            <link>https://medium.com/linedevth/line-chatbot-x-gemini-api-%E0%B8%AA%E0%B8%A3%E0%B9%89%E0%B8%B2%E0%B8%87%E0%B8%99%E0%B8%B1%E0%B8%81%E0%B9%82%E0%B8%A0%E0%B8%8A%E0%B8%99%E0%B8%B2%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%80%E0%B8%AD%E0%B8%B2%E0%B9%83%E0%B8%88%E0%B8%AA%E0%B8%B2%E0%B8%A2-healthy-ep1-087a35315dfb?source=rss-655fb7ee2ef3------2</link>
            <guid isPermaLink="false">https://medium.com/p/087a35315dfb</guid>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[linedevth]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[PamornT]]></dc:creator>
            <pubDate>Mon, 11 Mar 2024 00:51:44 GMT</pubDate>
            <atom:updated>2024-03-11T03:49:56.710Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HKwUyJD0e__gwmZ160Rkgg.png" /></figure><p>ปัจจุบัน AI เข้ามามีบทบาทกับเราในหลายๆ ด้าน ไม่ว่าจะเป็นการทำงาน หรือ ชีวิตประจำวัน ผมขอยกสักหนึ่งตัวอย่าง คือ การสร้าง AI เป็นนักโภชนาการ ที่จะช่วยแนะนำอาหารที่เหมาะสมกับเรา เพราะ AI ปัจจุบันฉลาดมากๆ สามารถเรียนรู้จากรูปภาพได้ทันทีว่าคือเมนูอาหารอะไร และ โภชนาการเป็นอย่างไร</p><p>บทความนี้เป็น <strong>ep1. จะเริ่มต้นที่บันทึกพฤติกรรมการบริโภคของ user พร้อมทั้งจำแนกข้อมูลโภชนาการต่างๆ</strong> ว่าอาหารแต่ละประเภทให้ พลังงาน, คอเลสเตอรอล, ไขมัน ฯลฯ ปริมาณเท่าไหร่ และสรุปปริมาณโภชนาการแต่ละประเภทเป็นรายวัน</p><p><strong>โดยเราจะใช้ LINE Chatbot เชื่อมต่อกับ Gemini API แบบ Multimodal โดยวิธีใช้งานเพียงให้ user ถ่ายรูปอาหารเท่านั้น ก็สามารถบันทึกโภชนาการต่างๆ ได้เลย</strong></p><p>ใครยังนึกไม่ออกลองดูคลิปตัวอย่างนี้ได้ก่อนเลยครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*gWd9bDS3LbPam5Ks.gif" /></figure><h4><strong>พร้อมแล้วเริ่มกันเลย</strong></h4><h4>1. สร้าง Provider และ Channel</h4><p>ใครที่ยังไม่เคยสร้าง Provider และ Channel สำหรับ LINE Chatbot มาก่อน ก็ให้อ่านบทความปฐมบทด้านล่างนี้ แต่ใครที่คุ้นเคยอยู่แล้วให้ข้ามขั้นตอนนี้ไปได้เลย</p><p><a href="https://medium.com/linedevth/%E0%B8%9B%E0%B8%90%E0%B8%A1%E0%B8%9A%E0%B8%97%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%AA%E0%B8%A3%E0%B9%89%E0%B8%B2%E0%B8%87-line-bot-b2cb90643901">ปฐมบทการสร้าง LINE Chatbot (ฉบับอัพเดท 2024)</a></p><h4>2. ติดตั้ง Cloud Functions for Firebase</h4><p>ใครที่ยังไม่เคยพัฒนาโปรแกรมด้วย Cloud Functions for Firebase มาก่อน ก็ให้อ่านบทความด้านล่างนี้(โดยเฉพาะข้อ 2) แต่สำหรับคนที่คุ้นเคยแล้วให้ข้ามไปได้เลย</p><p><a href="https://medium.com/firebasethailand/cloud-functions-for-firebase-2nd-gen-cdda33bbd7dd">รู้จัก Cloud Functions for Firebase 2nd Gen ตั้งแต่ Zero จนเป็น Hero</a></p><h4>3. สร้าง Webhook / Messaging API / Gemini</h4><p>ใครที่ยังไม่เคยพัฒนาโปรแกรมสร้าง Webhook เพื่อเชื่อมต่อกับ Gemini มาก่อน ให้อ่านบทความด้านล่างนี้ก่อนนะครับ เพราะต่อจากนี้เราจะ Clone Git จากบทความด้านล่างนี้เพื่อต่อยอดไอเดียเรากันนะครับ</p><p><a href="https://medium.com/linedevth/linebot-x-gemini-9cd2dc22d9c9">สร้าง LINE Chatbot x Gemini(Gen AI ที่เก่งที่สุดของ Google) ด้วย Cloud Functions for Firebase</a></p><h3>4. Fork Repository</h3><p>เราจะ Fork Repository ต้นแบบจากคุณตี๋ เพื่อสร้าง Repository ของเราเอง เข้าไปที่ GitHub ด้านล่างนี้เลยครับ</p><p><a href="https://github.com/jirawatee/LINE-Chatbot-x-Gemini-API/tree/main">GitHub - jirawatee/LINE-Chatbot-x-Gemini-API: A repo of building Gen AI Chatbot with Gemini by using LINE Messaging API and Cloud Functions for Firebase 2nd Gen</a></p><p>คลิกที่เมนู Fork ด้านขวาบนหน้าจอ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZNk3BXCgzPKM_SdBlA9zdQ.png" /></figure><p>ทำการตั้งชื่อ Repository ของเราเอง แล้ว คลิกที่ปุ่ม Create fork</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Avr_r3MDSuiapPnAyJEJ4g.png" /></figure><p>หลังจากสร้าง Repository เสร็จแล้วให้ทำการ Clone Repository ลงเครื่องของเราได้เลย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UOKHp0_EKZmF17Q-O310Bw.png" /><figcaption>copy Repository URL</figcaption></figure><pre>git clone https://github.com/PamornT/LINE-Chatbot-x-Gemini-API.git</pre><h3>5. Firebase Init &amp; Setup Environment</h3><p>หลังจาก Clone Git มาเสร็จแล้ว เราต้องทำการ Firebase Initial เพื่อกำหนด Firebase Project ก่อน จะได้ Deploy ขึ้นไปใช้งานได้ครับ</p><p>เข้าไปที่ Folder ที่เรา Clone มา</p><pre>cd LINE-Chatbot-x-Gemini-API</pre><p>สั่ง Firebase init</p><pre>LINE-Chatbot-x-Gemini-API % firebase init</pre><p>จากนั้นให้เราเลือกข้อมูลที่จะติดตั้งตามนี้ครับ</p><p>Firebase features : กด Spacebar เลือก Firestore / Functions / Storage<br>Firebase project : เลือก Project ของเราได้เลย<br>Would you like to initialize a new codebase, or overwrite : เลือก Overwrite</p><p>จากนั้น Enter ยาวๆ ได้เลยครับ</p><p>ถัดไปให้สร้างไฟล์ <strong>/functions/.env</strong> แล้วให้ไป copy ค่า <strong>Channel Access Token</strong> ของ Messaging API Channel ใน <a href="https://developers.line.biz/console/">LINE Developers console</a> มาระบุ และค่า API Key ทีได้จาก Gemini มาระบุ</p><pre>CHANNEL_ACCESS_TOKEN=YOUR-CHANNEL-ACCESS-TOKEN<br>API_KEY=YOUR-GEMINI-API-KEY</pre><p>จากนั้นให้เข้าไปที่ folder functions แล้วทำการ install dependency ต่างๆ แล้วทดสอบ deploy functions ด้วยคำสั่งด้านล่างนี้</p><pre>cd functions<br>firebase deploy --only functions</pre><p>เมื่อ deploy เสร็จเรียบร้อยเราจะเห็น Webhook URL โผล่อยู่ใน command line เลย ก็ให้เรา copy มา หรือกรณีที่ไม่พบก็ให้เข้าไปที่ <a href="https://console.firebase.google.com/">Firebase console</a> เลือกโปรเจคที่เราสร้างไว้ แล้วเลือกเมนู Build &gt; Functions จะเจอชื่อฟังก์ชันและ Webhook URL ที่นั่น</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXpfM72otDWhf1lkHkF56Q.png" /></figure><p>เมื่อได้ Webhook URL มาแล้ว ก็เอา URL นี้ไปอัพเดทที่ <strong>Messaging API Channel</strong> ใน <a href="https://developers.line.biz/console/">LINE Developers console</a> ได้เลย และตรวจสอบให้มั่นใจว่าได้เปิดใช้ <strong>Use webhook</strong> ด้วยแล้ว</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jBfAc6rREnc1uk7UHTNsiw.png" /></figure><h4>6. แก้ไข Prompt ใน multimodal</h4><p>ขั้นตอนนนี้เราจะแก้ไขข้อความ prompt เพื่อให้ Gemini ช่วยเราในการแปลงรูปภาพอาหารของเราเป็นข้อมูลโภชนาการ พลังงาน แคลลอรี่ ต่างๆ ตามโจทย์ที่เราต้องการ</p><p>เข้าไปที่ไฟล์ util &gt; gemini.js <br>แก้ไขข้อความ prompt ที่บรรทัด 14 ใน function multimodalโดยแก้ไขดังนี้ครับ</p><pre>const prompt = &quot;ขอคำตอบรูปแบบนี้ **ชื่ออาหาร** ขอปริมาณต่อไปนี้เป็นข้อๆ -พลังงาน, -น้ำตาล, -ไขมัน, -โปรตีน, -คอเลสเตอรอล, -คาร์โบไฮเดรต, -ใยอาหาร, -โซเดียม &quot;;</pre><p>ผลลัพธ์หลังจากเปลี่ยน prompt เมื่อส่งรูปไป จะได้ผลลัพธ์เป็นชื่อ รายละเอียดโภชนาการต่างๆ เช่น พลังงาน, ไขมัน, โปรตีน ฯลฯ ตามรูปด้านล่างเลยครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dEGPRoFLShJCw2eHboNgkw.jpeg" /></figure><h4>7. Extract Data Gemini Response</h4><p>ถัดไปเราจะ Extract ข้อมูลออกมาจาก Response ของ Geminiให้เป็นโครงสร้างเพื่อให้ง่ายในการนำไปใช้ต่อ ทำสรุปผลรวมค่าโภขนาการต่างๆ โดยข้อมูลจะเป็นตามด้านล่างนี้</p><ul><li>ชื่อเมนูอาหาร เป็น Text</li><li>รายการโภชนาการต่าง เป็น Array 3 ส่วน ชื่อ, ปริมาณ, หน่วย</li></ul><p>ถัดไปให้เราสร้างไฟล์ /functions/utils/util.js แล้ว copy โค้ดด้านล่างนี้ไปวาง โดยเราจะสร้างฟังก์ชั่น สำหรับ extractData และสำหรับ getCurrentDate เผื่อไว้ใช้สำหรับขั้นตอนถัดๆ ไปด้วยเลยครับ</p><pre>const extractData = async (message) =&gt; {<br>   const titleMatch = /\*\*(.*?)\*\*/.exec(message);<br>   const title = titleMatch ? titleMatch[1] : null;<br><br>   const dataMatches = /[\*-]\s*(.*?)\s+([\d,]+(?:\.\d+)?)\s*(\S+)/g;<br>   const extractedData = [];<br>   let match;<br>   while ((match = dataMatches.exec(message)) !== null) {<br>      extractedData.push({<br>         title: match[1].replace(&#39;-&#39;, &#39;&#39;).replace(&#39;*&#39;, &#39;&#39;).trim(),<br>         number: match[2].replace(&#39;,&#39;, &#39;&#39;),<br>         unit: match[3],<br>      });<br>   }<br><br>   return {<br>      title: title,<br>      items: extractedData<br>   }<br>}<br><br>const padTwoDigits = (number) =&gt; {<br>   return number &lt; 10 ? &#39;0&#39; + number : number;<br>}<br><br>const dateFormat = (dateTarget) =&gt; {<br>   const now = dateTarget;<br><br>   const year = now.getFullYear();<br>   const month = padTwoDigits(now.getMonth() + 1); // Months are zero-based<br>   const day = padTwoDigits(now.getDate());<br>   const hours = padTwoDigits(now.getHours());<br>   const minutes = padTwoDigits(now.getMinutes());<br>   const seconds = padTwoDigits(now.getSeconds());<br><br>   const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;<br>   return formattedDateTime<br>}<br><br>const getTodayDateThai = () =&gt; {<br>   const options = { year: &#39;numeric&#39;, month: &#39;long&#39;, day: &#39;numeric&#39; };<br>   const thaiDate = new Date().toLocaleDateString(&#39;th-TH&#39;, options);<br>   return thaiDate<br>}<br><br>const summaryMenu = async (docs) =&gt; {<br>   let summary = []<br>   await docs.forEach((doc) =&gt; {<br>      const data = doc.data()<br>      const details = data.detail<br>      details.forEach((detail) =&gt; {<br>         let title = detail.title<br>         detail.number = parseInt(detail.number)<br>         console.log(detail)<br>         if (Object.keys(summary).indexOf(title) &lt; 0) {<br>            summary[title] = detail<br>         } else {<br>            summary[title][&#39;number&#39;] += parseInt(detail.number)<br>         }<br>         console.log(summary)<br>      })<br>   });<br>   return summary<br>}<br><br>module.exports = { extractData, dateFormat, summaryMenu, getTodayDateThai };</pre><p>จากนั้นกลับไปที่ไฟล์ /functions/index.js แล้ว import util ที่ด้านบนไฟล์</p><pre>const util = require(&quot;./utils/util&quot;)</pre><p>แล้วเพิ่มโค้ดบรรทัดนี้เพื่อเรียกใช้ฟังก์ชั่น util.extractData ตรงหลังจากที่ได้ผลลัพธ์ msg จาก gemini.multimodal</p><pre>  const detail = util.extractData(msg)</pre><p>ผลลัพธ์ที่ได้จากการ extract data จะได้เป็นแบบนี้ครับ</p><pre>{<br>  &quot;title&quot;: &quot;ข้าวมันไก่&quot;,<br>  &quot;items&quot;: [<br>    {<br>      &quot;title&quot;: &quot;พลังงาน&quot;, &quot;number&quot;: &quot;475&quot;, &quot;unit&quot;: &quot;กิโลแคลอรี&quot;<br>    },<br>    {<br>      &quot;title&quot;: &quot;ไขมัน&quot;, &quot;number&quot;: &quot;23&quot;, &quot;unit&quot;: &quot;กรัม&quot;<br>    },<br>    {<br>      &quot;title&quot;: &quot;คาร์โบไฮเดรต&quot;, &quot;number&quot;: &quot;49&quot;, &quot;unit&quot;: &quot;กรัม&quot;<br>    },<br>    {<br>      &quot;title&quot;: &quot;โปรตีน&quot;, &quot;number&quot;: &quot;33&quot;, &quot;unit&quot;: &quot;กรัม&quot;<br>    },<br>    {<br>      &quot;title&quot;: &quot;ใยอาหาร&quot;, &quot;number&quot;: &quot;1&quot;, &quot;unit&quot;: &quot;กรัม&quot;<br>    },<br>    {<br>      &quot;title&quot;: &quot;น้ำตาล&quot;, &quot;number&quot;: &quot;1&quot;, &quot;unit&quot;: &quot;กรัม&quot;<br>    },<br>    {<br>      &quot;title&quot;: &quot;โซเดียม&quot;, &quot;number&quot;: &quot;1000&quot;, &quot;unit&quot;: &quot;มิลลิกรัม&quot;<br>     }<br>   ]<br>}</pre><h4>8. Upload รูปเข้าไปเก็บไว้ที่ Firebase Storage</h4><p>เราจะนำรูปอาหารที่ user ส่งมาเก็บไว้ที่ Storage ด้วย เพื่อใช้ในการแสดงข้อมูลประวัติการกินให้ user เห็นด้วยว่า กินอะไรไปบ้างและ รายละเอียดโภชนาการเป็นอะไรบ้าง</p><p>เริ่มต้นให้เราเพิ่มค่า Config ที่ไฟล์ /functions/.env ตามด้านล่างนี้ครับ</p><pre>BUCKET_URL=YOUR-BUCKET-URL</pre><p>โดยเราสามารถหา Bucket URL ได้จากเมนู Storage ที่ Firebase ครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2B1v6LwcWb1PmV2inc8xg.png" /></figure><p>ถัดไปให้สร้างไฟล์ที่ /functions/utils/firebase.js แล้ว copy โค้ดด้านล่างนี้ไปวาง</p><pre>const admin = require(&quot;firebase-admin&quot;);<br>const util = require(&quot;./util&quot;)<br>admin.initializeApp();<br><br>const saveMenu = async (messageId, data) =&gt; {<br>   await admin.firestore().collection(&quot;Menu&quot;).doc(`${messageId}`).set(data);<br>}<br><br>const updateMenuEat = async (messageId) =&gt; {<br>   await admin.firestore().collection(&quot;Menu&quot;).doc(`${messageId}`).update({status: &#39;eat&#39;});<br>}<br><br>const getMenuToday = async (userId) =&gt; {<br>   const currentDate = new Date();<br>   currentDate.setHours(0, 0, 0, 0);<br><br>   let startDate = currentDate;<br>   let endDate = new Date(currentDate);<br>   endDate.setDate(endDate.getDate() + 1);<br><br>   startDate = util.dateFormat(startDate)<br>   endDate = util.dateFormat(endDate)<br><br>   const query = admin.firestore().collection(&quot;Menu&quot;)<br>      .where(&#39;userId&#39;, &#39;=&#39;, userId)<br>      .where(&#39;status&#39;, &#39;=&#39;, &#39;eat&#39;)<br>      .where(&#39;createDate&#39;, &#39;&gt;=&#39;, startDate)<br>      .where(&#39;createDate&#39;, &#39;&lt;&#39;, endDate);<br><br>   // Execute the query<br>   return await query.get()<br>      .then((docs) =&gt; {<br>         return docs<br>      })<br>      .catch((error) =&gt; {<br>         console.error(&#39;Error getting documents: &#39;, error);<br>         return []<br>      });<br>}<br><br>const upload2Storage = async (messageId, binaryData) =&gt; {<br>   const { Storage } = require(&#39;@google-cloud/storage&#39;);<br>   const storage = new Storage();<br>   const fileName = `upload/${messageId}.jpg`;<br>   const bucket = storage.bucket(process.env.BUCKET_URL);<br>   const file = bucket.file(`${fileName}`);<br>   const contentType = &#39;image/jpeg&#39;;<br><br>   const stream = file.createWriteStream({<br>      metadata: {<br>         contentType: contentType,<br>      },<br>   });<br><br>   stream.end(binaryData);<br>   let publicUrl = &#39;&#39;<br>   stream.on(&#39;finish&#39;, async() =&gt; {<br>      await file.makePublic();<br>      publicUrl = `https://storage.googleapis.com/${bucket.name}/${fileName}`;<br>   });<br><br>   // Handle errors during the upload<br>   stream.on(&#39;error&#39;, (err) =&gt; {<br>      console.error(&#39;Error uploading binary data:&#39;, err);<br>   });<br><br>   return `https://storage.googleapis.com/${bucket.name}/${fileName}`<br>}<br><br>module.exports = { saveMenu, updateMenuEat, getMenuToday, upload2Storage };</pre><p>จากนั้นกลับไปที่ไฟล์ /functions/index.js แล้ว import firebase ที่ด้านบน</p><pre>const firebase = require(&quot;./utils/firebase&quot;)</pre><p>แล้วเพิ่มโค้ดบรรทัดนี้เพื่อเรียกใช้ฟังก์ชั่น firebase.upload2Storage ต่อจาก Extract Data ในข้อที่ 7 ก่อนหน้านี้ตามนี้ครับ</p><pre>const detail = util.extractData(msg)<br>const publicURL = firebase.upload2Storage(event.message.id, imageBinary)</pre><p>เป็นอันเสร็จขั้นตอนการ Upload file ขึ้น Storage เป็นที่เรียบร้อยครับ</p><h4>9. บันทึกข้อมูลลง Firestore</h4><p>ขั้นตอนนี้เราจะบันทึกข้อมูลลง Firestore โดยเราจะเก็บเป็น โครงสร้างแบบนี้ครับ</p><pre>Menu/[Message ID]/[รายการอาหาร]</pre><p>โดยจะเก็บข้อมูลตามนี้ครับ</p><ul><li>msg : ข้อความที่ Gemini ตอบกลับมา</li><li>title : ชื่อเมนูอาหาร</li><li>detail : ข้อมูลโภชนาการ</li><li>publicURL : รูปอาหาร</li><li>createDate : วันเวลาที่สร้างข้อมูล</li><li>userId: LINE UserId</li><li>status: “analyze”</li></ul><p>มีการเพิ่ม status ลงไปด้วยโดยใส่ค่าเป็น analyze เราจะใช้ status ในการแบ่งว่า user เลือกกินเมนูนี้รึป่าว หรือแค่ต้องการวิเคราะห์ (analyze) ดูเฉยๆ เท่านั้น</p><p>ต่อไปให้เราเพิ่มโค้ดด้านล่างนี้ที่ functions/index.js ต่อจากการสร้าง publicURL ในขั้นตอนก่อนหน้า</p><pre>const createDate = util.dateFormat(new Date())<br>const data = {<br>  msg,<br>  title: detail.title,<br>  detail: detail.items,<br>  publicURL,<br>  createDate,<br>  userId: event.source.userId,<br>  status: &#39;analyze&#39;<br>}<br>await firebase.saveMenu(event.message.id, data)</pre><p>เท่านี้เราก็จะบันทึกข้อมูลลง Firestore เรียบร้อยแล้ว</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-I3osDUEfjuYpie2CWSUpA.png" /><figcaption>ตัวอย่างข้อมูลที่บันทึกลง Firestore</figcaption></figure><h4>10. ส่งข้อความโภชนาการกลับหา User</h4><p>ขั้นตอนนี้เราจะส่งข้อความหา user โดยโค้ดเก่าที่เรา Clone มามีโค้ดสำหรับส่ง reply หา user อยู่แล้ว</p><p>แต่เราจะเพิ่มเติม quickReply เข้าไปในข้อความที่ส่งกลับหา user ด้วย เพื่อให้ user สามารถเลือกได้ว่า เลือกกินเมนูนี้หรือไม่ ถ้า user เลือกว่า “บันทึกการกิน” เมนูนี้ เราจะทำการเปลี่ยน status ใน Firestore เป็น “eat”</p><p>ให้เราเพิ่มโค้ดด้านล่างนี้ที่ functions/index.js ต่อจากการ Save ข้อมูลลง Firestore ในขั้นตอนก่อนหน้า เพื่อเตรียมรายละเอียดของ quickReply</p><pre>const quickReply = {<br>  &quot;items&quot;: [<br>    {<br>      &quot;type&quot;: &quot;action&quot;,<br>      &quot;action&quot;: {<br>        &quot;type&quot;: &quot;postback&quot;,<br>        &quot;label&quot;: &quot;บันทีกการกิน&quot;,<br>        &quot;data&quot;: `action=eat&amp;itemid=${event.message.id}`,<br>        &quot;displayText&quot;: &quot;ได้เลย ทานให้อร่อยนะครับ 🍽&quot;<br>      }<br>    }<br>  ]<br>}</pre><p>ต่อไปให้ทำการเพิ่ม quickReply เข้าไปที่ reply แบบโค้ดด้านล่างนี้ครับ</p><pre>await line.reply(event.replyToken, [{ type: &quot;text&quot;, text: msg, &quot;quickReply&quot;: quickReply}]);</pre><p>เท่านี้ก็เสร็จขั้นตอนการตอบกลับ user แล้วครับ 😅</p><p>หน้าตาหลังจากส่งไปแล้วจะเป็นประมาณนี้ และ หลังจาก user คลิกกลับมาจะได้ event postback กลับมาแบบนี้ครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TCH5OY8_zb4f9P9pK8dj1w.jpeg" /><figcaption>ตัวอย่างข้อความที่ส่งกลับหา user และ ตัวอย่าง event postback</figcaption></figure><h4>11. อัพเดทข้อมูล Status บน Firestore</h4><p>ขั้นตอนนี้เราจะดักจับ event postback ที่ user คลิก quickReply กลับมา เพื่อทำการเปลี่ยนสถานะรายการเมนูนั้นให้เป็น eat เพื่อให้เรารู้ว่าเมนูใดบ้างที่ user เลือกกินในแต่ละวัน</p><p>ให้เราเพิ่มโค้ดด้านล่างนี้ ใน switch (event.type) ต่อจาก case “message”</p><pre>case &quot;postback&quot;:<br>  const { data } = event.postback;<br>  const { action, itemid } = Object.fromEntries(new URLSearchParams(data));<br>  if (action === &#39;eat&#39;) {<br>    await firebase.updateMenuEat(itemid)<br>  }<br>  break;</pre><p>เท่านี้เราก็สามารถแยกได้แล้วว่าเมนูไหน eat หรือแค่ analyze ดูเฉยๆ การที่เราเก็บข้อมูล analyze ไว้ด้วย จะมีประโยชน์มากในการวิเคราะห์พฤติกรรมของ user ในอนาคตด้วย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZMtMkWItiS26VslOoe1Qmg.png" /><figcaption>ต้วอย่าง Document ใน Firestore หลังจาก update status</figcaption></figure><h4>12. ส่งข้อความสรุปรายวัน</h4><p>ขั้นตอนนี้เราจะเพิ่มเงื่อนไขให้ Webhook ว่าเมื่อได้รับข้อความจาก user ว่า “สรุป” ให้ส่ง Carousel ที่สรุป โภชนาการ ทั้งหมดที่มีการบันทึกการกินไว้ และ รายการอาหารทั้งหมดในวันปัจจุบันกลับไปให้ user</p><p>เริ่มต้น เราจะทำการสร้างไฟล์สำหรับเก็บ template Flex message ของเราก่อน ให้เราสร้างไฟล์ใหม่ที่ /functions/util/message.js และนำโค้ดด้านล่างนี้ไปใส่</p><pre>const todaySummaryFlex = (data) =&gt; (<br>   {<br>      &quot;type&quot;: &quot;flex&quot;,<br>      &quot;altText&quot;: &quot;Today Summary&quot;,<br>      &quot;contents&quot;: data<br>   }<br>)<br><br>const todayNoData = (date) =&gt; ({<br>   &quot;type&quot;: &quot;bubble&quot;,<br>   &quot;size&quot;: &quot;mega&quot;,<br>   &quot;hero&quot;: {<br>     &quot;type&quot;: &quot;image&quot;,<br>     &quot;url&quot;: &quot;https://firebasestorage.googleapis.com/v0/b/pamornt.appspot.com/o/flex_cover.jpg?alt=media&amp;token=6cbb6bf8-2f95-483e-b854-8d2f601d3786&quot;,<br>     &quot;size&quot;: &quot;full&quot;,<br>     &quot;aspectRatio&quot;: &quot;20:13&quot;,<br>     &quot;aspectMode&quot;: &quot;cover&quot;<br>   },<br>   &quot;body&quot;: {<br>     &quot;type&quot;: &quot;box&quot;,<br>     &quot;layout&quot;: &quot;vertical&quot;,<br>     &quot;spacing&quot;: &quot;md&quot;,<br>     &quot;contents&quot;: [<br>       {<br>         &quot;type&quot;: &quot;text&quot;,<br>         &quot;text&quot;: &quot;ยังไม่ได้บันทึกรายการอาหาร&quot;,<br>         &quot;size&quot;: &quot;lg&quot;,<br>         &quot;weight&quot;: &quot;bold&quot;<br>       },<br>       {<br>         &quot;type&quot;: &quot;text&quot;,<br>         &quot;text&quot;: `${date}`,<br>         &quot;margin&quot;: &quot;none&quot;,<br>         &quot;size&quot;: &quot;xs&quot;,<br>         &quot;color&quot;: &quot;#999999&quot;<br>       }<br>     ],<br>     &quot;paddingBottom&quot;: &quot;25px&quot;<br>   }<br> })<br><br>const todaySummaryCarousel = (bubble) =&gt; ({<br>   &quot;type&quot;: &quot;carousel&quot;,<br>   &quot;contents&quot;: bubble<br>})<br><br>const todaySummaryBubble = (total, date, items) =&gt; ({<br>   &quot;type&quot;: &quot;bubble&quot;,<br>   &quot;size&quot;: &quot;mega&quot;,<br>   &quot;hero&quot;: {<br>      &quot;type&quot;: &quot;image&quot;,<br>      &quot;url&quot;: &quot;https://firebasestorage.googleapis.com/v0/b/pamornt.appspot.com/o/flex_cover.jpg?alt=media&amp;token=6cbb6bf8-2f95-483e-b854-8d2f601d3786&quot;,<br>      &quot;size&quot;: &quot;full&quot;,<br>      &quot;aspectRatio&quot;: &quot;20:13&quot;,<br>      &quot;aspectMode&quot;: &quot;cover&quot;<br>   },<br>   &quot;body&quot;: {<br>      &quot;type&quot;: &quot;box&quot;,<br>      &quot;layout&quot;: &quot;vertical&quot;,<br>      &quot;spacing&quot;: &quot;md&quot;,<br>      &quot;contents&quot;: [<br>         {<br>            &quot;type&quot;: &quot;text&quot;,<br>            &quot;text&quot;: `บันทึกรวม ${total} รายการ`,<br>            &quot;size&quot;: &quot;xl&quot;,<br>            &quot;weight&quot;: &quot;bold&quot;<br>         },<br>         {<br>            &quot;type&quot;: &quot;text&quot;,<br>            &quot;text&quot;: `${date}`,<br>            &quot;margin&quot;: &quot;none&quot;,<br>            &quot;size&quot;: &quot;xs&quot;,<br>            &quot;color&quot;: &quot;#999999&quot;<br>         },<br>         {<br>            &quot;type&quot;: &quot;text&quot;,<br>            &quot;text&quot;: &quot;สรุปรายการโภชนาการ&quot;,<br>            &quot;size&quot;: &quot;lg&quot;,<br>            &quot;weight&quot;: &quot;bold&quot;,<br>            &quot;margin&quot;: &quot;xl&quot;<br>         },<br>         {<br>         &quot;type&quot;: &quot;separator&quot;<br>         },<br>         {<br>            &quot;type&quot;: &quot;box&quot;,<br>            &quot;layout&quot;: &quot;vertical&quot;,<br>            &quot;spacing&quot;: &quot;md&quot;,<br>            &quot;contents&quot;: items<br>         }<br>      ],<br>      &quot;paddingBottom&quot;: &quot;25px&quot;<br>   }<br>})<br><br>const todayItemBubble = (image, title, date, items) =&gt; ({<br>   &quot;type&quot;: &quot;bubble&quot;,<br>   &quot;size&quot;: &quot;mega&quot;,<br>   &quot;hero&quot;: {<br>      &quot;type&quot;: &quot;image&quot;,<br>      &quot;url&quot;: `${image}`,<br>      &quot;size&quot;: &quot;full&quot;,<br>      &quot;aspectRatio&quot;: &quot;20:13&quot;,<br>      &quot;aspectMode&quot;: &quot;cover&quot;<br>   },<br>   &quot;body&quot;: {<br>      &quot;type&quot;: &quot;box&quot;,<br>      &quot;layout&quot;: &quot;vertical&quot;,<br>      &quot;spacing&quot;: &quot;md&quot;,<br>      &quot;contents&quot;: [<br>         {<br>            &quot;type&quot;: &quot;text&quot;,<br>            &quot;text&quot;: `${title}`,<br>            &quot;size&quot;: &quot;xl&quot;,<br>            &quot;weight&quot;: &quot;bold&quot;<br>         },<br>         {<br>            &quot;type&quot;: &quot;text&quot;,<br>            &quot;text&quot;: `${date}`,<br>            &quot;margin&quot;: &quot;none&quot;,<br>            &quot;size&quot;: &quot;xs&quot;,<br>            &quot;color&quot;: &quot;#999999&quot;<br>         },<br>         {<br>            &quot;type&quot;: &quot;text&quot;,<br>            &quot;text&quot;: &quot;รายการโภชนาการ&quot;,<br>            &quot;size&quot;: &quot;lg&quot;,<br>            &quot;weight&quot;: &quot;bold&quot;,<br>            &quot;margin&quot;: &quot;xl&quot;<br>         },<br>         {<br>         &quot;type&quot;: &quot;separator&quot;<br>         },<br>         {<br>            &quot;type&quot;: &quot;box&quot;,<br>            &quot;layout&quot;: &quot;vertical&quot;,<br>            &quot;spacing&quot;: &quot;md&quot;,<br>            &quot;contents&quot;: items<br>         }<br>      ],<br>      &quot;paddingBottom&quot;: &quot;25px&quot;<br>   }<br>})<br><br>const nutritionItem = (title, number, unit) =&gt; ({<br>   &quot;type&quot;: &quot;box&quot;,<br>   &quot;layout&quot;: &quot;baseline&quot;,<br>   &quot;contents&quot;: [<br>      {<br>         &quot;type&quot;: &quot;icon&quot;,<br>         &quot;url&quot;: &quot;https://cdn-icons-png.flaticon.com/512/7362/7362100.png&quot;,<br>         &quot;offsetTop&quot;: &quot;2px&quot;<br>      },<br>      {<br>         &quot;type&quot;: &quot;text&quot;,<br>         &quot;text&quot;: `${title}`,<br>         &quot;weight&quot;: &quot;bold&quot;,<br>         &quot;margin&quot;: &quot;sm&quot;<br>      },<br>      {<br>         &quot;type&quot;: &quot;text&quot;,<br>         &quot;text&quot;: `${number} ${unit}`,<br>         &quot;size&quot;: &quot;sm&quot;,<br>         &quot;align&quot;: &quot;end&quot;,<br>         &quot;color&quot;: &quot;#999999&quot;<br>      }<br>   ]<br>})<br><br>module.exports = { todaySummaryFlex, todayNoData, todaySummaryCarousel, todaySummaryBubble, todayItemBubble, nutritionItem };</pre><p>จากนั้นกลับไปที่ไฟล์ /functions/index.js แล้ว import message ที่ด้านบน</p><pre>const message = require(&quot;./utils/message&quot;)</pre><p>ถัดไปให้เราแก้ไขต่อที่ไฟล์ /functions/index.js ตรงส่วนรับ event จาก webhook ตรงส่วนที่เช็คว่า event.type === “text” โดยให้เอาโค้ดด้านล่างไปใส่แทน</p><pre>if (event.message.type === &quot;text&quot;) {<br>  if(event.message.text.toLowerCase() === &#39;สรุป&#39;) {<br>    const currentDateThai = util.getTodayDateThai()<br>    const docs = await firebase.getMenuToday(event.source.userId);<br>    <br>    let dataFlex = &#39;&#39;<br>    if (docs.empty) {<br>      dataFlex = message.todayNoData(currentDateThai)<br>    } else {<br>      const nutrients = await util.summaryMenu(docs)<br>      let flexNutrient = []<br>      for (const nutrientName in nutrients) {<br>        const nutrient = nutrients[nutrientName];<br>        flexNutrient.push(message.nutritionItem(nutrientName, nutrient.number, nutrient.unit))<br>      }<br>      const todaySummaryBubble = message.todaySummaryBubble(docs.size, currentDateThai, flexNutrient)<br><br>      let todayBubble = []<br>      todayBubble.push(todaySummaryBubble)<br>      await docs.forEach((doc) =&gt; {<br>        const data = doc.data()<br>        let createDate = data.createDate.split(&#39; &#39;)[1]<br>        let detailNutrient = []<br>        const details = data.detail<br>        details.forEach((detail) =&gt; {<br>          detailNutrient.push(message.nutritionItem(detail.title, detail.number, detail.unit))<br>        })<br>        todayBubble.push(message.todayItemBubble(data.publicURL, data.title, createDate, detailNutrient))<br>        <br>      })<br>      dataFlex = message.todaySummaryCarousel(todayBubble)<br>    }<br><br>    const todayFlex = message.todaySummaryFlex(dataFlex)<br>    await line.reply(event.replyToken, [todayFlex]);<br>    return res.end();<br>  } else {<br>    const msg = await gemini.chat(event.message.text);<br>    await line.reply(event.replyToken, [{ type: &quot;text&quot;, text: msg }]);<br>    return res.end();<br>  }<br>}</pre><p>โดยโค้ดมีขั้นตอนการทำงานดังนี้</p><ul><li>ตรวจสอบกรณีเป็นข้อความคำว่า “สรุป”</li><li>ดึงข้อมูลจาก Firestore ผ่านฟังก์ชั่น firebase.getMenuToday</li><li>ตรวจสอบข้อมูล Menu ถ้ายังไม่มีการบันทึกการกินเลย จะส่งข้อความกลับหา user ว่า ยังไม่ได้บันทึกรายการอาหาร</li><li>กรณีที่มีข้อมูล จะทำการสรุปข้อมูลโภชนาการผ่านฟังก์ชั่น util.summaryMenu</li><li>สร้าง Bubble สำหรับ รายการสรุปประจำวันด้วยโครงสร้างข้อความใน message.todaySummaryBubble</li><li>สร้าง Bubble สำหรับ รายการแต่ละรายการด้วยโครงสร้างข้อความใน message.todayItemBubble</li><li>นำ Bubble 2 ข้อด้านบน ประกอบเป็น Carousel ตามโครงสร้างข้อความใน message.todaySummaryCarousel</li><li>ทำการส่งข้อความ reply กลับหา user</li></ul><p>** กรณีที่<strong>ดึงข้อมูลไม่ขึ้นให้ตรวจสอบ Log ของ Firebase Functions </strong>อาจพบกรณีที่ยังไม่ได้สร้าง index ดังภาพด้านล่าง ให้ทำการ copy link ใน error log แล้วนำไปเปิดบน Browser เพื่อสร้าง index ใน Firestore **</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7M36d-VsfqtCXB2PZ3fiMw.png" /></figure><h4>13. Deploy</h4><p>หลังจากเราทำผ่านมาทุกขั้นตอนแล้ว ก็ถึงเวลาที่เราจะได้ deploy เพื่อไปทดสอบกันแล้ว ให้เราเปิด Terminal แล้ว deploy ด้วยคำสั่งนี้เลยครับ</p><pre>firebase deploy --only functions</pre><p>เมื่อ deploy เสร็จแล้วให้ลองทดสอบดูครับ จะได้ผลลัพธ์ตามรูปด้านล่างนี้ครับ</p><ul><li>ทดสอบพิมพ์คำว่า สรุป จะได้ข้อความตอบกลับว่า ยังไม่ได้บันทึกรายการอาหาร</li><li>ทดสอบอัพโหลดรูปอาหาร จะเจอข้อมูลโภชนาการต่างๆ พร้อมบันทึกรายการอาหาร</li><li>ทดสอบพิมพ์คำว่า สรุป อีกครั้ง จะได้ Carousel รายการสรุปโภชนาการรายวัน และรายการอาหารในวันปัจจุบัน</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7zqWM79CSbyjuBczeLamRQ.jpeg" /></figure><p>ปล.เนื่องจาก Carousel ปัจจุบันได้สูงสุด 12 bubble ดังนั้นส่งรายการอาหารได้ไม่เกิน 11 เมนูนะค้าบบ ถ้าใครคาดว่าจะส่งรายการอาหารต่อวันเกิน 11 เมนูแน่ๆ ให้เปลี่ยนรูปแบบแสดงผลเลยนะครับ</p><h4>สรุป</h4><p>การใช้งาน Gemini API ทำให้การทำงานง่ายๆ ขึ้นมากๆ ปกติกว่าจะทำการดึงรายการโภชนาการออกมา จะต้องทำตั้งแต่ Image Recognition ซึ่งต้องทำ Model เมนูอาหารต่างๆ เอง แล้วยังต้องแปลงข้อมูลอาหารเป็น โภชนาการต่างๆ อีก เรียกว่าประหยัดเวลาไปเยอะเลย แล้วมั่นใจได้เลยว่าแต่ละแบรนด์มี LINE OA อยู่แล้ว หมายความว่า เราสามารถต่อ LINE Chatbot กับ Gemini API ได้อย่างเนียนๆ เลย เรียกว่าทำให้เราจินตนาการสร้างสรรค์ได้อย่างเต็มที่เลย</p><h4>ส่งท้าย End Credits</h4><p>บทความถัดไป ep2 ผมจะเอาข้อมูลการบริโภค กับ ข้อมูลส่วนตัวของ user ไปทำเป็น RAG แล้วใช้ Gemini เป็นนักโภชนาการ Recommend การบริโภคแบบ Personalize ใครสนใจกดติดตามไว้ได้เลยครับ ขอบคุณครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OFrfqY8zZD0jyKsRARm4Kw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=087a35315dfb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linedevth/line-chatbot-x-gemini-api-%E0%B8%AA%E0%B8%A3%E0%B9%89%E0%B8%B2%E0%B8%87%E0%B8%99%E0%B8%B1%E0%B8%81%E0%B9%82%E0%B8%A0%E0%B8%8A%E0%B8%99%E0%B8%B2%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%80%E0%B8%AD%E0%B8%B2%E0%B9%83%E0%B8%88%E0%B8%AA%E0%B8%B2%E0%B8%A2-healthy-ep1-087a35315dfb">LINE Chatbot x Gemini API สร้างนักโภชนาการเอาใจสาย Healthy ep1.</a> was originally published in <a href="https://medium.com/linedevth">LINE Developers Thailand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flex2HTML รองรับ Video Component แล้ว]]></title>
            <link>https://medium.com/linedevth/flex2html-%E0%B8%A3%E0%B8%AD%E0%B8%87%E0%B8%A3%E0%B8%B1%E0%B8%9A-video-component-%E0%B9%81%E0%B8%A5%E0%B9%89%E0%B8%A7-84207a508d2c?source=rss-655fb7ee2ef3------2</link>
            <guid isPermaLink="false">https://medium.com/p/84207a508d2c</guid>
            <category><![CDATA[linedevth]]></category>
            <category><![CDATA[flex2html]]></category>
            <category><![CDATA[flexmessage]]></category>
            <dc:creator><![CDATA[PamornT]]></dc:creator>
            <pubDate>Fri, 16 Jun 2023 12:01:25 GMT</pubDate>
            <atom:updated>2023-06-16T12:01:25.106Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h3gQb8t0HFFlHK94ki8bew.jpeg" /></figure><p>ข่าวดีจ้าา Flex2HTML อัพเดทใหม่รองรับ Video Component แล้วค้าบ! 🎉</p><p>สำหรับใครที่ยังไม่เคยรู้จัก lib Flex2HTML ผมขอเกริ่นเบื้องต้นว่าเป็น Javascript libraly ที่จะแปลง JSON ของ Flex Messages ให้แสดงผลอยู่ในรูปแบบ HTML สามารถไปศึกษาเพิ่มเติมจากบทความก่อนหน้าได้เลยค้าบ</p><p><a href="https://medium.com/linedevth/%E0%B9%81%E0%B8%AA%E0%B8%94%E0%B8%87%E0%B8%9C%E0%B8%A5-flex-message-%E0%B9%83%E0%B8%99-html-%E0%B9%80%E0%B8%AA%E0%B8%A1%E0%B8%B7%E0%B8%AD%E0%B8%99%E0%B8%AD%E0%B8%A2%E0%B8%B9%E0%B9%88%E0%B8%9A%E0%B8%99-line-cb8d32ece92a">แสดงผล Flex message ใน HTML เสมือนอยู่บน LINE</a></p><p>ก่อนอื่นเราไปทำความเข้าใจกับ Video Component บน Flex Messages กันก่อนดีกว่า เริ่มจากมาดูเงื่อนไขกันก่อนเลย ว่ามีเงื่อนไขอะไรบ้างในการจะใช้งานเจ้า Video Component บน Flex Messages</p><h3>เงื่อนไขการใส่ Video Component ใน Flex Messages</h3><p>(ณ.วันที่ 16/6/66)</p><ul><li>Video Component ต้องอยู่ภายใต้ Hero block เท่านั้น</li><li>ขนาดของ Bubble ต้องมีขนาด kilo, mega หรือ giga เท่านั้น</li><li>Flex Messages นั้นต้องเป็นแบบ Bubble เดี่ยวๆ เท่านั้น ไม่สามารถใช้เป็น Carousel ได้</li></ul><p>รู้เงื่อนไขการใช้งานแล้ว ต่อไปเรามาดูโครงสร้าง JSON ของ Video Component กันสักหน่อยค้าบ</p><h3>โครงสร้าง JSON ของ Video Component</h3><p>ตัวอย่างโครงสร้าง JSON จะเป็นประมาณนี้เลยครับ</p><pre>{<br>  &quot;type&quot;: &quot;bubble&quot;,<br>  &quot;size&quot;: &quot;mega&quot;,<br>  &quot;hero&quot;: {<br>    &quot;type&quot;: &quot;video&quot;,<br>    &quot;url&quot;: &quot;https://example.com/video.mp4&quot;,<br>    &quot;previewUrl&quot;: &quot;https://example.com/video_preview.jpg&quot;,<br>    &quot;altContent&quot;: {<br>      &quot;type&quot;: &quot;image&quot;,<br>      &quot;size&quot;: &quot;full&quot;,<br>      &quot;aspectRatio&quot;: &quot;20:13&quot;,<br>      &quot;aspectMode&quot;: &quot;cover&quot;,<br>      &quot;url&quot;: &quot;https://example.com/image.jpg&quot;<br>    },<br>    &quot;aspectRatio&quot;: &quot;20:13&quot;<br>  }<br>}</pre><p>หลักๆ เลยเราจะใช้ url สำหรับ link video และ previewUrl สำหรับรูป Preview ก่อนเล่นวีดีโอครับ</p><p>พอเราเข้าใจและเห็นภาพโครงสร้าง JSON กันแล้ว ทีนี้เรามาดูกันว่า Flex2HTML Lib ของเรามีหลักการทำงานกับเจ้า Video Component อย่างไรบ้างครับ</p><h3>Flex2HTML x Video Component</h3><p>หลักๆ เลยตัว Flex2HTML จะออกแบบโดยใช้ HTML5 เพื่อเล่นและแสดงผลวีดีโอกับรูป Preview ครับ โดยใช้ข้อมูลจาก Flex Message ตามภาพนี้ครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OhnV6aiVpngITpKgXSUTDw.png" /></figure><h3><strong>ผลลัพธ์</strong></h3><p>ผลลัพธ์ที่ได้ก็จะเป็นตามภาพด้านล่างนี้เลยค้าบ เราสามารถแสดงผลวีดีโอ พร้อมภาพ Preview และสามารถเล่นวีดีโอได้เลยครับผม ^^</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5D_LtiNHrCkvADzCLMEiRA.png" /></figure><p>หวังว่าจะมีประโยชน์กับเพื่อนๆ ชาว LINE Dev กันนะครับ ใครที่ใช้ Flex Messages อยู่กดติดตามไว้ได้เลยครับ เวลามี Feature อะไรใหม่ๆ จะได้อัพเดทก่อนใครเลย ขอบคุณครับ</p><p><a href="https://github.com/PamornT/flex2html.git">GitHub - PamornT/flex2html: Convert LINE Flex 2 HTML</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84207a508d2c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linedevth/flex2html-%E0%B8%A3%E0%B8%AD%E0%B8%87%E0%B8%A3%E0%B8%B1%E0%B8%9A-video-component-%E0%B9%81%E0%B8%A5%E0%B9%89%E0%B8%A7-84207a508d2c">Flex2HTML รองรับ Video Component แล้ว</a> was originally published in <a href="https://medium.com/linedevth">LINE Developers Thailand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[วิธีแยก Environment ใน Dialogflow]]></title>
            <link>https://medium.com/linedevth/%E0%B8%A7%E0%B8%B4%E0%B8%98%E0%B8%B5%E0%B9%81%E0%B8%A2%E0%B8%81-environment-%E0%B9%83%E0%B8%99-dialogflow-2847a97bf443?source=rss-655fb7ee2ef3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2847a97bf443</guid>
            <category><![CDATA[cloud-functions]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[dialogflow]]></category>
            <category><![CDATA[ngrok]]></category>
            <category><![CDATA[linedevth]]></category>
            <dc:creator><![CDATA[PamornT]]></dc:creator>
            <pubDate>Wed, 14 Dec 2022 02:57:23 GMT</pubDate>
            <atom:updated>2022-12-14T02:57:23.516Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o-utYi3ApbmGdsLHdlE6xQ.jpeg" /></figure><p>มั่นใจว่าเพื่อนๆ หลายคนที่ทำ LINE Chatbot คงมีไม่น้อยที่ใช้ Dialogflow เป็นตัวทำ NLP เพื่อทำให้ Chatbot ของเราฉลาดขึ้นเข้าใจผู้ใช้งานได้ดีขึ้น</p><p>แต่เพื่อนๆ คงเคยเจอปัญหาว่าการแก้ไข Intent ต่างๆ บน Dialogflow จะส่งผลกับ LINE OA บน Production ของเราเลย หลายๆ คนอาจจะใช้วิธีสร้าง Dialogflow อีกตัวนึงขึ้นมา แต่ก็ต้องมาคอย Export/Import ทุกครั้งที่มีการเปลี่ยนแปลง แล้วที่สำคัญยังไม่มีการเก็บ version ของ Intent อีกด้วย</p><p>บทความนี้จะนำเสนอแนวทางการทำ Environment บน Dialogflow เพื่อให้เพื่อนๆ สามารถทำงานบน Dialogflow ได้อย่างลื่นไหลและปลอดภัยมากขึ้น</p><p>โดยผลลัพธ์ของบทความนี้จะทำให้เพื่อนๆ สามารถสร้าง LINE OA สำหรับ Dev/Prod แยกกันได้โดยใช้ Dialogflow ตัวเดียวกัน ไม่ต้องแยกไปหลายตัวแล้วต้องคอย export/import และทุกการแก้ไขบน Dialogflow จะไม่กระทบกับ LINE OA ตัว Production แน่นอน</p><blockquote>แก้ไขบน Draft ได้เต็มที่ ไม่ต้องกลัวกระทบ Production</blockquote><h3>0. เริ่มต้นสร้าง LINE OA</h3><p>สร้าง LINE OA 2 ตัว สำหรับ test กับ production ใครไม่เคยสร้าง LINE OA ไปสร้างได้ที่ลิงก์นี้เลย <a href="https://manager.line.biz/">https://manager.line.biz/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GKg64x-BOeJrx5-im1P28g.jpeg" /></figure><h3>1. สร้าง Dialogflow</h3><p>สร้าง Dialogflow ชื่อ Multiple_ENV หลังจากสร้างเราก็จะได้ Dialogflow เปล่าๆ ที่มีแค่ 2 intent คือ Default Fallback Intent กับ Default Welcome Intent วันนี้เราจะเล่นอยู่แค่ 2 Intent นี้เลยนะค้าบ เข้าไปสร้างได้ที่ลิงก์นี้เลย <a href="https://dialogflow.cloud.google.com/">https://dialogflow.cloud.google.com/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CpSXdEyQBIMB74kzz64A4w.jpeg" /></figure><h3>2.สร้าง Webhook</h3><h4>2.1 ติดตั้ง Cloud Functions for Firebase</h4><p>สร้าง Webhook สำหรับเชื่อมต่อ Dialogflow โดยเราจะสร้างอยู่บน Cloud Functions for Firebase 🔥</p><p>ให้เปิด Terminal หรือ Command แล้วไปที่ folder ที่เราต้องการแล้ว run คำสั่งนี้เลยค้าบ</p><pre>firebase init</pre><p>หลังจากนั้นจะเริ่มการติดตั้ง firebase ให้เลือกติดตั้ง Functions กับ Emulators แค่ 2 ตัวนี้นะค้าบ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PdzV5S865z58Rd3K33BlJw.jpeg" /></figure><p>ต่อไปจะเป็นการ setup ตัว functions ผมเลือกเป็น Typescript จากนั้นก็ enter ยาวๆ เลยครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wz0y6DyGDn6XTUCTvWyokw.jpeg" /></figure><p>ต่อไปจะเป็นการ setup ตัว emulators ผมเลือกแค่ functions แล้วก็ enter ยาวๆ เลยค้าบบ เป็นอันเสร็จเรียบร้อยแล้วค้าบบบ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*unVna1v80vi9fdtpfT0n1Q.jpeg" /></figure><p>หลังจากนั้นจะได้ file หน้าตาประมาณนี้ค้าบ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B-PYged_RNwIRMtePGTXZw.png" /></figure><h4>2.2 ลง Dependency เพิ่มเติม</h4><p>เราต้องลง dependency เพิ่มเติม 2 ตัว ตามนี้เลยค้าบ (ก่อน run คำสั่ง npm ให้เข้าไปที่ โฟลเดอร์ /functions ก่อนนะค้าบบ)</p><ul><li><strong>axios : สำหรับเรียก LINE Messaging API เพื่อ reply ข้อความหา User</strong></li></ul><pre>npm install axios --save</pre><ul><li><strong>@google-cloud/dialogflow : สำหรับเรียก Dialogflow ผ่าน API</strong></li></ul><pre>npm install @google-cloud/dialogflow --save</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_lGWJzeMbZjtkegEeLfow.png" /></figure><h4>2.3 เปิด Functions สำหรับ Webhook</h4><p>เปิดไฟล์ index.ts แล้วเปิด comment บรรทัดที่ 5–8 แล้วเปลี่ยนชื่อ functions เป็น webHook</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zOiebmY3Bl0tQapWjLpUHA.jpeg" /></figure><h4>2.4 เริ่มรับค่า Request จาก LINE Webhook</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/502f172084646b4e21d3a302fc28fa96/href">https://medium.com/media/502f172084646b4e21d3a302fc28fa96/href</a></iframe><h3>3. Run Firebase Emulators</h3><p>เข้าไปที่ โฟลเดอร์ /functions แล้ว run คำสั่งใน Terminal ตามนี้</p><pre>npm run build:watch</pre><p>เนื่องจากบทความนี้เราใช้ภาษา TypeScript ซึ่งตัว Firebase Emulators มันจะไม่จับความเปลี่ยนแปลงของ Code เราให้อัตโนมัติเหมือน JavaScript นะครับ เราเลยต้อง run คำสั่ง npm run build:watch เพื่อ compile TypeScript ให้เป็น JavaScript ก่อน Firebase Emulators จึงจะสามารถรับความเปลี่ยนแปลงของ Code เราให้แบบอัตโนมัติครับผม</p><p>หลังจากนั้นเปิดอีก 1 Terminal แล้ว start Firebase Emulator ด้วยคำสั่งนี้</p><pre>firebase emulators:start</pre><p>เสร็จแล้วจะได้หน้าตาประมาณนี้ให้คลิกที่ลิงก์ Functions (http://127.0.0.1:4000/functions)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Qk3cUspgJjGTLGXbi7rfg.png" /></figure><p>สังเกตุหลังจากเปิดหน้าต่างขึ้นมาเราจะได้ url สำหรับ webhook ของเราแล้วแต่เรายังเอาไปใช้งานไม่ได้ต้องทำเป็น public url ในขั้นตอนถัดไปก่อน ไปต่อกันเลยยย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TS2DvQEii7Q4EJBKzaXO8Q.png" /></figure><h3>4. สร้าง Public URL ด้วย ngrok</h3><p>เราจะใช้ ngrok เพื่อสร้าง public URL ถ้าใครยังไม่ได้ติดตั้ง ngrok สามารถไปติดตั้งได้ที่นี่เลย <a href="https://ngrok.com/">https://ngrok.com/</a></p><p>หลังจากติดตั้งเรียบร้อย ให้เปิด Terminal หรือ Command ใหม่อีก 1 ตัว แล้ว run คำสั่ง</p><pre>ngrok http 5001</pre><p>หลังจาก run คำสั่งเราจะได้ url มา 2 url ให้เราใช้ url ที่เป็น https นะค้าบ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-GNocZxkN3gngN83LeFQ9w.png" /></figure><p>ให้เราเอา url https ที่ได้มา มาแทน <a href="http://127.0.0.1/">http://127.0.0.1</a> ของ webhook ของเรา เราก็จะได้ webhook url ที่เป็น public URL เพื่อไปใช้ในขั้นตอนถัดไปกันแล้วว</p><p><strong>Local:</strong> <a href="http://127.0.0.1:5001/multiple-env-pafg/us-central1/webHook"><strong><em>http://127.0.0.1:500</em></strong><em>1</em>/multiple-env-pafg/us-central1/webHook</a></p><p><strong>Public:</strong> <a href="https://5d4c-49-228-225-255.ngrok.io/"><strong><em>https://5d4c-49-228-225-255.ngrok.io</em></strong></a><a href="http://127.0.0.1:5001/multiple-env-pafg/us-central1/webHook">/multiple-env-pafg/us-central1/webHook</a></p><h3>5. เปิดใช้ Messaging API ใน LINE OA</h3><p>เราจะเปิดใช้งาน Messaging API <strong>โดยให้ทำตามขั้นตอนนี้ทั้ง 2 LINE OA</strong></p><ul><li>กลับไปที่ LINE OA Manager แล้วไปที่เมนู Setting &gt; Messaging API แล้วกดปุ่ม Enable Messaging API แล้วจะมีให้เลือก Provider จากนั้นกด OK ยาวๆ จนเสร็จเลยค้าบ</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pdWuGZuQ1ujwyUoAjj100g.png" /></figure><ul><li>จากนั้นให้เอา Webhook URL ที่ได้จาก ngrok มาใส่ที่ช่อง Webhook URL แล้วกด Save</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jOF5S2zbPVeWwyzCvqbTbw.png" /></figure><ul><li>จากนั้นให้ไปที่เมนู Settings &gt; Response Settings แล้วเลือกเปิด Webhook เลย</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h2J7BOcts-80qI5h6MtGdA.png" /></figure><h3>ทดสอบครั้งที่ 1 — หาค่า destination</h3><p>หลังจากเราเปิด Webhook เรียบร้อย ให้เราลองทักทายไปที่ LINE OA ทั้งสองตัว แล้วไปดูที่ log ของ Firebase Emulator จะพบว่ามี Log เข้ามาแล้ว โดย Log นี้จะเป็นข้อมูลต่างๆ ของ request.body ที่ส่งมาจาก LINE ให้เราสังเกตุว่าค่า destination ของ LINE OA แต่ละตัวจะไม่เหมือนกัน ให้เรา copy destination แต่ละ LINE OA เก็บไว้เพื่อใช้ในขั้นตอนถัดไป</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXnfWy5BIionjjjQ6ORBUQ.png" /></figure><h3>6. กำหนด Environment ให้ LINE OA แต่ละตัว</h3><p>ขั้นตอนนี้เราจะกำหนด Environment ให้แต่ละ LINE OA โดยใช้การตรวจสอบเงื่อนไขจากค่า destination ที่ได้จากขั้นตอนก่อนหน้า</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fa5f347d371004b5ffe915c8aa48a66/href">https://medium.com/media/8fa5f347d371004b5ffe915c8aa48a66/href</a></iframe><p>สังเกตุว่าเรามีการตั้งค่า environment ไว้ 2 ตัว คือ <strong>draft</strong> กับ <strong>production</strong></p><h3>7. เปิดใช้งาน Dialogflow API</h3><p>ต่อไปเราจะเริ่มทำส่วน detectIntent กันแล้ว แต่ก่อนจะใช้งานได้เราต้องเปิดใช้งาน Dialogflow API ก่อน ตามขั้นตอนด้านล่างนี้</p><ul><li>ไปที่เมนู setting ของ Dialogflow แล้วเลือกเปิด <strong>Enable beta features and APIs</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*aT02HOKrS5iTjDBMU2eyHA.png" /></figure><ul><li><strong>เข้าไปที่ GCP Console โดยการคลิกที่ Project Id</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BGju9bQ4c-d7dF6hUYrx1g.png" /></figure><ul><li><strong>ไปที่เมนู APIs &amp; Services &gt; Credentials</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MHphfMoPnI2iJc_-JXqAbg.png" /></figure><ul><li><strong>สร้าง Service Account ตามขั้นตอนนี้</strong></li></ul><ol><li>กรอก Service account name เท่ากับ “dialogflowAPI” กดปุ่ม CREATE AND CONTINUE</li><li>เลือก Role “Dialogflow API Client” แล้วกดปุ่ม CONTINUE</li><li>กดปุ่ม Done</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1xrO0UQ8UCzimJx7fmKdMw.png" /></figure><ul><li><strong>สร้าง Key แล้ว Download ไฟล์ JSON Service Account</strong></li></ul><ol><li>มองหา Service Account ที่ชื่อ dialogflowAPI แล้วกดปุ่ม ดินสอ ด้านหลัง</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ISQC_etx00etzaQWVIsG3A.png" /></figure><p>2. เลือก Tab Key แล้วกดปุ่ม Create new key แล้วเลือก JSON แล้วกดปุ่ม CREATE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sAFJjJ-yYemKwwDxMsuqFA.png" /></figure><p>หลังจากนั้นเราจะได้ไฟล์ json มาให้ copy ไปวางที่ โฟลเดอร์ /functions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HDxHI6kKMSHpUprz4oMI1A.png" /></figure><h3>8. สร้าง Environment บน Dialogflow</h3><p>ให้เรากลับไปที่ Dialogflow แล้วเข้าไปที่ Settings แล้วไปที่ Tab Environments</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kK4BTwyOvrmKlmMEIKw1Dw.jpeg" /></figure><p>สังเกตุว่าเรายังไม่มี Environment ใดๆ เลย ให้เรากดปุ่ม “PUBLISH A VERSION”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cZTVBiVk1DsU7KKis_DVjQ.png" /></figure><p>กรอก Description เป็นอะไรก็ได้แล้วกดปุ่ม NEXT</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iYtLh_Nv8nI6IagWQIkoBA.png" /></figure><p>ตอนนี้เราจะทำการสร้าง environment ใหม่ ให้กรอกคำว่า “production” ที่ Environment name แล้วเลื่อนไปด้านล่างกดปุ่ม PUBLISH เท่านี้เราก็จะได้ environment production มาแล้วว</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KJ4wmhGPLEWwjttIXnqV1w.jpeg" /></figure><h3>9. สร้าง function สำหรับ DetectIntent</h3><pre>events.forEach( async (event: any) =&gt; {<br>    console.log(event);<br>    if (event.type === &quot;message&quot;) {<br>      const text = event.message.text;<br>      const userId = event.source.userId;<br>      const output = await detectIntent(text, userId);<br>      console.log(output);<br>      // Reply<br>    }<br>});</pre><ul><li>สร้างตัวแปร text เพื่อเก็บข้อความที่ได้จาก user ในห้องแชท</li><li>สร้างตัวแปร userId เพื่อเก็บค่า LINE userId ของ user</li><li>เรียกฟังก์ชัน detectIntent โดยส่งค่า text กับ userId ไปด้วย</li></ul><pre>async function detectIntent(message: string, userId: string): Promise&lt;any&gt; {<br>  const sessionId = userId;<br>  const sessionClient = new dialogflow.SessionsClient({<br>    projectId,<br>    keyFilename: &quot;multiple-env-pafg-a9a11f6e8479.json&quot;,<br>  });<br>  const sessionPath = `projects/${projectId}/agent/environments/${dialogflowEnv}/users/${sessionId}/sessions/${sessionId}`;<br>  const request = {<br>    session: sessionPath,<br>    queryInput: {<br>      text: {<br>        text: message,<br>        languageCode: &quot;th-TH&quot;,<br>      },<br>    },<br>  };<br><br>  // Send request and log result<br>  const responses = await sessionClient.detectIntent(request);<br>  const result = responses[0].queryResult;<br>  return result?.fulfillmentText;<br>}</pre><ul><li>สร้าง function ชื่อ detectIntent โดยรับ parameter 2 ค่า คือ text กับ userId</li><li>ทำการสร้าง object สำหรับเชื่อมต่อ dialogflow ผ่านคำสั่ง dialogflow.SessionsClient โดย กำหนดค่าดังนี้</li></ul><ol><li>projectId คือ projectid ของ dialogflow</li><li>keyFilename คือ ไฟล์ JSON ที่เก็บค่า service account ที่เราได้มาก่อนหน้า</li></ol><blockquote>sessionPath คือ หัวใจในการแยก Environment</blockquote><ul><li>กำหนดค่า sessionPath โดย มีรูปแบบดังนี้</li></ul><pre>projects/${projectId}/agent/environments/${dialogflowEnv}/users/${sessionId}/sessions/${sessionId}`</pre><p>สังเกตุว่าจะมีการกำหนดค่า environment ไว้ที่ sessionPath เลย</p><ul><li>จากนั้นเราทำการสร้างตัวแปร request เพื่อทำการส่งไปเรียกใช้ฟังก์ชัน detectIntent ของ dialogflow</li><li>หลังจากนั้นเราจะได้ผลลัพธ์กลับมาใน fulfillmentText</li></ul><h3>ทดสอบครั้งที่ 2 — ดูผลลัพธ์ที่ได้จาก dialogflow</h3><p>สังเกตุว่าข้อความตอบกลับจาก Dialogflow ของทั้งสอง LINE OA ยังเหมือนกันอยู่</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VSfk-2ZN0YMLnrN9YOEQyQ.jpeg" /></figure><p>ให้เราลองไปที่ Dialogflow แล้วลองไปที่ Default Welcome Intent แล้วลองเปลี่ยน response ให้เป็นคำว่า “สบายดีไหม จาก Draft Version” แล้วลองทดสอบอีกครั้ง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oOCVwVuZeVo-IBWMT_D0FA.jpeg" /></figure><p>สังเกตุว่า LINE OA ตัว Dev ของเราข้อความเปลี่ยนไปเป็น “สบายดีไหม จาก Draft Version” เรียบร้อยแล้ววว ^^ ที่เป็นแบบนี้เพราะเรากำหนด environment ของ LINE OA ตัว Dev ให้ไปที่ Draft นั่นเอง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TBX6wWPoZobHWPKfpuuY7A.jpeg" /></figure><h3>10. Reply Message</h3><p>มาถึงงานสุดท้ายของบทความนี้แล้ววว นั่นก็คือส่งข้อความกลับไปหา user ผ่าน send reply messge ของ LINE Messaging API นั่นเอง</p><pre>async function reply(replyToken: string, text: string) {<br>  await axios({<br>    method: &quot;post&quot;,<br>    url: &quot;https://api.line.me/v2/bot/message/reply&quot;,<br>    headers: LINE_HEADER,<br>    data: {<br>      &quot;replyToken&quot;: replyToken,<br>      &quot;messages&quot;: [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: text}],<br>    },<br>  });<br>}</pre><p>คาดว่าเพื่อนๆ คงคุ้นเคยกับ send reply message เป็นอย่างดีแล้ว ผมจะขอข้ามไปไม่ได้อธิบายนะค้าบบ</p><p>ปล. เพื่อไม่ให้บทความนี้ยาวจนเกินไปขออนุญาติแสดงให้ดูแต่กรณีที่ตอบเป็นข้อความก่อนนะค้าบ</p><h3>ทดสอบครั้งสุดท้าย</h3><p>หลังจากทำทั้งหมดครบแล้วมาดูผลลัพธ์ครั้งสุดท้ายกันว่า LINE OA 2 ตัวที่ต่อ Dialogflow ตัวเดียวกันจะสามารถแยก environment ได้มั้ย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fpOdaFm6kflnp9d2oDxj3g.jpeg" /></figure><p>เรียบร้อยค้าบบ คราวนี้เราก็สามารถทำงานบน Draft version ได้อย่างสบายใจ ไม่กระทบกับ Production อย่างแน่นอน</p><p>เมื่อเราแก้ไขที่ Draft จนพอใจแล้ว ต้องการเอาขึ้น production ก็แค่ไปกด Publish version ใหม่แล้วเลือก environment เป็น production นั่นเอง</p><h3>ส่งท้าย</h3><p>จากบทความข้างต้นเป็นเพียง 1 วิธีที่เราจะสามารถแยก environment บน Dialogflow กับ LINE OA ของเราได้ ยังมีวิธีอื่นๆ อีกมากมาย เช่น แยก Dialogflow ไปเลย แล้วใช้วิธี Export/Import เอา ทั้งนี้อยู่ที่ความเหมาะสมในงานและความถนัดของเพื่อนๆ นะค้าบบ</p><p>Code ฉบับสมบูรณ์ของบทความนี้ไปโหลดได้ที่นี่เลยค้าบ<br><a href="https://gist.github.com/PamornT/669f90187d953cacdaeea7402c38f6b0">https://gist.github.com/PamornT/669f90187d953cacdaeea7402c38f6b0</a></p><p>ปล. ทิ้งท้ายเพื่อไม่ให้บทความนี้ยาวจนเกินไป</p><ol><li>ผมขอข้ามการเช็ค Security ต่างๆ ไปก่อนนะค้าบ</li><li>ผมขอแสดงให้ดูแต่กรณีที่ตอบเป็นข้อความก่อนนะค้าบ ข้อความแบบอื่นๆ ผมจะทำให้ดูในบทความถัดไปนะค้าบ กดติดตามกันไว้ได้เลย</li></ol><p>แล้วพบกันบทความถัดไปครับผม :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2847a97bf443" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linedevth/%E0%B8%A7%E0%B8%B4%E0%B8%98%E0%B8%B5%E0%B9%81%E0%B8%A2%E0%B8%81-environment-%E0%B9%83%E0%B8%99-dialogflow-2847a97bf443">วิธีแยก Environment ใน Dialogflow</a> was originally published in <a href="https://medium.com/linedevth">LINE Developers Thailand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[เทคนิคการสร้างเครื่องมือกระตุ้นยอดคนดู Video Content ใน LINE OA]]></title>
            <link>https://medium.com/linedevth/%E0%B9%80%E0%B8%97%E0%B8%84%E0%B8%99%E0%B8%B4%E0%B8%84%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%AA%E0%B8%A3%E0%B9%89%E0%B8%B2%E0%B8%87%E0%B9%80%E0%B8%84%E0%B8%A3%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%87%E0%B8%A1%E0%B8%B7%E0%B8%AD%E0%B8%81%E0%B8%A3%E0%B8%B0%E0%B8%95%E0%B8%B8%E0%B9%89%E0%B8%99%E0%B8%A2%E0%B8%AD%E0%B8%94%E0%B8%84%E0%B8%99%E0%B8%94%E0%B8%B9-video-content-%E0%B9%83%E0%B8%99-line-oa-b39e6cab589c?source=rss-655fb7ee2ef3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b39e6cab589c</guid>
            <category><![CDATA[firestore]]></category>
            <category><![CDATA[cloud-functions]]></category>
            <category><![CDATA[linemessagingapi]]></category>
            <category><![CDATA[linedevth]]></category>
            <category><![CDATA[chatbots]]></category>
            <dc:creator><![CDATA[PamornT]]></dc:creator>
            <pubDate>Mon, 06 Jun 2022 02:27:58 GMT</pubDate>
            <atom:updated>2022-06-06T02:27:58.775Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vbAc5BKSjV2nDKTKKhsLbQ.jpeg" /></figure><p>เคยมั้ยครับ ทีมสร้าง Video Content ขึ้นมา ไม่ว่าจะเป็น Promote สินค้าใหม่ หรือ โปรโมชั่นใหม่ๆ ส่ง Boardcast ออกไป แต่ไม่มี user คลิกกลับมาดู หรือ เปิดดูแค่ 3 วินาที ก็ปิดไปเลย วันนี้ผมจะมาเสนออีกหนึ่งวิธีการที่ช่วยให้ user ดู Video ที่เราสร้างมาจนจบกันค้าบบ</p><p>โดยวิธีการที่เราจะลองทำกันวันนี้คือ การตรวจสอบว่า user ดู Video ของเราจนจบหรือไม่ ถ้าดูจนจบเราอาจจะมีของรางวัล หรือ ส่วนลดต่างๆ มาล่อตาล่อใจ user ของเรากันครับ โดยการจะตรวจสอบว่า user ดู Video ของเราจนจบหรือไม่เราจะต้องใช้งานตัว Webhook Event ที่ชื่อว่า <strong>“Video viewing complete event”</strong> ครับ</p><p>ก่อนจะไปเริ่มลงมือทำกัน มาทำความรู้จักเจ้า Webhook Event ตัวนี้กันก่อนครับ</p><h3>Webhook Event — Video viewing complete คือ?</h3><p>เราจะได้รับ event นี้มาที่ webhook เมื่อ user ดู Video ที่เราส่งไปให้จนจบ โดยมีเงื่อนไขเล็กๆ น้อยๆ ตามนี้ครับ</p><ul><li>ใช้ได้เฉพาะรูปแบบข้อความแบบ Video เท่านั้น ไม่สามารถใช้ได้กับข้อความแบบ Imagemap และ Flex Message</li><li>ถ้า user กดดู Video หลายรอบโดยไม่ได้ปิดหน้าต่าง Chat จะส่ง event ไปแค่ครั้งเดียวเท่านั้น แต่ถ้าปิดหน้าต่าง Chat หรือ ปิดโปรแกรม LINE event นี้จะถูกส่งไปใหม่ เพราะฉะนั้น ถ้าเราออกแบบในการแจกรางวัลแค่ครั้งเดียวต้องตรวจสอบการ Duplicate ด้วยนะครัช</li></ul><h3>เริ่มต้น — กำหนดโจทย์</h3><p>โจทย์วันนี้ เดี๋ยวเรามาทดสอบ Event นี้กันดีกว่า โดยโจทย์วันนี้ผมจะส่งข้อความ Video โปรโมต Product ใหม่ของบริษัท โดยถ้า user เปิดดู Video จนจบ ผมจะแจกคะแนนให้ 10 คะแนน เป็นคะแนนสมมุติ เพื่อให้เห็นภาพตอนเอาไปต่อยอดใช้งานจริงนะครับ เริ่มกันเลย!!!</p><p>ปล.ในบทความนี้ผมจะสร้าง Webhook อยู่บน Cloud Functions for Firebase ถ้าเพื่อนๆ คนไหนยังไม่เคยทำมาก่อน ลองศึกษาเพิ่มเติมจากบทความนี้เลยครับ</p><p><a href="https://medium.com/linedevth/%E0%B8%AA%E0%B8%A3%E0%B9%89%E0%B8%B2%E0%B8%87-line-bot-%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-messaging-api-%E0%B9%81%E0%B8%A5%E0%B8%B0-cloud-functions-for-firebase-20d284edea1b">สร้าง LINE Bot ด้วย Messaging API และ Cloud Functions for Firebase</a></p><h3>เตรียมข้อความ Video</h3><p>ก่อนอื่นมาเตรียมข้อความ Video กันก่อนนะครับ โดยรูปแบบข้อความแบบ Video จะเป็นดังนี้ครับ</p><pre>{<br>    &quot;type&quot;: &quot;video&quot;,<br>    &quot;originalContentUrl&quot;: &quot;https://example.com/original.mp4&quot;,<br>    &quot;previewImageUrl&quot;: &quot;https://example.com/preview.jpg&quot;,<br>    &quot;trackingId&quot;: &quot;track-id&quot;<br>}</pre><ul><li>originalContentUrl คือ URL ของ Video</li><li>previewImageUrl คือ URL รูป preview ของ Video</li><li>trackingId คือ เราต้องกำหนดค่านี้ด้วย เพราะ trackingId จะถูก Webhook ส่งมาด้วยตอน user ดู Video จบ เพื่อให้เราตรวจสอบได้ว่า Video ที่ user ดูคือ Video ตัวไหน</li></ul><h3>ยิง Broadcast ให้ user</h3><p>เตรียมข้อความ Video เรียบร้อยแล้วก็ส่งให้ user กันเลย โดยในตัวอย่างผมจะเพิ่มข้อความ Text ต่อท้าย Video ด้วย เพื่อบอก user ว่า ดู Video ให้จบเพื่อรับของรางวัล</p><p>โดยผมยิง Broadcast ผ่าน Postman ผลลัพธ์การส่งดูได้จากรูป GIF ด้านล่างเลย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GNYOKEMF9WHsHryKoDK2mA.gif" /></figure><h3>ทดสอบรับ Webhook Event</h3><p>หลังจาก user ได้รับข้อความ Video เราแล้ว มาถึงขั้นตอนสำคัญ เรามาดูกันดีกว่าว่าถ้า user กดดู Video จนจบเราจะได้ Webhook Event มาแบบไหน ลองดูจากรูป GIF ด้านล่างได้เลย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_koOL2kNmaICfrx2bMeCw.gif" /></figure><p>จะเห็นว่าพอ user ดู Video จนจบแล้ว เราจะได้ Webhook Event ที่ชื่อว่า <strong>“videoPlayComplete“</strong> มาทันที เรามาดูรายละเอียดของ event นี้กัน</p><pre>{<br>  &quot;destination&quot;: &quot;xxxxxxxxxx&quot;,<br>  &quot;events&quot;: [<br>    {<br>      &quot;replyToken&quot;: &quot;nHuyWiB7yP5Zw52FIkcQobQuGDXCTA&quot;,<br>      &quot;type&quot;: &quot;videoPlayComplete&quot;,<br>      &quot;mode&quot;: &quot;active&quot;,<br>      &quot;timestamp&quot;: 1462629479859,<br>      &quot;source&quot;: {<br>        &quot;type&quot;: &quot;user&quot;,<br>        &quot;userId&quot;: &quot;U4af4980629...&quot;<br>      },<br>      &quot;webhookEventId&quot;: &quot;01FZ74A0TDDPYRVKNK77XKC3ZR&quot;,<br>      &quot;deliveryContext&quot;: {<br>        &quot;isRedelivery&quot;: false<br>      },<br>      &quot;videoPlayComplete&quot;: {<br>        &quot;trackingId&quot;: &quot;track-id&quot;<br>      }<br>    }<br>  ]<br>}</pre><p>เราดูใน events เป็นหลักนะครับ</p><ul><li><strong>replyToken</strong> เราได้ replyToken มาด้วย!! หมายความว่าเราสามารถส่งข้อความตอบกลับไปให้ user ได้ฟรี หลังดูวีดีโอจบ แจ่มเลยย</li><li><strong>timestamp</strong> คือ เวลาที่ usre ดูวีดีโอจบ</li><li><strong>source.userId</strong> แน่นอนเราได้ userId มาด้วย จะได้รู้ว่าเป็น user คนไหน</li><li><strong>videoPlayComplete.trackingId </strong>คือ trackingId ที่เราใส่ไว้ตอนสร้างข้อความ Video นั่นเอง</li></ul><blockquote>ได้ข้อมูลครบแล้ว มาทำตามโจทย์ที่ตั้งไว้กันเลย</blockquote><h3>Verify X-Line-Signature</h3><p>เริ่มต้นเลยเพื่อความปลอดภัย ตรวจสอบ X-Line-Signature กันก่อนเลย ใครยังไม่รู้เรื่องนี้อยากศึกษาเพิ่มเติมเข้าไปอ่านได้ที่บทความนี้เลย<br><a href="https://medium.com/linedevth/7a94d9548f34">https://medium.com/linedevth/7a94d9548f34</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2121b813fa60ec6ded691a18202ecc37/href">https://medium.com/media/2121b813fa60ec6ded691a18202ecc37/href</a></iframe><p>ผมสร้าง function ชื่อ verify_signature แล้วเรียกใช้ที่ต้น functions webhook บรรทัดที่ 5 เพื่อตรวจสอบ X-Line-Signature</p><h3>ตรวจสอบข้อมูล Events</h3><p>จากนั้น ผมจะเช็คซะหน่อยว่า request ที่ส่งมามีข้อมูล events ส่งมาหรือไม่</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5cf59b4cda2023736e2028afe924d05/href">https://medium.com/media/a5cf59b4cda2023736e2028afe924d05/href</a></iframe><h3>Handle Events</h3><p>ต่อมาเราจะตรวจสอบ event ที่ได้รับมาว่าอใช่ event <strong>“</strong><strong>videoPlayComplete”</strong> ที่เราต้องการหรือไม่</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc2f4bdef1ce20bc7a3bd1c9e8cbf7f9/href">https://medium.com/media/bc2f4bdef1ce20bc7a3bd1c9e8cbf7f9/href</a></iframe><p>โดยถ้าใช่ event นี้เราจะทำการเรียก function <strong>“savePointVideoComplete”</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1383b0b51829c0307c6976a14c848a8f/href">https://medium.com/media/1383b0b51829c0307c6976a14c848a8f/href</a></iframe><p>function “<strong>savePointVideoComplete</strong>” จะเป็น function หลักในการตรวจสอบและแจกคะแนนให้ user โดยจะทำงานเรียก function อื่น ตามนี้</p><ul><li><strong>checkPointExists</strong> คือ function เพื่อตรวจสอบว่า user นี้เคยได้คะแนนจากกิจกรรมนี้ไปรึยัง</li><li><strong>collectPoint</strong> กรณีที่ user ยังไม่ได้รับคะแนนกิจกรรมนี้จะเรียก function นี้เพื่อเก็บคะแนนให้ user</li><li><strong>reply</strong> สุดท้ายเราจะส่งข้อความ reply กลับไปบอก user ว่าเค้าได้รับคะแนน หรือ เคยได้คะแนนไปแล้ว</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac050c4e953a906630e87b5989d5c3ca/href">https://medium.com/media/ac050c4e953a906630e87b5989d5c3ca/href</a></iframe><p>function “<strong>checkPointExists</strong>” ทำหน้าที่ตรวจสอบว่า user ได้คะแนนกิจกรรมนี้ไปรึยัง โดยเช็คจากข้อมูลใน firestore โดยใช้ userId กับ trackingId ในการตรวจสอบ</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de939c4be0a4cbba1645e77f0ee580e7/href">https://medium.com/media/de939c4be0a4cbba1645e77f0ee580e7/href</a></iframe><p>function “<strong>collectPoint</strong>” ทำหน้าที่ เก็บคะแนนให้ user</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48c5aab3dd0876db164993c52f77c1f1/href">https://medium.com/media/48c5aab3dd0876db164993c52f77c1f1/href</a></iframe><p>function “<strong>reply</strong>” ทำหน้าที่ส่งข้อความตอบกลับให้ user</p><h3>Result</h3><p>มาดูผลลัพธ์กันครับ ข้อมูลใน Firestore เข้าถูกต้องแล้ว</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DdiR2DtHV1H-l-X4gI7zeQ.png" /></figure><p>ที่หน้า Chat สุดท้าย user ก็จะเห็นข้อความประมาณนี้ค้าบบ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nP_4Ibv0Er6g1cP-SlOorQ.jpeg" /></figure><h4><strong><em>สรุป</em></strong></h4><p>สำหรับ Webhook Event “Video viewing complete” เราสามารถประยุกต์ใช้ได้หลากหลายวิธีเลยนะครับ ลองไปปรับใช้กันดูนะครับ</p><p>เพื่อนๆ สามารถ Download Code ตัวอย่างในบทความ ได้จาก git นี้เลยนะครับ</p><p><a href="https://github.com/PamornT/LINE_VideoPlayComplete.git">GitHub - PamornT/LINE_VideoPlayComplete</a></p><p>หวังว่าจะมีประโยชน์กับเพื่อนๆ นะครับ</p><p>สุดท้ายนี้ถ้าชอบฝากให้กด <strong><em>Clap </em></strong>ถ้าใช่ให้กด<strong><em> Share </em></strong>แต่ถ้าอยากได้ระบบ CRM หรือ Member Loyalty ที่ใช้กับ user บน LINE OA แบบเนียนๆ <strong><em>ทักมาหาผมได้เลยครับ </em></strong>😄</p><p>แล้วพบกันบทความต่อไปครับ ขอบคุณครับ</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b39e6cab589c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linedevth/%E0%B9%80%E0%B8%97%E0%B8%84%E0%B8%99%E0%B8%B4%E0%B8%84%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%AA%E0%B8%A3%E0%B9%89%E0%B8%B2%E0%B8%87%E0%B9%80%E0%B8%84%E0%B8%A3%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%87%E0%B8%A1%E0%B8%B7%E0%B8%AD%E0%B8%81%E0%B8%A3%E0%B8%B0%E0%B8%95%E0%B8%B8%E0%B9%89%E0%B8%99%E0%B8%A2%E0%B8%AD%E0%B8%94%E0%B8%84%E0%B8%99%E0%B8%94%E0%B8%B9-video-content-%E0%B9%83%E0%B8%99-line-oa-b39e6cab589c">เทคนิคการสร้างเครื่องมือกระตุ้นยอดคนดู Video Content ใน LINE OA</a> was originally published in <a href="https://medium.com/linedevth">LINE Developers Thailand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ตรวจสอบข้อมูลที่เปลี่ยนแปลงบน Google Sheets ด้วย Firebase RTDB + LINE Notify]]></title>
            <link>https://medium.com/linedevth/%E0%B8%95%E0%B8%A3%E0%B8%A7%E0%B8%88%E0%B8%AA%E0%B8%AD%E0%B8%9A%E0%B8%82%E0%B9%89%E0%B8%AD%E0%B8%A1%E0%B8%B9%E0%B8%A5%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B9%80%E0%B8%9B%E0%B8%A5%E0%B8%B5%E0%B9%88%E0%B8%A2%E0%B8%99%E0%B9%81%E0%B8%9B%E0%B8%A5%E0%B8%87%E0%B8%9A%E0%B8%99-google-sheets-%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-firebase-rtdb-line-notify-18100c495066?source=rss-655fb7ee2ef3------2</link>
            <guid isPermaLink="false">https://medium.com/p/18100c495066</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[linedevth]]></category>
            <category><![CDATA[line-notify]]></category>
            <category><![CDATA[google-sheets]]></category>
            <category><![CDATA[firebase-realtime]]></category>
            <dc:creator><![CDATA[PamornT]]></dc:creator>
            <pubDate>Thu, 23 Dec 2021 09:35:12 GMT</pubDate>
            <atom:updated>2021-12-23T09:35:12.207Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNJ8r18EE912MHazRNiDAw.jpeg" /></figure><p>สวัสดีครับบทความนี้จะมาแนะนำวิธีการนำเข้าข้อมูลที่มีการเปลี่ยนแปลงจาก Google Sheets เข้าไปที่ Firebase Realtime Database แล้วส่งข้อความแจ้งเตือนไปที่ LINE Group ของผู้ดูแลทุกครั้งเมื่อข้อมูลที่ Google Sheets ถูกแก้ไข</p><p>และด้วย Firebase ทำการ Deprecated ตัว Database Secret เรียบร้อยแล้ว บทความนี้เลยจะแนะนำวิธีการต่อกับ Firebase ผ่าน OAuth แทนครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tWl42MmZe4JKwN7vk7LhYg.png" /></figure><h3>เริ่มกันเลย!!!!</h3><h3>1. สร้าง Project on Google Firebase</h3><p>เข้าไป Firebase Console ตามลิงก์นี้เลย (<a href="https://console.firebase.google.com/">https://console.firebase.google.com/</a>)</p><p><a href="https://console.firebase.google.com/"></a></p><p>คลิกที่กล่อง Add project ตามรูปด้านล่าง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BSMvxAoItKKTkKPYqdl_Zg.png" /></figure><p>ตั้งชื่อ Project ที่ต้องการเลยครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KDVWPkHNPi_B2aoY0cwew.png" /></figure><p>ส่วน Google Analytics ผมยังไม่ได้ใช้จะปิดไปก่อนนะครับ เสร็จแล้วกดปุ่ม Create project ได้เลย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nb72vLine7rygmM_2FUdng.png" /></figure><p>หลังจากนั้นจะมาเจอหน้าตาเหมือนรูปด้านล่าง ก็เป็นอันเสร็จขั้นตอนการสร้าง Project แล้วครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EC170hwPtm97svESubGYQQ.png" /></figure><h3>2. เปิดใช้งาน RTDB (Realtime Database)</h3><p>จากหน้า Firebase Console ให้คลิกที่เมนู Realtime Database แล้วกดปุ่ม Create Database เลยครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BEy5llM4SUt7NU6BftFkag.png" /></figure><p>หลังจากกดปุ่ม Create Database แล้วจะมี Dialog ขึ้นมาให้เรา<strong><em>เลือก Region</em></strong><em> </em>หรือสถานที่เก็บข้อมูลใน Database นั่นเอง ณ. ตอนนี้จะมีให้เลือก 3 ที่ ผมเลือกที่ <strong><em>Singapore (asia-southeast1)</em></strong><em> </em>นะครับ เพราะน่าจะใกล้บ้านเราที่สุดแล้ว เลือกแล้วกดปุ่ม Next ได้เลยครับ</p><blockquote><em>(ถ้าอยากศึกษาเรื่อง Region มากขึ้นเข้าไปอ่านต่อได้ที่นี่เลยครับ </em><a href="https://medium.com/linedevth/539e06bb001d"><em>https://medium.com/linedevth/539e06bb001d</em></a><em>)</em></blockquote><p><a href="https://medium.com/linedevth/region-%E0%B9%80%E0%B8%A3%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%87%E0%B8%87%E0%B9%88%E0%B8%B2%E0%B8%A2%E0%B9%86-%E0%B8%97%E0%B8%B5%E0%B9%88-line-dev-%E0%B8%AA%E0%B8%B2%E0%B8%A2-cloud-functions-for-firebase-%E0%B9%84%E0%B8%A1%E0%B9%88%E0%B8%84%E0%B8%A7%E0%B8%A3%E0%B8%A1%E0%B8%AD%E0%B8%87%E0%B8%82%E0%B9%89%E0%B8%B2%E0%B8%A1-539e06bb001d">Region เรื่องง่ายๆ ที่ ​LINE Dev สาย Cloud Functions for Firebase ไม่ควรมองข้าม</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HUvMiaJ9VxZN8BtT4XiAOw.png" /></figure><p>ขั้นตอนถัดมาจะเป็นการเลือก <strong><em>Mode ของ Database ให้เลือกเป็น locked mode</em> </strong>ไปเลยนะครับ เพื่อความปลอดภัยของข้อมูลครับ เลือกแล้วกดปุ่ม Enable ได้เลยครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dsirlSgRBpYuCjSd-KbF3w.png" /></figure><p>สร้าง RTDB เสร็จเรียบร้อยแล้ว จะได้หน้าตาแบบในรูปด้านล่างนี้ครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FaJS1yGxNz60rATPKB6XqA.png" /></figure><h3>3. สร้าง Google Sheets</h3><p>ผมลองสร้างตัวอย่าง Google Sheets ข้อมูลประมาณนี้นะครับ (<a href="https://docs.google.com/spreadsheets/">https://docs.google.com/spreadsheets/</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GTyyJSbYrw6HlC3bfZ4i1g.png" /></figure><h3>4. สร้าง Apps Script</h3><p>ขั้นตอนนี้เราจะสร้าง Apps Script สำหรับ Sync ข้อมูลจาก Google Sheets ไป RTDB</p><ul><li><strong>เริ่มต้นคลิกที่เมนู Extensions &gt; Apps Script</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Oe8H7xJZNnPn9nq0Llwxw.png" /></figure><p>เข้ามาแล้วหน้าตาก็จะประมาณนี้นะครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7Cc7x4LY8QFqZAOI0-5bA.png" /></figure><p>ต่อไปเราต้องเปิด appsscript.json ขึ้นมาก่อน เพื่อจะเปิดใช้ Libraly OAuth สำหรับเชื่อมต่อกับ Firebase</p><ul><li><strong>เข้าไปที่ Project Settings คลิกเลือก Show “appsscript.json” manifest file in editor</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iU_cBiqXKcY0XbqtmdxeIg.png" /></figure><ul><li><strong>เสร็จแล้วกลับไปที่ Editor &gt; appsscript.json แล้วเพิ่ม Libraly</strong></li></ul><blockquote>“oauthScopes”: [</blockquote><blockquote>“https://www.googleapis.com/auth/userinfo.email&quot;,</blockquote><blockquote>“https://www.googleapis.com/auth/firebase.database&quot;,</blockquote><blockquote>“https://www.googleapis.com/auth/script.external_request&quot;,</blockquote><blockquote>“https://www.googleapis.com/auth/spreadsheets&quot;</blockquote><blockquote>]</blockquote><p>เสร็จแล้วหน้าตา appsscript.json ก็จะประมาณนี้ครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w1Uk8kqrOB_TGGF0rmShAw.png" /></figure><ul><li><strong>ต่อไปคลิกที่ Code.gs เพื่อเริ่มสร้าง Code สำหรับ Sync Data</strong></li></ul><p>ให้ Copy Code ด้านล่างนี้ไปใส่ Code.gs ได้เลยครับ โดยให้เปลี่ยนค่าตามนี้</p><p>dataPath = ชื่อของข้อมูลที่ต้องการเก็บเทียบแล้วจะคล้ายๆ กับชื่อ DB Table<br>projectId = ID ของ Firebase Project เข้าไปเอาได้ที่ Project settings ใน Firebase<br>region = region ที่เราเลือกตอนสร้าง RTDB</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f2a687c09dc4e233467ecabac5b01a7/href">https://medium.com/media/5f2a687c09dc4e233467ecabac5b01a7/href</a></iframe><ul><li><strong>เสร็จแล้วกดปุ่ม Save Project</strong></li></ul><h3>5. สร้างปุ่มใน Google Sheets</h3><p>ขั้นตอนนี้เราจะสร้างปุ่มใน Google Sheets เพื่อเรียกให้ Functions syncData() ทำงาน</p><ul><li><strong>คลิกที่เมนู Insert &gt; Drawing</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j09HptyWT_lNuhYF4Z-ONA.png" /></figure><ul><li>หลังจากเปิด Drawing ขึ้นมาแล้วให้เลือก Shapes แล้วเลือกรูปสี่เหลี่ยม</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Pu-bBgYRreiA2afZTxDkw.png" /></figure><ul><li>ทำการวาดรูปสี่เหลี่ยมแล้วใส่ข้อความ Sync Data แล้วกดปุ่ม Save and Close</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*msrRcHfOsGCRQQK-EoXI3A.png" /></figure><ul><li>หลังจากนั้นคลิกที่เมนู 3 จุดแล้วเลือก Assign script</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yWgO1BDfetvUrg2P06V1ZA.png" /></figure><ul><li>หลังจากนั้นเอาชื่อ function ที่เราสร้างใน Apps Script มาใส่ จากตัวอย่างจะชื่อ syncData แล้วคลิก OK</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*7y9V1-RNOAZt7CF2rVw1lg.png" /></figure><ul><li>ต่อไปกดปุ่ม Sync Data จะมี Dialog ขึ้นมาเพื่อขอสิทธิ Authorize ของ Firebase ให้กดปุ่ม Continue เลย</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V40gO6am_xeLDgSsZm3e2Q.png" /></figure><ul><li>เสร็จแล้วให้เลือก Account ที่ใช้สร้าง Firebase Project</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8D9KZMU0uVEWCfLmsPnu7A.png" /></figure><ul><li>หลังจากเลือก Account แล้วจะมีหน้าจอเด้งขึ้นมาแจ้งเรื่อง Security ให้กดที่คำว่า Advance แล้วเลือก Go to (unsafe)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*liiCDA8A2UCgDWxrMBN2Sg.png" /></figure><ul><li>หลังจากนั้นจะมีหน้าต่างขึ้นมาเพื่อขอให้ Allow สิทธิในการเข้าถึง Firebase Realtime ให้คลิกที่ปุ่ม Allow</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j_nIzw7YLgadhfN92XP60A.png" /></figure><ul><li>หลังจาก Allow แล้วจะกลับมาที่หน้า Google Sheets ให้<strong>กดปุ่ม Sync Data อีกครั้ง</strong>จะขึ้นข้อความว่า <strong><em>Finished script </em></strong>แสดงว่า function เราทำงานได้แล้ว :)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vptXzf46KqKHj5x6XHOAOg.png" /></figure><ul><li>ลองทดสอบเปิด Realtime Database ใน Firebase ดูจะพบว่าข้อมูลเข้าเรียบร้อยแล้วครับ</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXeZdHbc24tCFgla6Td5hQ.png" /></figure><h3>6. ส่ง LINE Notify แจ้งเตือนเมื่อมีข้อมูลเปลี่ยนแปลง</h3><h4>สร้าง LINE Group สำหรับรับ Notify แจ้งเตือน</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*_g0aK4n56RglsxsYbsGHzw.png" /></figure><h4>สร้าง LINE Notify Token</h4><ul><li>เข้าไปที่ <a href="https://notify-bot.line.me/my/">https://notify-bot.line.me/my/</a> แล้วคลิกที่ปุ่ม Generate Token ด้านล่าง</li><li>จะมีหน้าต่างขึ้นมาให้เลือก LINE Group ที่เราต้องการส่ง Notify เลือกกลุ่มที่ต้องการแล้วกดปุ่ม Generate Token</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jx7b51IkwYt00MG7F-XXmA.png" /></figure><ul><li>หลังจากนั้นจะมีหน้าต่างแสดง Token ให้เรา Copy เก็บไว้ก่อน <strong><em>อย่าทำหายเด็ดขาด!!</em></strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZvkyhT0AZWB_ltVjX_ERKw.png" /></figure><h4>สร้าง Funtions สำหรับ แจ้งเตือนเมื่อข้อมูลเปลี่ยนแปลง</h4><p>เปิด Terminal/CMD แล้ว run คำสั่งตามนี้</p><ul><li><strong>สร้าง Folder ใหม่</strong></li></ul><pre>mkdir GGSheets2RTDB</pre><ul><li><strong>เข้าไปที่ Folder ใหม่</strong></li></ul><pre>cd GGSheets2RTDB</pre><ul><li><strong>Initialize Firebase Functions</strong></li></ul><pre>firebase init functions</pre><ul><li><strong>เลือก Use an existing project</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wHA7dE2jG6OQ2c6LqBbD8g.png" /></figure><ul><li><strong>เลือก Project Firebase ที่เราสร้างเมื่อต้นบทความ</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dg5P2_ubSUbE1AMDN-MRwg.png" /></figure><ul><li><strong>หลังจากนั้นให้ Enter ไปเรื่อยๆ จนเสร็จสิ้นการติดตั้ง</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*gY1h_Gv-7u5AZ5Zndi5kaQ.png" /></figure><ul><li>ติดตัง axios เพื่อเรียก service LINE Notify API</li></ul><pre>cd functions</pre><pre>npm install axios --save</pre><h3>เปลี่ยน Firebase Billing Plan</h3><p>ก่อนเปิดใช้งาน Firebase functions เราต้องเปลี่ยน Billing Plan จาก Spark plan เป็น Blaze plan ก่อน</p><blockquote>กรณีใช้ Blaze Plan คุณจะได้โควต้าฟรีทั้งหมดของ Spark Plan มาสมทบด้วย แปลว่าคุณจะต้องใช้โควต้าฟรีให้หมดก่อน จึงจะเริ่มคิดเงิน</blockquote><ul><li>คลิกลิงก์ Upgrade ตรงด้านล่างขวา ตามรูปด้านล่าง</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-r04C-UQvRsvKQ6YP5eEpQ.png" /></figure><ul><li>หลังจากนั้นจะมีหน้าต่างขึ้นมาให้เลือก Plan ให้คลิกเลือกปุ่ม Select plan ตรง Blaze plan</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N6Bt0RO219vBLPLxlina3Q.png" /></figure><ul><li>เลือก Billing ที่เราต้องการใช้งาน แล้วกดปุ่ม Continue</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p86Sbxtuw8ZfZZFcOdI08A.png" /></figure><ul><li>หลังจากนั้นจะมีหน้าจอสรุปขึ้นมาให้ตรวจสอบ ถ้าถูกต้องแล้วกดปุ่ม Purchase</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OdovJpId7zssvB17pV9fjA.png" /></figure><p>ทำการเปลี่ยน Plan เรียบร้อยแล้ว ถัดไปเราจะทำการแก้ไข Code เพื่อตรวจสอบข้อมูลที่เปลี่ยนแปลงแล้วส่ง LINE Notify กันค้าบ</p><h4>เริ่มแก้ไข Code!!</h4><ul><li><strong>เปิด Folder ที่เราสร้างไว้ด้วย Editor จะเห็นโครงสร้าง File แบบในรูปด้านล่าง</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nesf1-Mrbfpr4d-LnSrdkg.png" /></figure><ul><li>เปิดไฟล์ functions/index.js แล้วเอา Code ด้านล่างไปใส่ โดย<strong>เอาค่า LINE Notify Token ที่บันทึกไว้ใส่แทนคำว่า <em>REPLACE LINE NOTIFY TOKEN HERE</em></strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26dbc41050f96617d89a76cdb3825cd1/href">https://medium.com/media/26dbc41050f96617d89a76cdb3825cd1/href</a></iframe><p>จากตัวอย่าง Code จะเป็นการสร้าง Functions ด้วยการอ้างอิงไปที่ RTDB ชื่อ Product โดยดัก Event ทุกครั้งที่ข้อมูลมีการเปลี่ยนแปลงข้อมูล (onWrite) ความสะดวก ของการใช้ functions แบบ onWrite คือ functions นี้จะทำงานแค่ตอนข้อมูลมีการเปลี่ยนแปลงเท่านั้น ทำให้ง่ายต่อการจัดการ</p><ul><li><strong>Deploy functions</strong></li></ul><p>วิธีการ deploy functions ก็ง่ายมากครับ run คำสั่งด้านล่างได้เลย</p><pre>firebase deploy</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EXWsuTpHWbv_F-mAuMj4Og.png" /></figure><h3>ทดสอบ</h3><p>ทดสอบแก้ไขข้อมูลบน Google Sheets แล้วกดปุ่ม Sync Data ถ้ามีข้อมูลถูกแก้ไข จะมี Notify แจ้งเตือนใน LINE Group ทันทีเลย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*LlcFLKuJizaro4T0fEh7CQ.png" /></figure><p>เสร็จเรียบร้อยแล้วนะครับ หวังว่าบทความนี้จะมีประโยชน์กับเพื่อนๆ นะครับ แล้วพบกันบทความถัดไปครับ ขอบคุณครับ</p><blockquote>สำหรับผู้ที่สนใจพัฒนา Application บน ​Platform LINE เข้ามาแลกเปลี่ยนความรู้กันได้ที่ Facebook LINE Developer Group ที่ลิงก์ด้านล่างได้เลยนะครับ</blockquote><p><a href="https://www.facebook.com/groups/LINEDEVTH">Log in or sign up to view</a></p><blockquote>และสำหรับใครที่ชอบในการดูเนื้อหาต่างๆ เป็นวีดีโอ สามารถเข้าไปดูที่ Youtube Channel ของ LINE Developer Thailand ที่ลิงก์ด้านล่างได้เลยค้าบ</blockquote><p><a href="https://www.youtube.com/channel/UCKryrZWw3vTpR-Q8KJQHOYw">LINE Developers Thailand</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18100c495066" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linedevth/%E0%B8%95%E0%B8%A3%E0%B8%A7%E0%B8%88%E0%B8%AA%E0%B8%AD%E0%B8%9A%E0%B8%82%E0%B9%89%E0%B8%AD%E0%B8%A1%E0%B8%B9%E0%B8%A5%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B9%80%E0%B8%9B%E0%B8%A5%E0%B8%B5%E0%B9%88%E0%B8%A2%E0%B8%99%E0%B9%81%E0%B8%9B%E0%B8%A5%E0%B8%87%E0%B8%9A%E0%B8%99-google-sheets-%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-firebase-rtdb-line-notify-18100c495066">ตรวจสอบข้อมูลที่เปลี่ยนแปลงบน Google Sheets ด้วย Firebase RTDB + LINE Notify</a> was originally published in <a href="https://medium.com/linedevth">LINE Developers Thailand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>