我正在Tego上写一个机器人,我不知道如何在机器人中实现有限状态机.在此之前,我用内置了FSM的python aigraph编写了机器人.在golang 怎么做呢?

package main

import (
    "fmt"
    "os"

    "github.com/mymmrac/telego"
    th "github.com/mymmrac/telego/telegohandler"
    tu "github.com/mymmrac/telego/telegoutil"
)

func main() {
    botToken := os.Getenv("TOKEN")

    // Note: Please keep in mind that default logger may expose sensitive information,
    // use in development only
    bot, err := telego.NewBot(botToken, telego.WithDefaultDebugLogger())
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    // Get updates channel
    updates, _ := bot.UpdatesViaLongPolling(nil)

    // Create bot handler and specify from where to get updates
    bh, _ := th.NewBotHandler(bot, updates)

    // Stop handling updates
    defer bh.Stop()

    // Stop getting updates
    defer bot.StopLongPolling()

    // Register new handler with match on command `/start`
    bh.Handle(func(bot *telego.Bot, update telego.Update) {
        // Send message
        _, _ = bot.SendMessage(tu.Message(
            tu.ID(update.Message.Chat.ID),
            fmt.Sprintf("Hello %s!", update.Message.From.FirstName),
        ))
    }, th.CommandEqual("start"))

    // Register new handler with match on any command
    // Handlers will match only once and in order of registration,
    // so this handler will be called on any command except `/start` command
    bh.Handle(func(bot *telego.Bot, update telego.Update) {
        // Send message
        _, _ = bot.SendMessage(tu.Message(
            tu.ID(update.Message.Chat.ID),
            "Unknown command, use /start",
        ))
    }, th.AnyCommand())

    // Start handling updates
    bh.Start()
}

此代码摘自官方文档https://github.com/mymmrac/telego

我用谷歌搜索了一下,没有找到任何对我有帮助的东西.

推荐答案

在Golang中,您可以通过定义用于处理不同用户交互的状态和转换,在Telegram机器人中实现有限状态机(FSM).尽管您正在使用的telego库没有内置的对FSM的支持,但是您可以使用一个简单的Switch-Case语句或使用像github.com/looplab/fsm这样的状态管理包自己实现它.

下面是一个简单的示例,说明如何使用github.com/looplab/fsm包和现有的telego bot代码来实现FSM:

定义FSM的状态和事件.在此示例中,让我们创建一个简单的FSM来管理用户的注册过程:

const (
    StateIdle      = "idle"
    StateRegister  = "register"
    StateCompleted = "completed"
)

const (
    EventStartRegistration = "start_registration"
    EventSubmitDetails     = "submit_details"
    EventFinishRegistration = "finish_registration"
)

修改您的主函数以创建FSM并处理状态转换:

func main() {
    // ... Your existing code ...

    // Create a new FSM
    f := fsm.NewFSM(
        StateIdle,
        fsm.Events{
            {Name: EventStartRegistration, Src: []string{StateIdle}, Dst: StateRegister},
            {Name: EventSubmitDetails, Src: []string{StateRegister}, Dst: StateRegister},
            {Name: EventFinishRegistration, Src: []string{StateRegister}, Dst: StateCompleted},
        },
        fsm.Callbacks{},
    )

    // Start handling updates
    bh.Start()

    // Process updates and handle FSM transitions
    for update := range updates {
        switch {
        case th.CommandEqual("start")(update):
            // Start registration process
            if err := f.Event(EventStartRegistration); err != nil {
                fmt.Println("Error processing start_registration event:", err)
            }
            // Respond to the user with a welcome message or instructions for registration
        case update.Message != nil:
            switch f.Current() {
            case StateRegister:
                // Process user's submitted details and update FSM accordingly
                if err := f.Event(EventSubmitDetails); err != nil {
                    fmt.Println("Error processing submit_details event:", err)
                }
            case StateCompleted:
                // The registration process is completed. Handle the user's interactions here.
                // You can use another switch-case statement to handle different interactions based on the current state.
                // For example:
                // if update.Message.Text == "some_command" {
                //     // Handle a command specific to the completed state
                // } else {
                //     // Respond to other interactions in the completed state
                // }
            default:
                // Respond to the user with an "Unknown command" message
            }
        }
    }
}

在本例中,我们创建了一个基本的FSM来管理用户的注册过程.FSM从StateIdle开始,当接收到/start命令时,它转换到StateRegister.在用户提交他们的详细信息之后,它保持在StateRegister中,直到EventFinishRegistration事件被触发,转换到StateCompleted.根据当前状态,您可以以不同方式处理用户交互.

请注意,这是一个简单的示例,根据您的特定用例,您可能需要定义更多状态和事件,并添加额外的逻辑来处理每个状态下的用户交互.

请务必阅读github.com/looplab/fsm包文档,以了解更高级的用法和功能.

Go相关问答推荐

Golang ==错误:OCI运行时创建失败:无法启动容器进程:exec:./" bin:stat./" bin:没有这样的文件或目录:未知

如何使用 Go 连接到非默认 firestore 数据库?

Go 中将 int 切片转换为自定义 int 切片指针类型的函数

Golang Gorm Fiber - 如何将定义为别名的名称发送到索引模板?

Kperf 构建失败

使用 OpenTelemetry 统一不同服务的范围

Golang和Gin web框架在router.Run()之后执行代码

如何从Go项目连接Microsoft Access数据库?

对 CSV 进行单元测试失败

Go 的垃圾收集器在使用时删除 ZeroMQ 套接字

为什么互斥量比 golang 中的通道慢?

如何在切片增长时自动将切片的新元素添加到函数参数

如何使用带有方法的字符串枚举作为通用参数?

go-libp2p - 从流中接收字节

golang pic.ShowImage 为什么它不生成图像而是向我发送base64值

Golang invopop jsonschema 使用 if/then/else

Golang模板无法访问embedFS中的文件

go 堆栈跟踪:在某些函数调用参数或返回值之后的问题(?)标记是什么意思?

有没有一种方法可以确保传递的值具有使用泛型的某些字段?

Go 错误:cannot use generic type without instantiation