Skip to content

Commit

Permalink
add sessions
Browse files Browse the repository at this point in the history
  • Loading branch information
vildan-valeev committed Dec 23, 2023
1 parent 2fca0fa commit 5528b38
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 0 deletions.
17 changes: 17 additions & 0 deletions dispatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,23 @@ func NewDispatcher(token string, groupID int64, newBotFn NewBotFn) (*Dispatcher,
return d, nil
}

// DelSession deletes the Bot instance, seen as a session, from the
// map with all of them.
func (d *Dispatcher) DelSession(chatID int64) {
d.mu.Lock()
delete(d.sessionMap, chatID)
d.mu.Unlock()
}

// AddSession allows to arbitrarily create a new Bot instance.
func (d *Dispatcher) AddSession(chatID int64) {
d.mu.Lock()
if _, isIn := d.sessionMap[chatID]; !isIn {
d.sessionMap[chatID] = d.newBot(chatID)
}
d.mu.Unlock()
}

// Poll is a wrapper function for PollOptions.
func (d *Dispatcher) Poll() error {

Expand Down
77 changes: 77 additions & 0 deletions example/sessions/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package main

import (
"fmt"
"log"
"strings"
"time"

"github.com/vildan-valeev/gvk"
)

const (
groupID = 194299208
token = "b30fae3f8d488e20cdbe041cbec9a0aa62e7c52e6107f97f97a9fd9007abe32223e1373cce590bfabf374"
)

type stateFn func(event *gvk.Update) stateFn

type Bot struct {
chatID int64
state stateFn
name string

gvk.API
}

var dsp *gvk.Dispatcher

func newBot(chatID int64) gvk.Bot {
b := &Bot{
chatID: chatID,
API: gvk.NewAPI(token),
}
go b.selfDestruct(time.After(time.Minute))
b.state = b.EntryHandler
return b
}

func (b *Bot) selfDestruct(timech <-chan time.Time) {
<-timech
b.MessagesSend("goodbye...", &gvk.MessagesSendOptions{UserID: b.chatID})
dsp.DelSession(b.chatID)
}

func (b *Bot) Update(update *gvk.Update) {
b.state = b.state(update)
}

func (b *Bot) EntryHandler(update *gvk.Update) stateFn {
if strings.HasPrefix(update.Object.MessageNew.Message.Text, "ping") {
b.MessagesSend("pong", &gvk.MessagesSendOptions{UserID: b.chatID})
return b.handleNext
}

b.MessagesSend("not understand...", &gvk.MessagesSendOptions{UserID: b.chatID})

return b.EntryHandler
}

func (b *Bot) handleNext(update *gvk.Update) stateFn {

b.MessagesSend("pong again )))", &gvk.MessagesSendOptions{
UserID: b.chatID,
})

return b.EntryHandler
}

func main() {
fmt.Print("Start!")
var err error

dsp, err = gvk.NewDispatcher(token, groupID, newBot)

log.Println(err)
log.Println(dsp.Poll())
}

0 comments on commit 5528b38

Please sign in to comment.