lemmy-reply-bot/main.go

277 lines
6.5 KiB
Go
Raw Normal View History

2022-12-11 04:08:29 +00:00
package main
import (
"context"
"os"
"os/signal"
"strings"
"syscall"
"text/template"
"unsafe"
2022-12-11 04:08:29 +00:00
"github.com/spf13/pflag"
"github.com/vmihailenco/msgpack/v5"
"go.arsenm.dev/go-lemmy"
"go.arsenm.dev/go-lemmy/types"
"go.arsenm.dev/logger/log"
)
type itemType uint8
const (
comment itemType = iota
post
)
type item struct {
Type itemType
ID int
}
func (it itemType) String() string {
switch it {
case comment:
return "comment"
case post:
return "post"
default:
return "<unknown>"
}
}
type Submatches []string
func (sm Submatches) Item(i int) string {
return sm[i]
}
type TmplContext struct {
Matches []Submatches
Type itemType
}
func (tc TmplContext) Match(i, j int) string {
return tc.Matches[i][j]
}
2022-12-11 04:08:29 +00:00
func main() {
configPath := pflag.StringP("config", "c", "./lemmy-reply-bot.toml", "Path to the config file")
dryRun := pflag.BoolP("dry-run", "D", false, "Don't actually send comments, just check for matches")
pflag.Parse()
ctx := context.Background()
ctx, cancel := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM)
defer cancel()
err := loadConfig(*configPath)
if err != nil {
log.Fatal("Error loading config file").Err(err).Send()
}
2022-12-13 02:23:29 +00:00
c, err := lemmy.NewWebSocket(cfg.Lemmy.InstanceURL)
2022-12-11 04:08:29 +00:00
if err != nil {
log.Fatal("Error creating new Lemmy API client").Err(err).Send()
}
2023-01-05 22:01:33 +00:00
err = c.ClientLogin(ctx, types.Login{
2022-12-11 04:08:29 +00:00
UsernameOrEmail: cfg.Lemmy.Account.UserOrEmail,
Password: cfg.Lemmy.Account.Password,
})
if err != nil {
log.Fatal("Error logging in to Lemmy instance").Err(err).Send()
}
log.Info("Successfully logged in to Lemmy instance").Send()
2023-01-09 20:55:51 +00:00
joinAll(c)
2022-12-13 02:23:29 +00:00
2023-01-09 20:55:51 +00:00
c.OnReconnect(func(c *lemmy.WSClient) {
joinAll(c)
log.Info("Successfully reconnected to WebSocket").Send()
2022-12-13 02:23:29 +00:00
})
2022-12-11 04:08:29 +00:00
replyCh := make(chan replyJob, 200)
if !*dryRun {
go commentReplyWorker(ctx, c, replyCh)
}
commentWorker(ctx, c, replyCh)
}
2022-12-13 02:23:29 +00:00
func commentWorker(ctx context.Context, c *lemmy.WSClient, replyCh chan<- replyJob) {
2023-01-23 21:34:36 +00:00
repliedIDs := map[item]struct{}{}
2022-12-11 04:08:29 +00:00
repliedStore, err := os.Open("replied.bin")
if err == nil {
err = msgpack.NewDecoder(repliedStore).Decode(&repliedIDs)
if err != nil {
log.Warn("Error decoding reply store").Err(err).Send()
}
repliedStore.Close()
}
for {
select {
2022-12-13 02:23:29 +00:00
case res := <-c.Responses():
2023-01-07 23:32:35 +00:00
if res.IsOneOf(types.UserOperationCRUDCreateComment, types.UserOperationCRUDEditComment) {
2022-12-13 02:23:29 +00:00
var cr types.CommentResponse
err = lemmy.DecodeResponse(res.Data, &cr)
if err != nil {
log.Warn("Error while trying to decode comment").Err(err).Send()
continue
}
2022-12-11 04:08:29 +00:00
2023-01-23 21:34:36 +00:00
if _, ok := repliedIDs[item{comment, cr.CommentView.Comment.ID}]; ok {
2022-12-11 04:08:29 +00:00
continue
}
for i, reply := range cfg.Replies {
re := compiledRegexes[reply.Regex]
2022-12-13 02:23:29 +00:00
if !re.MatchString(cr.CommentView.Comment.Content) {
2022-12-11 04:08:29 +00:00
continue
}
log.Info("Matched comment body").
Int("reply-index", i).
2022-12-13 02:23:29 +00:00
Int("comment-id", cr.CommentView.Comment.ID).
2022-12-11 04:08:29 +00:00
Send()
job := replyJob{
2023-01-23 21:34:36 +00:00
CommentID: types.NewOptional(cr.CommentView.Comment.ID),
2022-12-13 02:23:29 +00:00
PostID: cr.CommentView.Comment.PostID,
2022-12-11 04:08:29 +00:00
}
matches := re.FindAllStringSubmatch(cr.CommentView.Comment.Content, -1)
job.Content, err = executeTmpl(compiledTmpls[reply.Regex], TmplContext{
Matches: toSubmatches(matches),
Type: comment,
})
if err != nil {
log.Warn("Error while executing template").Err(err).Send()
continue
}
2022-12-11 04:08:29 +00:00
replyCh <- job
2023-01-23 21:34:36 +00:00
repliedIDs[item{comment, cr.CommentView.Comment.ID}] = struct{}{}
}
} else if res.IsOneOf(types.UserOperationCRUDCreatePost, types.UserOperationCRUDEditPost) {
var pr types.PostResponse
err = lemmy.DecodeResponse(res.Data, &pr)
if err != nil {
log.Warn("Error while trying to decode comment").Err(err).Send()
continue
}
if _, ok := repliedIDs[item{post, pr.PostView.Post.ID}]; ok {
continue
}
2023-01-23 22:21:04 +00:00
body := pr.PostView.Post.URL.ValueOr("") + "\n\n" + pr.PostView.Post.Body.ValueOr("")
2023-01-23 21:34:36 +00:00
for i, reply := range cfg.Replies {
re := compiledRegexes[reply.Regex]
2023-01-23 22:13:39 +00:00
if !re.MatchString(body) {
2023-01-23 21:34:36 +00:00
continue
}
log.Info("Matched post body").
2023-01-23 21:34:36 +00:00
Int("reply-index", i).
Int("post-id", pr.PostView.Post.ID).
Send()
job := replyJob{PostID: pr.PostView.Post.ID}
2023-01-23 22:13:39 +00:00
matches := re.FindAllStringSubmatch(body, -1)
job.Content, err = executeTmpl(compiledTmpls[reply.Regex], TmplContext{
Matches: toSubmatches(matches),
Type: post,
})
2023-01-23 21:34:36 +00:00
if err != nil {
log.Warn("Error while executing template").Err(err).Send()
continue
}
replyCh <- job
repliedIDs[item{post, pr.PostView.Post.ID}] = struct{}{}
2022-12-11 04:08:29 +00:00
}
}
2023-01-09 20:55:51 +00:00
case err := <-c.Errors():
log.Warn("Lemmy client error").Err(err).Send()
2022-12-11 04:08:29 +00:00
case <-ctx.Done():
repliedStore, err := os.Create("replied.bin")
if err != nil {
log.Warn("Error creating reply store file").Err(err).Send()
return
}
err = msgpack.NewEncoder(repliedStore).Encode(repliedIDs)
if err != nil {
log.Warn("Error encoding replies to reply store").Err(err).Send()
}
repliedStore.Close()
return
}
}
}
type replyJob struct {
Content string
2023-01-23 21:34:36 +00:00
CommentID types.Optional[int]
2022-12-11 04:08:29 +00:00
PostID int
}
2022-12-13 02:23:29 +00:00
func commentReplyWorker(ctx context.Context, c *lemmy.WSClient, ch <-chan replyJob) {
2022-12-11 04:08:29 +00:00
for {
select {
case reply := <-ch:
2023-01-07 23:32:35 +00:00
err := c.Request(types.UserOperationCRUDCreateComment, types.CreateComment{
2022-12-11 04:08:29 +00:00
PostID: reply.PostID,
2023-01-23 21:34:36 +00:00
ParentID: reply.CommentID,
2022-12-11 04:08:29 +00:00
Content: reply.Content,
})
if err != nil {
log.Warn("Error while trying to create new comment").Err(err).Send()
}
log.Info("Created new comment").
Int("post-id", reply.PostID).
2023-01-23 21:34:36 +00:00
Int("parent-id", reply.CommentID.ValueOr(-1)).
2022-12-11 04:08:29 +00:00
Send()
case <-ctx.Done():
return
}
}
}
func executeTmpl(tmpl *template.Template, tc TmplContext) (string, error) {
sb := &strings.Builder{}
err := tmpl.Execute(sb, tc)
return sb.String(), err
2022-12-11 04:08:29 +00:00
}
2023-01-09 20:55:51 +00:00
func joinAll(c *lemmy.WSClient) {
err := c.Request(types.UserOperationUserJoin, nil)
if err != nil {
log.Fatal("Error joining WebSocket user context").Err(err).Send()
}
err = c.Request(types.UserOperationCommunityJoin, types.CommunityJoin{
CommunityID: 0,
})
if err != nil {
log.Fatal("Error joining WebSocket community context").Err(err).Send()
}
}
// toSubmatches converts matches coming from PCRE2 to a
// submatch array used for the template
func toSubmatches(s [][]string) []Submatches {
// Unfortunately, Go doesn't allow for this conversion
// even though the memory layout is identical and it's
// safe, so it is done using unsafe pointer magic
return *(*[]Submatches)(unsafe.Pointer(&s))
}