start of automating command handling

Former-commit-id: 7b356113772bdb9dab681b93bfcfda39f065f5f2
botanswer
AnisB 3 years ago
parent c241063191
commit b67cd45e29

@ -1 +1 @@
48551875d076651ba93a3b5e60e2c2589eb09883
ccfbe1adb71858c6f07073d72fd686b90ef95dbb

@ -5,22 +5,22 @@
package main
import (
"fmt"
"log"
"os"
"flag"
"net/http"
"io/ioutil"
"encoding/json"
"encoding/xml"
"errors"
"gosrc.io/xmpp"
"gosrc.io/xmpp/stanza"
"flag"
"fmt"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"strings"
"strconv"
"gosrc.io/xmpp"
"gosrc.io/xmpp/stanza"
"io/ioutil"
"log"
"net/http"
"os"
"path"
"encoding/xml"
"strconv"
"strings"
"time"
)
@ -28,23 +28,23 @@ const (
// APIEndpoint = "https://hodlhodl.com/api/v1"
//TestAPIEndpoint = "https://hhtestnet.com/api/v1"
//APIkey = "***REMOVED***"
JobSchedulerInterval = 60 * time.Second
JobSchedulerInterval = 60 * time.Second
// Config
infoFormat = "====== "
infoFormat = "====== "
defaultConfigFilePath = "./"
configFileName = "config"
configType = "yaml"
logStanzasOn = "logger_on"
logFilePath = "logfile_path"
configFileName = "config"
configType = "yaml"
logStanzasOn = "logger_on"
logFilePath = "logfile_path"
//Keys in config
serverAddressKey = "full_address"
clientJid = "jid"
clientPass = "pass"
configContactSep = ";"
APIEndPoint = "testapiendpoint"
APIKey = "apikey"
APIEndPoint = "testapiendpoint"
APIKey = "apikey"
)
var (
@ -58,6 +58,14 @@ var (
disconnectErr = errors.New("disconnecting client")
)
var (
Commands = map[string]Command{
"hello": &HelloCmd{},
"help": &HelpCmd{},
"default": &DefaultCmd{},
}
)
// Notification export
type Notification struct {
Status string `json:"status"`
@ -75,13 +83,45 @@ type config struct {
Contacts string `string:"contact"`
Hodlhodl map[string]string `mapstructure:"hodlhodl"`
LogStanzas map[string]string `mapstructure:"logstanzas"`
}
}
type Command interface {
Run(args []string) (string, error)
}
type HelpCmd struct {
}
func (*HelpCmd) Run(args []string) (string, error) {
helpText := " this is help"
return helpText, nil
}
type DefaultCmd struct {
}
func (*DefaultCmd) Run(args []string) (string, error) {
return "Type help to get available commands", nil
}
type HelloCmd struct {
}
func (*HelloCmd) Run(args []string) (string, error) {
return "Hi, My name is Skynet 1.0. \n How can I help you ? ", nil
}
func handleCommand(command Command, args []string) string {
result, err := command.Run(args)
if err != nil {
return "error"
}
return result
}
func main() {
//body:= strings.NewReader(' -X POST -H "Authorization: Bearer ***REMOVED***" -H "Content-Type: application/json"`)
// ============================================================
// Parse the flag with the config directory path as argument
@ -115,22 +155,21 @@ func main() {
func startClient(config *config) {
// Client Setup
clientCfg := &xmpp.Config {
clientCfg := &xmpp.Config{
TransportConfiguration: xmpp.TransportConfiguration{
Address: config.Server[serverAddressKey],
},
Jid: config.Client[clientJid],
Jid: config.Client[clientJid],
Credential: xmpp.Password(config.Client[clientPass]),
Insecure: true,
Insecure: true,
}
var err error
var client *xmpp.Client
router := xmpp.NewRouter()
router.HandleFunc("message", answerMessage)
errorHandler:= func(err error) {
errorHandler := func(err error) {
fmt.Println(err.Error())
}
@ -151,37 +190,19 @@ func startClient(config *config) {
fmt.Println("Client is running")
}
/*client, err := xmpp.NewClient(clientCfg, router, errorHandler)
if err != nil {
log.Panicln(fmt.Sprintf("Could not create a new client ! %s", err))
//log.Fatalf("%+v", err)
} else {
fmt.Println("Client running....")
}*/
//Connection manager, reconect automatically
/*cm := xmpp.NewStreamManager(client, nil)
log.Fatal(cm.Run())*/
// ====================
// Start working
// fmt.Println("CONFIG.HODLHDOL :", config.Hodlhodl[APIKey])
timer := time.NewTicker(5 * time.Second)
notifications := make(chan string, 100)
go startMessaging(client, config, notifications)
go hodlNotifications(client, config, notifications)
for {
select {
case <- timer.C:
fmt.Println("cheking notifs ...")
notifications <- gethdlNotif(config.Hodlhodl[APIKey], config.Hodlhodl[APIEndPoint])
case <-timer.C:
fmt.Println("cheking notifs ...")
notifications <- gethdlNotif(config.Hodlhodl[APIKey], config.Hodlhodl[APIEndPoint])
}
}
}
func answerMessage(s xmpp.Sender, p stanza.Packet) {
@ -192,52 +213,66 @@ func answerMessage(s xmpp.Sender, p stanza.Packet) {
}
_, _ = fmt.Fprintf(os.Stdout, "Body = %s - from = %s\n", msg.Body, msg.From)
fmt.Println("keep the message", msg.Body)
answersArray := []string {"Test","Help","Time"}
//answersArray := []string{"Test", "Help", "Time"}
switch {
case strings.Contains(strings.ToLower(msg.Body), "test") :
answer := "succesful test"
reply := stanza.Message{Attrs: stanza.Attrs{To: msg.From}, Body: answer}
fmt.Println("ANSEWERING.....")
s.Send(reply)
receivedCmd := strings.Fields(msg.Body)[0]
args := strings.Fields(msg.Body)[1:]
fmt.Println("command is : ", receivedCmd)
fmt.Println("args are : ", args)
case strings.Contains(strings.ToLower(msg.Body), "help") :
answer := strings.Join(answersArray,", ")
reply := stanza.Message{Attrs: stanza.Attrs{To: msg.From}, Body: "here is the list of commands : " + answer}
s.Send(reply)
case strings.Contains(strings.ToLower(msg.Body), "time") :
answer := time.Now().String()
reply := stanza.Message{Attrs: stanza.Attrs{To: msg.From}, Body: answer}
s.Send(reply)
// if command is handled
/*if strings.Contains(strings.ToLower(keepMessage), "help") {
testMessage := "test"
reply := stanza.Message{Attrs: stanza.Attrs{To: msg.From}, Body: testMessage}
s.Send(reply)
}*/
// Commands is a dict of Commands=map[ string ]Command
// [ regCommandName ]regCommand
for regCommandName, regCommand := range Commands {
var result string
if receivedCmd == regCommandName {
result = handleCommand(regCommand, args)
} else {
result = handleCommand(Commands["default"], args)
}
/*reply := stanza.Message{Attrs: stanza.Attrs{To: msg.From}, Body: msg.Body}
_ = s.Send(reply)*/
reply := stanza.Message{Attrs: stanza.Attrs{To: msg.From}, Body: result}
s.Send(reply)
}
}
//switch {
//case strings.Contains(strings.ToLower(msg.Body), "test"):
//answer := "succesful test"
//reply := stanza.Message{Attrs: stanza.Attrs{To: msg.From}, Body: answer}
//fmt.Println("ANSEWERING.....")
//s.Send(reply)
//case strings.Contains(strings.ToLower(msg.Body), "help"):
//answer := strings.Join(answersArray, ", ")
//reply := stanza.Message{Attrs: stanza.Attrs{To: msg.From}, Body: "here is the list of commands : " + answer}
//s.Send(reply)
func startMessaging(client xmpp.Sender, config *config, notifications chan string) {
//case strings.Contains(strings.ToLower(msg.Body), "time"):
//answer := time.Now().String()
//reply := stanza.Message{Attrs: stanza.Attrs{To: msg.From}, Body: answer}
//s.Send(reply)
//}
}
func hodlNotifications(client xmpp.Sender, config *config, notifications chan string) {
fmt.Println("START MESSAGING")
currentContact := strings.Split(config.Contacts, configContactSep)[1]
fmt.Println(infoFormat+"Now sending messages to "+currentContact+" in a private conversation\n")
fmt.Println(infoFormat + "Now sending messages to " + currentContact + " in a private conversation\n")
fmt.Println("currentContacts", currentContact)
for {
select {
case notif := <-notifications:
// Test if notif is nil or skip this loop
if notif == "" { break ;}
if notif == "" {
break
}
fmt.Println("sending notification through xmpp")
@ -258,18 +293,18 @@ func startMessaging(client xmpp.Sender, config *config, notifications chan strin
}
}
func gethdlNotif(APIKey string, APIEndPoint string ) string {
func gethdlNotif(APIKey string, APIEndPoint string) string {
fmt.Println("get notif")
req, err := http.NewRequest("POST", APIEndPoint + "/notifications/read", nil)
req, err := http.NewRequest("POST", APIEndPoint+"/notifications/read", nil)
if err != nil {
fmt.Println(err)
}
req.Header.Add("Authorization", "Bearer " + APIKey)
req.Header.Add("Authorization", "Bearer "+APIKey)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err!= nil {
if err != nil {
fmt.Println(err)
}
@ -278,21 +313,14 @@ func gethdlNotif(APIKey string, APIEndPoint string ) string {
if err != nil {
fmt.Println(err)
} else {
res:= Notification{}
res := Notification{}
json.Unmarshal([]byte(body), &res)
//fmt.Println("RESULT title", res.Notifications[0].Title)
//fmt.Println("RESULT body", res.Notifications[0].Body)
//fmt.Println("res: ", res)
//fmt.Println("res.Notifications: ", res.Notifications)
if (len(res.Notifications) > 0) {
//fmt.Println("type of notif = ", reflect.TypeOf(res.Notifications[0]))
if len(res.Notifications) > 0 {
fmt.Println("Join: ", strings.Join([]string{res.Notifications[0].Title, res.Notifications[0].Body}, " "))
//fmt.Println("RESULT stirng(body)", string(body))
//fmt.Println("RESULTAT", string(body))
notif := strings.Join([]string{res.Notifications[0].Title, res.Notifications[0].Body}, " ")
return notif
}
}
defer resp.Body.Close()
@ -300,7 +328,6 @@ func gethdlNotif(APIKey string, APIEndPoint string ) string {
return ""
}
func readConfig() *config {
viper.SetConfigName(configFileName) // name of config file (without extension)
viper.BindPFlags(pflag.CommandLine)
@ -343,7 +370,6 @@ func errorHandler(err error) {
killChan <- err
}
func isDirectory(path string) (bool, error) {
fileInfo, err := os.Stat(path)
if err != nil {
@ -351,4 +377,3 @@ func isDirectory(path string) (bool, error) {
}
return fileInfo.IsDir(), err
}

Loading…
Cancel
Save