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

     1  package main
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  	"os"
     7  	"os/signal"
     8  	"syscall"
     9  
    10  	"github.com/bwmarrin/discordgo"
    11  )
    12  
    13  // Variables used for command line parameters
    14  var (
    15  	Token string
    16  )
    17  
    18  func init() {
    19  
    20  	flag.StringVar(&Token, "t", "", "Bot Token")
    21  	flag.Parse()
    22  }
    23  
    24  func main() {
    25  
    26  	// Create a new Discord session using the provided bot token.
    27  	dg, err := discordgo.New("Bot " + Token)
    28  	if err != nil {
    29  		fmt.Println("error creating Discord session,", err)
    30  		return
    31  	}
    32  
    33  	// Register the messageCreate func as a callback for MessageCreate events.
    34  	dg.AddHandler(messageCreate)
    35  
    36  	// In this example, we only care about receiving message events.
    37  	dg.Identify.Intents = discordgo.IntentsGuildMessages
    38  
    39  	// Open a websocket connection to Discord and begin listening.
    40  	err = dg.Open()
    41  	if err != nil {
    42  		fmt.Println("error opening connection,", err)
    43  		return
    44  	}
    45  
    46  	// Wait here until CTRL-C or other term signal is received.
    47  	fmt.Println("Bot is now running.  Press CTRL-C to exit.")
    48  	sc := make(chan os.Signal, 1)
    49  	signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
    50  	<-sc
    51  
    52  	// Cleanly close down the Discord session.
    53  	dg.Close()
    54  }
    55  
    56  // This function will be called (due to AddHandler above) every time a new
    57  // message is created on any channel that the authenticated bot has access to.
    58  func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
    59  
    60  	// Ignore all messages created by the bot itself
    61  	// This isn't required in this specific example but it's a good practice.
    62  	if m.Author.ID == s.State.User.ID {
    63  		return
    64  	}
    65  	// If the message is "ping" reply with "Pong!"
    66  	if m.Content == "ping" {
    67  		s.ChannelMessageSend(m.ChannelID, "Pong!")
    68  	}
    69  
    70  	// If the message is "pong" reply with "Ping!"
    71  	if m.Content == "pong" {
    72  		s.ChannelMessageSend(m.ChannelID, "Ping!")
    73  	}
    74  }