Skip to content

Instantly share code, notes, and snippets.

@rexagod
Last active March 5, 2023 23:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rexagod/f2d796c195e6be22ca90ab2ceb2e12b7 to your computer and use it in GitHub Desktop.
Save rexagod/f2d796c195e6be22ca90ab2ceb2e12b7 to your computer and use it in GitHub Desktop.
WhatsApp Reminder (?) I dunno I'm bad at naming things but you get the idea.
package main
import (
"context"
"os"
"time"
driver "github.com/chromedp/chromedp"
"k8s.io/klog/v2"
)
func main() {
opts := append(driver.DefaultExecAllocatorOptions[:],
driver.Flag("headless", false),
)
ctx, cancel := driver.NewExecAllocator(context.Background(), opts...)
defer cancel()
// Create context with logger interface.
ctx, cancel = driver.NewContext(ctx, driver.WithDebugf(klog.Infof))
defer cancel()
// Pre-definitions.
urlStr := "https://web.whatsapp.com/"
group := "Heyo!"
groupSel := `//span[@title="` + group + `"]`
typeSel := `//div[@title="Type a message"]`
message := "Avengers assemble!"
sender := `//span[@data-testid="send"]`
waitBeforeClose := 10 * time.Second
var buf []byte
dir := "artefacts"
// Current time to string.
t := time.Now()
tStr := t.Format("2006-01-02_15-04-05")
// Run driver.
err := driver.Run(ctx, driver.Tasks{
driver.Navigate(urlStr),
driver.WaitVisible(groupSel),
driver.Click(groupSel),
driver.SendKeys(typeSel, message),
driver.Click(sender),
driver.Sleep(waitBeforeClose),
driver.CaptureScreenshot(&buf),
})
if err != nil {
klog.Fatalf("error during run: %v", err)
}
// Save screenshot.
// Create artefacts directory if it doesn't exist.
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err := os.Mkdir(dir, 0755); err != nil {
klog.Fatalf("error on creating artefacts directory: %v", err)
}
}
// Save screenshot to file.
if err := os.WriteFile(dir+"/screenshot_"+tStr+".png", buf, 0644); err != nil {
klog.Fatalf("error on saving to buffer: %v", err)
}
// Done.
klog.Info("done!")
}
@rexagod
Copy link
Author

rexagod commented Mar 5, 2023

To use this in a containerized env, use the Dockerfile below.

# Build application.
FROM golang:1.19-alpine3.17 AS build

# Install git.
# Git is required for fetching the dependencies.
RUN apk update && apk add --no-cache git

# Create appuser.
RUN adduser -D -g '' appuser

WORKDIR $GOPATH/src/github.com/rexagod/wa-reminder
COPY . .

# Fetch dependencies.
# Using go get.
RUN go get -d -v

# Build the binary.
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o /go/bin/wa-reminder .

# Run application.
FROM chromedp/headless-shell:latest

# Import from builder.
COPY --from=build /etc/passwd /etc/passwd
COPY --from=build /go/bin/wa-reminder /go/bin/wa-reminder

# Use an unprivileged user.
USER appuser

# Run the binary.
ENTRYPOINT ["/go/bin/wa-reminder"]

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