Go client for MG Bot API
Go to file
2018-09-08 16:26:39 +03:00
v1 Add Bot.Roles 2018-09-08 15:34:06 +03:00
.gitignore add initial set of methods 2018-08-29 02:44:06 +03:00
.travis.yml update channels request struct 2018-08-30 13:58:55 +03:00
LICENSE Initial commit 2018-06-29 20:07:35 +03:00
README.md Add websocket example 2018-09-04 11:53:41 +03:00

Build Status GitHub release GoLang version Godoc reference

retailCRM Message Gateway Bot API Go client

Install

go get -u -v github.com/retailcrm/mg-bot-api-client-go

Usage

package main

import (
	"fmt"
	"net/http"

	"github.com/retailcrm/mg-bot-api-client-go/v1"
)

func main() {
    var client = v1.New("https://token.url", "cb8ccf05e38a47543ad8477d49bcba99be73bff503ea6")
    message := MessageSendRequest{
        Scope:   "public",
        Content: "test",
        ChatID:  12,
    }

    data, status, err := c.MessageSend(message)
    if err != nil {
        t.Errorf("%d %v", status, err)
    }

    fmt.Printf("%v", data.MessageID)
}

Websocket Example

package main

import (
	"encoding/json"
	"log"
	"strings"

	"github.com/gorilla/websocket"
	"github.com/retailcrm/mg-bot-api-client-go/v1"
)

func main() {
	var client = v1.New("https://token.url", "cb8ccf05e38a47543ad8477d49bcba99be73bff503ea6")

	url, headers, err := client.WsMeta([]string{"message_new"})
	if err != nil {
		log.Fatal("wsMeta:", err)
	}

	wsConn, _, err := websocket.DefaultDialer.Dial(url, headers)
	if err != nil {
		log.Fatal("dial:", err)
	}

	for {
		var wsEvent v1.WsEvent
		err = wsConn.ReadJSON(&wsEvent)
		if err != nil {
			log.Fatal("ReadJSON:", err)
		}

		var eventData v1.WsEventMessageNewData
		err = json.Unmarshal(wsEvent.Data, &eventData)
		if err != nil {
			log.Fatal("Unmarshal:", err)
		}

		if !strings.HasPrefix(eventData.Message.Content, "Hello") {
			continue
		}

		message := v1.MessageSendRequest{
			Scope:   "public",
			Content: "Bonjour!",
			ChatID:  eventData.Message.ChatID,
		}

		_, status, err := client.MessageSend(message)
		if err != nil {
			log.Fatalf("%d %v", status, err)
		}
	}
}