Skip to content

Instantly share code, notes, and snippets.

@xvbnm48
Created March 1, 2023 04:13
Show Gist options
  • Save xvbnm48/e2a78e6e33b52a06e4aa6bd0b8c172f8 to your computer and use it in GitHub Desktop.
Save xvbnm48/e2a78e6e33b52a06e4aa6bd0b8c172f8 to your computer and use it in GitHub Desktop.
go whatsapp
package main
import (
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/Rhymen/go-whatsapp"
)
func main() {
// buat instance WhatsApp client
wac, err := whatsapp.NewConnWithLogin(context.Background(), &whatsapp.Login{
Phone: "+6281234567890", // nomor telepon Anda
Password: "password_anda", // password WhatsApp Anda
})
if err != nil {
log.Fatalf("Error creating WhatsApp connection: %v", err)
}
// buat channel untuk menerima pesan masuk
cm := make(chan whatsapp.TextMessage)
wac.AddHandler(&waHandler{cm})
// tunggu hingga pesan masuk
fmt.Println("Waiting for incoming message...")
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL)
select {
case message := <-cm:
// tampilkan pesan yang diterima
fmt.Printf("Received message from %s: %s\n", message.Info.RemoteJID, message.Text)
// balas pesan dengan pesan yang sama
reply := whatsapp.TextMessage{
Info: whatsapp.MessageInfo{
RemoteJID: message.Info.RemoteJID,
},
Text: message.Text,
}
if _, err := wac.Send(reply); err != nil {
log.Fatalf("Error sending message: %v", err)
}
fmt.Printf("Sent message to %s: %s\n", reply.Info.RemoteJID, reply.Text)
case <-sigChan:
// tutup koneksi WhatsApp saat aplikasi berhenti
wac.Disconnect()
fmt.Println("Disconnected from WhatsApp")
os.Exit(0)
}
}
type waHandler struct {
cm chan<- whatsapp.TextMessage
}
func (h *waHandler) HandleError(err error) {
log.Printf("WhatsApp error: %v", err)
}
func (h *waHandler) HandleTextMessage(message whatsapp.TextMessage) {
// terima pesan masuk dan kirim ke channel
h.cm <- message
}
@xvbnm48
Copy link
Author

xvbnm48 commented Mar 1, 2023

not testing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment