(Golang) Go bindings for Discord

DiscordGo

GoDoc Go report Build Status Discord Gophers Discord API

DiscordGo is a Go package that provides low level bindings to the Discord chat client API. DiscordGo has nearly complete support for all of the Discord API endpoints, websocket interface, and voice interface.

If you would like to help the DiscordGo package please use this link to add the official DiscordGo test bot dgo to your server. This provides indispensable help to this project.

  • See dgVoice package for an example of additional voice helper functions and features for DiscordGo.

  • See dca for an experimental stand alone tool that wraps ffmpeg to create opus encoded audio appropriate for use with Discord (and DiscordGo).

For help with this package or general Go discussion, please join the Discord Gophers chat server.

Getting Started

Installing

This assumes you already have a working Go environment, if not please see this page first.

go get will always pull the latest tagged release from the master branch.

go get github.com/bwmarrin/discordgo

Usage

Import the package into your project.

import "github.com/bwmarrin/discordgo"

Construct a new Discord client which can be used to access the variety of Discord API functions and to set callback functions for Discord events.

discord, err := discordgo.New("Bot " + "authentication token")

See Documentation and Examples below for more detailed information.

Documentation

NOTICE: This library and the Discord API are unfinished. Because of that there may be major changes to library in the future.

The DiscordGo code is fairly well documented at this point and is currently the only documentation available. Both GoDoc and GoWalker (below) present that information in a nice format.

  • GoDoc
  • Go Walker
  • Hand crafted documentation coming eventually.

Examples

Below is a list of examples and other projects using DiscordGo. Please submit an issue if you would like your project added or removed from this list.

Troubleshooting

For help with common problems please reference the Troubleshooting section of the project wiki.

Contributing

Contributions are very welcomed, however please follow the below guidelines.

  • First open an issue describing the bug or enhancement so it can be discussed.
  • Try to match current naming conventions as closely as possible.
  • This package is intended to be a low level direct mapping of the Discord API, so please avoid adding enhancements outside of that scope without first discussing it.
  • Create a Pull Request with your changes against the master branch.

List of Discord APIs

See this chart for a feature comparison and list of other Discord API libraries.

Special Thanks

Chris Rhodes - For the DiscordGo logo and tons of PRs.

Comments
  • Slash commands

    Slash commands

    Here we go! Slash commands are ready to use (almost). So... I saw that everyone wants it, so I'm opening it now, not when I will complete it. Now it includes some example in examples/ folder of using this new feature and basic API of slash commands (CRUD).

    Well, enjoy!

  • Rewrite of the library

    Rewrite of the library

    When I first time reading and trying to understand how DiscordGo works... I was a bit confused and went into many tutorials, but DiscordGophers mostly helped me. So... now I'm here, to propose rewrite this library with the newest best practices, and also caching, logging and many more features. I have a fork of this project, the main work on rewriting will be there. Here will be showed the progress of rewriting. And... one more thing: any contributors to this rewrite will be really welcomed.

    In continuation, I want to discuss and make structure of discordgo better and easier, especially for beginners, but for advanced users too.

    Down here will be shown my vision and some already made examples of how DiscordGo might look at the end of the work.

    So, thanks everyone for attention.

  • Go path returns error

    Go path returns error

    go get github.com/bwmarrin/discordgo

    golang.org/x/crypto/poly1305

    /usr/local/go/src/golang.org/x/crypto/poly1305/sum_amd64.s:8 6a: No such file or directory: textflag.h

    github.com/gorilla/websocket

    /usr/local/go/src/github.com/gorilla/websocket/compression.go:95: undefined: sync.Pool

    How do I fix this? Did I do something wrong?

  • Add Guild Scheduled Event Support

    Add Guild Scheduled Event Support

    Discord just released a new feature: Guild Scheduled Event

    Today I will start to add all endpoints listed in the API Reference (https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event)

    Following this issue : https://github.com/bwmarrin/discordgo/issues/1031

  • i can't receive sound from discord

    i can't receive sound from discord

    problem commits c8554477e44900990a8fbad29ca17ecb3412e832 73f6772a2b7cc95e29c462e4f15bf07cbe0d3854

    problem: hello i can't receive sound from discord because data from channel don't arrive. my code for test https://gist.github.com/kinoher/fb9da8545a5db2ab342ebd524163c849 it's very dirty code i cuted from another my service

  • Add rate limit buffering support

    Add rate limit buffering support

    My anti-spam bot needs to be able to detect when it is about to get rate limited, and then in response to this start aggregating small messages together into a single larger message. This is intended to deal with bot raids, which can trigger 300+ "user has joined" notifications at the same time.

    Doing this in a thread-safe manner requires several modifications to discordgo, and the core "buffered message" function must also be implemented in the Session object because it must access the ratelimiter object. While this pull request tries to make the absolute minimum amount of changes necessary to support this feature, it could be shrunk even more by exposing the rate limiter object and internal requestInner function outside of discordgo, which would then allow the bot to implement the buffered Post function.

    However, if that involves exposing too much of the internal library, the following is the minimum number of changes required to make this work:

    • Break request into requestInner
    • Break LockBucket into LockBucketObject
    • Change getBucket to GetBucket so it can be externally accessed
    • Add RequestBuffer interface
    • Add RequestBuffer pointer to Bucket struct
    • Add RequestPostWithBuffer() function to Session

    If you believe RequestPostWithBuffer should, in fact, be added to Session, tests will need to be made to ensure it works properly, which are not currently included - suggestions for how to implement those tests or where similar tests can be found are appreciated.

  • [Question ]Do we implement the auto guild sharding ?

    [Question ]Do we implement the auto guild sharding ?

    https://github.com/hammerandchisel/discord-api-docs/issues/17 Do we let user deal with that or do we automatically do that ? (I personally it's better that the users deal with that because they can put the programs on multiple computers for big bots like airhorn)

  • Update handlers to receive an interface for the Session

    Update handlers to receive an interface for the Session

    Please be aware, this is a breaking API change.

    This change adds a new discordgo type, Sessioner, which is an interface that describes the full method set for the *Session type. In addition to the new type, this change updates the package to no longer send a concrete *Session value in to handlers it invokes as the first argument but a Sessioner instead. This is to make testing of handlers much easier, as mock implementations of the Sessioner interface can be passed right in.

    This also renames the internal state field from State to state, and adds a new method to *Session, State(), to expose that internal state to consumers. A test was added to ensure this method works as expected.

    The example projects were updated where necessary to work with the new API

    Fixes #662.

    Signed-off-by: Tim Heckman [email protected]

  • Threads reloaded

    Threads reloaded

    So, seeing still ongoing problem with lack of threads implementation, I decided to make my own PR on them. This PR should include everything that's on threads currently.

    This PR also includes some code from #982 and #922 (it is meant to be continuation of those two, but written from scratch). So credits to the authors.

    The roadmap

    • [x] Gateway
    • [x] REST
    • [x] State
      • [x] CRUD
      • [x] Membership
  • Selects component

    Selects component

    Well, during the development of the #933 I was also busy working on Selects component implementation. Now, since all API is experimental this request will be marked as draft one. Also this PR includes some fixes and improvements: like adding WebhookMessage endpoint and files support to webhooks API ( #951). Anyways, here it is: selects component. Feel free to give a feedback on this PR.

  • Ratelimits

    Ratelimits

    Handles the new ratelimit headers

    • X-RateLimit-Remaining
    • X-RateLimit-Reset
    • X-RateLimit-Global

    I stuck it in an internal package, hope that's okay. This is probably not the best way to do the removal of minor url variables, the alternative is to redo the whole endpoint system.

    As for the reliability of this, after sending around 1k requests non-stop i didn't encounter a single 429.

    I pad the reset time with 1 second, because if i don't it will still occasionally run into 429's of the size 1ms - 50ms (yeah, i got ratelimited for 1 ms a lot...), padding with anything less than 1 second would still give those tiny ratelimits sometimes.

  • Can't install (go get error)

    Can't install (go get error)

    When i tried to install this library with this command i have got an error

    go get github.com/bwmarrin/discordgo
    

    The error:

    'go get' is no longer supported outside a module.                                                           To build and install a command, use 'go install' with a version,                                            like 'go install example.com/cmd@latest'              For more information, see https://golang.org/doc/go-get-install-deprecation                                 or run 'go help get' or 'go help install'.
    

    I've tried with go install but i have another error:

    go: downloading github.com/bwmarrin/discordgo v0.26.1 go: downloading github.com/gorilla/websocket v1.4.2   go: downloading golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b                                      package github.com/bwmarrin/discordgo is not a main package
    
  • Options

    Options

    Since the beginning, DiscordGo did not have ability for adding per-call customization:

    • What if you want to disable automatic rate limit handling when you call ChannelMessageDelete, instead handling the error by yourself?
    • Or what if you want to set additional headers on GuildBanCreate, like X-Audit-Log-Reason, to comment your action in audit log?

    We’ve been thinking on how to combat this problem, and came up with the following solutions:

    • Builders pattern

      s.WithAuditLogReason("my reason").GuildBanCreate(...)
      s.WithRetryOnRateLimit(false).ChannelMessageDelete(...)
      
    • Functional options

      s.GuildBanCreate(..., discordgo.WithAuditLogReason("reason"))
      s.ChannelMessageDelete(..., discordgo.WithRetryOnRateLimit(false))
      

    This PR implements the latter. It provides a few pre-built options. However, you can always supply your custom option.

    Options have access to a RequestConfig struct, which is internally used by RequestX functions. This config allows you to modify a few global settings, like Client, ShouldRetryOnRateLimit and MaxRestRetries, but it also allows you to modify the request directly.

    A typical functional option would look like this:

    func WithQuery(key string, value string) discordgo.RequestOption {
    	return func(cfg *discordgo.RequestConfig) {
    		q := cfg.Request.Query()
    		q.Add(key, value)
    		cfg.Request.RawQuery = q.Encode()
    	}
    }
    

    These are built-in options discordgo will provide:

    • [x] WithClient - Control http.Client used for the request (defaults to s.Client)
    • [x] WithHeader - Change a certain header in the request
      • [x] WithAuditLogReason - Set X-Audit-Log-Reason header
      • [x] WithLocale - Set X-Discord-Locale header
    • [x] WithRetryOnRateLimit - Control Session.ShouldRetryOnRateLimit field for the request
    • [x] WithMaxRestRetries - Control Session.MaxRestRetries field for the request
    • [x] WithContext - Provide a context.Context to the http.Request

    This change will be affecting all of the REST endpoints. However it should be non-breaking.

    If you have used any function signatures though, you would need to change them accordingly:

    - func (s *Session) XXX(...) (...) {}
    + func (s *Session) XXX(..., options ...RequestOption) (...) {}
    
  • Slash-commands: Attachment option can't be used

    Slash-commands: Attachment option can't be used

    When I try to get the attachment of a slash command I can't use the available option. Can you please fix that? Because when I try to use i.Interaction.ApplicationCommand.Data().Options[0].Value I can't get the file.

  • Unable to get the Guild members

    Unable to get the Guild members

    func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
    	g, err := s.State.Guild(m.guildID)
    	if err != nil {
    		fmt.Println(err.Error())
    
    	}
    	fmt.Println(g.Members)
    }
    

    Not at all getting guildmembers as when I am trying to get guild member count then it shows 0 as output , May I know how do I use guildMembers

    Thank you

  • How to send Opus data correctly

    How to send Opus data correctly

    I do see that there's dgVoice and dca, but they have been a mess to get working on Windows.

    I have now downloaded Opus tools, which include opusenc, which allows me to convert a .wav to .opus. However, I'm not sure how to send the data correctly... here's what I'm currently doing:

    package main
    
    import (
    	"os"
    	"flag"
    	"fmt"
    	// "time"
    	"bufio"
    	"github.com/bwmarrin/discordgo"
    )
    
    // Variables used for command line parameters
    var (
    	Token     string
    	ChannelID string
    	GuildID   string
    )
    
    const (
    	channels = 2 // --raw-chan 2
    	frameRate = 48000 // --raw-rate 48000
    	frameSize = 60 // --framesize 60 (this can't be set to 960 according to opusenc)
    	maxBytes = frameSize * 2 * 2
    )
    
    func init() {
    	flag.StringVar(&Token, "t", "", "Bot Token")
    	flag.StringVar(&GuildID, "g", "", "Guild in which voice channel exists")
    	flag.StringVar(&ChannelID, "c", "", "Voice channel to connect to")
    	flag.Parse()
    }
    
    // Read chunks of the .opus file and send
    func play(v *discordgo.VoiceConnection) {
    	file, err := os.Open("Audiorezout - Anpiel.opus")
    	if err != nil {
    		return
    	}
    	defer file.Close()
    
    	reader := bufio.NewReader(file)
    	buffer := make([]byte, maxBytes)
    
    	v.Speaking(true)
    	defer v.Speaking(false)
    
    	for {
    		read, err := reader.Read(buffer)
    		if err != nil {
    			break
    		}
    
    		if !v.Ready || v.OpusSend == nil {
    			fmt.Println("Ain't ready")
    			return
    		}
    		
    		// time.Sleep(2000)
    		v.OpusSend <- buffer[:read]
    	}
    }
    
    func main() {
    	s, err := discordgo.New("Bot " + Token)
    	if err != nil {
    		fmt.Println("error creating Discord session:", err)
    		return
    	}
    	defer s.Close()
    
    	s.Identify.Intents = discordgo.MakeIntent(discordgo.IntentsGuildVoiceStates)
    
    	err = s.Open()
    	if err != nil {
    		fmt.Println("error opening connection:", err)
    		return
    	}
    
    	v, err := s.ChannelVoiceJoin(GuildID, ChannelID, true, false)
    	if err != nil {
    		fmt.Println("failed to join voice channel:", err)
    		return
    	}
    
    	play(v)
    }
    

    So basically I have frameSize * 2 * 2, which is the amount of bytes I read from "Audiorezout - Anpiel.opus" and send to the Discord voice channel, without any time out because I'm not sure what it should be.

    It does send audio, but not pleasantly at all.

    I have attached the music I'm trying to use (from Free Music Archive) Audiorezout - Anpiel.zip

    ffmpeg -i "Audiorezout - Anpiel.mp3" "Audiorezout - Anpiel.wav"
    opusenc --raw-rate 48000 --raw-chan 2 --framesize 60 "Audiorezout - Anpiel.wav" "Audiorezout - Anpiel.opus"
    
Golang bindings for the Telegram Bot API

Golang bindings for the Telegram Bot API

Jan 2, 2023
(Golang) Go bindings for the Hugging Face Inference API

hfapigo (Golang) Go bindings for the Hugging Face Inference API. Directly call any model available in the Model Hub. An API key is required for author

Dec 18, 2022
Go bindings for libappindicator3 C library

go-appindicator Go bindings for libappindicator3 C library. Libappindicator is a library to allow applications to export a menu into the Unity Menu ba

Sep 26, 2022
🤖🚀📦 A Discord Bot for accessing the cdnjs platform
🤖🚀📦 A Discord Bot for accessing the cdnjs platform

A bridge between https://cdnjs.com/api and Discord Big shoutout to Br1ght0ne for helping me with writing helpers.go/SplitIn

Aug 17, 2022
🤖 Chegg answers requested and sent by the Discord BOT to the targeted user.
🤖 Chegg answers requested and sent by the Discord BOT to the targeted user.

"I believe that open-source resources are a must for everyone around. Especially in the field of education. As Chegg costs some money monthly, unfortunately, not all of us are capable of to charge ourselves that cost, which ends up blocking all those valuable resources to us. That is why, I have developed this bot, which unblurs the blurred question answers and sends them to you. I will develop it to a next level in the upcoming days, whereas, it will send the images/text, answers in short, directly through the Discord server you are in, or just DM/PM."

Aug 20, 2021
Abusing Discord for unlimited cloud storage

Discord Cloud Storage Abusing Discord's servers for unlimited cloud storage! So, what is this? Infamous 8MB limit for non-nitro users can get pretty a

Nov 26, 2022
DiscSpam is the best free and open source tool to spam/raid Discord servers.
DiscSpam is the best free and open source tool to spam/raid Discord servers.

DiscSpam Fast, Free, Easy to use Discord.com raid tool Report Bug , Request Feature About The Project There are a few Discord raid tools on GitHub, ho

Dec 27, 2022
Leave Discord servers using the folder names.

leavemealone ------------ Leave Discord servers using the folder names. Usage ----- 1. `export TOKEN="<token>"` 2. `go run . <folder_name>` 3. Chec

Feb 4, 2022
Go library for interacting with the Discord API (work-in-progress)

zombiezen Go Client for Discord zombiezen.com/go/discord is a WIP Go library for interacting with the Discord API. It differs from DiscordGo by provid

Nov 9, 2022
Easy creation of review tasks for the Jira with a Discord notifications.

easy-jira-task-review Easy creation of review tasks for the Jira with a Discord notifications. Any ideas and help are welcome Installation Install go

Dec 1, 2022
Desenvolvendo-Sistema-Planejamento-Financeiro-GoLang - Developing a Financial Planning System with Golang

dio-expert-session-finance Pré Desenvolvimento Vamos criar um projeto no Github

Jan 27, 2022
Client-server-golang-sqs - Client Server with SQS and golang

Client Server with SQS and golang Multi-threaded client-server demo with Go What

Feb 14, 2022
Golang-action - A template repository for writing custom GitHub Actions in Golang

Golang Action A template repository for writing custom GitHub Actions in Golang.

Feb 12, 2022
Simple golang airtable API wrapper

Golang Airtable API A simple #golang package to access the Airtable API. Table of contents Golang Airtable API Table of contents Installation Basic us

Jan 5, 2023
Golang client for ethereum json rpc api

Ethrpc Golang client for ethereum JSON RPC API. web3_clientVersion web3_sha3 net_version net_peerCount net_listening eth_protocolVersion eth_syncing e

Jan 7, 2023
A golang client for the Twitch v3 API - public APIs only (for now)

go-twitch Test CLIENT_ID="<my client ID>" go test -v -cover Usage Example File: package main import ( "log" "os" "github.com/knspriggs/go-twi

Sep 27, 2022
This is a Golang wrapper for working with TMDb API. It aims to support version 3.
This is a Golang wrapper for working with TMDb API. It aims to support version 3.

This is a Golang wrapper for working with TMDb API. It aims to support version 3. An API Key is required. To register for one, head over to themoviedb

Dec 27, 2022
a Go (Golang) MusicBrainz WS2 client library - work in progress
a Go (Golang) MusicBrainz WS2 client library - work in progress

gomusicbrainz a Go (Golang) MusicBrainz WS2 client library - a work in progress. Current state Currently GoMusicBrainz provides methods to perform sea

Sep 28, 2022
⚡️ SharePoint authentication, HTTP client & fluent API wrapper for Go (Golang)
⚡️ SharePoint authentication, HTTP client & fluent API wrapper for Go (Golang)

Gosip - SharePoint authentication, HTTP client & fluent API wrapper for Go (Golang) Main features Unattended authentication using different strategies

Jan 2, 2023