mtfosbot/module/twitch-irc/twitch-irc.go

140 lines
2.1 KiB
Go
Raw Normal View History

2018-09-12 10:07:49 +00:00
package twitchirc
import (
"fmt"
"net"
2018-09-12 15:34:28 +00:00
"time"
2018-09-12 10:07:49 +00:00
"gopkg.in/irc.v2"
"git.trj.tw/golang/mtfosbot/module/config"
)
var client *irc.Client
2018-09-12 15:34:28 +00:00
var queue *QueueList
var channels []string
2018-09-12 10:07:49 +00:00
// InitIRC -
func InitIRC() (err error) {
conf := config.GetConf()
conn, err := net.Dial("tcp", conf.Twitch.ChatHost)
if err != nil {
return
}
config := irc.ClientConfig{
Handler: irc.HandlerFunc(ircHandle),
}
client = irc.NewClient(conn, config)
err = client.Run()
2018-09-12 15:34:28 +00:00
queue = NewQueue()
go runQueue()
channels = make([]string, 0)
2018-09-12 10:07:49 +00:00
return
}
2018-09-13 10:18:59 +00:00
// SendMessage -
func SendMessage(ch, msg string) {
if len(ch) == 0 {
return
}
if indexOf(channels, ch) == -1 {
return
}
m := &MsgObj{
Command: "PRIVMSG",
Params: []string{
fmt.Sprintf("#%s", ch),
fmt.Sprintf(":%s", msg),
},
}
queue.Add(m)
}
2018-09-12 15:34:28 +00:00
// JoinChannel -
func JoinChannel(ch string) {
if len(ch) == 0 {
return
}
if indexOf(channels, ch) != -1 {
return
}
m := &MsgObj{
Command: "JOIN",
Params: []string{
fmt.Sprintf("#%s", ch),
},
}
queue.Add(m)
}
// LeaveChannel -
func LeaveChannel(ch string) {
if len(ch) == 0 {
return
}
if indexOf(channels, ch) == -1 {
return
}
m := &MsgObj{
Command: "PART",
Params: []string{
fmt.Sprintf("#%s", ch),
},
}
queue.Add(m)
}
func runQueue() {
for {
if !queue.IsEmpty() {
m := queue.Get()
msg := &irc.Message{}
msg.Command = m.Command
msg.Params = m.Params
2018-09-13 10:18:59 +00:00
if m.Command == "JOIN" {
if indexOf(channels, m.Params[0][1:]) != -1 {
continue
}
channels = append(channels, m.Params[0][1:])
} else if m.Command == "PART" {
if indexOf(channels, m.Params[0][1:]) == -1 {
continue
2018-09-12 15:34:28 +00:00
}
2018-09-13 10:18:59 +00:00
idx := indexOf(channels, m.Params[0][1:])
channels = append(channels[:idx], channels[idx+1:]...)
2018-09-12 15:34:28 +00:00
}
2018-09-13 10:18:59 +00:00
fmt.Println("< ", msg.String())
client.WriteMessage(msg)
2018-09-12 15:34:28 +00:00
}
2018-09-13 10:18:59 +00:00
2018-09-12 15:34:28 +00:00
time.Sleep(time.Microsecond * 1500)
}
}
2018-09-12 10:07:49 +00:00
func ircHandle(c *irc.Client, m *irc.Message) {
2018-09-13 10:18:59 +00:00
fmt.Println("> ", m.String())
2018-09-12 15:34:28 +00:00
}
func indexOf(c []string, data string) int {
if len(c) == 0 {
return -1
}
for k, v := range c {
if v == data {
return k
}
}
return -1
2018-09-12 10:07:49 +00:00
}