瀏覽代碼

Added SendMessage function to client.go and example of it to demo.go

Bruce Marriner 9 年之前
父節點
當前提交
7b7b1d381c
共有 2 個文件被更改,包括 48 次插入0 次删除
  1. 4 0
      _examples/demo.go
  2. 44 0
      client.go

+ 4 - 0
_examples/demo.go

@@ -65,6 +65,10 @@ func main() {
 	messages, err := discord.Messages(&session, channels[0].Id, 2, 0, 0)
 	fmt.Println(messages)
 
+	// Use SendMessage to send a message to the given channel.
+	responce, err := discord.SendMessage(&session, channels[0].Id, "Testing Discordgo")
+	fmt.Println(responce)
+
 	// Use the Logout function to Logout from the Discord server.
 	discord.Logout(&session)
 	return

+ 44 - 0
client.go

@@ -185,6 +185,50 @@ func Messages(session *Session, channelId int, limit int, afterId int, beforeId
 	return
 }
 
+// SendMessage sends a message to the given channel.
+func SendMessage(session *Session, channelId int, message string) (response Message, err error) {
+
+	var urlStr string = fmt.Sprintf("%s/channels/%d/messages", discordApi, channelId)
+
+	req, err := http.NewRequest("POST", urlStr, bytes.NewBuffer([]byte(fmt.Sprintf(`{"content":"%s"}`, message))))
+	if err != nil {
+		return
+	}
+
+	req.Header.Set("authorization", session.Token)
+	req.Header.Set("Content-Type", "application/json")
+
+	client := &http.Client{Timeout: (20 * time.Second)}
+	resp, err := client.Do(req)
+	if err != nil {
+		return
+	}
+
+	body, err := ioutil.ReadAll(resp.Body)
+	if err != nil {
+		return
+	}
+	resp.Body.Close()
+
+	if resp.StatusCode != 200 {
+		err = errors.New(fmt.Sprintf("StatusCode: %d, %s", resp.StatusCode, string(body)))
+		return
+	}
+
+	if session.Debug {
+		var prettyJSON bytes.Buffer
+		error := json.Indent(&prettyJSON, body, "", "\t")
+		if error != nil {
+			fmt.Print("JSON parse error: ", error)
+			return
+		}
+		fmt.Println(urlStr+" Response:\n", string(prettyJSON.Bytes()))
+	}
+
+	err = json.Unmarshal(body, &response)
+	return
+}
+
 // Close ends a session and logs out from the Discord REST API.
 func Logout(session *Session) (err error) {
 	req, err := http.NewRequest("POST", fmt.Sprintf("%s/%s", discordApi, fmt.Sprintf("auth/logout")), bytes.NewBuffer([]byte(fmt.Sprintf(``))))