feat: job hunt bot and feed scanner

This commit is contained in:
2026-11-25 09:15:50 +01:00
commit 3b66030413
15 changed files with 2421 additions and 0 deletions
+219
View File
@@ -0,0 +1,219 @@
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"path/filepath"
"strings"
"time"
)
// Scanner is the scheduled half: it reads the company feeds, keeps the jobs
// that match the search profile and have not been seen before, and runs each
// through the same assessment the bot uses. Postings that require a language
// the CV does not list are dropped silently.
type Scanner struct {
cfg Config
sources []Source
list func(context.Context, Source) ([]Job, error)
text func(context.Context, Job) (string, error)
assess func(context.Context, Posting) (*Package, error)
post func(ctx context.Context, content, fileName string, file []byte) error
now func() time.Time
}
func newScanner(cfg Config, web *http.Client) *Scanner {
return &Scanner{
cfg: cfg,
sources: sources,
list: func(ctx context.Context, s Source) ([]Job, error) { return listJobs(ctx, web, s) },
text: func(ctx context.Context, j Job) (string, error) { return jobText(ctx, web, j) },
assess: (&Assessor{Config: cfg}).Assess,
now: time.Now,
}
}
func (s *Scanner) seenPath() string { return filepath.Join(s.cfg.StateDir, "seen.json") }
func (s *Scanner) loadSeen() (map[string]string, error) {
seen := map[string]string{}
raw, err := os.ReadFile(s.seenPath())
if errors.Is(err, os.ErrNotExist) {
return seen, nil
}
if err != nil {
return nil, err
}
// A corrupt file must stop the run: starting empty would re-post everything.
if err := json.Unmarshal(raw, &seen); err != nil {
return nil, fmt.Errorf("%s is not valid JSON: %w", s.seenPath(), err)
}
return seen, nil
}
func (s *Scanner) saveSeen(seen map[string]string) error {
raw, err := json.MarshalIndent(seen, "", " ")
if err != nil {
return err
}
tmp := s.seenPath() + ".tmp"
if err := os.WriteFile(tmp, raw, 0o600); err != nil {
return err
}
return os.Rename(tmp, s.seenPath())
}
// candidates returns the unseen jobs that match the profile, and the feeds
// that failed.
func (s *Scanner) candidates(ctx context.Context, seen map[string]string) (jobs []Job, failed []string) {
for _, src := range s.sources {
all, err := s.list(ctx, src)
if err != nil {
slog.Warn("feed failed", "company", src.Company, "err", err)
failed = append(failed, src.Company)
continue
}
n := 0
for _, j := range all {
if _, done := seen[j.Key]; !done && wanted(j) {
jobs = append(jobs, j)
n++
}
}
slog.Info("feed read", "company", src.Company, "jobs", len(all), "new_matches", n)
}
return jobs, failed
}
func runScan(ctx context.Context, cfg Config, dryRun bool) error {
s := newScanner(cfg, newHTTPClient(false))
if dryRun {
jobs, failed := s.candidates(ctx, map[string]string{})
for _, j := range jobs {
fmt.Printf("%-13s %-60s %s\n", j.Company, truncateRunes(j.Title, 60), j.Location)
}
fmt.Printf("\n%d matching jobs, %d feeds failed %v\n", len(jobs), len(failed), failed)
return nil
}
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
}
discord := newDiscord(strings.TrimSpace(string(token)))
s.post = func(ctx context.Context, content, fileName string, file []byte) error {
return discord.Reply(ctx, cfg.ChannelID, "", content, fileName, file)
}
return s.run(ctx)
}
// run handles at most cfg.ScanMax postings; the rest stay unseen and are
// picked up by the next run, so a first run cannot flood the channel or burn
// through the Claude allowance.
func (s *Scanner) run(ctx context.Context) error {
seen, err := s.loadSeen()
if err != nil {
return err
}
jobs, failedFeeds := s.candidates(ctx, seen)
var posted, dropped int
var stopped error
done := 0
for _, j := range jobs {
if done >= s.cfg.ScanMax || ctx.Err() != nil {
break
}
outcome, err := s.handle(ctx, j)
if err != nil {
// Most likely Claude itself (logged out, usage limit): no point
// trying the rest. The job stays unseen for the next run.
slog.Error("scan stopped", "company", j.Company, "title", j.Title, "err", err)
stopped = err
break
}
done++
seen[j.Key] = s.now().Format(time.DateOnly) + " " + outcome
if err := s.saveSeen(seen); err != nil {
return fmt.Errorf("saving seen jobs: %w", err) // or the next run posts duplicates
}
switch outcome {
case "posted":
posted++
case "language":
dropped++
}
}
slog.Info("scan finished", "matches", len(jobs), "posted", posted, "dropped_language", dropped, "queued", len(jobs)-done)
if done == 0 && stopped == nil && len(failedFeeds) == 0 {
return nil // nothing new: stay quiet
}
line := fmt.Sprintf("Scan: %d posted, %d dropped for a language requirement, %d still queued.", posted, dropped, len(jobs)-done)
if len(failedFeeds) > 0 {
line += " Feeds that failed: " + strings.Join(failedFeeds, ", ") + "."
}
if stopped != nil {
line += " Stopped early: " + truncateRunes(stopped.Error(), 300)
}
if err := s.post(ctx, line, "", nil); err != nil {
slog.Warn("posting the scan summary failed", "err", err)
}
return stopped
}
// handle assesses one job. The returned outcome is recorded next to the job
// in seen.json; an error means the job should be retried on a later run.
func (s *Scanner) handle(ctx context.Context, j Job) (string, error) {
text, err := s.text(ctx, j)
if err != nil {
return "", fmt.Errorf("reading the description: %w", err)
}
if len(text) < minPostingChars {
slog.Warn("description too short, skipping", "company", j.Company, "title", j.Title)
return "empty", nil
}
// The feed's own title and location lead, so Claude has them even when
// the description leaves them out.
head := fmt.Sprintf("Company: %s\nTitle: %s\nLocation: %s\n\n", j.Company, j.Title, j.Location)
slog.Info("assessing", "company", j.Company, "title", j.Title)
pkg, err := s.assess(ctx, Posting{URL: j.URL, Text: head + text})
switch {
case errors.Is(err, errNotAPosting):
return "not a posting", nil
case err != nil:
return "", err
case pkg.LanguageBlocker:
slog.Info("dropped: language requirement", "company", j.Company, "title", j.Title, "why", pkg.DutchRequirement)
return "language", nil
}
note := renderNote(pkg, j.URL, s.now())
name := noteName(pkg)
saved := "the note could not be saved to the vault"
if path, err := writeNote(s.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 + "`"
}
content := "🔎 New on the watch list: <" + j.URL + ">\n" + summaryMessage(pkg, saved)
if err := s.post(ctx, content, name+".md", []byte(note)); err != nil {
// The note is in the vault either way; do not assess it again.
slog.Warn("posting to discord failed", "err", err)
}
return "posted", nil
}