瀏覽代碼

Add ping pong example for direct messages (#882)

This commit adds an example on sending direct messages as it's a
frequently asked question.
The example sends a "Pong" response through DM when a user sends "ping"
in any channel the bot has the permission to see.

The example is simply adopted from the ping pong example.
chanbakjsd 3 年之前
父節點
當前提交
8dc42757be
共有 2 個文件被更改,包括 146 次插入0 次删除
  1. 43 0
      examples/dm_pingpong/README.md
  2. 103 0
      examples/dm_pingpong/main.go

+ 43 - 0
examples/dm_pingpong/README.md

@@ -0,0 +1,43 @@
+<img align="right" src="http://bwmarrin.github.io/discordgo/img/discordgo.png">
+
+## DiscordGo Direct Message Ping Pong Example
+
+This example demonstrates how to utilize DiscordGo to create a Ping Pong Bot
+that sends the response through Direct Message.
+
+This Bot will respond to "ping" in any server it's in with "Pong!" in the
+sender's DM.
+
+**Join [Discord Gophers](https://discord.gg/0f1SbxBZjYoCtNPP)
+Discord chat channel for support.**
+
+### Build
+
+This assumes you already have a working Go environment setup and that
+DiscordGo is correctly installed on your system.
+
+From within the dm_pingpong example folder, run the below command to compile the
+example.
+
+```sh
+go build
+```
+
+### Usage
+
+This example uses bot tokens for authentication only. While user/password is
+supported by DiscordGo, it is not recommended for bots.
+
+```
+./dm_pingpong --help
+Usage of ./dm_pingpong:
+  -t string
+        Bot Token
+```
+
+The below example shows how to start the bot
+
+```sh
+./dm_pingpong -t YOUR_BOT_TOKEN
+Bot is now running.  Press CTRL-C to exit.
+```

+ 103 - 0
examples/dm_pingpong/main.go

@@ -0,0 +1,103 @@
+package main
+
+import (
+	"flag"
+	"fmt"
+	"os"
+	"os/signal"
+	"syscall"
+
+	"github.com/bwmarrin/discordgo"
+)
+
+// Variables used for command line parameters
+var (
+	Token string
+)
+
+func init() {
+	flag.StringVar(&Token, "t", "", "Bot Token")
+	flag.Parse()
+}
+
+func main() {
+	// 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 messageCreate func as a callback for MessageCreate events.
+	dg.AddHandler(messageCreate)
+
+	// Just like the ping pong example, we only care about receiving message
+	// events in this example.
+	dg.Identify.Intents = discordgo.IntentsGuildMessages
+
+	// Open a websocket connection to Discord and begin listening.
+	err = dg.Open()
+	if err != nil {
+		fmt.Println("error opening connection,", err)
+		return
+	}
+
+	// Wait here until CTRL-C or other term signal is received.
+	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, os.Kill)
+	<-sc
+
+	// Cleanly close down the Discord session.
+	dg.Close()
+}
+
+// This function will be called (due to AddHandler above) every time a new
+// message is created on any channel that the authenticated bot has access to.
+//
+// It is called whenever a message is created but only when it's sent through a
+// server as we did not request IntentsDirectMessages.
+func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
+	// Ignore all messages created by the bot itself
+	// This isn't required in this specific example but it's a good practice.
+	if m.Author.ID == s.State.User.ID {
+		return
+	}
+	// In this example, we only care about messages that are "ping".
+	if m.Content != "ping" {
+		return
+	}
+
+	// We create the private channel with the user who sent the message.
+	channel, err := s.UserChannelCreate(m.Author.ID)
+	if err != nil {
+		// If an error occurred, we failed to create the channel.
+		//
+		// Some common causes are:
+		// 1. We don't share a server with the user (not possible here).
+		// 2. We opened enough DM channels quickly enough for Discord to
+		//    label us as abusing the endpoint, blocking us from opening
+		//    new ones.
+		fmt.Println("error creating channel:", err)
+		s.ChannelMessageSend(
+			m.ChannelID,
+			"Something went wrong while sending the DM!",
+		)
+		return
+	}
+	// Then we send the message through the channel we created.
+	_, err = s.ChannelMessageSend(channel.ID, "Pong!")
+	if err != nil {
+		// If an error occurred, we failed to send the message.
+		//
+		// It may occur either when we do not share a server with the
+		// user (highly unlikely as we just received a message) or
+		// the user disabled DM in their settings (more likely).
+		fmt.Println("error sending DM message:", err)
+		s.ChannelMessageSend(
+			m.ChannelID,
+			"Failed to send you a DM. "+
+				"Did you disable DM in your privacy settings?",
+		)
+	}
+}