How to integrate ChatGPT with WhatsApp using Golang Part 1

How to integrate ChatGPT with WhatsApp using Golang Part 1

a close up of a person touching a cell phone

Integrating ChatGPT with WhatsApp using Golang allows you to leverage the power of OpenAI’s language model and provide intelligent responses to WhatsApp messages. In this tutorial, we’ll walk through the steps to set up the integration.
In this first part of the tutorial, we will cover the initialization of the whatsapp bot using whatsmewow and the authentication.

Prerequisites

Before getting started, make sure you have the following:

  • A WhatsApp Account
  • Golang installed on your system
  • OpenAI API key for accessing the ChatGPT API

Getting Started

First create a simple go module:

Bash
mkdir whatsapp-chatgpt-tutorial
cd whatsapp-chatgpt-tutorial
go mod init github.com/SushiWaUmai/whatsapp-chatgpt-tutorial

In order to send whatsapp messages via go we will import the whatsmeow package. Also we need to import that Golang OpenAI API wrapper to get easy access to ChatGPT. There are also other dependencies that need to be added, which we will cover later in this tutorial.

Bash
go get go.mau.fi/whatsmeow github.com/sashabaranov/go-openai
go get github.com/mattn/go-sqlite github.com/mdp/qrterminal github.com/joho/godotenv

Initializing Client

Now we need can start writing code and creating our whatsmeow client.

Go
import (
	"log"

	"go.mau.fi/whatsmeow"
	"go.mau.fi/whatsmeow/store/sqlstore"
	_ "github.com/mattn/go-sqlite3"
	waLog "go.mau.fi/whatsmeow/util/log"
)


func CreateClient() (*whatsmeow.Client) {
	dbLog := waLog.Stdout("Database", "INFO", true)
	container, err := sqlstore.New("sqlite3", "file:accounts.db?_foreign_keys=on", dbLog)
	if err != nil {
		log.Fatalln(err)
	}

	deviceStore, err := container.GetFirstDevice()
	if err != nil {
		log.Fatalln(err)
	}

	clientLog := waLog.Stdout("Client", "INFO", true)
	client := whatsmeow.NewClient(deviceStore, clientLog)

	return client
}

This code does 3 things:

  1. It sets up a database logger for logging information related to the database operations.
  2. It initializes a container using the SQLite3 database driver and specifies the database file path.
  3. It retrieves the first device stored in the container and initializes a client by passing the device store and client logger.

Connecting Account

Since we have our whatsapp client now, we need to connect it with our account using a QR code.

Go
import (
	"context"
	"log"
	"os"

	"github.com/mdp/qrterminal"
	"go.mau.fi/whatsmeow"
)

func ConnectClient(client *whatsmeow.Client) {
	if client.Store.ID == nil {
		// No ID stored, new login, show a qr code
		qrChan, _ := client.GetQRChannel(context.Background())
		err := client.Connect()
		if err != nil {
			log.Fatalln(err)
		}

		for evt := range qrChan {
			if evt.Event == "code" {
				qrterminal.GenerateHalfBlock(evt.Code, qrterminal.L, os.Stdout)
			} else {
				log.Println("Login event:", evt.Event)
			}
		}
	} else {
		// Already logged in, just connect
		err := client.Connect()
		if err != nil {
			log.Fatalln(err)
		}
	}
}

The above connect client function establishes a connection to our account using a QR code. It handles two scenarios:

  1. If no on has logged in in the previous session, it displays a QR code for login and connects to WhatsApp after scanning.
  2. If we can find a session, it connects directly to WhatsApp without the need for a QR code.

Now when we call these functions from main like this:

Go
import (
	"os"
	"os/signal"
	"syscall"
)

func main() {
	WhatsmeowClient = CreateClient()
	ConnectClient(WhatsmeowClient)

	WhatsmeowClient.Connect()

	// Listen to Ctrl+C (you can also do something else that prevents the program from exiting)
	c := make(chan os.Signal)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
	<-c
	WhatsmeowClient.Disconnect()
}

We should get something like this:

screenshot-2023-06-19-13_32-05 How to integrate ChatGPT with WhatsApp using Golang Part 1

This is the WhatApp login QR Code which we will need to scan.

The repo of the above tutorial can be found here:
https://github.com/SushiWaUmai/whatsapp-chatgpt-tutorial/

Part 2:
http://www.mindevice.net/posts/whatsapp-chatgpt-part2

Share this content:

Leave a Reply

Your email address will not be published. Required fields are marked *