github.com/meowstercatel/discordgo@v0.0.0-20250615204139-29b43d676735/examples/airhorn/main.go (about)

     1  package main
     2  
     3  import (
     4  	"encoding/binary"
     5  	"flag"
     6  	"fmt"
     7  	"io"
     8  	"os"
     9  	"os/signal"
    10  	"strings"
    11  	"syscall"
    12  	"time"
    13  
    14  	"github.com/bwmarrin/discordgo"
    15  )
    16  
    17  func init() {
    18  	flag.StringVar(&token, "t", "", "Bot Token")
    19  	flag.Parse()
    20  }
    21  
    22  var token string
    23  var buffer = make([][]byte, 0)
    24  
    25  func main() {
    26  
    27  	if token == "" {
    28  		fmt.Println("No token provided. Please run: airhorn -t <bot token>")
    29  		return
    30  	}
    31  
    32  	// Load the sound file.
    33  	err := loadSound()
    34  	if err != nil {
    35  		fmt.Println("Error loading sound: ", err)
    36  		fmt.Println("Please copy $GOPATH/src/github.com/bwmarrin/examples/airhorn/airhorn.dca to this directory.")
    37  		return
    38  	}
    39  
    40  	// Create a new Discord session using the provided bot token.
    41  	dg, err := discordgo.New("Bot " + token)
    42  	if err != nil {
    43  		fmt.Println("Error creating Discord session: ", err)
    44  		return
    45  	}
    46  
    47  	// Register ready as a callback for the ready events.
    48  	dg.AddHandler(ready)
    49  
    50  	// Register messageCreate as a callback for the messageCreate events.
    51  	dg.AddHandler(messageCreate)
    52  
    53  	// Register guildCreate as a callback for the guildCreate events.
    54  	dg.AddHandler(guildCreate)
    55  
    56  	// We need information about guilds (which includes their channels),
    57  	// messages and voice states.
    58  	dg.Identify.Intents = discordgo.IntentsGuilds | discordgo.IntentsGuildMessages | discordgo.IntentsGuildVoiceStates
    59  
    60  	// Open the websocket and begin listening.
    61  	err = dg.Open()
    62  	if err != nil {
    63  		fmt.Println("Error opening Discord session: ", err)
    64  	}
    65  
    66  	// Wait here until CTRL-C or other term signal is received.
    67  	fmt.Println("Airhorn is now running.  Press CTRL-C to exit.")
    68  	sc := make(chan os.Signal, 1)
    69  	signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
    70  	<-sc
    71  
    72  	// Cleanly close down the Discord session.
    73  	dg.Close()
    74  }
    75  
    76  // This function will be called (due to AddHandler above) when the bot receives
    77  // the "ready" event from Discord.
    78  func ready(s *discordgo.Session, event *discordgo.Ready) {
    79  
    80  	// Set the playing status.
    81  	s.UpdateGameStatus(0, "!airhorn")
    82  }
    83  
    84  // This function will be called (due to AddHandler above) every time a new
    85  // message is created on any channel that the autenticated bot has access to.
    86  func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
    87  
    88  	// Ignore all messages created by the bot itself
    89  	// This isn't required in this specific example but it's a good practice.
    90  	if m.Author.ID == s.State.User.ID {
    91  		return
    92  	}
    93  
    94  	// check if the message is "!airhorn"
    95  	if strings.HasPrefix(m.Content, "!airhorn") {
    96  
    97  		// Find the channel that the message came from.
    98  		c, err := s.State.Channel(m.ChannelID)
    99  		if err != nil {
   100  			// Could not find channel.
   101  			return
   102  		}
   103  
   104  		// Find the guild for that channel.
   105  		g, err := s.State.Guild(c.GuildID)
   106  		if err != nil {
   107  			// Could not find guild.
   108  			return
   109  		}
   110  
   111  		// Look for the message sender in that guild's current voice states.
   112  		for _, vs := range g.VoiceStates {
   113  			if vs.UserID == m.Author.ID {
   114  				err = playSound(s, g.ID, vs.ChannelID)
   115  				if err != nil {
   116  					fmt.Println("Error playing sound:", err)
   117  				}
   118  
   119  				return
   120  			}
   121  		}
   122  	}
   123  }
   124  
   125  // This function will be called (due to AddHandler above) every time a new
   126  // guild is joined.
   127  func guildCreate(s *discordgo.Session, event *discordgo.GuildCreate) {
   128  
   129  	if event.Guild.Unavailable {
   130  		return
   131  	}
   132  
   133  	for _, channel := range event.Guild.Channels {
   134  		if channel.ID == event.Guild.ID {
   135  			_, _ = s.ChannelMessageSend(channel.ID, "Airhorn is ready! Type !airhorn while in a voice channel to play a sound.")
   136  			return
   137  		}
   138  	}
   139  }
   140  
   141  // loadSound attempts to load an encoded sound file from disk.
   142  func loadSound() error {
   143  
   144  	file, err := os.Open("airhorn.dca")
   145  	if err != nil {
   146  		fmt.Println("Error opening dca file :", err)
   147  		return err
   148  	}
   149  
   150  	var opuslen int16
   151  
   152  	for {
   153  		// Read opus frame length from dca file.
   154  		err = binary.Read(file, binary.LittleEndian, &opuslen)
   155  
   156  		// If this is the end of the file, just return.
   157  		if err == io.EOF || err == io.ErrUnexpectedEOF {
   158  			err := file.Close()
   159  			if err != nil {
   160  				return err
   161  			}
   162  			return nil
   163  		}
   164  
   165  		if err != nil {
   166  			fmt.Println("Error reading from dca file :", err)
   167  			return err
   168  		}
   169  
   170  		// Read encoded pcm from dca file.
   171  		InBuf := make([]byte, opuslen)
   172  		err = binary.Read(file, binary.LittleEndian, &InBuf)
   173  
   174  		// Should not be any end of file errors
   175  		if err != nil {
   176  			fmt.Println("Error reading from dca file :", err)
   177  			return err
   178  		}
   179  
   180  		// Append encoded pcm data to the buffer.
   181  		buffer = append(buffer, InBuf)
   182  	}
   183  }
   184  
   185  // playSound plays the current buffer to the provided channel.
   186  func playSound(s *discordgo.Session, guildID, channelID string) (err error) {
   187  
   188  	// Join the provided voice channel.
   189  	vc, err := s.ChannelVoiceJoin(guildID, channelID, false, true)
   190  	if err != nil {
   191  		return err
   192  	}
   193  
   194  	// Sleep for a specified amount of time before playing the sound
   195  	time.Sleep(250 * time.Millisecond)
   196  
   197  	// Start speaking.
   198  	vc.Speaking(true)
   199  
   200  	// Send the buffer data.
   201  	for _, buff := range buffer {
   202  		vc.OpusSend <- buff
   203  	}
   204  
   205  	// Stop speaking
   206  	vc.Speaking(false)
   207  
   208  	// Sleep for a specificed amount of time before ending.
   209  	time.Sleep(250 * time.Millisecond)
   210  
   211  	// Disconnect from the provided voice channel.
   212  	vc.Disconnect()
   213  
   214  	return nil
   215  }