Golang中如何解决Discord机器人包文件的帮助问题

Golang中如何解决Discord机器人包文件的帮助问题 我正在用Go语言开发一个Discord机器人。我需要在Gilded服务器上注册为斜杠命令的命令位于commands文件夹和commands包中,但我希望在commands下创建子文件夹,例如./commands/orders./commands/stockpile……,并将registry.go文件保留在./commands目录下。

当前的问题是,./commands/orders目录下的.go文件无法找到Registry.go中的Register函数。

请帮帮我。

这是Git仓库的链接,以便您查看所有内容:GitHub/FFG-Bot


更多关于Golang中如何解决Discord机器人包文件的帮助问题的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于Golang中如何解决Discord机器人包文件的帮助问题的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Go语言中,当你在子包(如 commands/orders)中需要访问父包(commands)的函数时,需要正确理解Go的包导入机制。你的问题在于子包无法直接访问父包的未导出函数或变量,因为Go的包是基于目录隔离的。

首先,查看你的项目结构:

commands/
├── registry.go
├── orders/
│   └── order.go
└── stockpile/
    └── stockpile.go

解决方案:

  1. commands/registry.go 中导出 Register 函数:
// commands/registry.go
package commands

import "github.com/bwmarrin/discordgo"

var Commands = make(map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate))

// 导出Register函数(首字母大写)
func Register(name string, handler func(s *discordgo.Session, i *discordgo.InteractionCreate)) {
    Commands[name] = handler
}

// 导出GetCommands函数用于获取所有命令
func GetCommands() map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate) {
    return Commands
}
  1. 在子包中导入父包并注册命令:
// commands/orders/order.go
package orders

import (
    "github.com/bwmarrin/discordgo"
    "your-module-path/internal/commands" // 导入父包
)

func init() {
    // 使用父包的导出函数注册命令
    commands.Register("order", OrderCommand)
}

func OrderCommand(s *discordgo.Session, i *discordgo.InteractionCreate) {
    // 命令处理逻辑
    s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
        Type: discordgo.InteractionResponseChannelMessageWithSource,
        Data: &discordgo.InteractionResponseData{
            Content: "Order command executed!",
        },
    })
}
  1. 确保go.mod中的模块路径正确:
// go.mod
module github.com/TFAURE56/FFG-Bot

go 1.21
  1. 在主文件中导入所有子包以触发init函数:
// main.go 或 bot.go
package main

import (
    _ "your-module-path/internal/commands/orders"    // 导入orders包触发init
    _ "your-module-path/internal/commands/stockpile" // 导入stockpile包触发init
    "your-module-path/internal/commands"
    "github.com/bwmarrin/discordgo"
)

func main() {
    // 获取所有已注册的命令
    commandHandlers := commands.GetCommands()
    
    // 使用commandHandlers设置Discord机器人
    // ...
}

关键点说明:

  • Go语言中,每个目录都是一个独立的包
  • 只有首字母大写的函数、变量、类型才能被其他包访问
  • 使用 init() 函数可以在包导入时自动执行注册逻辑
  • 通过下划线导入 (_ "package/path") 可以只执行包的init函数而不直接使用其导出内容

这样设计后,commands/orderscommands/stockpile 子包都能通过导入父包 commands 来调用 Register 函数,同时保持代码的组织结构清晰。

回到顶部