Golang 电报机器人

问题描述 投票:0回答:1

我正在 telego 上编写一个机器人,我不明白如何在机器人中实现 fsm。在此之前,我用内置了 fsm 的 python aiogram 编写了机器人。在 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

我用谷歌搜索,没有找到任何可以帮助我的东西。

go bots telegram telegram-bot fsm
1个回答
0
投票

在 Golang 中,您可以通过定义处理不同用户交互的状态和转换来在 Telegram 机器人中实现有限状态机 (FSM)。尽管您使用的

telego
库没有对 FSM 的内置支持,但您可以使用简单的 switch-case 语句或使用像
github.com/looplab/fsm
这样的状态管理包自行实现。

这是一个简单的示例,说明如何使用

github.com/looplab/fsm
包和现有
telego
机器人代码来实现 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
软件包文档以获取更高级的用法和功能。

© www.soinside.com 2019 - 2024. All rights reserved.