Search code examples
godiscorddiscordgo

How to create channel with discordgo


I want to make a bot create a channel on discord.

I have made a connection with the discord token:

// Create a new Discord session using the provided bot token.
dg, err := discordgo.New("Bot " + Token)
if err != nil {
    fmt.Println("error creating Discord session,", err)
    return
}

// Register the channelCreate func as a callback for ChannelCreate events.
dg.AddHandler(channelCreate)

// Open a websocket connection to Discord and begin listening.
err = dg.Open()
if err != nil {
    fmt.Println("error opening connection,", err)
    return
 }
}

// channel is create
func channelCreate(s *discordgo.Session, event *discordgo.ChannelCreate ) {

     // create channel here
}

How to use the ChannelCreate type on https://gowalker.org/github.com/jonas747/discordgo#ChannelCreate


Solution

  • discordgo.MessageCreate is the channel created event. Meaning the handler will trigger when a channel is created. I'm not sure what are the conditions you want your bot to create a channel. Let's say you want to create a channel by messaging the bot. You will first need to add a handler on the message event

    func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
    
        // Ignore all messages created by the bot itself
        if m.Author.ID == s.State.User.ID {
            return
        }
    
        if m.Content == "create channel" {
            s.GuildChannelCreate(guildID, name, type)
        }
    }
    

    With the type being one of the following:

    // Block contains known ChannelType values
    const (
        ChannelTypeGuildText ChannelType = iota
        ChannelTypeDM
        ChannelTypeGuildVoice
        ChannelTypeGroupDM
        ChannelTypeGuildCategory
        ChannelTypeGuildNews
        ChannelTypeGuildStore
    )