First Commit

This commit is contained in:
2018-11-11 13:18:05 +01:00
commit 0ecbc16bdb
15 changed files with 686 additions and 0 deletions
+122
View File
@@ -0,0 +1,122 @@
package bot
import (
"context"
"log"
"strings"
"time"
"git.aiterp.net/gisle/irc"
"git.aiterp.net/rpdata/logbot3/internal/models/channels"
)
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
}
// New creates a new Bot.
func New(ctx context.Context, nick string, alternatives []string) *Bot {
client := irc.New(ctx, irc.Config{
Nick: nick,
Alternatives: alternatives,
SendRate: 2,
SkipSSLVerification: false,
})
bot := &Bot{
client: client,
}
client.SetValue(botKey, bot)
return bot
}
// Connect connects the bot to the IRC server. This will disconnect already
// established connections.
func (bot *Bot) Connect(server string, ssl bool) error {
if bot.ctxCancel != nil {
bot.ctxCancel()
}
bot.ctx, bot.ctxCancel = context.WithCancel(bot.client.Context())
return bot.client.Connect(server, ssl)
}
func (bot *Bot) loop() {
ticker := time.NewTicker(time.Second * 10)
defer ticker.Stop()
log.Println("Client ready.")
for {
select {
case <-ticker.C:
{
bot.syncChannels()
}
case <-bot.ctx.Done():
{
log.Println("Spinning down bot main 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()
}
}
+34
View File
@@ -0,0 +1,34 @@
package bot
import (
"log"
"strings"
"git.aiterp.net/gisle/irc"
)
func handler(event *irc.Event, client *irc.Client) {
bot, ok := client.Value(botKey).(*Bot)
if !ok {
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() {
case "hook.ready":
{
go bot.loop()
}
case "client.disconnect":
{
bot.stopLoop()
}
}
}
func init() {
irc.Handle(handler)
}