go-ricochet/examples/echobot/main.go

99 lines
2.5 KiB
Go
Raw Normal View History

2016-01-02 02:08:28 +00:00
package main
import (
"github.com/s-rah/go-ricochet"
2017-05-02 23:33:51 +00:00
"github.com/s-rah/go-ricochet/channels"
"github.com/s-rah/go-ricochet/connection"
"github.com/s-rah/go-ricochet/utils"
"log"
2017-05-02 23:33:51 +00:00
"time"
2016-01-02 02:08:28 +00:00
)
2016-11-08 23:12:50 +00:00
// EchoBotService is an example service which simply echoes back what a client
// sends it.
2017-05-02 23:33:51 +00:00
type RicochetEchoBot struct {
connection.AutoConnectionHandler
messages chan string
}
2016-01-02 02:08:28 +00:00
2017-05-02 23:33:51 +00:00
func (echobot *RicochetEchoBot) GetContactDetails() (string, string) {
return "EchoBot", "I LIVE 😈😈!!!!"
}
2017-05-02 23:33:51 +00:00
func (echobot *RicochetEchoBot) ContactRequest(name string, message string) string {
return "Pending"
}
2017-05-02 23:33:51 +00:00
func (echobot *RicochetEchoBot) ContactRequestRejected() {
}
func (echobot *RicochetEchoBot) ContactRequestAccepted() {
}
func (echobot *RicochetEchoBot) ContactRequestError() {
}
func (echobot *RicochetEchoBot) ChatMessage(messageID uint32, when time.Time, message string) bool {
echobot.messages <- message
return true
}
2016-01-02 02:08:28 +00:00
2017-05-02 23:33:51 +00:00
func (echobot *RicochetEchoBot) ChatMessageAck(messageID uint32) {
}
2016-01-02 02:08:28 +00:00
2017-05-02 23:33:51 +00:00
func (echobot *RicochetEchoBot) Connect(privateKeyFile string, hostname string) {
privateKey, _ := utils.LoadPrivateKeyFromFile(privateKeyFile)
echobot.messages = make(chan string)
echobot.Init(privateKey, hostname)
echobot.RegisterChannelHandler("im.ricochet.contact.request", func() channels.Handler {
contact := new(channels.ContactRequestChannel)
contact.Handler = echobot
return contact
})
echobot.RegisterChannelHandler("im.ricochet.chat", func() channels.Handler {
chat := new(channels.ChatChannel)
chat.Handler = echobot
return chat
})
rc, _ := goricochet.Open(hostname)
known, err := connection.HandleOutboundConnection(rc).ProcessAuthAsClient(privateKey)
2017-05-02 23:33:51 +00:00
if err == nil {
go rc.Process(echobot)
if !known {
err := rc.RequestOpenChannel("im.ricochet.contact.request", echobot)
if err != nil {
log.Printf("could not contact %s", err)
}
}
rc.RequestOpenChannel("im.ricochet.chat", echobot)
for {
message := <-echobot.messages
log.Printf("Received Message: %s", message)
rc.Do(func() error {
log.Printf("Finding Chat Channel")
channel := rc.Channel("im.ricochet.chat", channels.Outbound)
if channel != nil {
log.Printf("Found Chat Channel")
chatchannel, ok := (*channel.Handler).(*channels.ChatChannel)
if ok {
chatchannel.SendMessage(message)
}
} else {
log.Printf("Could not find chat channel")
}
return nil
})
}
2016-01-02 02:08:28 +00:00
}
}
func main() {
2017-05-02 23:33:51 +00:00
echoBot := new(RicochetEchoBot)
echoBot.Connect("private_key", "oqf7z4ot6kuejgam")
2016-01-02 02:08:28 +00:00
}