bot: Bot setup and teardown done: Connect w/retry, join/leave, full config, and logging.
This commit is contained in:
@@ -1 +1,5 @@
|
|||||||
|
# Binaries
|
||||||
debug
|
debug
|
||||||
|
debug.exe
|
||||||
|
logbot3
|
||||||
|
logbot3.exe
|
||||||
@@ -83,7 +83,7 @@ func (client *Client) Query(ctx context.Context, query string, variables map[str
|
|||||||
if res.StatusCode >= 500 {
|
if res.StatusCode >= 500 {
|
||||||
stuff, _ := ioutil.ReadAll(res.Body)
|
stuff, _ := ioutil.ReadAll(res.Body)
|
||||||
fmt.Println(string(stuff))
|
fmt.Println(string(stuff))
|
||||||
return nil, errors.New("Internal srever error")
|
return nil, errors.New("Internal server error")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse response
|
// Parse response
|
||||||
|
|||||||
+72
-54
@@ -3,10 +3,10 @@ package bot
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"log"
|
"log"
|
||||||
"strings"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.aiterp.net/gisle/irc"
|
"git.aiterp.net/gisle/irc"
|
||||||
|
"git.aiterp.net/rpdata/logbot3/internal/models"
|
||||||
"git.aiterp.net/rpdata/logbot3/internal/models/channels"
|
"git.aiterp.net/rpdata/logbot3/internal/models/channels"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -14,16 +14,19 @@ var botKey = "git.aiterp.net/rpdata/logbot.Bot.key"
|
|||||||
|
|
||||||
// The Bot is the IRC client.
|
// The Bot is the IRC client.
|
||||||
type Bot struct {
|
type Bot struct {
|
||||||
commandChannel string
|
|
||||||
client *irc.Client
|
client *irc.Client
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
ctxCancel context.CancelFunc
|
ctxCancel context.CancelFunc
|
||||||
|
loopCtx context.Context
|
||||||
|
loopCancel context.CancelFunc
|
||||||
}
|
}
|
||||||
|
|
||||||
// New creates a new Bot.
|
// New creates a new Bot.
|
||||||
func New(ctx context.Context, nick string, alternatives []string) *Bot {
|
func New(ctx context.Context, nick string, alternatives []string, user string, realName string) *Bot {
|
||||||
client := irc.New(ctx, irc.Config{
|
client := irc.New(ctx, irc.Config{
|
||||||
Nick: nick,
|
Nick: nick,
|
||||||
|
User: user,
|
||||||
|
RealName: realName,
|
||||||
Alternatives: alternatives,
|
Alternatives: alternatives,
|
||||||
SendRate: 2,
|
SendRate: 2,
|
||||||
SkipSSLVerification: false,
|
SkipSSLVerification: false,
|
||||||
@@ -40,83 +43,98 @@ func New(ctx context.Context, nick string, alternatives []string) *Bot {
|
|||||||
|
|
||||||
// Connect connects the bot to the IRC server. This will disconnect already
|
// Connect connects the bot to the IRC server. This will disconnect already
|
||||||
// established connections.
|
// established connections.
|
||||||
func (bot *Bot) Connect(server string, ssl bool) error {
|
func (bot *Bot) Connect(server string, ssl bool, maxRetries int) (err error) {
|
||||||
if bot.ctxCancel != nil {
|
if bot.ctxCancel != nil {
|
||||||
bot.ctxCancel()
|
bot.ctxCancel()
|
||||||
}
|
}
|
||||||
bot.ctx, bot.ctxCancel = context.WithCancel(bot.client.Context())
|
bot.ctx, bot.ctxCancel = context.WithCancel(bot.client.Context())
|
||||||
|
|
||||||
return bot.client.Connect(server, ssl)
|
retries := 0
|
||||||
|
for maxRetries == 0 || retries < maxRetries {
|
||||||
|
err = bot.client.Connect(server, ssl)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("Connect failed:", err.Error())
|
||||||
|
if maxRetries > 0 && retries < maxRetries {
|
||||||
|
retries++
|
||||||
|
log.Printf("Retrying in 5s (Retry %d/%d)", retries, maxRetries)
|
||||||
|
} else {
|
||||||
|
log.Println("Retrying in 5s (No retry limit)")
|
||||||
|
}
|
||||||
|
|
||||||
|
time.Sleep(time.Second * 10)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (bot *Bot) loop() {
|
func (bot *Bot) loop() {
|
||||||
ticker := time.NewTicker(time.Second * 10)
|
bot.loopCtx, bot.loopCancel = context.WithCancel(bot.ctx)
|
||||||
defer ticker.Stop()
|
|
||||||
|
|
||||||
log.Println("Client ready.")
|
channelChanges, err := channels.SubscribeLogged(bot.ctx)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("Failed to get channel changes:", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ticker.C:
|
case channel := <-channelChanges:
|
||||||
{
|
{
|
||||||
bot.syncChannels()
|
channels := []models.Channel{channel}
|
||||||
}
|
deadline := time.After(time.Second * 1)
|
||||||
|
buffering := true
|
||||||
case <-bot.ctx.Done():
|
for buffering {
|
||||||
{
|
select {
|
||||||
log.Println("Spinning down bot main loop.")
|
case channel := <-channelChanges:
|
||||||
return
|
channels = append(channels, channel)
|
||||||
}
|
case <-deadline:
|
||||||
}
|
buffering = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (bot *Bot) syncChannels() {
|
decisions := make(map[string]bool)
|
||||||
channels, err := channels.ListOpen(bot.ctx)
|
|
||||||
if err != nil {
|
|
||||||
log.Println("Failed to update channel-list:", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
names := make([]string, 0, len(channels))
|
|
||||||
joins := make([]string, 0, len(channels))
|
|
||||||
leaves := make([]string, 0, len(names))
|
|
||||||
|
|
||||||
// Add new channels to join list.
|
|
||||||
for _, channel := range channels {
|
for _, channel := range channels {
|
||||||
name := channel.Name
|
decisions[channel.Name] = channel.Logged
|
||||||
names = append(names, name)
|
}
|
||||||
|
joins := make([]string, 0, len(decisions))
|
||||||
if bot.client.Channel(name) == nil {
|
parts := make([]string, 0, len(decisions))
|
||||||
joins = append(joins, name)
|
for channelName, logged := range decisions {
|
||||||
|
if logged {
|
||||||
|
if bot.client.Channel(channelName) != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
joins = append(joins, channelName)
|
||||||
|
} else {
|
||||||
|
if bot.client.Channel(channelName) == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
parts = append(parts, channelName)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add no longer logged channels to leave list.
|
|
||||||
LeaveLoop:
|
|
||||||
for _, channel := range bot.client.Channels() {
|
|
||||||
for _, name := range names {
|
|
||||||
if strings.ToLower(channel.Name()) == strings.ToLower(name) {
|
|
||||||
continue LeaveLoop
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Join channels.
|
|
||||||
if len(joins) > 0 {
|
if len(joins) > 0 {
|
||||||
log.Println("Joining", strings.Join(joins, ", "))
|
bot.client.Join(joins...)
|
||||||
bot.client.SendQueuedf("JOIN %s", strings.Join(joins, ","))
|
}
|
||||||
|
if len(parts) > 0 {
|
||||||
|
bot.client.Part(parts...)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// leave channels.
|
case <-bot.loopCtx.Done():
|
||||||
if len(leaves) > 0 {
|
{
|
||||||
log.Println("Leaving", strings.Join(leaves, ", "))
|
log.Println("Spinning down bot loop.")
|
||||||
bot.client.SendQueuedf("PART %s :Channel removed.", strings.Join(leaves, ","))
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (bot *Bot) stopLoop() {
|
func (bot *Bot) stopLoop() {
|
||||||
if bot.ctxCancel != nil {
|
if bot.loopCancel != nil {
|
||||||
bot.ctxCancel()
|
bot.loopCancel()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+39
-4
@@ -5,6 +5,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"git.aiterp.net/gisle/irc"
|
"git.aiterp.net/gisle/irc"
|
||||||
|
"git.aiterp.net/rpdata/logbot3/internal/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
func handler(event *irc.Event, client *irc.Client) {
|
func handler(event *irc.Event, client *irc.Client) {
|
||||||
@@ -13,18 +14,52 @@ func handler(event *irc.Event, client *irc.Client) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if event.Kind() == "packet" && len(event.Verb()) == 3 {
|
|
||||||
log.Printf("(%s) %s %s\n", event.Verb(), strings.Join(event.Args[1:], " "), event.Text)
|
|
||||||
}
|
|
||||||
|
|
||||||
switch event.Name() {
|
switch event.Name() {
|
||||||
|
// Handle bot loop
|
||||||
case "hook.ready":
|
case "hook.ready":
|
||||||
{
|
{
|
||||||
|
log.Println("Client is ready!")
|
||||||
go bot.loop()
|
go bot.loop()
|
||||||
}
|
}
|
||||||
case "client.disconnect":
|
case "client.disconnect":
|
||||||
{
|
{
|
||||||
|
log.Println("Client disconnected!")
|
||||||
bot.stopLoop()
|
bot.stopLoop()
|
||||||
|
|
||||||
|
conf := config.Get().Server
|
||||||
|
go bot.Connect(conf.Address, conf.SSL, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Log joins and leaves
|
||||||
|
case "packet.join":
|
||||||
|
{
|
||||||
|
if client.Nick() == event.Nick {
|
||||||
|
// TODO: Open channel handler
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Println("(JOIN)", event.Nick, "joined", event.Arg(0))
|
||||||
|
}
|
||||||
|
case "packet.part":
|
||||||
|
{
|
||||||
|
if client.Nick() == event.Nick {
|
||||||
|
// TODO: Close channel handler
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Println("(PART)", event.Nick, "left", event.Arg(0))
|
||||||
|
}
|
||||||
|
case "packet.quit":
|
||||||
|
{
|
||||||
|
log.Println("(QUIT)", event.Nick, "quit")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Log initial numerics for debugging's sake
|
||||||
|
case "packet.001", "packet.002", "packet.003", "packet.251", "packet.255", "packet.265", "packet.266", "packet.250", "packet.375", "packet.372", "packet.376":
|
||||||
|
{
|
||||||
|
log.Printf("(%s) %s\n", event.Verb(), event.Text)
|
||||||
|
}
|
||||||
|
case "packet.005", "packet.254":
|
||||||
|
{
|
||||||
|
log.Printf("(%s) %s %s\n", event.Verb(), strings.Join(event.Args, " "), event.Text)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,9 +11,13 @@ import (
|
|||||||
type Config struct {
|
type Config struct {
|
||||||
Bot struct {
|
Bot struct {
|
||||||
Nicks []string `json:"nicks"`
|
Nicks []string `json:"nicks"`
|
||||||
Server string `json:"server"`
|
User string `json:"user"`
|
||||||
CommandChannel string `json:"commandChannel"`
|
RealName string `json:"realName"`
|
||||||
} `json:"bot"`
|
} `json:"bot"`
|
||||||
|
Server struct {
|
||||||
|
Address string `json:"server"`
|
||||||
|
SSL bool `json:"ssl"`
|
||||||
|
}
|
||||||
API struct {
|
API struct {
|
||||||
Endpoint string `json:"endpoint"`
|
Endpoint string `json:"endpoint"`
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
|
|||||||
@@ -13,12 +13,23 @@ type Change struct {
|
|||||||
Op string `json:"op"`
|
Op string `json:"op"`
|
||||||
Author string `json:"author"`
|
Author string `json:"author"`
|
||||||
Date time.Time `json:"date"`
|
Date time.Time `json:"date"`
|
||||||
|
Keys []ChangeKey `json:"keys"`
|
||||||
Objects []ChangeObject `json:"objects"`
|
Objects []ChangeObject `json:"objects"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A ChangeKey describes a model directly or indirectly affected by the change.
|
||||||
|
type ChangeKey struct {
|
||||||
|
Model string `json:"model"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
|
||||||
// A ChangeObject is an object affected by the change.
|
// A ChangeObject is an object affected by the change.
|
||||||
type ChangeObject struct {
|
type ChangeObject struct {
|
||||||
Data json.RawMessage `json:"-"`
|
Data json.RawMessage `json:"-"`
|
||||||
|
TypeName string `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type changeObjectHeader struct {
|
||||||
TypeName string `json:"__typename"`
|
TypeName string `json:"__typename"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -38,12 +49,15 @@ func (co *ChangeObject) Channel() (Channel, error) {
|
|||||||
func (co *ChangeObject) UnmarshalJSON(b []byte) error {
|
func (co *ChangeObject) UnmarshalJSON(b []byte) error {
|
||||||
data := make([]byte, len(b))
|
data := make([]byte, len(b))
|
||||||
copy(data, b)
|
copy(data, b)
|
||||||
co.Data = data
|
|
||||||
|
|
||||||
err := json.Unmarshal(data, co)
|
header := changeObjectHeader{}
|
||||||
|
err := json.Unmarshal(data, &header)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
co.Data = data
|
||||||
|
co.TypeName = header.TypeName
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
package changes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.aiterp.net/rpdata/logbot3/internal/api"
|
||||||
|
"git.aiterp.net/rpdata/logbot3/internal/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The Filter for List.
|
||||||
|
type Filter struct {
|
||||||
|
Keys []models.ChangeKey `json:"keys,omitempty"`
|
||||||
|
EarliestDate *time.Time `json:"earliestDate,omitempty"`
|
||||||
|
Limit int `json:"limit,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// List lists all changes according to the filter.
|
||||||
|
func List(ctx context.Context, filter *Filter) ([]models.Change, error) {
|
||||||
|
data, err := api.Global().Query(ctx, listGQL, map[string]interface{}{"filter": filter}, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
res := listResult{}
|
||||||
|
err = json.Unmarshal(data, &res)
|
||||||
|
|
||||||
|
return res.Changes, err
|
||||||
|
}
|
||||||
|
|
||||||
|
type listResult struct {
|
||||||
|
Changes []models.Change `json:"changes"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var listGQL = `
|
||||||
|
query ListChanges($filter:ChangesFilter) {
|
||||||
|
changes(filter:$filter) {
|
||||||
|
id
|
||||||
|
model
|
||||||
|
op
|
||||||
|
author
|
||||||
|
listed
|
||||||
|
date
|
||||||
|
keys {
|
||||||
|
model
|
||||||
|
id
|
||||||
|
}
|
||||||
|
objects {
|
||||||
|
__typename
|
||||||
|
...on Channel {
|
||||||
|
name
|
||||||
|
logged
|
||||||
|
hub
|
||||||
|
eventName
|
||||||
|
locationName
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`
|
||||||
@@ -2,13 +2,16 @@ package channels
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"log"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.aiterp.net/rpdata/logbot3/internal/models"
|
"git.aiterp.net/rpdata/logbot3/internal/models"
|
||||||
|
"git.aiterp.net/rpdata/logbot3/internal/models/changes"
|
||||||
)
|
)
|
||||||
|
|
||||||
// SubscribeLogged returns a channel that gets all the channel changes.
|
// SubscribeLogged returns a channel that gets all the channel changes.
|
||||||
func SubscribeLogged(ctx context.Context) (<-chan models.Channel, error) {
|
func SubscribeLogged(ctx context.Context) (<-chan models.Channel, error) {
|
||||||
|
earliest := time.Now()
|
||||||
channels, err := ListLogged(ctx)
|
channels, err := ListLogged(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -21,8 +24,28 @@ func SubscribeLogged(ctx context.Context) (<-chan models.Channel, error) {
|
|||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
for {
|
for {
|
||||||
time.Sleep(time.Second * 20)
|
time.Sleep(time.Second * 5)
|
||||||
|
|
||||||
|
// Get the changes.
|
||||||
|
changes, err := changes.List(ctx, &changes.Filter{EarliestDate: &earliest, Keys: []models.ChangeKey{{Model: "Channel", ID: "*"}}})
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return
|
||||||
|
} else if err != nil {
|
||||||
|
log.Println("Failed to get chnges:", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Group changes to the same model.
|
||||||
|
for _, change := range changes {
|
||||||
|
for _, obj := range change.Objects {
|
||||||
|
channel, err := obj.Channel()
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
output <- channel
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
|||||||
@@ -25,10 +25,10 @@ func main() {
|
|||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
bot := bot.New(context.Background(), conf.Bot.Nicks[0], conf.Bot.Nicks[1:])
|
bot := bot.New(context.Background(), conf.Bot.Nicks[0], conf.Bot.Nicks[1:], conf.Bot.User, conf.Bot.RealName)
|
||||||
err = bot.Connect(conf.Bot.Server, false)
|
err = bot.Connect(conf.Server.Address, conf.Server.SSL, 3)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("Warning:", err)
|
log.Println("IRC server cannot be reached:", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,6 +36,7 @@ func main() {
|
|||||||
interrupt := make(chan os.Signal, 1)
|
interrupt := make(chan os.Signal, 1)
|
||||||
signal.Notify(interrupt, os.Interrupt)
|
signal.Notify(interrupt, os.Interrupt)
|
||||||
signal.Notify(interrupt, syscall.SIGTERM)
|
signal.Notify(interrupt, syscall.SIGTERM)
|
||||||
|
<-interrupt
|
||||||
|
|
||||||
log.Println("Interrupt received, stopping...")
|
log.Println("Interrupt received, stopping...")
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user