Skip to content

Commit

Permalink
adding text message receiver
Browse files Browse the repository at this point in the history
  • Loading branch information
abansal88 committed Apr 4, 2020
1 parent 1593667 commit c64f982
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
70 changes: 70 additions & 0 deletions executors/receive_message_manager.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package executors

import (
"fmt"
"github.com/Rhymen/go-whatsapp"
"os"
"os/signal"
"strings"
"syscall"
"time"
)

type textHandler struct{}

// HandleError implements the handler interface for go-whatsapp
func (t textHandler) HandleError(err error) {
// TODO : handle go routine here
fmt.Printf("error in textHandler : %v", err)
return
}

// checks if the string is of interest to the handler.
// checks for "youtube:" tag in this case.
// returns the "song:" tag if successful.
func interesting(str string) (string, bool) {
parts := strings.Split(str, ":")
if len(parts) < 2 {
return "", false
}
fmt.Println(parts, strings.EqualFold(strings.TrimSpace(parts[0]), "youtube"), strings.TrimSpace(parts[0]))
if strings.EqualFold(strings.TrimSpace(parts[0]), "youtube") {
return strings.TrimSpace(parts[1]), true
}
return "", false
}

// HandleTextMessage implements the text message handler interface for go-whatsapp
func (t textHandler) HandleTextMessage(msg whatsapp.TextMessage) {
fmt.Println("received message")
text := msg.Text
if song, ok := interesting(text); ok && song != "" {
fmt.Printf("going to play %v on youtube\n", song)
}
}

// StartTextReceiver starts the handler for the text messages received
func StartTextReceiver() error {
wac, err := whatsapp.NewConn(5 * time.Second)
if err != nil {
return fmt.Errorf("error creating connection: %v\n", err)
}

err = LoginWithConnection(wac)
if err != nil {
return fmt.Errorf("error logging in: %v\n", err)
}

<-time.After(3 * time.Second)

handler := textHandler{}
wac.AddHandler(handler)

c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c

fmt.Println("closing the receiver")
wac.Disconnect()
return nil
}
1 change: 1 addition & 0 deletions executors/send_message_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ func sendMessage(msg interface{}) error {
return fmt.Errorf("error sending message: %v", err)
}

wac.Disconnect()
fmt.Printf("successfully sent, messaageID : %v\n", msgID)
return nil
}
5 changes: 5 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ func main() {
return
}

case "startTextReceiver":
if err = executors.StartTextReceiver(); err != nil {
return
}

default:
// TODO : add a list of all permitted actions
err = fmt.Errorf("wrong command provided. please see below for the list of permitted actions")
Expand Down

0 comments on commit c64f982

Please sign in to comment.