bot: Bot setup and teardown done: Connect w/retry, join/leave, full config, and logging.

This commit is contained in:
2018-11-14 21:01:29 +01:00
parent 112c29694d
commit 7336ea2b47
9 changed files with 236 additions and 76 deletions
+79 -61
View File
@@ -3,10 +3,10 @@ package bot
import (
"context"
"log"
"strings"
"time"
"git.aiterp.net/gisle/irc"
"git.aiterp.net/rpdata/logbot3/internal/models"
"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.
type Bot struct {
commandChannel string
client *irc.Client
ctx context.Context
ctxCancel context.CancelFunc
client *irc.Client
ctx context.Context
ctxCancel context.CancelFunc
loopCtx context.Context
loopCancel context.CancelFunc
}
// 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{
Nick: nick,
User: user,
RealName: realName,
Alternatives: alternatives,
SendRate: 2,
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
// 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 {
bot.ctxCancel()
}
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() {
ticker := time.NewTicker(time.Second * 10)
defer ticker.Stop()
bot.loopCtx, bot.loopCancel = context.WithCancel(bot.ctx)
log.Println("Client ready.")
channelChanges, err := channels.SubscribeLogged(bot.ctx)
if err != nil {
log.Println("Failed to get channel changes:", err)
return
}
for {
select {
case <-ticker.C:
case channel := <-channelChanges:
{
bot.syncChannels()
channels := []models.Channel{channel}
deadline := time.After(time.Second * 1)
buffering := true
for buffering {
select {
case channel := <-channelChanges:
channels = append(channels, channel)
case <-deadline:
buffering = false
}
}
decisions := make(map[string]bool)
for _, channel := range channels {
decisions[channel.Name] = channel.Logged
}
joins := make([]string, 0, len(decisions))
parts := make([]string, 0, len(decisions))
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)
}
}
if len(joins) > 0 {
bot.client.Join(joins...)
}
if len(parts) > 0 {
bot.client.Part(parts...)
}
}
case <-bot.ctx.Done():
case <-bot.loopCtx.Done():
{
log.Println("Spinning down bot main loop.")
log.Println("Spinning down bot loop.")
return
}
}
}
}
func (bot *Bot) syncChannels() {
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 {
name := channel.Name
names = append(names, name)
if bot.client.Channel(name) == nil {
joins = append(joins, name)
}
}
// 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 {
log.Println("Joining", strings.Join(joins, ", "))
bot.client.SendQueuedf("JOIN %s", strings.Join(joins, ","))
}
// leave channels.
if len(leaves) > 0 {
log.Println("Leaving", strings.Join(leaves, ", "))
bot.client.SendQueuedf("PART %s :Channel removed.", strings.Join(leaves, ","))
}
}
func (bot *Bot) stopLoop() {
if bot.ctxCancel != nil {
bot.ctxCancel()
if bot.loopCancel != nil {
bot.loopCancel()
}
}
+39 -4
View File
@@ -5,6 +5,7 @@ import (
"strings"
"git.aiterp.net/gisle/irc"
"git.aiterp.net/rpdata/logbot3/internal/config"
)
func handler(event *irc.Event, client *irc.Client) {
@@ -13,18 +14,52 @@ func handler(event *irc.Event, client *irc.Client) {
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() {
// Handle bot loop
case "hook.ready":
{
log.Println("Client is ready!")
go bot.loop()
}
case "client.disconnect":
{
log.Println("Client disconnected!")
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)
}
}
}