Untitled
raw download clone
TEXT
views 12
,
size 4668 b
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"
	"strings"

	"github.com/mattermost/mattermost-server/v5/model"
	"github.com/mattermost/mattermost-server/v5/plugin"
)

const (
	commandSms = "sms" //Trigger word for the slash command

	// wsEventList = "list"
)

// const helpCommandText = "###### TrueTrader Trade sms  - Slash Command Help\n" +
// 	"\n* `/sms [GROUP_NAME ] [MESSAGE]` - /sms swing This is a swing message  \n"

// func (p *Plugin) registerCommands() error {
// 	if err := p.API.RegisterCommand(createSmsCommand()); err != nil {
// 		return errors.Wrapf(err, "failed to register %s command", commandSms)
// 	}

// 	return nil
// }

// ExecuteCommand executes a command that has been previously registered via the RegisterCommand
func (p *Plugin) ExecuteCommand(c *plugin.Context, args *model.CommandArgs) (*model.CommandResponse, *model.AppError) {
	split := strings.Fields(args.Command)

	if len(split) < 3 { //expecting atleast 3 words
		return responsef("Not in right format. Try again"), nil
	}

	//action := split[1]
	return p.executeCommandList(args), nil

}

//Check the user is system_admin , otherwise disable plugin
func (p *Plugin) UserHasLoggedIn(c *plugin.Context, user *model.User) {
	if !(strings.Contains(user.Roles, "system_admin") || strings.Contains(user.Roles, "owner")) {
		if err := p.API.DisablePlugin("tt-sms-slash-command"); err != nil {
			//return errors.Wrapf(err)
			p.API.LogInfo("Disabling Plugin sms-slash-cmd")
		}

	}
}

func (p *Plugin) executeCommandList(args *model.CommandArgs) *model.CommandResponse {
	split := strings.Fields(args.Command)
	group := split[1]
	messageArray := split[2:len(split)] //The message starts from the 3rd word onwards
	smsMessage := strings.Join(messageArray, " ")

	wpURL := "https://staging-web.truetrader.net"
	clientID := "NVMYqvi4mUk8qa0N4rKAnY3zhBDoKpBWEqfhjI07"
	/* #nosec */
	clientSecret := "JwaJrMdRS0iTLtYqIa3ihwPYA78U5S4oqKVjCvid"
	userName := "maneesh"
	/* #nosec */
	password := "XJoR4lY6mT@"

	payload := strings.NewReader("grant_type=password&username=" + userName + "&password=" + password + "&client_id=" + clientID + "&client_secret=" + clientSecret)

	client := &http.Client{}

	tokenURL := wpURL + "/oauth/token/"
	req, _ := http.NewRequest("POST", tokenURL, payload)
	req.Header.Add("content-type", "application/x-www-form-urlencoded")
	resp, err2 := client.Do(req)
	if err2 != nil {
		p.API.LogError(err2.Error())
		return nil
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	//var message = ""
	var result map[string]interface{}
	var message = ""

	if err != nil {
		message = "Something went wrong!"
	} else {
		_ = json.Unmarshal(body, &result)
		accessToken := result["access_token"].(string)

		smsAPIURL := wpURL + "/wp-json/smsbatch/v1/sms/"

		//req, _ := http.NewRequest("POST", smsAPIURL, nil)

		data := url.Values{}
		//data.Set("pw", "MEOW")
		data.Set("message", smsMessage)
		data.Set("smsgroup", group)

		u, _ := url.ParseRequestURI(smsAPIURL)
		//u.Path = resource
		urlStr := u.String()

		client := &http.Client{}
		req1, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
		//req1.Header.Add("content-type", "application/json")
		req1.Header.Add("authorization", "Bearer "+accessToken)
		req1.Header.Add("Content-Type", "application/x-www-form-urlencoded")
		req1.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

		resp, err1 := client.Do(req1)

		if err1 != nil {
			p.API.LogError(err1.Error())
			return nil
		}

		defer resp.Body.Close()
		body, err3 := ioutil.ReadAll(resp.Body)

		if err3 != nil {
			message = "Something went wrong"
		} else {
			respBody := string(body)
			message = "Sent Message,\"Truetrader.net " + group + " Alert: " + smsMessage + "\""
			message = message + "\n" + respBody[1:len(respBody)-1]

		}
	}
	post := &model.Post{
		Message:   message,
		UserId:    args.UserId,
		ChannelId: args.ChannelId,
	}
	_ = p.API.SendEphemeralPost(args.UserId, post)

	return &model.CommandResponse{}
}
func responsef(format string, args ...interface{}) *model.CommandResponse {
	return &model.CommandResponse{
		ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
		Text:         fmt.Sprintf(format, args...),
		Type:         model.POST_DEFAULT,
	}
}

func createSmsCommand() *model.Command {

	return &model.Command{
		Trigger:          commandSms,
		AutoComplete:     true,
		AutoCompleteHint: " /sms [GROUP_NAME] [MESSAGE]",
	}
}
close fullscreen
Login or Register to edit or fork this paste. It's free.