能否使用go-cqhttp框架写入群欢迎
时间: 2023-12-30 09:03:11 浏览: 35
当然可以,使用Go-CQHTTP框架编写QQ机器人的入群欢迎功能也是非常方便的。您只需要在配置文件中加入相应的插件配置,然后在插件代码中编写处理逻辑即可。
以下是一个简单的入群欢迎插件示例:
1. 在Go-CQHTTP配置文件中加入插件配置
在Go-CQHTTP的配置文件中加入以下插件配置:
```yaml
enable: true
post-message-format: string
use-http: true
post-url: http://127.0.0.1:8000/
```
其中,`post-url`指定了插件处理的HTTP请求地址,`post-message-format`指定了插件处理的消息格式,这里我们使用了`string`格式。
2. 编写插件代码
使用Go语言编写一个简单的插件,代码如下:
```go
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
)
type Message struct {
PostType string `json:"post_type"`
Message string `json:"message"`
Sender Sender `json:"sender"`
GroupID int64 `json:"group_id"`
MessageID int64 `json:"message_id"`
}
type Sender struct {
UserID int64 `json:"user_id"`
NickName string `json:"nickname"`
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
bodyBytes, _ := ioutil.ReadAll(r.Body)
defer r.Body.Close()
var message Message
err := json.Unmarshal(bodyBytes, &message)
if err == nil && message.PostType == "message" && message.GroupID > 0 && strings.Contains(message.Message, "加入了群聊") {
welcomeMsg := fmt.Sprintf("欢迎新朋友 @%s 加入群聊!", message.Sender.NickName)
resp, err := http.Post(fmt.Sprintf("http://127.0.0.1:5700/send_group_msg?group_id=%d&message=%s", message.GroupID, welcomeMsg), "", nil)
if err == nil {
defer resp.Body.Close()
}
}
}
})
http.ListenAndServe(":8000", nil)
}
```
在以上代码中,我们使用了Go标准库的`http`包,监听了一个HTTP请求地址,当接收到POST请求时,解析请求体中的JSON数据,并且判断是否为群聊消息,并且判断是否为新用户加入群聊,如果是,则发送欢迎消息。
欢迎消息的发送使用了Go标准库的`http.Post()`方法,向Go-CQHTTP的API接口发送消息。
希望这个代码可以帮到您。如果还有其他问题,请随时与我联系。