mtn_go_discord_framework

package module
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 27, 2025 License: AGPL-3.0 Imports: 7 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

MTN Go Discord Framework

This is a Go framework for building Discord bots using the discordgo library. It's a little helper to get bots running pretty easy but it still gives you full control over then discordgo objects behind the scenes. So if you need to do anything custom, you can do that.

Installation

To use the MTN Go Discord Framework in your project:

  1. Initialize Go Modules (if you haven't already): This framework uses Go Modules. If you are starting a new project, you'll need to initialize Go modules in your project directory. If you already have a go.mod file, you can skip this step.

    go mod init yourprojectname
    

    Replace yourprojectname with the desired module path for your project (e.g., github.com/yourusername/yourprojectname).

  2. Get the package: Open your terminal and run the following command to download the framework package. This command will fetch the framework and add it as a dependency to your project's go.mod file.

    go get github.com/MTN-Media-Dev-Team/mtn_go_discord_framework
    

After these steps, you can import the framework into your Go files like so:

import "github.com/MTN-Media-Dev-Team/mtn_go_discord_framework" // Or specific sub-packages

Usage

Examples of how to use the project.

Framework Functions

This section describes the main functions provided by the MTN Go Discord Framework.

InitFramework(debugMode bool, testingGuildId string, botToken string) *discordgo.Session
  • Purpose: Initializes the Discord bot framework. This function sets up the Discord session and prepares the bot for operation.
  • Parameters:
    • debugMode bool: A boolean flag to enable or disable debug mode. When true, additional logging and diagnostic information may be outputted.
    • testingGuildId string: The Discord Guild ID to use for testing slash commands. If empty, commands are registered globally.
    • botToken string: The authentication token for the Discord bot.
  • Returns: *discordgo.Session: A pointer to the initialized discordgo.Session object, which is used for all further interactions with the Discord API if you need to do anything custom. Returns nil if initialization fails.
RegisterSlashCommandWithFramework(command SlashCommand)
  • Purpose: Registers a single slash command with the framework.
  • Parameters:
    • command SlashCommand: A SlashCommand struct instance representing the command to be registered. This struct should define the command's name, description, options, and handler function.
  • Returns: None.
RegisterSlashCommandsWithFramework(commands []SlashCommand)
  • Purpose: Registers multiple slash commands with the framework at once.
  • Parameters:
    • commands []SlashCommand: A slice of SlashCommand structs, each representing a command to be registered.
  • Returns: None.
RegisterButtonHandlerWithFramework(handler ButtonHandler)
  • Purpose: Registers a single button interaction handler with the framework.
  • Parameters:
    • handler ButtonHandler: A ButtonHandler struct instance. This struct should define the custom ID of the button and the function to execute when the button is pressed.
  • Returns: None.
RegisterButtonHandlersWithFramework(handlers []ButtonHandler)
  • Purpose: Registers multiple button interaction handlers with the framework at once.
  • Parameters:
    • handlers []ButtonHandler: A slice of ButtonHandler structs, each defining a button and its handler.
  • Returns: None.
StartFramework()
  • Purpose: Starts the bot and connects it to Discord. This function will block until the bot is shut down.
  • Parameters: None.
  • Returns: None.
ShutdownFramework()
  • Purpose: Gracefully shuts down the bot, closes the Discord session, and cleans up any resources.
  • Parameters: None.
  • Returns: None.

Data Structures

This section describes the main data structures used by the MTN Go Discord Framework.

SlashCommand Struct
  • Purpose: The SlashCommand struct is used to define a slash command that your bot will listen for and respond to. It encapsulates all the necessary information for registering and handling a slash command.
  • Fields:
    • Name string: The name of the slash command as it will appear in Discord. This is the primary identifier for the command.
    • Description string: A brief description of what the slash command does. This is visible to users in Discord when they are selecting a command.
    • Handler func(s *discordgo.Session, i *discordgo.InteractionCreate, options *OptionContainer): The function that will be executed when this slash command is invoked by a user.
      • s *discordgo.Session: The current Discord session.
      • i *discordgo.InteractionCreate: The interaction object containing data about the command invocation.
      • options *OptionContainer: A pointer to an OptionContainer struct, which holds the parsed values of any options provided by the user with the command.
    • RequiredOptions []OptionRequirement: A slice of OptionRequirement structs that define the options (parameters) that this command accepts. This field is used to specify the name, type, description, and whether each option is required for the command.
ButtonHandler Struct
  • Purpose: The ButtonHandler struct is used to define a handler for button interactions within your Discord bot. It links a specific button, identified by its CustomID, to a function that should be executed when that button is pressed.
  • Fields:
    • CustomID string: The unique identifier for the button. This ID is set when the button is created and is used by Discord to identify which button was pressed. The framework uses this ID to route the interaction to the correct handler.
    • Handler func(s *discordgo.Session, i *discordgo.InteractionCreate, args ...string): The function that will be executed when a button with the matching CustomID is pressed.
      • s *discordgo.Session: The current Discord session.
      • i *discordgo.InteractionCreate: The interaction object containing data about the button press.
      • args ...string: Optional string arguments that can be encoded into the CustomID when the button is created. These arguments are parsed by the framework and passed to the handler, allowing for dynamic behavior based on the context in which the button was generated.
OptionRequirement Struct
  • Purpose: The OptionRequirement struct is used within the SlashCommand struct to define the individual options (or parameters) that a slash command can accept. Each instance of this struct specifies the details for one command option.
  • Fields:
    • Required bool: A boolean value indicating whether this option must be provided by the user when invoking the slash command. If true, the command cannot be submitted without this option.
    • Name string: The name of the option. This is how the option is identified internally and often how it's displayed to the user in Discord.
    • Description string: A brief description of the option, explaining what value is expected or what the option does. This is shown to the user in Discord.
    • Type discordgo.ApplicationCommandOptionType: Specifies the data type of the option. This uses the discordgo.ApplicationCommandOptionType enum, which includes types like String, Integer, Boolean, User, Channel, Role, etc.
    • Default CommandOption: Represents the default value for this option if the user does not provide one. The CommandOption type would typically be a wrapper or interface that can hold various types of default values (e.g., string, int, bool). If an option is not Required and has a Default value, this default will be used.

Helper Functions

This section describes various helper functions provided by the framework to simplify common bot development tasks.

SendEphemeralResponse(s *discordgo.Session, i *discordgo.InteractionCreate, msg string)
  • Purpose: Sends an ephemeral message in response to an interaction. Ephemeral messages are only visible to the user who triggered the interaction.
  • Parameters:
    • s *discordgo.Session: The current Discord session.
    • i *discordgo.InteractionCreate: The interaction object to respond to.
    • msg string: The text content of the ephemeral message.
SendEphemeralEmbed(s *discordgo.Session, i *discordgo.InteractionCreate, embed *discordgo.MessageEmbed)
  • Purpose: Sends an ephemeral message containing an embed in response to an interaction.
  • Parameters:
    • s *discordgo.Session: The current Discord session.
    • i *discordgo.InteractionCreate: The interaction object to respond to.
    • embed *discordgo.MessageEmbed: A pointer to the discordgo.MessageEmbed struct to be sent.
SendDeferResponse(s *discordgo.Session, i *discordgo.InteractionCreate)
  • Purpose: Sends a deferred response to an interaction. This is useful when a command might take longer to process, preventing the interaction from timing out. The bot should later follow up with an actual response using functions like s.InteractionResponseEdit().
  • Parameters:
    • s *discordgo.Session: The current Discord session.
    • i *discordgo.InteractionCreate: The interaction object to respond to.
CheckForRoles(s *discordgo.Session, i *discordgo.InteractionCreate, roles ...string) bool
  • Purpose: Checks if the user who triggered the interaction has at least one of the specified roles in the guild.
  • Parameters:
    • s *discordgo.Session: The current Discord session.
    • i *discordgo.InteractionCreate: The interaction object, used to identify the user and guild.
    • roles ...string: A variadic list of role IDs or role names to check for.
  • Returns: bool: true if the user has at least one of the specified roles, false otherwise.
CheckForRolesOrAdmin(s *discordgo.Session, i *discordgo.InteractionCreate, roles ...string) bool
  • Purpose: Checks if the user who triggered the interaction either has at least one of the specified roles or has administrator permissions in the guild.
  • Parameters:
    • s *discordgo.Session: The current Discord session.
    • i *discordgo.InteractionCreate: The interaction object.
    • roles ...string: A variadic list of role IDs or role names to check for.
  • Returns: bool: true if the user has at least one of the specified roles or is an administrator, false otherwise.
CheckForAdmin(s *discordgo.Session, i *discordgo.InteractionCreate) bool
  • Purpose: Checks if the user who triggered the interaction has administrator permissions in the guild.
  • Parameters:
    • s *discordgo.Session: The current Discord session.
    • i *discordgo.InteractionCreate: The interaction object.
  • Returns: bool: true if the user is an administrator, false otherwise.

Basic Usage Example

This example demonstrates how to set up a simple Discord bot using the MTN Go Discord Framework. It shows how to initialize the framework, define a basic "ping" slash command, register it, and start the bot.

package main

import (
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"

	"github.com/bwmarrin/discordgo"
	"github.com/MTN-Media-Dev-Team/mtn_go_discord_framework"
)

func main() {
	// 1. Initialize the framework
	// Replace "YOUR_BOT_TOKEN" with your actual bot token.
	// Set debugMode to true for more verbose logging.
	// Set testingGuildId to your guild ID for testing, or "" for global commands.
	sess, err := framework.InitFramework(true, "YOUR_TESTING_GUILD_ID", "YOUR_BOT_TOKEN")
	if err != nil {
		log.Fatalf("Failed to initialize framework: %v", err)
	}

	// 2. Define a simple slash command
	pingCommand := framework.SlashCommand{
		Name:        "ping",
		Description: "Replies with Pong!",
		Handler: func(s *discordgo.Session, i *discordgo.InteractionCreate, options *framework.OptionContainer) {
			log.Println("Ping command executed")
			err := framework.SendEphemeralResponse(s, i, "Pong!")
			if err != nil {
				log.Printf("Failed to send pong response: %v", err)
			}
		},
		RequiredOptions: []framework.OptionRequirement{}, // No options for this simple command
	}

	// 3. Register the command
	framework.RegisterSlashCommandWithFramework(pingCommand)
	log.Printf("Registered command: %s", pingCommand.Name)

	// 4. Start the framework
	// This will connect to Discord and start listening for events.
	// The framework needs to be started after all commands and handlers are registered.
	err = framework.StartFramework()
	if err != nil {
		log.Fatalf("Failed to start framework: %v", err)
	}
	defer framework.ShutdownFramework() // Ensure graceful shutdown

	fmt.Println("Bot is now running. Press CTRL-C to exit.")
	sc := make(chan os.Signal, 1)
	signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
	<-sc

	log.Println("Shutting down...")
}

Note:

  • Replace "YOUR_BOT_TOKEN" with your actual Discord bot token.
  • Replace "YOUR_TESTING_GUILD_ID" with your Discord server's ID if you want to register commands only to that server for testing. Leave it as an empty string ("") to register commands globally (this might take up to an hour to propagate).
  • Adjust the import path github.com/MTN-Media-Dev-Team/mtn_go_discord_framework to match your project's actual module path.

Contributing

We welcome contributions to the MTN Go Discord Framework! Whether you've found a bug, have a feature request, or want to improve the documentation, your help is appreciated.

Here are some ways you can contribute:

  • Reporting Bugs: If you encounter a bug, please open an issue on the GitHub repository. Include as much detail as possible, such as steps to reproduce, expected behavior, and actual behavior.
  • Suggesting Enhancements: If you have an idea for a new feature or an improvement to an existing one, feel free to open an issue to discuss it.
  • Submitting Pull Requests: If you'd like to contribute code or documentation changes:
    1. Fork the repository.
    2. Create a new branch for your changes (git checkout -b feature/your-feature-name or bugfix/your-bug-fix).
    3. Make your changes and commit them with clear, descriptive messages.
    4. Push your branch to your forked repository.
    5. Open a pull request against the main repository, detailing the changes you've made.

We will review your contributions and provide feedback as soon as possible. Thank you for helping to make this framework better!

License

This project is licensed under the GNU Affero General Public License v3.0 - see the LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	EphemeralFlag = 64
)

Variables

View Source
var (
	ErrInvalidOptionType     = errors.New("invalid option type")
	ErrMissingRequiredOption = errors.New("missing required option")
)

declare errors

Functions

func BusySleep

func BusySleep()

busySleep pauses execution for up to 10 seconds if the system is busy

func CheckForAdmin added in v0.1.13

func CheckForAdmin(s *discordgo.Session, i *discordgo.InteractionCreate) bool

func CheckForRoles

func CheckForRoles(s *discordgo.Session, i *discordgo.InteractionCreate, roles ...string) bool

checkForRoles checks if a member has one of the provided roles

func CheckForRolesOrAdmin added in v0.1.13

func CheckForRolesOrAdmin(s *discordgo.Session, i *discordgo.InteractionCreate, roles ...string) bool

func InitFramework

func InitFramework(debugMode bool, testingGuildId string, botToken string) *discordgo.Session

Initializes the framework and returns a discord session, needed for the other functions

func RegisterButtonHandlerWithFramework

func RegisterButtonHandlerWithFramework(handler ButtonHandler)

Registers a button handler with the framework

func RegisterButtonHandlersWithFramework added in v0.1.3

func RegisterButtonHandlersWithFramework(handlers []ButtonHandler)

Registers multiple button handlers with the framework

func RegisterSlashCommandWithFramework

func RegisterSlashCommandWithFramework(command SlashCommand)

Registers a slash command with the framework

func RegisterSlashCommandsWithFramework added in v0.1.3

func RegisterSlashCommandsWithFramework(commands []SlashCommand)

Registers multiple slash commands with the framework

func ReleaseSystem

func ReleaseSystem()

Set systemBusy to false. Should be deferred after a successful tryAcquireSystem.

func SendDeferResponse

func SendDeferResponse(s *discordgo.Session, i *discordgo.InteractionCreate)

sendDeferResponse sends a deferred response to an interaction

func SendEphemeralEmbed added in v0.1.4

func SendEphemeralEmbed(s *discordgo.Session, i *discordgo.InteractionCreate, embed *discordgo.MessageEmbed)

func SendEphemeralResponse

func SendEphemeralResponse(s *discordgo.Session, i *discordgo.InteractionCreate, msg string)

sendEphemeralResponse sends a response to an interaction that only the user can see

func ShutdownFramework

func ShutdownFramework()

Shuts down the framework and closes the discord session

func StartFramework

func StartFramework()

Launches the framework and registers all commands and handlers

func TryAcquireSystem

func TryAcquireSystem() bool

Check if the system is busy. If not, set it to busy and return true. If it is busy, return false.

Types

type BooleanOption added in v0.1.6

type BooleanOption struct {
	Value bool
	Name  string
}

func (BooleanOption) GetName added in v0.1.6

func (s BooleanOption) GetName() string

func (BooleanOption) GetValue added in v0.1.6

func (s BooleanOption) GetValue() any

type ButtonHandler

type ButtonHandler struct {
	CustomID string
	Handler  func(s *discordgo.Session, i *discordgo.InteractionCreate, args ...string)
}

type ChannelOption added in v0.1.6

type ChannelOption struct {
	Value *discordgo.Channel
	Name  string
}

func (ChannelOption) GetName added in v0.1.6

func (s ChannelOption) GetName() string

func (ChannelOption) GetValue added in v0.1.6

func (s ChannelOption) GetValue() any

type CommandOption added in v0.1.6

type CommandOption interface {
	GetValue() any
	GetName() string
}

type FloatOption added in v0.1.6

type FloatOption struct {
	Value float64
	Name  string
}

func (FloatOption) GetName added in v0.1.6

func (s FloatOption) GetName() string

func (FloatOption) GetValue added in v0.1.6

func (s FloatOption) GetValue() any

type IntegerOption added in v0.1.6

type IntegerOption struct {
	Value int64
	Name  string
}

func (IntegerOption) GetName added in v0.1.6

func (s IntegerOption) GetName() string

func (IntegerOption) GetValue added in v0.1.6

func (s IntegerOption) GetValue() any

type OptionContainer added in v0.1.6

type OptionContainer struct {
	Options map[string]CommandOption
}

type OptionRequirement added in v0.1.6

type OptionRequirement struct {
	Required    bool
	Name        string
	Description string
	Type        discordgo.ApplicationCommandOptionType
	Default     CommandOption
}

type RoleOption added in v0.1.6

type RoleOption struct {
	Value *discordgo.Role
	Name  string
}

func (RoleOption) GetName added in v0.1.6

func (s RoleOption) GetName() string

func (RoleOption) GetValue added in v0.1.6

func (s RoleOption) GetValue() any

type SlashCommand added in v0.1.4

type SlashCommand struct {
	Name            string
	Description     string
	Handler         func(s *discordgo.Session, i *discordgo.InteractionCreate, options *OptionContainer)
	RequiredOptions []OptionRequirement
	// contains filtered or unexported fields
}

type StringOption added in v0.1.6

type StringOption struct {
	Value string
	Name  string
}

func (StringOption) GetName added in v0.1.6

func (s StringOption) GetName() string

func (StringOption) GetValue added in v0.1.6

func (s StringOption) GetValue() any

type UnsignedIntergerOption added in v0.1.6

type UnsignedIntergerOption struct {
	Value uint64
	Name  string
}

func (UnsignedIntergerOption) GetName added in v0.1.6

func (s UnsignedIntergerOption) GetName() string

func (UnsignedIntergerOption) GetValue added in v0.1.6

func (s UnsignedIntergerOption) GetValue() any

type UserOption added in v0.1.6

type UserOption struct {
	Value *discordgo.User
	Name  string
}

func (UserOption) GetName added in v0.1.6

func (s UserOption) GetName() string

func (UserOption) GetValue added in v0.1.6

func (s UserOption) GetValue() any

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL