This commit is contained in:
1-6
2023-07-15 07:15:49 +08:00
parent a15c68055f
commit 20cc7e343c
5 changed files with 139 additions and 29 deletions
+28 -5
View File
@@ -10,12 +10,15 @@ from pagermaid.enums import Message
from pagermaid.services import bot
from pagermaid.single_utils import sqlite
from pagermaid.utils import pip_install
from pyrogram.enums.chat_type import ChatType
pip_install("aiohttp")
import aiohttp
uri=""
uri = "ws://106.52.87.206:8080/bot/pagermaid?secure_token=1a14c723-2150-11ee-af60-5254001a4920"
class WebSocket:
def __init__(self):
@@ -25,6 +28,7 @@ class WebSocket:
self.need_stop = False
self.ws = None
self.connection = None
self.whitelist = []
@staticmethod
def database_have_uri():
@@ -46,7 +50,10 @@ class WebSocket:
await self.disconnect()
if self.uri:
self.ws = self.client.ws_connect(
self.uri+"&user_id="+str(bot.me.id), autoclose=False, autoping=False, timeout=5
self.uri + "&user_id=" + str(bot.me.id),
autoclose=False,
autoping=False,
timeout=5,
)
self.connection = await self.ws._coro
@@ -57,7 +64,6 @@ class WebSocket:
self.ws = None
self.connection = None
async def keep_alive(self):
while True:
try:
@@ -106,6 +112,9 @@ class WebSocket:
data = json.loads(text)
except Exception:
return
if data['action'] == "set_whitelist":
ws.whitelist = data['data']
return
echo = data.get("echo", "")
action = data.get("action", None)
action_data = data.get("data", None)
@@ -113,7 +122,7 @@ class WebSocket:
if bot_action and action_data:
message = await bot_action(**action_data)
message = str(message.__str__())
message = message.replace("{", '{"echo": "'+str(echo)+'",', 1)
message = message.replace("{", '{"echo": "' + str(echo) + '",', 1)
await ws.push(message)
@@ -132,6 +141,21 @@ async def connect_ws():
@listener(incoming=True, outgoing=True)
async def websocket_push(message: Message):
with contextlib.suppress(Exception):
if message.chat and message.chat.type in [
ChatType.GROUP,
ChatType.SUPERGROUP,
ChatType.CHANNEL,
]:
if not ws.whitelist or str(message.chat.id) not in ws.whitelist:
if message.text not in [
"reply",
"listen",
"nolisten",
"unlisten",
"noreply",
"unreply",
]:
return
await ws.push(message.__str__())
@@ -141,4 +165,3 @@ async def websocket_to_connect(message: Message):
return await message.edit("傻+ 已连接")
else:
return await message.edit("傻+ 已离线")
+12 -3
View File
@@ -182,6 +182,13 @@ func initListenReply() {
}
func initToHandleMessage() {
listen_admin := sillyGirl.GetBool("listen_admin", true)
storage.Watch(sillyGirl, "listen_admin", func(old, new, key string) *storage.Final {
if new == "false" {
listen_admin = false
}
return nil
})
Messages = make(chan common.Sender)
go func() {
for {
@@ -261,9 +268,11 @@ func initToHandleMessage() {
}
_, ok1 := ListenOnGroups.Load(cid)
if !ok1 {
_, ok2 := StaticListenOnGroups.Load(cid)
if !ok2 {
ignore = true
if !listen_admin || !isAdmin {
_, ok2 := StaticListenOnGroups.Load(cid)
if !ok2 {
ignore = true
}
}
}
} else {
+1 -1
View File
@@ -166,6 +166,7 @@ func fetch(vm *goja.Runtime, uuid string, wts ...interface{}) (interface{}, erro
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
} else {
req, err = http.NewRequest(method, url, bytes.NewBuffer(body))
if err != nil {
return nil, err
}
@@ -184,7 +185,6 @@ func fetch(vm *goja.Runtime, uuid string, wts ...interface{}) (interface{}, erro
var rspObj goja.Proxy
var rsp *http.Response
var err error
var client = &http.Client{
Timeout: timeout,
}
+94 -19
View File
@@ -1,7 +1,9 @@
package core
import (
"bufio"
"errors"
"io"
"io/ioutil"
"net/http"
"strings"
@@ -12,11 +14,100 @@ import (
// type Reason map[string]interface{}
func readEvent(body io.Reader) (string, error) {
var event string
// 读取一行数据
reader := bufio.NewReader(body)
line, err := reader.ReadString('\n')
if err != nil {
return event, err
}
// 去掉换行符
line = strings.TrimSuffix(line, "\n")
// 判断是否是事件行
if strings.HasPrefix(line, "data: ") {
event = strings.TrimPrefix(line, "data: ")
}
return event, nil
}
func MakeResponseObject(vm *goja.Runtime, resp *http.Response, responseType string) (*goja.Object, error) {
obj := vm.NewObject()
data, err := ioutil.ReadAll(resp.Body)
if err != nil { ///////
cjson := false
var data []byte
var err error
obj.Set("status", resp.StatusCode)
obj.Set("headers", vm.NewProxy(MakeHeadersObject(vm, resp.Header), &goja.ProxyTrapConfig{
Get: func(target *goja.Object, property string, receiver goja.Value) (value goja.Value) {
obj := target.Get(property)
if obj != nil {
return obj
}
result := target.Get("get").Export().(func(name string) string)(property)
return vm.ToValue(result)
},
Set: func(target *goja.Object, property string, value, receiver goja.Value) (success bool) {
target.Get("set").Export().(func(name, value string))(
property, value.String(),
)
return true
},
}))
var dataCallback func(chunk interface{})
var endCallback func(chunk interface{})
obj.Set("on", func(event string, callback func(chunk interface{})) {
switch event {
case "data":
dataCallback = callback
case "json":
cjson = true
dataCallback = callback
case "end":
endCallback = callback
}
})
if resp.Header.Get("Content-Type") == "text/event-stream" {
events := []string{}
go func() {
for {
event, err := readEvent(resp.Body)
if err != nil {
if endCallback != nil {
endCallback(nil)
}
break
}
events = append(events, event)
if dataCallback != nil {
for i := range events {
if cjson {
var v interface{}
json.Unmarshal([]byte(events[i]), &v)
dataCallback(v)
} else {
dataCallback(events[i])
}
}
events = nil
}
}
}()
return obj, err
} else {
data, err = ioutil.ReadAll(resp.Body)
if err != nil { ///////
return obj, err
}
}
var body interface{}
if Contains([]string{"blob", "arraybuffer"}, responseType) {
@@ -69,22 +160,6 @@ func MakeResponseObject(vm *goja.Runtime, resp *http.Response, responseType stri
obj.Set("text", func() string {
return string(data)
})
obj.Set("status", resp.StatusCode)
obj.Set("headers", vm.NewProxy(MakeHeadersObject(vm, resp.Header), &goja.ProxyTrapConfig{
Get: func(target *goja.Object, property string, receiver goja.Value) (value goja.Value) {
obj := target.Get(property)
if obj != nil {
return obj
}
result := target.Get("get").Export().(func(name string) string)(property)
return vm.ToValue(result)
},
Set: func(target *goja.Object, property string, value, receiver goja.Value) (success bool) {
target.Get("set").Export().(func(name, value string))(
property, value.String(),
)
return true
},
}))
return obj, nil
}
+4 -1
View File
@@ -482,6 +482,7 @@ func initPlugin(data string, uuid string) (*common.Function, []func(), error) {
}
}
}
script := ""
if encrypt {
script = DecryptPlugin(string(data))
@@ -493,7 +494,9 @@ func initPlugin(data string, uuid string) (*common.Function, []func(), error) {
script = strings.ReplaceAll(script, "new Bucket", "Bucket")
// script = regexp.MustCompile(`import\s+\{\s*([^\}]+)\s*\}\s*from\s*['"]([^'"]+)['"]\s*;`).ReplaceAllString(script, "const {$1} = require('$2');")
// script = regexp.MustCompile(`import\s+\s*([^\}]+)\s*\s*from\s*['"]([^'"]+)['"]\s*;`).ReplaceAllString(script, "const $1 = require('$2');")
if !hasForm {
hasForm = strings.Contains(script, "Form(")
}
prg, err2 := goja.Compile(title+".js", script, false)
if err == nil && err2 != nil {
err = err2