230 lines
7.0 KiB
Go
230 lines
7.0 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const helpText = "Send me a link to a job posting, or paste the posting text (a long paste that Discord turns into a file works too). " +
|
|
"I reply with the summary, fit, gaps and a cover letter draft, and file the note under Job Hunt in the vault."
|
|
|
|
var reURL = regexp.MustCompile(`https?://[^\s<>"']+`)
|
|
|
|
// Bot wires Discord, the page fetcher and the assessor together.
|
|
type Bot struct {
|
|
cfg Config
|
|
discord *Discord
|
|
web *http.Client
|
|
assess func(context.Context, Posting) (*Package, error)
|
|
now func() time.Time
|
|
}
|
|
|
|
func runBot(ctx context.Context, cfg Config) error {
|
|
if cfg.TokenFile == "" || cfg.ChannelID == "" {
|
|
return errors.New("JOBHUNT_DISCORD_TOKEN_FILE and JOBHUNT_DISCORD_CHANNEL must be set")
|
|
}
|
|
token, err := os.ReadFile(cfg.TokenFile)
|
|
if err != nil {
|
|
return fmt.Errorf("reading the bot token: %w", err)
|
|
}
|
|
if err := os.MkdirAll(cfg.StateDir, 0o700); err != nil {
|
|
return err
|
|
}
|
|
b := &Bot{
|
|
cfg: cfg,
|
|
discord: newDiscord(strings.TrimSpace(string(token))),
|
|
web: newHTTPClient(false),
|
|
assess: (&Assessor{Config: cfg}).Assess,
|
|
now: time.Now,
|
|
}
|
|
return b.run(ctx)
|
|
}
|
|
|
|
func (b *Bot) cursorPath() string { return filepath.Join(b.cfg.StateDir, "last_message_id") }
|
|
|
|
func (b *Bot) run(ctx context.Context) error {
|
|
raw, _ := os.ReadFile(b.cursorPath())
|
|
cursor := strings.TrimSpace(string(raw))
|
|
slog.Info("jobhunt bot started", "channel", b.cfg.ChannelID, "resume_after", cursor)
|
|
|
|
delay := b.cfg.Poll
|
|
for {
|
|
msgs, err := b.discord.MessagesAfter(ctx, b.cfg.ChannelID, cursor)
|
|
switch {
|
|
case ctx.Err() != nil:
|
|
return ctx.Err()
|
|
case err != nil:
|
|
slog.Warn("polling discord failed", "err", err)
|
|
delay = min(delay*2, 2*time.Minute)
|
|
default:
|
|
delay = b.cfg.Poll
|
|
for _, m := range msgs {
|
|
first := cursor == ""
|
|
cursor = m.ID
|
|
// Saved before handling: a message that crashes the bot is
|
|
// skipped on restart instead of being assessed in a loop.
|
|
if err := os.WriteFile(b.cursorPath(), []byte(cursor), 0o600); err != nil {
|
|
slog.Warn("saving the cursor failed", "err", err)
|
|
}
|
|
// First run: the newest message only marks where to start.
|
|
if !first {
|
|
b.handle(ctx, m)
|
|
}
|
|
}
|
|
if cursor == "" {
|
|
cursor = "0" // empty channel: everything from now on is new
|
|
}
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
case <-time.After(delay):
|
|
}
|
|
}
|
|
}
|
|
|
|
// postingFrom works out what the message is offering: pasted text (inline or
|
|
// as a text attachment) wins over a link, because pasting is what the user
|
|
// does after a link could not be read.
|
|
func (b *Bot) postingFrom(ctx context.Context, m Message) (Posting, error) {
|
|
link := reURL.FindString(m.Content)
|
|
text := strings.TrimSpace(m.Content)
|
|
|
|
for _, a := range m.Attachments {
|
|
if !isTextAttachment(a) {
|
|
continue
|
|
}
|
|
_, body, err := httpGet(ctx, b.web, a.URL, 1<<20)
|
|
if err != nil {
|
|
return Posting{}, fmt.Errorf("downloading %s: %w", a.Filename, err)
|
|
}
|
|
text = strings.TrimSpace(text + "\n\n" + string(body))
|
|
}
|
|
|
|
withoutLink := strings.TrimSpace(strings.ReplaceAll(text, link, ""))
|
|
if len(withoutLink) >= minPostingChars {
|
|
return Posting{URL: strings.TrimRight(link, ".,)"), Text: truncate(text, maxPostingChars)}, nil
|
|
}
|
|
if link != "" {
|
|
return fetchPosting(ctx, b.web, strings.TrimRight(link, ".,)"))
|
|
}
|
|
return Posting{}, nil
|
|
}
|
|
|
|
func isTextAttachment(a Attachment) bool {
|
|
u, err := url.Parse(a.URL)
|
|
if err != nil || u.Scheme != "https" || (u.Host != "cdn.discordapp.com" && u.Host != "media.discordapp.net") {
|
|
return false
|
|
}
|
|
name := strings.ToLower(a.Filename)
|
|
return a.Size <= 1<<20 && (strings.HasPrefix(a.ContentType, "text/") ||
|
|
strings.HasSuffix(name, ".txt") || strings.HasSuffix(name, ".md"))
|
|
}
|
|
|
|
func (b *Bot) handle(ctx context.Context, m Message) {
|
|
if m.Author.Bot {
|
|
return
|
|
}
|
|
reply := func(text string) {
|
|
if err := b.discord.Reply(ctx, b.cfg.ChannelID, m.ID, text, "", nil); err != nil {
|
|
slog.Warn("replying failed", "err", err)
|
|
}
|
|
}
|
|
if b.cfg.OwnerID == "" {
|
|
reply("I am not locked to a user yet, so I ignore everything. Your Discord user ID is `" + m.Author.ID +
|
|
"`. Set it as `ownerId` in the jobhunt module and redeploy.")
|
|
return
|
|
}
|
|
if m.Author.ID != b.cfg.OwnerID {
|
|
slog.Info("ignoring message from another user", "author", m.Author.ID)
|
|
return
|
|
}
|
|
|
|
posting, err := b.postingFrom(ctx, m)
|
|
switch {
|
|
case errors.Is(err, errUnreadable):
|
|
reply("I could not read that page: " + strings.TrimPrefix(err.Error(), errUnreadable.Error()+": ") +
|
|
".\nSome sites (Indeed, Glassdoor, LinkedIn) refuse servers. Open the posting, copy its text and paste it here; keep the link in the same message if you want it in the note.")
|
|
return
|
|
case err != nil:
|
|
reply("Something went wrong reading that: " + err.Error())
|
|
return
|
|
case posting.Text == "":
|
|
reply(helpText)
|
|
return
|
|
}
|
|
|
|
_ = b.discord.React(ctx, b.cfg.ChannelID, m.ID, "👀")
|
|
slog.Info("assessing posting", "url", posting.URL, "chars", len(posting.Text))
|
|
|
|
pkg, err := b.assess(ctx, posting)
|
|
if err != nil {
|
|
slog.Warn("assessment failed", "err", err)
|
|
reply("I could not assess that posting: " + truncateRunes(err.Error(), 500))
|
|
return
|
|
}
|
|
|
|
note := renderNote(pkg, posting.URL, b.now())
|
|
name := noteName(pkg)
|
|
saved := "the note could not be saved to the vault"
|
|
if path, err := writeNote(b.cfg.NotesDir, name, note); err != nil {
|
|
slog.Error("writing the note failed", "err", err)
|
|
saved += ": " + err.Error()
|
|
} else {
|
|
name = strings.TrimSuffix(filepath.Base(path), ".md")
|
|
saved = "Note: `Job Hunt/" + name + "`"
|
|
}
|
|
|
|
if err := b.discord.Reply(ctx, b.cfg.ChannelID, m.ID, summaryMessage(pkg, saved), name+".md", []byte(note)); err != nil {
|
|
slog.Warn("posting the package failed", "err", err)
|
|
return
|
|
}
|
|
_ = b.discord.React(ctx, b.cfg.ChannelID, m.ID, "✅")
|
|
}
|
|
|
|
// summaryMessage is the short version shown in the channel; the attached
|
|
// file and the vault note hold the full package.
|
|
func summaryMessage(pkg *Package, saved string) string {
|
|
var b strings.Builder
|
|
fmt.Fprintf(&b, "**%s**", pkg.Title)
|
|
if pkg.Company != "" {
|
|
fmt.Fprintf(&b, " at **%s**", pkg.Company)
|
|
}
|
|
b.WriteString("\n")
|
|
var facts []string
|
|
for _, f := range []string{pkg.Location, pkg.WorkMode, pkg.Seniority, pkg.Salary} {
|
|
if f = strings.TrimSpace(f); f != "" {
|
|
facts = append(facts, f)
|
|
}
|
|
}
|
|
if len(facts) > 0 {
|
|
b.WriteString(strings.Join(facts, " · ") + "\n")
|
|
}
|
|
fmt.Fprintf(&b, "\n**Fit %d/100, %s.** %s\n", pkg.FitScore, strings.ToLower(pkg.Verdict), pkg.VerdictReason)
|
|
if pkg.DutchRequirement != "" {
|
|
fmt.Fprintf(&b, "**Language:** %s\n", pkg.DutchRequirement)
|
|
}
|
|
list := func(heading string, items []string) {
|
|
if len(items) == 0 {
|
|
return
|
|
}
|
|
fmt.Fprintf(&b, "\n**%s**\n", heading)
|
|
for _, it := range items[:min(len(items), 4)] {
|
|
fmt.Fprintf(&b, "- %s\n", truncateRunes(strings.TrimSpace(it), 220))
|
|
}
|
|
}
|
|
list("Strengths", pkg.Strengths)
|
|
list("Gaps", pkg.Gaps)
|
|
fmt.Fprintf(&b, "\n%s. The attached file has the full package with the cover letter draft.", saved)
|
|
return b.String()
|
|
}
|