mirror of
https://github.com/FloatTech/ZeroBot-Plugin.git
synced 2025-12-20 06:20:08 +08:00
✏️ Diana 插件实装教你一篇小作文
This commit is contained in:
parent
4bce4b2dd1
commit
0bffc38be4
@ -2,10 +2,13 @@
|
||||
package data
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
@ -20,6 +23,10 @@ var (
|
||||
compo Composition
|
||||
// Array 小作文数组指针
|
||||
Array = &compo.Array
|
||||
// m 小作文保存锁
|
||||
m sync.Mutex
|
||||
// md5s 验证重复
|
||||
md5s [][16]byte
|
||||
)
|
||||
|
||||
func init() {
|
||||
@ -31,7 +38,12 @@ func init() {
|
||||
}
|
||||
err1 := LoadText()
|
||||
if err1 == nil {
|
||||
log.Printf("[Diana]读取%d条小作文", len(*Array))
|
||||
arrl := len(*Array)
|
||||
log.Printf("[Diana]读取%d条小作文", arrl)
|
||||
md5s = make([][16]byte, arrl)
|
||||
for i, t := range *Array {
|
||||
md5s[i] = md5.Sum(str2bytes(t))
|
||||
}
|
||||
} else {
|
||||
log.Printf("[Diana]读取小作文错误:%v", err1)
|
||||
}
|
||||
@ -79,15 +91,36 @@ func LoadText() error {
|
||||
|
||||
// AddText 添加小作文
|
||||
func AddText(txt string) error {
|
||||
if txt != "" {
|
||||
sum := md5.Sum(str2bytes(txt))
|
||||
if txt != "" && !isin(sum) {
|
||||
compo.Array = append(compo.Array, txt)
|
||||
md5s = append(md5s, sum)
|
||||
savecompo()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isin(sum [16]byte) bool {
|
||||
for _, t := range md5s {
|
||||
if t == sum {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// savecompo 同步保存作文
|
||||
func savecompo() error {
|
||||
data, err := compo.Marshal()
|
||||
if err == nil {
|
||||
if _, err := os.Stat(datapath); err == nil || os.IsExist(err) {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
f, err1 := os.OpenFile(pbfile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
|
||||
if err1 == nil {
|
||||
defer f.Close()
|
||||
_, err2 := f.Write(data)
|
||||
f.Close()
|
||||
|
||||
return err2
|
||||
}
|
||||
return err1
|
||||
@ -95,5 +128,10 @@ func AddText(txt string) error {
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
|
||||
// str2bytes Fast convert
|
||||
func str2bytes(s string) []byte {
|
||||
x := (*[2]uintptr)(unsafe.Pointer(&s))
|
||||
h := [3]uintptr{x[0], x[1], x[1]}
|
||||
return *(*[]byte)(unsafe.Pointer(&h))
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user