ホームページ バックエンド開発 Golang データスターを使用したボットとのリアルタイムチャット

データスターを使用したボットとのリアルタイムチャット

Oct 18, 2024 am 06:08 AM

realtime chat with bot using data-star

皆さんこんにちは、

パート 1 では、シンプルなサーバー側時計を作成しました https://dev.to/blinkinglight/golang-data-star-1o53/

そして今度は、https://nats.io と https://data-star.dev を使用して、より複雑なものを書くことにしました -

書き込んだ内容を返すチャットボット:

いくつかの Golang コード:

package handlers

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"

    "github.com/blinkinglight/chat-data-star/web/views/chatview"
    "github.com/delaneyj/datastar"
    "github.com/delaneyj/toolbelt"
    "github.com/delaneyj/toolbelt/embeddednats"
    "github.com/go-chi/chi/v5"
    "github.com/gorilla/sessions"
    "github.com/nats-io/nats.go"
)

func SetupChat(router chi.Router, session sessions.Store, ns *embeddednats.Server) error {

    type Message struct {
        Message string `json:"message"`
        Sender  string `json:"sender"`
    }

    nc, err := ns.Client()
    if err != nil {
        return err
    }

    nc.Subscribe("chat.>", func(msg *nats.Msg) {
        var message = Message{}
        err := json.Unmarshal(msg.Data, &message)
        if err != nil {
            log.Printf("%v", err)
            return
        }

        if message.Sender != "bot" {
            // do something with user message and send back response
            nc.Publish("chat."+message.Sender, []byte(`{"message":"hello, i am bot. You send me: `+message.Message+`", "sender":"bot"}`))
        }
    })

    _ = nc
    chatIndex := func(w http.ResponseWriter, r *http.Request) {
        _, err := upsertSessionID(session, r, w)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        chatview.Index().Render(r.Context(), w)
    }

    chatMessage := func(w http.ResponseWriter, r *http.Request) {
        id, err := upsertSessionID(session, r, w)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }

        var state = Message{}

        err = datastar.BodyUnmarshal(r, &state)
        if err != nil {
            http.Error(w, err.Error(), http.StatusBadRequest)
            return
        }

        state.Sender = id
        b, err := json.Marshal(state)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        nc.Publish("chat."+id, b)
        sse := datastar.NewSSE(w, r)
        _ = sse
    }

    chatMessages := func(w http.ResponseWriter, r *http.Request) {

        id, err := upsertSessionID(session, r, w)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }

        var ch = make(chan *nats.Msg)
        sub, err := nc.Subscribe("chat."+id, func(msg *nats.Msg) {
            ch <- msg
        })

        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        defer close(ch)
        defer sub.Unsubscribe()

        sse := datastar.NewSSE(w, r)

        for {
            select {
            case <-r.Context().Done():
                return

            case msg := <-ch:
                var message = Message{}
                err := json.Unmarshal(msg.Data, &message)
                if err != nil {
                    datastar.Error(sse, err)
                    return
                }
                if message.Sender == "bot" {
                    datastar.RenderFragmentTempl(sse, chatview.Bot(message.Message), datastar.WithMergeAppend(), datastar.WithQuerySelector("#chatbox"))
                } else {
                    datastar.RenderFragmentTempl(sse, chatview.Me(message.Message), datastar.WithMergeAppend(), datastar.WithQuerySelector("#chatbox"))
                }
            }
        }
    }

    router.Get("/chat", chatIndex)
    router.Post("/chat", chatMessage)
    router.Get("/messages", chatMessages)

    return nil
}

func upsertSessionID(store sessions.Store, r *http.Request, w http.ResponseWriter) (string, error) {

    sess, err := store.Get(r, "chatters")
    if err != nil {
        return "", fmt.Errorf("failed to get session: %w", err)
    }
    id, ok := sess.Values["id"].(string)
    if !ok {
        id = toolbelt.NextEncodedID()
        sess.Values["id"] = id
        if err := sess.Save(r, w); err != nil {
            return "", fmt.Errorf("failed to save session: %w", err)
        }
    }
    return id, nil
}

ログイン後にコピー

とテンプレート

package chatview

import "github.com/blinkinglight/chat-data-star/web/views/layoutview"

templ Index() {
    @layoutview.Main() {
        <!-- component -->
        <div class="fixed bottom-0 right-0 mb-4 mr-4">
            <button id="open-chat" class="bg-blue-500 text-white py-2 px-4 rounded-md hover:bg-blue-600 transition duration-300 flex items-center">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
                </svg>
                Chat with Admin Bot
            </button>
        </div>
        <div id="chat-container" class="hidden fixed bottom-16 right-4 w-96">
            <div class="bg-white shadow-md rounded-lg max-w-lg w-full">
                <div class="p-4 border-b bg-blue-500 text-white rounded-t-lg flex justify-between items-center">
                    <p class="text-lg font-semibold">Admin Bot</p>
                    <button id="close-chat" class="text-gray-300 hover:text-gray-400 focus:outline-none focus:text-gray-400">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                        </svg>
                    </button>
                </div>
                <div id="chatbox" class="p-4 h-80 overflow-y-auto" data-on-load="$$get('/messages')" data-store="{ message: '' }">
                    <!-- Chat messages will be displayed here -->
                </div>
                <div class="p-4 border-t flex">
                    <input data-model="message" id="user-input" type="text" placeholder="Type a message" class="w-full px-3 py-2 border rounded-l-md focus:outline-none focus:ring-2 focus:ring-blue-500"/>
                    <button data-on-keydown.window.key_enter="$$post('/chat'); $message=''" data-on-click="$$post('/chat'); $message=''" id="send-button" class="bg-blue-500 text-white px-4 py-2 rounded-r-md hover:bg-blue-600 transition duration-300">Send</button>
                </div>
            </div>
        </div>
        <script>
        const chatbox = document.getElementById("chatbox");
                const chatContainer = document.getElementById("chat-container");
                const userInput = document.getElementById("user-input");
                const sendButton = document.getElementById("send-button");
                const openChatButton = document.getElementById("open-chat");
                const closeChatButton = document.getElementById("close-chat");

                let isChatboxOpen = true; // Set the initial state to open

                function toggleChatbox() {
                    chatContainer.classList.toggle("hidden");
                    isChatboxOpen = !isChatboxOpen; // Toggle the state
                }

                openChatButton.addEventListener("click", toggleChatbox);

                closeChatButton.addEventListener("click", toggleChatbox);
                toggleChatbox();

        </script>
    }
}

templ Me(message string) {
    <div class="mb-2 text-right">
        <p class="bg-blue-500 text-white rounded-lg py-2 px-4 inline-block">{ message }</p>
    </div>
}

templ Bot(message string) {
    <div class="mb-2">
        <p class="bg-gray-200 text-gray-700 rounded-lg py-2 px-4 inline-block">{ message }</p>
    </div>
}

ログイン後にコピー

https://github.com/blinkinglight/chat-data-star で実際の例を見つけることができます

以上がデータスターを使用したボットとのリアルタイムチャットの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

Debian OpenSSLの脆弱性は何ですか Debian OpenSSLの脆弱性は何ですか Apr 02, 2025 am 07:30 AM

OpenSSLは、安全な通信で広く使用されているオープンソースライブラリとして、暗号化アルゴリズム、キー、証明書管理機能を提供します。ただし、その歴史的バージョンにはいくつかの既知のセキュリティの脆弱性があり、その一部は非常に有害です。この記事では、Debian SystemsのOpenSSLの共通の脆弱性と対応測定に焦点を当てます。 Debianopensslの既知の脆弱性:OpenSSLは、次のようないくつかの深刻な脆弱性を経験しています。攻撃者は、この脆弱性を、暗号化キーなどを含む、サーバー上の不正な読み取りの敏感な情報に使用できます。

フロントエンドからバックエンドの開発に変身すると、JavaやGolangを学ぶことはより有望ですか? フロントエンドからバックエンドの開発に変身すると、JavaやGolangを学ぶことはより有望ですか? Apr 02, 2025 am 09:12 AM

バックエンド学習パス:フロントエンドからバックエンドへの探査の旅は、フロントエンド開発から変わるバックエンド初心者として、すでにNodeJSの基盤を持っています...

GOの浮動小数点番号操作に使用されるライブラリは何ですか? GOの浮動小数点番号操作に使用されるライブラリは何ですか? Apr 02, 2025 pm 02:06 PM

GO言語の浮動小数点数操作に使用されるライブラリは、精度を確保する方法を紹介します...

Go's Crawler Collyのキュースレッドの問題は何ですか? Go's Crawler Collyのキュースレッドの問題は何ですか? Apr 02, 2025 pm 02:09 PM

Go Crawler Collyのキュースレッドの問題は、Go言語でColly Crawler Libraryを使用する問題を調査します。 �...

Beego ormのモデルに関連付けられているデータベースを指定する方法は? Beego ormのモデルに関連付けられているデータベースを指定する方法は? Apr 02, 2025 pm 03:54 PM

Beegoormフレームワークでは、モデルに関連付けられているデータベースを指定する方法は?多くのBEEGOプロジェクトでは、複数のデータベースを同時に操作する必要があります。 Beegoを使用する場合...

Goでは、Printlnとstring()関数を備えた文字列を印刷すると、なぜ異なる効果があるのですか? Goでは、Printlnとstring()関数を備えた文字列を印刷すると、なぜ異なる効果があるのですか? Apr 02, 2025 pm 02:03 PM

Go言語での文字列印刷の違い:printlnとstring()関数を使用する効果の違いはGOにあります...

Redisストリームを使用してGO言語でメッセージキューを実装する場合、user_idタイプの変換の問題を解決する方法は? Redisストリームを使用してGO言語でメッセージキューを実装する場合、user_idタイプの変換の問題を解決する方法は? Apr 02, 2025 pm 04:54 PM

redisstreamを使用してGo言語でメッセージキューを実装する問題は、GO言語とRedisを使用することです...

Golandのカスタム構造ラベルが表示されない場合はどうすればよいですか? Golandのカスタム構造ラベルが表示されない場合はどうすればよいですか? Apr 02, 2025 pm 05:09 PM

Golandのカスタム構造ラベルが表示されない場合はどうすればよいですか?ゴーランドを使用するためにGolandを使用する場合、多くの開発者はカスタム構造タグに遭遇します...

See all articles