Refactoring
This commit is contained in:
1 parent
121de88a57
commit
736f6830b9
137 files changed
+2478
-2549
No files matched your search
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 Changhua
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,22 @@
|
||||
# WeChatFerry-go
|
||||
|
||||
[WeChatFerry](https://github.com/lich0821/WeChatFerry) golang client
|
||||
|
||||
## Usage
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/danbai225/WeChatFerry-go/wcf"
|
||||
)
|
||||
|
||||
func main() {
|
||||
c, err := wcf.NewWCF("")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
println(c.IsLogin())
|
||||
}
|
||||
|
||||
```
|
||||
@@ -0,0 +1,18 @@
|
||||
module github.com/danbai225/WeChatFerry-go
|
||||
|
||||
go 1.20
|
||||
|
||||
require (
|
||||
github.com/danbai225/go-logs v0.1.9
|
||||
go.nanomsg.org/mangos/v3 v3.4.2
|
||||
google.golang.org/protobuf v1.30.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/Microsoft/go-winio v0.5.2 // indirect
|
||||
github.com/goccy/go-json v0.9.11 // indirect
|
||||
github.com/gorilla/websocket v1.5.0 // indirect
|
||||
github.com/kpango/fastime v1.1.4 // indirect
|
||||
github.com/kpango/glg v1.6.13 // indirect
|
||||
golang.org/x/sys v0.7.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,83 @@
|
||||
github.com/Microsoft/go-winio v0.5.2 h1:a9IhgEQBCUEk6QCdml9CiJGhAws+YwffDHEMp1VMrpA=
|
||||
github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY=
|
||||
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
|
||||
github.com/danbai225/go-logs v0.1.9 h1:Q/CbLM2YXFCSSfS2TFJ+OoZGVakTuZNUQ8uBIrVWvng=
|
||||
github.com/danbai225/go-logs v0.1.9/go.mod h1:giaa3Y1vBw9zODSzI+ad3NVhXAmU77cewMuBwgB0D7A=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/gdamore/optopia v0.2.0/go.mod h1:YKYEwo5C1Pa617H7NlPcmQXl+vG6YnSSNB44n8dNL0Q=
|
||||
github.com/goccy/go-json v0.9.11 h1:/pAaQDLHEoCq/5FFmSKBswWmK6H0e8g4159Kc/X/nqk=
|
||||
github.com/goccy/go-json v0.9.11/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
|
||||
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/kpango/fastime v1.1.4 h1:pus9JgJBg/8Jie3ozayA4yNIV67BUPhbq0wMZY3CtYo=
|
||||
github.com/kpango/fastime v1.1.4/go.mod h1:tTNDbIo5qL6D7g5vh2YbkyUbOVP2kD/we3rSjN22PMY=
|
||||
github.com/kpango/glg v1.6.13 h1:QMhxOm/Oo1k8qraMtH4SQOYIgB/SI2RW2Hvrn1kgAZw=
|
||||
github.com/kpango/glg v1.6.13/go.mod h1:fwP/c6NJTXe0vd9L3He6myDnO33lFVfgQGtGmlMnyws=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
||||
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
|
||||
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
||||
go.nanomsg.org/mangos/v3 v3.4.2 h1:gHlopxjWvJcVCcUilQIsRQk9jdj6/HB7wrTiUN8Ki7Q=
|
||||
go.nanomsg.org/mangos/v3 v3.4.2/go.mod h1:8+hjBMQub6HvXmuGvIq6hf19uxGQIjCofmc62lbedLA=
|
||||
go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
|
||||
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
||||
go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ=
|
||||
go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4=
|
||||
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
|
||||
go.uber.org/zap v1.23.0 h1:OjGQ5KQDEUawVHxNwQgPpiypGHOxo2mNZsOqTak4fFY=
|
||||
go.uber.org/zap v1.23.0/go.mod h1:D+nX8jyLsMHMYrln8A0rJjFt/T/9/bGgIhAqxv5URuY=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=
|
||||
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng=
|
||||
google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,172 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package wcf;
|
||||
option go_package = "./wcf";
|
||||
option java_package = "com.iamteer";
|
||||
|
||||
enum Functions {
|
||||
FUNC_RESERVED = 0x00;
|
||||
FUNC_IS_LOGIN = 0x01;
|
||||
FUNC_GET_SELF_WXID = 0x10;
|
||||
FUNC_GET_MSG_TYPES = 0x11;
|
||||
FUNC_GET_CONTACTS = 0x12;
|
||||
FUNC_GET_DB_NAMES = 0x13;
|
||||
FUNC_GET_DB_TABLES = 0x14;
|
||||
FUNC_GET_USER_INFO = 0x15;
|
||||
FUNC_SEND_TXT = 0x20;
|
||||
FUNC_SEND_IMG = 0x21;
|
||||
FUNC_SEND_FILE = 0x22;
|
||||
FUNC_SEND_XML = 0x23;
|
||||
FUNC_SEND_EMOTION = 0x24;
|
||||
FUNC_ENABLE_RECV_TXT = 0x30;
|
||||
FUNC_DISABLE_RECV_TXT = 0x40;
|
||||
FUNC_EXEC_DB_QUERY = 0x50;
|
||||
FUNC_ACCEPT_FRIEND = 0x51;
|
||||
FUNC_ADD_ROOM_MEMBERS = 0x52;
|
||||
FUNC_RECV_TRANSFER = 0x53;
|
||||
FUNC_DECRYPT_IMAGE = 0x60;
|
||||
}
|
||||
|
||||
message Request
|
||||
{
|
||||
Functions func = 1;
|
||||
oneof msg
|
||||
{
|
||||
Empty empty = 2;
|
||||
string str = 3;
|
||||
TextMsg txt = 4;
|
||||
PathMsg file = 5;
|
||||
DbQuery query = 6;
|
||||
Verification v = 7;
|
||||
AddMembers m = 8;
|
||||
XmlMsg xml = 9;
|
||||
DecPath dec = 10;
|
||||
Transfer tf = 11;
|
||||
}
|
||||
}
|
||||
|
||||
message Response
|
||||
{
|
||||
Functions func = 1;
|
||||
oneof msg
|
||||
{
|
||||
int32 status = 2; // Int 状态,通用
|
||||
string str = 3; // 字符串
|
||||
WxMsg wxmsg = 4; // 微信消息
|
||||
MsgTypes types = 5; // 消息类型
|
||||
RpcContacts contacts = 6; // 联系人
|
||||
DbNames dbs = 7; // 数据库列表
|
||||
DbTables tables = 8; // 表列表
|
||||
DbRows rows = 9; // 行列表
|
||||
UserInfo ui = 10; // 个人信息
|
||||
};
|
||||
}
|
||||
|
||||
message Empty { }
|
||||
|
||||
message WxMsg
|
||||
{
|
||||
bool is_self = 1; // 是否自己发送的
|
||||
bool is_group = 2; // 是否群消息
|
||||
int32 type = 3; // 消息类型
|
||||
string id = 4; // 消息 id
|
||||
string xml = 5; // 消息 xml
|
||||
string sender = 6; // 消息发送者
|
||||
string roomid = 7; // 群 id(如果是群消息的话)
|
||||
string content = 8; // 消息内容
|
||||
string thumb = 9; // 缩略图
|
||||
string extra = 10; // 附加内容
|
||||
}
|
||||
|
||||
message TextMsg
|
||||
{
|
||||
string msg = 1; // 要发送的消息内容
|
||||
string receiver = 2; // 消息接收人,当为群时可@
|
||||
string aters = 3; // 要@的人列表,逗号分隔
|
||||
}
|
||||
|
||||
message PathMsg
|
||||
{
|
||||
string path = 1; // 要发送的图片的路径
|
||||
string receiver = 2; // 消息接收人
|
||||
}
|
||||
|
||||
message XmlMsg
|
||||
{
|
||||
string receiver = 1; // 消息接收人
|
||||
string content = 2; // xml 内容
|
||||
string path = 3; // 图片路径
|
||||
int32 type = 4; // 消息类型
|
||||
}
|
||||
|
||||
message MsgTypes { map<int32, string> types = 1; }
|
||||
|
||||
message RpcContact
|
||||
{
|
||||
string wxid = 1; // 微信 id
|
||||
string code = 2; // 微信号
|
||||
string remark = 3; // 备注
|
||||
string name = 4; // 微信昵称
|
||||
string country = 5; // 国家
|
||||
string province = 6; // 省/州
|
||||
string city = 7; // 城市
|
||||
int32 gender = 8; // 性别
|
||||
}
|
||||
message RpcContacts { repeated RpcContact contacts = 1; }
|
||||
|
||||
message DbNames { repeated string names = 1; }
|
||||
|
||||
message DbTable
|
||||
{
|
||||
string name = 1; // 表名
|
||||
string sql = 2; // 建表 SQL
|
||||
}
|
||||
message DbTables { repeated DbTable tables = 1; }
|
||||
|
||||
message DbQuery
|
||||
{
|
||||
string db = 1; // 目标数据库
|
||||
string sql = 2; // 查询 SQL
|
||||
}
|
||||
|
||||
message DbField
|
||||
{
|
||||
int32 type = 1; // 字段类型
|
||||
string column = 2; // 字段名称
|
||||
bytes content = 3; // 字段内容
|
||||
}
|
||||
message DbRow { repeated DbField fields = 1; }
|
||||
message DbRows { repeated DbRow rows = 1; }
|
||||
|
||||
message Verification
|
||||
{
|
||||
string v3 = 1; // 加密的用户名
|
||||
string v4 = 2; // Ticket
|
||||
int32 scene = 3; // 添加方式:17 名片,30 扫码
|
||||
}
|
||||
|
||||
message AddMembers
|
||||
{
|
||||
string roomid = 1; // 要加的群ID
|
||||
string wxids = 2; // 要加群的人列表,逗号分隔
|
||||
}
|
||||
|
||||
message UserInfo
|
||||
{
|
||||
string wxid = 1; // 微信ID
|
||||
string name = 2; // 昵称
|
||||
string mobile = 3; // 手机号
|
||||
string home = 4; // 文件/图片等父路径
|
||||
}
|
||||
|
||||
message DecPath
|
||||
{
|
||||
string src = 1; // 源路径
|
||||
string dst = 2; // 目标路径
|
||||
}
|
||||
|
||||
message Transfer
|
||||
{
|
||||
string wxid = 1; // 转账人
|
||||
string tid = 2; // 转账id transferid
|
||||
}
|
||||
@@ -0,0 +1,411 @@
|
||||
package wcf
|
||||
|
||||
import (
|
||||
logs "github.com/danbai225/go-logs"
|
||||
"go.nanomsg.org/mangos/v3"
|
||||
"go.nanomsg.org/mangos/v3/protocol"
|
||||
"go.nanomsg.org/mangos/v3/protocol/pair1"
|
||||
_ "go.nanomsg.org/mangos/v3/transport/all"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
add string
|
||||
socket protocol.Socket
|
||||
RecvTxt bool
|
||||
}
|
||||
|
||||
func (c *Client) conn() error {
|
||||
socket, err := pair1.NewSocket()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = socket.Dial(c.add)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.socket = socket
|
||||
return err
|
||||
}
|
||||
func (c *Client) send(data []byte) error {
|
||||
return c.socket.Send(data)
|
||||
}
|
||||
func (c *Client) Recv() (*Response, error) {
|
||||
msg := &Response{}
|
||||
recv, err := c.socket.Recv()
|
||||
if err != nil {
|
||||
return msg, err
|
||||
}
|
||||
err = proto.Unmarshal(recv, msg)
|
||||
return msg, err
|
||||
}
|
||||
func (c *Client) IsLogin() bool {
|
||||
err := c.send(genFunReq(Functions_FUNC_IS_LOGIN).build())
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
recv, err := c.Recv()
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
if recv.GetStatus() == 1 {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (c *Client) GetSelfWXID() string {
|
||||
err := c.send(genFunReq(Functions_FUNC_GET_SELF_WXID).build())
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
recv, err := c.Recv()
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
return recv.GetStr()
|
||||
}
|
||||
func (c *Client) GetMsgTypes() map[int32]string {
|
||||
err := c.send(genFunReq(Functions_FUNC_GET_MSG_TYPES).build())
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
recv, err := c.Recv()
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
return recv.GetTypes().GetTypes()
|
||||
}
|
||||
func (c *Client) GetContacts() []*RpcContact {
|
||||
err := c.send(genFunReq(Functions_FUNC_GET_CONTACTS).build())
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
recv, err := c.Recv()
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
return recv.GetContacts().GetContacts()
|
||||
}
|
||||
func (c *Client) GetDBNames() []string {
|
||||
err := c.send(genFunReq(Functions_FUNC_GET_DB_NAMES).build())
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
recv, err := c.Recv()
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
return recv.GetDbs().Names
|
||||
}
|
||||
func (c *Client) GetDBTables(tab string) []*DbTable {
|
||||
req := genFunReq(Functions_FUNC_GET_DB_TABLES)
|
||||
str := &Request_Str{Str: tab}
|
||||
req.Msg = str
|
||||
err := c.send(req.build())
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
recv, err := c.Recv()
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
return recv.GetTables().GetTables()
|
||||
}
|
||||
func (c *Client) ExecDBQuery(db, sql string) []*DbRow {
|
||||
req := genFunReq(Functions_FUNC_EXEC_DB_QUERY)
|
||||
q := Request_Query{
|
||||
Query: &DbQuery{
|
||||
Db: db,
|
||||
Sql: sql,
|
||||
},
|
||||
}
|
||||
req.Msg = &q
|
||||
err := c.send(req.build())
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
recv, err := c.Recv()
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
return recv.GetRows().GetRows()
|
||||
}
|
||||
|
||||
/*AcceptFriend 接收好友请求
|
||||
* 接收好友请求
|
||||
*
|
||||
* @param v3 xml.attrib["encryptusername"] // 加密的用户名
|
||||
* @param v4 xml.attrib["ticket"] // Ticket
|
||||
* @param scene 17 // 添加方式:17 名片,30 扫码
|
||||
*/
|
||||
func (c *Client) AcceptFriend(v3, v4 string, scene int32) int32 {
|
||||
req := genFunReq(Functions_FUNC_ACCEPT_FRIEND)
|
||||
q := Request_V{
|
||||
V: &Verification{
|
||||
V3: v3,
|
||||
V4: v4,
|
||||
Scene: scene,
|
||||
}}
|
||||
|
||||
req.Msg = &q
|
||||
err := c.send(req.build())
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
recv, err := c.Recv()
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
return recv.GetStatus()
|
||||
}
|
||||
func (c *Client) AddChatroomMembers(roomID, wxIDs string) int32 {
|
||||
req := genFunReq(Functions_FUNC_ADD_ROOM_MEMBERS)
|
||||
q := Request_M{
|
||||
M: &AddMembers{Roomid: roomID, Wxids: wxIDs},
|
||||
}
|
||||
req.Msg = &q
|
||||
err := c.send(req.build())
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
recv, err := c.Recv()
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
return recv.GetStatus()
|
||||
}
|
||||
|
||||
// ReceiveTransfer 接收转账
|
||||
func (c *Client) ReceiveTransfer(transferId, wxID string) int32 {
|
||||
req := genFunReq(Functions_FUNC_RECV_TRANSFER)
|
||||
q := Request_Tf{
|
||||
Tf: &Transfer{Tid: transferId, Wxid: wxID},
|
||||
}
|
||||
req.Msg = &q
|
||||
err := c.send(req.build())
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
recv, err := c.Recv()
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
return recv.GetStatus()
|
||||
}
|
||||
|
||||
// DecryptImage 解密图片 加密路径,解密路径
|
||||
func (c *Client) DecryptImage(src, dst string) int32 {
|
||||
req := genFunReq(Functions_FUNC_DECRYPT_IMAGE)
|
||||
q := Request_Dec{
|
||||
Dec: &DecPath{Src: src, Dst: dst},
|
||||
}
|
||||
req.Msg = &q
|
||||
err := c.send(req.build())
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
recv, err := c.Recv()
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
return recv.GetStatus()
|
||||
}
|
||||
|
||||
func (c *Client) AddChatRoomMembers(roomId string, wxIds []string) int32 {
|
||||
req := genFunReq(Functions_FUNC_ADD_ROOM_MEMBERS)
|
||||
q := Request_M{
|
||||
M: &AddMembers{Roomid: roomId,
|
||||
Wxids: strings.Join(wxIds, ",")},
|
||||
}
|
||||
req.Msg = &q
|
||||
err := c.send(req.build())
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
recv, err := c.Recv()
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
return recv.GetStatus()
|
||||
}
|
||||
func (c *Client) GetUserInfo() *UserInfo {
|
||||
err := c.send(genFunReq(Functions_FUNC_GET_USER_INFO).build())
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
recv, err := c.Recv()
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
return recv.GetUi()
|
||||
}
|
||||
|
||||
/*
|
||||
SendTxt
|
||||
@param msg: 消息内容(如果是 @ 消息则需要有跟 @ 的人数量相同的 @)
|
||||
@param receiver: 消息接收人,私聊为 wxid(wxid_xxxxxxxxxxxxxx),群聊为roomid(xxxxxxxxxx@chatroom)
|
||||
@param ates: 群聊时要 @ 的人(私聊时为空字符串),多个用逗号分隔。@所有人 用notify@all(必须是群主或者管理员才有权限)
|
||||
*/
|
||||
func (c *Client) SendTxt(msg string, receiver string, ates []string) int32 {
|
||||
req := genFunReq(Functions_FUNC_SEND_TXT)
|
||||
req.Msg = &Request_Txt{
|
||||
Txt: &TextMsg{
|
||||
Msg: msg,
|
||||
Receiver: receiver,
|
||||
Aters: strings.Join(ates, ","),
|
||||
},
|
||||
}
|
||||
err := c.send(req.build())
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
recv, err := c.Recv()
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
return recv.GetStatus()
|
||||
}
|
||||
|
||||
/*
|
||||
SendIMG
|
||||
path 绝对路径
|
||||
*/
|
||||
func (c *Client) SendIMG(path string, receiver string) int32 {
|
||||
req := genFunReq(Functions_FUNC_SEND_IMG)
|
||||
req.Msg = &Request_File{
|
||||
File: &PathMsg{
|
||||
Path: path,
|
||||
Receiver: receiver,
|
||||
},
|
||||
}
|
||||
err := c.send(req.build())
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
recv, err := c.Recv()
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
return recv.GetStatus()
|
||||
}
|
||||
|
||||
/*
|
||||
SendFile
|
||||
path 绝对路径
|
||||
*/
|
||||
func (c *Client) SendFile(path string, receiver string) int32 {
|
||||
req := genFunReq(Functions_FUNC_SEND_FILE)
|
||||
req.Msg = &Request_File{
|
||||
File: &PathMsg{
|
||||
Path: path,
|
||||
Receiver: receiver,
|
||||
},
|
||||
}
|
||||
err := c.send(req.build())
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
recv, err := c.Recv()
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
return recv.GetStatus()
|
||||
}
|
||||
func (c *Client) SendXml(path, content, receiver string, Type int32) int32 {
|
||||
req := genFunReq(Functions_FUNC_SEND_XML)
|
||||
req.Msg = &Request_Xml{
|
||||
Xml: &XmlMsg{
|
||||
Receiver: receiver,
|
||||
Content: content,
|
||||
Path: path,
|
||||
Type: Type,
|
||||
},
|
||||
}
|
||||
err := c.send(req.build())
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
recv, err := c.Recv()
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
return recv.GetStatus()
|
||||
}
|
||||
func (c *Client) EnableRecvTxt() int32 {
|
||||
err := c.send(genFunReq(Functions_FUNC_ENABLE_RECV_TXT).build())
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
recv, err := c.Recv()
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
c.RecvTxt = true
|
||||
return recv.GetStatus()
|
||||
}
|
||||
func (c *Client) DisableRecvTxt() int32 {
|
||||
err := c.send(genFunReq(Functions_FUNC_DISABLE_RECV_TXT).build())
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
recv, err := c.Recv()
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
}
|
||||
c.RecvTxt = false
|
||||
return recv.GetStatus()
|
||||
}
|
||||
func (c *Client) OnMSG(f func(msg *WxMsg)) error {
|
||||
socket, err := pair1.NewSocket()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_ = socket.SetOption(mangos.OptionRecvDeadline, 2000)
|
||||
_ = socket.SetOption(mangos.OptionSendDeadline, 2000)
|
||||
err = socket.Dial(addPort(c.add))
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for c.RecvTxt {
|
||||
msg := &Response{}
|
||||
recv, err := socket.Recv()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_ = proto.Unmarshal(recv, msg)
|
||||
go f(msg.GetWxmsg())
|
||||
}
|
||||
return err
|
||||
}
|
||||
func NewWCF(add string) (*Client, error) {
|
||||
if add == "" {
|
||||
add = "tcp://127.0.0.1:10086"
|
||||
}
|
||||
client := &Client{add: add}
|
||||
err := client.conn()
|
||||
return client, err
|
||||
}
|
||||
|
||||
type cmdMSG struct {
|
||||
*Request
|
||||
}
|
||||
|
||||
func (c *cmdMSG) build() []byte {
|
||||
marshal, _ := proto.Marshal(c)
|
||||
return marshal
|
||||
}
|
||||
func genFunReq(fun Functions) *cmdMSG {
|
||||
return &cmdMSG{
|
||||
&Request{Func: fun,
|
||||
Msg: nil},
|
||||
}
|
||||
}
|
||||
func addPort(add string) string {
|
||||
parts := strings.Split(add, ":")
|
||||
port, _ := strconv.Atoi(parts[2])
|
||||
newPort := port + 1
|
||||
return parts[0] + ":" + parts[1] + ":" + strconv.Itoa(newPort)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,152 @@
|
||||
package wcf
|
||||
|
||||
import (
|
||||
logs "github.com/danbai225/go-logs"
|
||||
"go.nanomsg.org/mangos/v3/protocol/pair1"
|
||||
_ "go.nanomsg.org/mangos/v3/transport/all"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestConn(t *testing.T) {
|
||||
socket, err := pair1.NewSocket()
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
return
|
||||
}
|
||||
err = socket.Dial("tcp://127.0.0.1:10086")
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
return
|
||||
}
|
||||
response := Response{
|
||||
Func: Functions_FUNC_IS_LOGIN,
|
||||
Msg: nil,
|
||||
}
|
||||
marshal, err := proto.Marshal(&response)
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
return
|
||||
}
|
||||
socket.Send(marshal)
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
return
|
||||
}
|
||||
recv, err := socket.Recv()
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
return
|
||||
}
|
||||
msg := Response{}
|
||||
err = proto.Unmarshal(recv, &msg)
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
return
|
||||
}
|
||||
logs.Info(msg.GetStatus())
|
||||
|
||||
}
|
||||
func TestIsLogin(t *testing.T) {
|
||||
wcf, err := NewWCF("")
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
return
|
||||
}
|
||||
logs.Info(wcf.IsLogin())
|
||||
}
|
||||
func TestGetSelfWXID(t *testing.T) {
|
||||
wcf, err := NewWCF("")
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
return
|
||||
}
|
||||
logs.Info(wcf.GetSelfWXID())
|
||||
}
|
||||
func TestGetMsgTypes(t *testing.T) {
|
||||
wcf, err := NewWCF("")
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
return
|
||||
}
|
||||
logs.Info(wcf.GetMsgTypes())
|
||||
}
|
||||
func TestGetContacts(t *testing.T) {
|
||||
wcf, err := NewWCF("")
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
return
|
||||
}
|
||||
for _, contact := range wcf.GetContacts() {
|
||||
logs.Info(contact.Remark, contact.Wxid)
|
||||
}
|
||||
logs.Info(wcf.GetContacts())
|
||||
}
|
||||
func TestGetDBNames(t *testing.T) {
|
||||
wcf, err := NewWCF("")
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
return
|
||||
}
|
||||
logs.Info(wcf.GetDBNames())
|
||||
}
|
||||
func TestGetDBTables(t *testing.T) {
|
||||
wcf, err := NewWCF("")
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
return
|
||||
}
|
||||
logs.Info(wcf.GetDBTables("ChatMsg.db"))
|
||||
}
|
||||
func TestExecDBQuery(t *testing.T) {
|
||||
wcf, err := NewWCF("")
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
return
|
||||
}
|
||||
logs.Info(wcf.ExecDBQuery("ChatMsg.db", "SELECT * FROM Name2ID_v1"))
|
||||
}
|
||||
func TestAcceptFriend(t *testing.T) {
|
||||
wcf, err := NewWCF("")
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
return
|
||||
}
|
||||
logs.Info(wcf.AcceptFriend("encryptusername", "ticket", 17))
|
||||
}
|
||||
func TestGetUserInfo(t *testing.T) {
|
||||
wcf, err := NewWCF("")
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
return
|
||||
}
|
||||
logs.Info(wcf.GetUserInfo())
|
||||
}
|
||||
func TestSendTxT(t *testing.T) {
|
||||
wcf, err := NewWCF("")
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
return
|
||||
}
|
||||
logs.Info(wcf.SendTxt(" Hello @ 淡白", "45415088466@chatroom", []string{"wxid_xxxxxxxx"}))
|
||||
}
|
||||
func TestSendIMG(t *testing.T) {
|
||||
wcf, err := NewWCF("")
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
return
|
||||
}
|
||||
logs.Info(wcf.SendIMG("C:\\Users\\danbai\\Desktop\\work\\code\\WeChatFerry-go\\图片1.png", "wxid_qvo0irhbw9fk22"))
|
||||
}
|
||||
func TestOnMSG(t *testing.T) {
|
||||
wcf, err := NewWCF("")
|
||||
if err != nil {
|
||||
logs.Err(err)
|
||||
return
|
||||
}
|
||||
logs.Info(wcf.EnableRecvTxt())
|
||||
defer wcf.DisableRecvTxt()
|
||||
wcf.OnMSG(func(msg *WxMsg) {
|
||||
logs.Info(msg.GetContent())
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
include wcferry/*.dll
|
||||
include wcferry/*.exe
|
||||
@@ -0,0 +1,32 @@
|
||||
# WeChatFerry HTTP 客户端
|
||||
[](https://pypi.python.org/pypi/wcfhttp) [](https://pypi.python.org/pypi/wcfhttp) [](https://wechatferry.readthedocs.io/zh/latest/?badge=latest)
|
||||
|
||||
基于 [wcferry](https://pypi.org/project/wcferry/) 封装的 HTTP 客户端。
|
||||
|
||||
## 快速开始
|
||||
### 安装
|
||||
```sh
|
||||
pip install --upgrade wcfhttp
|
||||
```
|
||||
|
||||
### 运行
|
||||
```sh
|
||||
# 查看版本
|
||||
wcfhttp -v
|
||||
|
||||
# 查看帮助
|
||||
wcfhttp -h
|
||||
|
||||
# 忽略新消息运行
|
||||
wcfhttp
|
||||
|
||||
# 新消息转发到指定地址
|
||||
wcfhttp --cb http://your_host:your_port/callback
|
||||
```
|
||||
|
||||
### 接收消息回调接口文档
|
||||
参考文档(默认地址为:http://localhost:9999/docs )`接收消息回调样例`。
|
||||
|
||||
|||
|
||||
|:-:|:-:|
|
||||
|后台回复 `WeChatFerry` 加群交流|如果你觉得有用|
|
||||
@@ -0,0 +1,50 @@
|
||||
#! /usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
|
||||
from __future__ import print_function
|
||||
from setuptools import setup, find_packages
|
||||
|
||||
import wcfhttp
|
||||
|
||||
with open("README.md", "r", encoding="utf-8") as fh:
|
||||
long_description = fh.read()
|
||||
|
||||
|
||||
setup(
|
||||
name="wcfhttp",
|
||||
version=wcfhttp.core.__version__,
|
||||
author="Changhua",
|
||||
author_email="lichanghua0821@gmail.com",
|
||||
description="一个玩微信的工具",
|
||||
long_description=long_description,
|
||||
long_description_content_type="text/markdown",
|
||||
license="MIT",
|
||||
url="https://github.com/lich0821/WeChatFerry",
|
||||
python_requires=">=3.8",
|
||||
packages=find_packages(),
|
||||
include_package_data=True,
|
||||
entry_points={
|
||||
'console_scripts': [
|
||||
'wcfhttp=wcfhttp.main:main'
|
||||
]
|
||||
},
|
||||
install_requires=[
|
||||
"setuptools",
|
||||
"fastapi",
|
||||
"uvicorn[standard]",
|
||||
"wcferry>=39.0.0.0",
|
||||
],
|
||||
classifiers=[
|
||||
"Environment :: Win32 (MS Windows)",
|
||||
"Intended Audience :: Developers",
|
||||
"Intended Audience :: Customer Service",
|
||||
"Topic :: Communications :: Chat",
|
||||
"Operating System :: Microsoft :: Windows",
|
||||
"Programming Language :: Python",
|
||||
],
|
||||
project_urls={
|
||||
"Documentation": "https://wechatferry.readthedocs.io/zh/latest/index.html",
|
||||
"GitHub": "https://github.com/lich0821/WeChatFerry/",
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from wcfhttp.core import Http, __version__
|
||||
@@ -0,0 +1,340 @@
|
||||
#! /usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import base64
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
from fastapi import Body, FastAPI
|
||||
from pydantic import BaseModel
|
||||
from wcferry import Wcf, WxMsg
|
||||
|
||||
__version__ = "39.0.0.1"
|
||||
|
||||
|
||||
class Msg(BaseModel):
|
||||
id: str
|
||||
type: int
|
||||
xml: str
|
||||
sender: str
|
||||
roomid: str
|
||||
content: str
|
||||
thumb: str
|
||||
extra: str
|
||||
is_at: bool
|
||||
is_self: bool
|
||||
is_group: bool
|
||||
|
||||
|
||||
class Http(FastAPI):
|
||||
"""WeChatFerry HTTP 客户端,文档地址:http://IP:PORT/docs"""
|
||||
|
||||
def __init__(self, wcf: Wcf, cb: str, **extra: Any) -> None:
|
||||
super().__init__(**extra)
|
||||
self.LOG = logging.getLogger(__name__)
|
||||
self.LOG.info(f"wcfhttp version: {__version__}")
|
||||
self.wcf = wcf
|
||||
self._set_cb(cb)
|
||||
self.add_api_route("/msg_cb", self.msg_cb, methods=["POST"], summary="接收消息回调样例", tags=["示例"])
|
||||
|
||||
self.add_api_route("/login", self.is_login, methods=["GET"], summary="获取登录状态")
|
||||
self.add_api_route("/wxid", self.get_self_wxid, methods=["GET"], summary="获取登录账号 wxid")
|
||||
self.add_api_route("/user-info", self.get_user_info, methods=["GET"], summary="获取登录账号个人信息")
|
||||
self.add_api_route("/msg-types", self.get_msg_types, methods=["GET"], summary="获取消息类型")
|
||||
self.add_api_route("/contacts", self.get_contacts, methods=["GET"], summary="获取完整通讯录")
|
||||
self.add_api_route("/friends", self.get_friends, methods=["GET"], summary="获取好友列表")
|
||||
self.add_api_route("/dbs", self.get_dbs, methods=["GET"], summary="获取所有数据库")
|
||||
self.add_api_route("/{db}/tables", self.get_tables, methods=["GET"], summary="获取 db 中所有表")
|
||||
|
||||
self.add_api_route("/text", self.send_text, methods=["POST"], summary="发送文本消息")
|
||||
self.add_api_route("/image", self.send_image, methods=["POST"], summary="发送图片消息")
|
||||
self.add_api_route("/file", self.send_file, methods=["POST"], summary="发送文件消息")
|
||||
# self.add_api_route("/xml", self.send_xml, methods=["POST"], summary="发送 XML 消息")
|
||||
# self.add_api_route("/emotion", self.send_emotion, methods=["POST"], summary="发送表情消息")
|
||||
self.add_api_route("/sql", self.query_sql, methods=["POST"], summary="执行 SQL,如果数据量大注意分页,以免 OOM")
|
||||
self.add_api_route("/new-friend", self.accept_new_friend, methods=["POST"], summary="通过好友申请")
|
||||
self.add_api_route("/chatroom-member", self.add_chatroom_members, methods=["POST"], summary="添加群成员")
|
||||
self.add_api_route("/chatroom-member", self.del_chatroom_members, methods=["DELETE"], summary="删除群成员")
|
||||
self.add_api_route("/transfer", self.receive_transfer, methods=["POST"], summary="接收转账")
|
||||
self.add_api_route("/dec-image", self.decrypt_image, methods=["POST"], summary="解密图片")
|
||||
|
||||
def _set_cb(self, cb):
|
||||
def callback(msg: WxMsg):
|
||||
data = {}
|
||||
data["id"] = msg.id
|
||||
data["type"] = msg.type
|
||||
data["xml"] = msg.xml
|
||||
data["sender"] = msg.sender
|
||||
data["roomid"] = msg.roomid
|
||||
data["content"] = msg.content
|
||||
data["thumb"] = msg.thumb
|
||||
data["extra"] = msg.extra
|
||||
data["is_at"] = msg.is_at(self.wcf.self_wxid)
|
||||
data["is_self"] = msg.from_self()
|
||||
data["is_group"] = msg.from_group()
|
||||
|
||||
try:
|
||||
rsp = requests.post(url=cb, json=data)
|
||||
if rsp.status_code != 200:
|
||||
self.LOG.error(f"消息转发失败,HTTP 状态码为: {rsp.status_code}")
|
||||
except Exception as e:
|
||||
self.LOG.error(f"消息转发异常: {e}")
|
||||
|
||||
if cb:
|
||||
self.LOG.info(f"消息回调: {cb}")
|
||||
self.wcf.enable_recv_msg(callback=callback)
|
||||
else:
|
||||
self.LOG.info(f"没有设置回调,打印消息")
|
||||
self.wcf.enable_recv_msg(print)
|
||||
|
||||
def is_login(self) -> dict:
|
||||
"""获取登录状态"""
|
||||
ret = self.wcf.is_login()
|
||||
return {"status": 0, "message": "成功", "data": {"login": ret}}
|
||||
|
||||
def get_self_wxid(self) -> dict:
|
||||
"""获取登录账号 wxid"""
|
||||
ret = self.wcf.get_self_wxid()
|
||||
if ret:
|
||||
return {"status": 0, "message": "成功", "data": {"wxid": ret}}
|
||||
return {"status": -1, "message": "失败"}
|
||||
|
||||
def get_msg_types(self) -> dict:
|
||||
"""获取消息类型"""
|
||||
ret = self.wcf.get_msg_types()
|
||||
if ret:
|
||||
return {"status": 0, "message": "成功", "data": {"types": ret}}
|
||||
return {"status": -1, "message": "失败"}
|
||||
|
||||
def get_contacts(self) -> dict:
|
||||
"""获取完整通讯录"""
|
||||
ret = self.wcf.get_contacts()
|
||||
if ret:
|
||||
return {"status": 0, "message": "成功", "data": {"contacts": ret}}
|
||||
return {"status": -1, "message": "失败"}
|
||||
|
||||
def get_friends(self) -> dict:
|
||||
"""获取好友列表"""
|
||||
ret = self.wcf.get_friends()
|
||||
if ret:
|
||||
return {"status": 0, "message": "成功", "data": {"friends": ret}}
|
||||
return {"status": -1, "message": "失败"}
|
||||
|
||||
def get_dbs(self) -> dict:
|
||||
"""获取所有数据库"""
|
||||
ret = self.wcf.get_dbs()
|
||||
if ret:
|
||||
return {"status": 0, "message": "成功", "data": {"dbs": ret}}
|
||||
return {"status": -1, "message": "失败"}
|
||||
|
||||
def get_tables(self, db: str) -> dict:
|
||||
"""获取 db 中所有表
|
||||
|
||||
Args:
|
||||
db (str): 数据库名(可通过 `get_dbs` 查询)
|
||||
|
||||
Returns:
|
||||
List[dict]: `db` 下的所有表名及对应建表语句
|
||||
"""
|
||||
ret = self.wcf.get_tables(db)
|
||||
if ret:
|
||||
return {"status": 0, "message": "成功", "data": {"tables": ret}}
|
||||
return {"status": -1, "message": "失败"}
|
||||
|
||||
def get_user_info(self) -> dict:
|
||||
"""获取登录账号个人信息"""
|
||||
ret = self.wcf.get_user_info()
|
||||
if ret:
|
||||
return {"status": 0, "message": "成功", "data": {"ui": ret}}
|
||||
return {"status": -1, "message": "失败"}
|
||||
|
||||
def msg_cb(self, msg: Msg = Body(description="微信消息")):
|
||||
"""示例回调方法,简单打印消息"""
|
||||
print(f"收到消息:{msg}")
|
||||
return {"status": 0, "message": "成功"}
|
||||
|
||||
def send_text(
|
||||
self, msg: str = Body(description="要发送的消息,换行用\\n表示"),
|
||||
receiver: str = Body("filehelper", description="消息接收者,roomid 或者 wxid"),
|
||||
aters: str = Body("", description="要 @ 的 wxid,多个用逗号分隔;@所有人 用 notify@all")) -> dict:
|
||||
"""发送文本消息,可参考:https://github.com/lich0821/WeChatRobot/blob/master/robot.py 里 sendTextMsg
|
||||
|
||||
Args:
|
||||
msg (str): 要发送的消息,换行使用 `\\n`;如果 @ 人的话,需要带上跟 `aters` 里数量相同的 @
|
||||
receiver (str): 消息接收人,wxid 或者 roomid
|
||||
aters (str): 要 @ 的 wxid,多个用逗号分隔;`@所有人` 只需要 `notify@all`
|
||||
|
||||
Returns:
|
||||
int: 0 为成功,其他失败
|
||||
"""
|
||||
ret = self.wcf.send_text(msg, receiver, aters)
|
||||
return {"status": ret, "message": "成功"if ret == 0 else "失败"}
|
||||
|
||||
def send_image(self,
|
||||
path: str = Body("C:\\Projs\\WeChatRobot\\TEQuant.jpeg", description="图片路径"),
|
||||
receiver: str = Body("filehelper", description="消息接收者,roomid 或者 wxid")) -> dict:
|
||||
"""发送图片,非线程安全
|
||||
|
||||
Args:
|
||||
path (str): 图片路径,如:`C:/Projs/WeChatRobot/TEQuant.jpeg` 或 `https://raw.githubusercontent.com/lich0821/WeChatRobot/master/TEQuant.jpeg`
|
||||
receiver (str): 消息接收人,wxid 或者 roomid
|
||||
|
||||
Returns:
|
||||
int: 0 为成功,其他失败
|
||||
"""
|
||||
ret = self.wcf.send_image(path, receiver)
|
||||
return {"status": ret, "message": "成功"if ret == 0 else "失败"}
|
||||
|
||||
def send_file(self,
|
||||
path: str = Body("C:\\Projs\\WeChatRobot\\TEQuant.jpeg", description="本地文件路径,不支持网络路径"),
|
||||
receiver: str = Body("filehelper", description="roomid 或者 wxid")) -> dict:
|
||||
"""发送文件
|
||||
|
||||
Args:
|
||||
path (str): 本地文件路径,如:`C:/Projs/WeChatRobot/README.MD`
|
||||
receiver (str): 消息接收人,wxid 或者 roomid
|
||||
|
||||
Returns:
|
||||
int: 0 为成功,其他失败
|
||||
"""
|
||||
ret = self.wcf.send_file(path, receiver)
|
||||
return {"status": ret, "message": "成功"if ret == 0 else "失败"}
|
||||
|
||||
def send_xml(
|
||||
self, receiver: str = Body("filehelper", description="roomid 或者 wxid"),
|
||||
xml:
|
||||
str = Body(
|
||||
'<?xml version="1.0"?><msg><appmsg appid="" sdkver="0"><title>叮当药房,24小时服务,28分钟送药到家!</title><des>叮当快药首家承诺范围内28分钟送药到家!叮当快药核心区域内7*24小时全天候服务,送药上门!叮当快药官网为您提供快捷便利,正品低价,安全放心的购药、送药服务体验。</des><action>view</action><type>33</type></appmsg><fromusername>wxid_xxxxxxxxxxxxxx</fromusername><scene>0</scene><appinfo><version>1</version><appname /></appinfo><commenturl /></msg>',
|
||||
description="xml 内容"),
|
||||
type: int = Body(0x21, description="xml 类型,0x21 为小程序"),
|
||||
path: str = Body(None, description="封面图片路径")) -> dict:
|
||||
"""发送 XML
|
||||
|
||||
Args:
|
||||
receiver (str): 消息接收人,wxid 或者 roomid
|
||||
xml (str): xml 内容
|
||||
type (int): xml 类型,如:0x21 为小程序
|
||||
path (str): 封面图片路径
|
||||
|
||||
Returns:
|
||||
int: 0 为成功,其他失败
|
||||
"""
|
||||
ret = self.wcf.send_xml(receiver, xml, type, path)
|
||||
return {"status": ret, "message": "成功"if ret == 0 else "失败"}
|
||||
|
||||
def send_emotion(self,
|
||||
path: str = Body("C:/Projs/WeChatRobot/emo.gif", description="本地文件路径,不支持网络路径"),
|
||||
receiver: str = Body("filehelper", description="roomid 或者 wxid")) -> dict:
|
||||
"""发送表情
|
||||
|
||||
Args:
|
||||
path (str): 本地表情路径,如:`C:/Projs/WeChatRobot/emo.gif`
|
||||
receiver (str): 消息接收人,wxid 或者 roomid
|
||||
|
||||
Returns:
|
||||
int: 0 为成功,其他失败
|
||||
"""
|
||||
ret = self.wcf.send_emotion(path, receiver)
|
||||
return {"status": ret, "message": "成功"if ret == 0 else "失败"}
|
||||
|
||||
def query_sql(self,
|
||||
db: str = Body("MicroMsg.db", description="数据库"),
|
||||
sql: str = Body("SELECT * FROM Contact LIMIT 1;", description="SQL 语句")) -> dict:
|
||||
"""执行 SQL,如果数据量大注意分页,以免 OOM
|
||||
|
||||
Args:
|
||||
db (str): 要查询的数据库
|
||||
sql (str): 要执行的 SQL
|
||||
|
||||
Returns:
|
||||
List[dict]: 查询结果
|
||||
"""
|
||||
ret = self.wcf.query_sql(db, sql)
|
||||
if ret:
|
||||
for row in ret:
|
||||
for k, v in row.items():
|
||||
print(k, type(v))
|
||||
if type(v) is bytes:
|
||||
row[k] = base64.b64encode(v)
|
||||
return {"status": 0, "message": "成功", "data": {"bs64": ret}}
|
||||
return {"status": -1, "message": "失败"}
|
||||
|
||||
def accept_new_friend(self,
|
||||
v3: str = Body("v3", description="加密用户名 (好友申请消息里 v3 开头的字符串)"),
|
||||
v4: str = Body("v4", description="Ticket (好友申请消息里 v4 开头的字符串)"),
|
||||
scene: int = Body(30, description="申请方式 (好友申请消息里的 scene)")) -> dict:
|
||||
"""通过好友申请
|
||||
|
||||
Args:
|
||||
v3 (str): 加密用户名 (好友申请消息里 v3 开头的字符串)
|
||||
v4 (str): Ticket (好友申请消息里 v4 开头的字符串)
|
||||
scene: 申请方式 (好友申请消息里的 scene)
|
||||
|
||||
Returns:
|
||||
int: 1 为成功,其他失败
|
||||
"""
|
||||
ret = self.wcf.accept_new_friend(v3, v4, scene)
|
||||
return {"status": ret, "message": "成功"if ret == 1 else "失败"}
|
||||
|
||||
def add_chatroom_members(self,
|
||||
roomid: str = Body("xxxxxxxx@chatroom", description="待加群的 id"),
|
||||
wxids: str = Body("wxid_xxxxxxxxxxxxx", description="要加到群里的 wxid,多个用逗号分隔")) -> dict:
|
||||
"""添加群成员
|
||||
|
||||
Args:
|
||||
roomid (str): 待加群的 id
|
||||
wxids (str): 要加到群里的 wxid,多个用逗号分隔
|
||||
|
||||
Returns:
|
||||
int: 1 为成功,其他失败
|
||||
"""
|
||||
ret = self.wcf.add_chatroom_members(roomid, wxids)
|
||||
return {"status": ret, "message": "成功"if ret == 1 else "失败"}
|
||||
|
||||
def del_chatroom_members(self,
|
||||
roomid: str = Body("xxxxxxxx@chatroom", description="群的 id"),
|
||||
wxids: str = Body("wxid_xxxxxxxxxxxxx", description="要删除的 wxid,多个用逗号分隔")) -> dict:
|
||||
"""删除群成员
|
||||
|
||||
Args:
|
||||
roomid (str): 群的 id
|
||||
wxids (str): 要删除的 wxid,多个用逗号分隔
|
||||
|
||||
Returns:
|
||||
int: 1 为成功,其他失败
|
||||
"""
|
||||
ret = self.wcf.del_chatroom_members(roomid, wxids)
|
||||
return {"status": ret, "message": "成功"if ret == 1 else "失败"}
|
||||
|
||||
def receive_transfer(self,
|
||||
wxid: str = Body("wxid_xxxxxxxxxxxxx", description="转账消息里的发送人 wxid"),
|
||||
transferid: str = Body("transferid", description="转账消息里的 transferid"),
|
||||
transactionid: str = Body("transactionid", description="转账消息里的 transactionid")) -> dict:
|
||||
"""接收转账
|
||||
|
||||
Args:
|
||||
wxid (str): 转账消息里的发送人 wxid
|
||||
transferid (str): 转账消息里的 transferid
|
||||
transactionid (str): 转账消息里的 transactionid
|
||||
|
||||
Returns:
|
||||
int: 1 为成功,其他失败
|
||||
"""
|
||||
ret = self.wcf.receive_transfer(wxid, transferid, transactionid)
|
||||
return {"status": ret, "message": "成功"if ret == 1 else "失败"}
|
||||
|
||||
def decrypt_image(self,
|
||||
src: str = Body("C:\\...", description="加密的图片路径,从图片消息中获取"),
|
||||
dst: str = Body("C:\\...", description="解密的图片路径")) -> dict:
|
||||
"""解密图片:
|
||||
|
||||
Args:
|
||||
src (str): 加密的图片路径
|
||||
dst (str): 解密的图片路径
|
||||
|
||||
Returns:
|
||||
bool: 是否成功
|
||||
"""
|
||||
ret = self.wcf.decrypt_image(src, dst)
|
||||
return {"status": ret, "message": "成功"if ret else "失败"}
|
||||
@@ -0,0 +1,40 @@
|
||||
#! /usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import logging
|
||||
import argparse
|
||||
|
||||
import uvicorn
|
||||
from wcferry import Wcf
|
||||
from wcfhttp import Http, __version__
|
||||
|
||||
|
||||
def main():
|
||||
parse = argparse.ArgumentParser()
|
||||
parse.add_argument("-v", "--version", action="version", version=f"{__version__}")
|
||||
parse.add_argument("--wcf_host", type=str, default=None, help="WeChatFerry 监听地址,默认本地启动监听 0.0.0.0")
|
||||
parse.add_argument("--wcf_port", type=int, default=10086, help="WeChatFerry 监听端口 (同时占用 port + 1 端口),默认 10086")
|
||||
parse.add_argument("--wcf_debug", type=bool, default=False, help="是否打开 WeChatFerry 调试开关")
|
||||
parse.add_argument("--host", type=str, default="0.0.0.0", help="wcfhttp 监听地址,默认监听 0.0.0.0")
|
||||
parse.add_argument("--port", type=int, default=9999, help="wcfhttp 监听端口,默认 9999")
|
||||
parse.add_argument("--cb", type=str, default="", help="接收消息回调地址")
|
||||
|
||||
logging.basicConfig(level="INFO", format="%(asctime)s %(message)s")
|
||||
args = parse.parse_args()
|
||||
cb = args.cb
|
||||
if not cb:
|
||||
logging.warning("没有设置接收消息回调,消息直接通过日志打印;请通过 --cb 设置消息回调")
|
||||
logging.warning(f"回调接口规范参考接收消息回调样例:http://{args.host}:{args.port}/docs")
|
||||
|
||||
wcf = Wcf(args.wcf_host, args.wcf_port, args.wcf_debug)
|
||||
home = "https://github.com/lich0821/WeChatFerry"
|
||||
http = Http(wcf=wcf,
|
||||
cb=cb,
|
||||
title="WeChatFerry HTTP 客户端",
|
||||
description=f"Github: <a href='{home}'>WeChatFerry</a>",)
|
||||
|
||||
uvicorn.run(app=http, host=args.host, port=args.port)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,63 @@
|
||||
# WeChatFerry Java 客户端
|
||||
⚠️ **只支持 Windows** ⚠️
|
||||
|
||||
## 快速开始
|
||||
* 下载 [最新发布的版本](https://github.com/lich0821/WeChatFerry/releases/latest),解压,找到 java 客户端。
|
||||
|
||||
* 使用惯用 IDE,打开工程,编译,运行。
|
||||
|
||||
## 从头开始
|
||||
【添加 `wcferry` 依赖】是必须要执行的,工程里不带这几个文件;如果开发新功能,一般需要修改 `wcf.proto`,从而需要重新生成 PB 文件;其他的,一般不需要关注。
|
||||
|
||||
### 添加 `nng` 依赖
|
||||
* 新建一个 `libs` 目录
|
||||
* 参考 [nng-java](https://github.com/voutilad/nng-java),编译 jar 包(`nng-java-1.4.0-SNAPSHOT.jar`)
|
||||
* 添加依赖 `nng-java-1.4.0-SNAPSHOT.jar`
|
||||
```groovy
|
||||
implementation 'net.java.dev.jna:jna:5.6.0'
|
||||
implementation fileTree(dir: 'libs', include: ['*.jar'])
|
||||
```
|
||||
|
||||
#### 编译 / 安装 `mbedtls`
|
||||
* 下载 [Mbed TLS](https://github.com/Mbed-TLS/mbedtls) 代码并解压
|
||||
* 新建 `build` 目录,生成 VS 工程
|
||||
```sh
|
||||
cd build
|
||||
cmake ..
|
||||
```
|
||||
|
||||
* 以管理员身份运行 VS2019,打开 `mbed TLS.sln`,选择 `Release` `x64`,编译即可
|
||||
* [参考](https://github.com/Mbed-TLS/mbedtls)
|
||||
|
||||
#### 编译 / 安装 `nng`
|
||||
* 下载 [nng](https://github.com/nanomsg/nng) 代码并解压
|
||||
* 新建 `build` 目录,生成 VS 工程
|
||||
```sh
|
||||
cmake -DBUILD_SHARED_LIBS=ON -DNNG_ENABLE_TLS=ON -DMBEDTLS_ROOT_DIR="C:\Program Files (x86)\mbed TLS" ..
|
||||
```
|
||||
|
||||
* 打开 `nng.sln`,选择 `Release` `x64`,编译即可
|
||||
* [参考](https://github.com/nanomsg/nng/issues/953)
|
||||
|
||||
### 添加 PB 依赖
|
||||
```groovy
|
||||
implementation 'com.google.protobuf:protobuf-java:3.22.2' // 版本需要和 protoc 一致
|
||||
```
|
||||
|
||||
#### 重新生成 PB 文件
|
||||
参考 [Protocol Buffer Basics: Java](https://protobuf.dev/getting-started/javatutorial/#problem-domain)。
|
||||
* 下载 `protoc` 工具(注意,需要与 `com.google.protobuf:protobuf-java` 一致):
|
||||
这里下载 [protoc-22.2](https://github.com/protocolbuffers/protobuf/releases/download/v22.2/protoc-22.2-win64.zip),解压,并将所在路径加入环境变量(以便随处可用)。
|
||||
|
||||
* 编译 PB 文件
|
||||
```sh
|
||||
cd C:/Projs/WeChatFerry/java/wcferry/src/main/java
|
||||
protoc.exe --java_out=. --proto_path=C:\Projs\WeChatFerry\rpc\proto wcf.proto
|
||||
```
|
||||
|
||||
### 添加 `wcferry` 依赖
|
||||
将 `wcf.exe` 、 `spy.dll` 、 `spy_debug.dll` 添加到 `C:\Projs\WeChatFerry\java\wcferry\src\main\resources\win32-x86-64`。
|
||||
|
||||
### 其他问题
|
||||
### 乱码
|
||||
参考 [这篇文章](https://www.quanxiaoha.com/idea/idea-chinese-garbled-code.html)。
|
||||
@@ -0,0 +1,25 @@
|
||||
plugins {
|
||||
id 'java'
|
||||
}
|
||||
|
||||
group 'org.example'
|
||||
version '1.0-SNAPSHOT'
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'org.slf4j:slf4j-api:2.0.7'
|
||||
implementation 'ch.qos.logback:logback-core:1.3.6'
|
||||
implementation 'ch.qos.logback:logback-classic:1.3.6'
|
||||
implementation 'com.google.protobuf:protobuf-java:3.22.2'
|
||||
implementation 'net.java.dev.jna:jna:5.6.0'
|
||||
implementation fileTree(dir: 'libs', include: ['*.jar'])
|
||||
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
|
||||
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
|
||||
}
|
||||
|
||||
test {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,5 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
Vendored
+234
@@ -0,0 +1,234 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=${0##*/}
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
Vendored
+89
@@ -0,0 +1,89 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
Binary file not shown.
@@ -0,0 +1,2 @@
|
||||
rootProject.name = 'wcferry'
|
||||
|
||||
@@ -0,0 +1,564 @@
|
||||
package com.iamteer;
|
||||
|
||||
import com.iamteer.Wcf.*;
|
||||
import io.sisu.nng.Socket;
|
||||
import io.sisu.nng.pair.Pair1Socket;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.net.URL;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
|
||||
public class Client {
|
||||
private static final Logger logger = LoggerFactory.getLogger(Client.class);
|
||||
private final int BUFFER_SIZE = 16 * 1024 * 1024; // 16M
|
||||
private Socket cmdSocket = null;
|
||||
private Socket msgSocket = null;
|
||||
private String host = "127.0.0.1";
|
||||
private int port = 10086;
|
||||
private boolean isReceivingMsg = false;
|
||||
private boolean isLocalHostPort = false;
|
||||
private BlockingQueue<WxMsg> msgQ;
|
||||
private String wcfPath;
|
||||
|
||||
public Client(String host, int port) {
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
String cmdUrl = "tcp://" + host + ":" + port;
|
||||
connectRPC(cmdUrl);
|
||||
}
|
||||
|
||||
public Client(int port, boolean debug) {
|
||||
initClient(this.host, port, debug);
|
||||
}
|
||||
|
||||
public Client(boolean debug) {
|
||||
initClient(this.host, this.port, debug);
|
||||
}
|
||||
|
||||
private void initClient(String host, int port, boolean debug) {
|
||||
try {
|
||||
URL url = this.getClass().getResource("/win32-x86-64/wcf.exe");
|
||||
wcfPath = url.getFile();
|
||||
String[] cmd = new String[4];
|
||||
cmd[0] = wcfPath;
|
||||
cmd[1] = "start";
|
||||
cmd[2] = Integer.toString(port);
|
||||
if (debug) {
|
||||
cmd[3] = "debug";
|
||||
} else {
|
||||
cmd[3] = "";
|
||||
}
|
||||
int status = Runtime.getRuntime().exec(cmd).waitFor();
|
||||
if (status != 0) {
|
||||
logger.error("启动 RPC 失败: {}", status);
|
||||
System.exit(-1);
|
||||
}
|
||||
isLocalHostPort = true;
|
||||
String cmdUrl = "tcp://" + host + ":" + port;
|
||||
connectRPC(cmdUrl);
|
||||
} catch (Exception e) {
|
||||
logger.error("初始化失败: {}", e);
|
||||
System.exit(-1);
|
||||
}
|
||||
}
|
||||
|
||||
private void connectRPC(String url) {
|
||||
try {
|
||||
cmdSocket = new Pair1Socket();
|
||||
cmdSocket.dial(url);
|
||||
logger.info("请点击登录微信");
|
||||
while (!isLogin()) { // 直到登录成功
|
||||
waitMs(1000);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("连接 RPC 失败: ", e);
|
||||
System.exit(-1);
|
||||
}
|
||||
Runtime.getRuntime().addShutdownHook(new Thread() {
|
||||
public void run() {
|
||||
logger.info("关闭...");
|
||||
diableRecvMsg();
|
||||
if (isLocalHostPort) {
|
||||
try {
|
||||
String[] cmd = new String[2];
|
||||
cmd[0] = wcfPath;
|
||||
cmd[1] = "stop";
|
||||
Process process = Runtime.getRuntime().exec(cmd);
|
||||
int status = process.waitFor();
|
||||
if (status != 0) {
|
||||
System.err.println("停止机器人失败: " + status);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Response sendCmd(Request req) {
|
||||
try {
|
||||
ByteBuffer bb = ByteBuffer.wrap(req.toByteArray());
|
||||
cmdSocket.send(bb);
|
||||
ByteBuffer ret = ByteBuffer.allocate(BUFFER_SIZE);
|
||||
long size = cmdSocket.receive(ret, true);
|
||||
return Response.parseFrom(Arrays.copyOfRange(ret.array(), 0, (int) size));
|
||||
} catch (Exception e) {
|
||||
logger.error("命令调用失败: ", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前微信客户端是否登录微信号
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public boolean isLogin() {
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_IS_LOGIN_VALUE).build();
|
||||
Response rsp = sendCmd(req);
|
||||
if (rsp != null) {
|
||||
return rsp.getStatus() == 1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得微信客户端登录的微信ID
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public String getSelfWxid() {
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_GET_SELF_WXID_VALUE).build();
|
||||
Response rsp = sendCmd(req);
|
||||
if (rsp != null) {
|
||||
return rsp.getStr();
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有消息类型
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public Map<Integer, String> getMsgTypes() {
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_GET_MSG_TYPES_VALUE).build();
|
||||
Response rsp = sendCmd(req);
|
||||
if (rsp != null) {
|
||||
return rsp.getTypes().getTypesMap();
|
||||
}
|
||||
|
||||
return Wcf.MsgTypes.newBuilder().build().getTypesMap();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有联系人
|
||||
* "fmessage": "朋友推荐消息",
|
||||
* "medianote": "语音记事本",
|
||||
* "floatbottle": "漂流瓶",
|
||||
* "filehelper": "文件传输助手",
|
||||
* "newsapp": "新闻",
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public List<RpcContact> getContacts() {
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_GET_CONTACTS_VALUE).build();
|
||||
Response rsp = sendCmd(req);
|
||||
if (rsp != null) {
|
||||
return rsp.getContacts().getContactsList();
|
||||
}
|
||||
|
||||
return Wcf.RpcContacts.newBuilder().build().getContactsList();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取sql执行结果
|
||||
*
|
||||
* @param db 数据库名
|
||||
* @param sql 执行的sql语句
|
||||
* @return
|
||||
*/
|
||||
public List<DbRow> querySql(String db, String sql) {
|
||||
DbQuery dbQuery = DbQuery.newBuilder().setSql(sql).setDb(db).build();
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_EXEC_DB_QUERY_VALUE).setQuery(dbQuery).build();
|
||||
Response rsp = sendCmd(req);
|
||||
if (rsp != null) {
|
||||
return rsp.getRows().getRowsList();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有数据库名
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public List<String> getDbNames() {
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_GET_DB_NAMES_VALUE).build();
|
||||
Response rsp = sendCmd(req);
|
||||
if (rsp != null) {
|
||||
return rsp.getDbs().getNamesList();
|
||||
}
|
||||
|
||||
return Wcf.DbNames.newBuilder().build().getNamesList();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定数据库中的所有表
|
||||
*
|
||||
* @param db
|
||||
* @return
|
||||
*/
|
||||
public Map<String, String> getDbTables(String db) {
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_GET_DB_TABLES_VALUE).setStr(db).build();
|
||||
Response rsp = sendCmd(req);
|
||||
Map<String, String> tables = new HashMap<>();
|
||||
if (rsp != null) {
|
||||
for (DbTable tbl : rsp.getTables().getTablesList()) {
|
||||
tables.put(tbl.getName(), tbl.getSql());
|
||||
}
|
||||
}
|
||||
|
||||
return tables;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param msg: 消息内容(如果是 @ 消息则需要有跟 @ 的人数量相同的 @)
|
||||
* @param receiver: 消息接收人,私聊为 wxid(wxid_xxxxxxxxxxxxxx),群聊为
|
||||
* roomid(xxxxxxxxxx@chatroom)
|
||||
* @param aters: 群聊时要 @ 的人(私聊时为空字符串),多个用逗号分隔。@所有人 用
|
||||
* notify@all(必须是群主或者管理员才有权限)
|
||||
* @return int
|
||||
* @Description 发送文本消息
|
||||
* @author Changhua
|
||||
* @example sendText(" Hello @ 某人1 @ 某人2 ", " xxxxxxxx @ chatroom ",
|
||||
* "wxid_xxxxxxxxxxxxx1,wxid_xxxxxxxxxxxxx2");
|
||||
**/
|
||||
public int sendText(String msg, String receiver, String aters) {
|
||||
Wcf.TextMsg textMsg = Wcf.TextMsg.newBuilder().setMsg(msg).setReceiver(receiver).setAters(aters).build();
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_SEND_TXT_VALUE).setTxt(textMsg).build();
|
||||
logger.debug("sendText: {}", bytesToHex(req.toByteArray()));
|
||||
Response rsp = sendCmd(req);
|
||||
int ret = -1;
|
||||
if (rsp != null) {
|
||||
ret = rsp.getStatus();
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送图片消息
|
||||
*
|
||||
* @param path 图片地址
|
||||
* @param receiver 接收者微信id
|
||||
* @return 发送结果状态码
|
||||
*/
|
||||
public int sendImage(String path, String receiver) {
|
||||
Wcf.PathMsg pathMsg = Wcf.PathMsg.newBuilder().setPath(path).setReceiver(receiver).build();
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_SEND_IMG_VALUE).setFile(pathMsg).build();
|
||||
logger.debug("sendImage: {}", bytesToHex(req.toByteArray()));
|
||||
Response rsp = sendCmd(req);
|
||||
int ret = -1;
|
||||
if (rsp != null) {
|
||||
ret = rsp.getStatus();
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送文件消息
|
||||
*
|
||||
* @param path 文件地址
|
||||
* @param receiver 接收者微信id
|
||||
* @return 发送结果状态码
|
||||
*/
|
||||
public int sendFile(String path, String receiver) {
|
||||
Wcf.PathMsg pathMsg = Wcf.PathMsg.newBuilder().setPath(path).setReceiver(receiver).build();
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_SEND_FILE_VALUE).setFile(pathMsg).build();
|
||||
logger.debug("sendFile: {}", bytesToHex(req.toByteArray()));
|
||||
Response rsp = sendCmd(req);
|
||||
int ret = -1;
|
||||
if (rsp != null) {
|
||||
ret = rsp.getStatus();
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送Xml消息
|
||||
*
|
||||
* @param receiver 接收者微信id
|
||||
* @param xml xml内容
|
||||
* @param path
|
||||
* @param type
|
||||
* @return 发送结果状态码
|
||||
*/
|
||||
public int sendXml(String receiver, String xml, String path, int type) {
|
||||
Wcf.XmlMsg xmlMsg = Wcf.XmlMsg.newBuilder().setContent(xml).setReceiver(receiver).setPath(path).setType(type).build();
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_SEND_XML_VALUE).setXml(xmlMsg).build();
|
||||
logger.debug("sendXml: {}", bytesToHex(req.toByteArray()));
|
||||
Response rsp = sendCmd(req);
|
||||
int ret = -1;
|
||||
if (rsp != null) {
|
||||
ret = rsp.getStatus();
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送表情消息
|
||||
*
|
||||
* @param path 表情路径
|
||||
* @param receiver 消息接收者
|
||||
* @return 发送结果状态码
|
||||
*/
|
||||
public int sendEmotion(String path, String receiver) {
|
||||
Wcf.PathMsg pathMsg = Wcf.PathMsg.newBuilder().setPath(path).setReceiver(receiver).build();
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_SEND_EMOTION_VALUE).setFile(pathMsg).build();
|
||||
logger.debug("sendEmotion: {}", bytesToHex(req.toByteArray()));
|
||||
Response rsp = sendCmd(req);
|
||||
int ret = -1;
|
||||
if (rsp != null) {
|
||||
ret = rsp.getStatus();
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收好友请求
|
||||
*
|
||||
* @param v3 xml.attrib["encryptusername"]
|
||||
* @param v4 xml.attrib["ticket"]
|
||||
* @return 结果状态码
|
||||
*/
|
||||
public int acceptNewFriend(String v3, String v4) {
|
||||
int ret = -1;
|
||||
Verification verification = Verification.newBuilder().setV3(v3).setV4(v4).build();
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_ACCEPT_FRIEND_VALUE).setV(verification).build();
|
||||
Response rsp = sendCmd(req);
|
||||
if (rsp != null) {
|
||||
ret = rsp.getStatus();
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加群成员为微信好友
|
||||
*
|
||||
* @param roomID 群ID
|
||||
* @param wxIds 要加群的人列表,逗号分隔
|
||||
* @return 1 为成功,其他失败
|
||||
*/
|
||||
public int addChatroomMembers(String roomID, String wxIds) {
|
||||
int ret = -1;
|
||||
AddMembers addMembers = AddMembers.newBuilder().setRoomid(roomID).setWxids(wxIds).build();
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_ADD_ROOM_MEMBERS_VALUE).setM(addMembers).build();
|
||||
Response rsp = sendCmd(req);
|
||||
if (rsp != null) {
|
||||
ret = rsp.getStatus();
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收转账
|
||||
*
|
||||
* @param transferid 转账消息里的 transferid
|
||||
* @param wxId 转账消息里的发送人
|
||||
* @return 1 为成功,其他失败
|
||||
*/
|
||||
public int receiveTransfer(String transferid, String wxId) {
|
||||
int ret = -1;
|
||||
Transfer build = Transfer.newBuilder().setTid(transferid).setWxid(wxId).build();
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_RECV_TRANSFER_VALUE).setTf(build).build();
|
||||
Response rsp = sendCmd(req);
|
||||
if (rsp != null) {
|
||||
ret = rsp.getStatus();
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密图片
|
||||
*
|
||||
* @param srcPath 加密的图片路径
|
||||
* @param dstPath 解密的图片路径
|
||||
* @return 是否成功
|
||||
*/
|
||||
public boolean decryptImage(String srcPath, String dstPath) {
|
||||
int ret = -1;
|
||||
DecPath build = DecPath.newBuilder().setSrc(srcPath).setDst(dstPath).build();
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_DECRYPT_IMAGE_VALUE).setDec(build).build();
|
||||
Response rsp = sendCmd(req);
|
||||
if (rsp != null) {
|
||||
ret = rsp.getStatus();
|
||||
}
|
||||
return ret == 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取个人信息
|
||||
*
|
||||
* @return 个人信息
|
||||
*/
|
||||
public UserInfo getUserInfo() {
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_GET_USER_INFO_VALUE).build();
|
||||
Response rsp = sendCmd(req);
|
||||
if (rsp != null) {
|
||||
return rsp.getUi();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean getIsReceivingMsg() {
|
||||
return isReceivingMsg;
|
||||
}
|
||||
|
||||
public WxMsg getMsg() {
|
||||
try {
|
||||
return msgQ.take();
|
||||
} catch (Exception e) {
|
||||
// TODO: handle exception
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否是艾特自己的消息
|
||||
*
|
||||
* @param wxMsgXml
|
||||
* @param wxMsgContent
|
||||
* @return
|
||||
*/
|
||||
public boolean isAtMeMsg(String wxMsgXml, String wxMsgContent) {
|
||||
String format = String.format("<atuserlist><![CDATA[%s]]></atuserlist>", getSelfWxid());
|
||||
boolean isAtAll = wxMsgContent.startsWith("@所有人") || wxMsgContent.startsWith("@all");
|
||||
if (wxMsgXml.contains(format) && !isAtAll) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void listenMsg(String url) {
|
||||
try {
|
||||
msgSocket = new Pair1Socket();
|
||||
msgSocket.dial(url);
|
||||
msgSocket.setReceiveTimeout(2000); // 2 秒超时
|
||||
} catch (Exception e) {
|
||||
logger.error("创建消息 RPC 失败: {}", e);
|
||||
return;
|
||||
}
|
||||
ByteBuffer bb = ByteBuffer.allocate(BUFFER_SIZE);
|
||||
while (isReceivingMsg) {
|
||||
try {
|
||||
long size = msgSocket.receive(bb, true);
|
||||
WxMsg wxMsg = Response.parseFrom(Arrays.copyOfRange(bb.array(), 0, (int) size)).getWxmsg();
|
||||
msgQ.put(wxMsg);
|
||||
} catch (Exception e) {
|
||||
// 多半是超时,忽略吧
|
||||
}
|
||||
}
|
||||
try {
|
||||
msgSocket.close();
|
||||
} catch (Exception e) {
|
||||
logger.error("关闭连接失败: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void enableRecvMsg(int qSize) {
|
||||
if (isReceivingMsg) {
|
||||
return;
|
||||
}
|
||||
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_ENABLE_RECV_TXT_VALUE).build();
|
||||
Response rsp = sendCmd(req);
|
||||
if (rsp == null) {
|
||||
logger.error("启动消息接收失败");
|
||||
isReceivingMsg = false;
|
||||
return;
|
||||
}
|
||||
|
||||
isReceivingMsg = true;
|
||||
msgQ = new ArrayBlockingQueue<WxMsg>(qSize);
|
||||
String msgUrl = "tcp://" + this.host + ":" + (this.port + 1);
|
||||
Thread thread = new Thread(new Runnable() {
|
||||
public void run() {
|
||||
listenMsg(msgUrl);
|
||||
}
|
||||
});
|
||||
thread.start();
|
||||
}
|
||||
|
||||
public int diableRecvMsg() {
|
||||
if (!isReceivingMsg) {
|
||||
return 1;
|
||||
}
|
||||
int ret = -1;
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_DISABLE_RECV_TXT_VALUE).build();
|
||||
Response rsp = sendCmd(req);
|
||||
if (rsp != null) {
|
||||
ret = rsp.getStatus();
|
||||
if (ret == 0) {
|
||||
isReceivingMsg = false;
|
||||
}
|
||||
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
public void waitMs(int ms) {
|
||||
try {
|
||||
Thread.sleep(ms);
|
||||
} catch (InterruptedException ex) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
public void printContacts(List<RpcContact> contacts) {
|
||||
for (RpcContact c : contacts) {
|
||||
int value = c.getGender();
|
||||
String gender;
|
||||
if (value == 1) {
|
||||
gender = "男";
|
||||
} else if (value == 2) {
|
||||
gender = "女";
|
||||
} else {
|
||||
gender = "未知";
|
||||
}
|
||||
|
||||
logger.info("{}, {}, {}, {}, {}, {}, {}", c.getWxid(), c.getName(), c.getCode(), c.getCountry(), c.getProvince(), c.getCity(), gender);
|
||||
}
|
||||
}
|
||||
|
||||
public void printWxMsg(WxMsg msg) {
|
||||
logger.info("{}[{}]:{}:{}:{}\n{}", msg.getSender(), msg.getRoomid(), msg.getId(), msg.getType(), msg.getXml().replace("\n", "").replace("\t", ""), msg.getContent());
|
||||
}
|
||||
|
||||
public String bytesToHex(byte[] bytes) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (byte b : bytes) {
|
||||
sb.append(String.format("%02x", b));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public void keepRunning() {
|
||||
while (true) {
|
||||
waitMs(1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.iamteer;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class Main {
|
||||
private static Logger logger = LoggerFactory.getLogger(Main.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
// 连接远程 RPC
|
||||
// Client client = new Client("127.0.0.1", 10086);
|
||||
|
||||
// 本地启动 RPC
|
||||
Client client = new Client(true); // 默认 10086 端口
|
||||
// Client client = new Client(10088,true); // 也可以指定端口
|
||||
|
||||
// 是否已登录
|
||||
logger.info("isLogin: {}", client.isLogin());
|
||||
|
||||
// 登录账号 wxid
|
||||
logger.info("wxid: {}", client.getSelfWxid());
|
||||
|
||||
// 消息类型
|
||||
logger.info("message types: {}", client.getMsgTypes());
|
||||
|
||||
// 所有联系人(包括群聊、公众号、好友……)
|
||||
client.printContacts(client.getContacts());
|
||||
|
||||
// 获取数据库
|
||||
logger.info("dbs: {}", client.getDbNames());
|
||||
|
||||
// 获取数据库下的表
|
||||
String db = "MicroMsg.db";
|
||||
logger.info("tables in {}: {}", db, client.getDbTables(db));
|
||||
|
||||
// 发送文本消息,aters 是要 @ 的 wxid,多个用逗号分隔;消息里@的数量要与aters里的数量对应
|
||||
client.sendText("Hello", "filehelper", "");
|
||||
// client.sendText("Hello @某人1 @某人2", "xxxxxxxx@chatroom", "wxid_xxxxxxxxxxxxx1,wxid_xxxxxxxxxxxxx2");
|
||||
|
||||
// 发送图片消息,图片必须要存在
|
||||
client.sendImage("C:\\Projs\\WeChatFerry\\TEQuant.jpeg", "filehelper");
|
||||
|
||||
// 发送文件消息,文件必须要存在
|
||||
client.sendFile("C:\\Projs\\WeChatFerry\\README.MD", "filehelper");
|
||||
|
||||
String xml = "<?xml version=\"1.0\"?><msg><appmsg appid=\"\" sdkver=\"0\"><title>叮当药房,24小时服务,28分钟送药到家!</title><des>叮当快药首家承诺范围内28分钟送药到家!叮当快药核心区域内7*24小时全天候服务,送药上门!叮当快药官网为您提供快捷便利,正品低价,安全放心的购药、送药服务体验。</des><action>view</action><type>33</type><showtype>0</showtype><content /><url>https://mp.weixin.qq.com/mp/waerrpage?appid=wxc2edadc87077fa2a&type=upgrade&upgradetype=3#wechat_redirect</url><dataurl /><lowurl /><lowdataurl /><recorditem /><thumburl /><messageaction /><md5>7f6f49d301ebf47100199b8a4fcf4de4</md5><extinfo /><sourceusername>gh_c2b88a38c424@app</sourceusername><sourcedisplayname>叮当快药 药店送药到家夜间买药</sourcedisplayname><commenturl /><appattach><totallen>0</totallen><attachid /><emoticonmd5></emoticonmd5><fileext>jpg</fileext><filekey>da0e08f5c7259d03da150d5e7ca6d950</filekey><cdnthumburl>3057020100044b30490201000204e4c0232702032f4ef20204a6bace6f02046401f62d042430326337303430352d333734332d343362652d623335322d6233333566623266376334620204012400030201000405004c537600</cdnthumburl><aeskey>0db26456caf243fbd4efb99058a01d66</aeskey><cdnthumbaeskey>0db26456caf243fbd4efb99058a01d66</cdnthumbaeskey><encryver>1</encryver><cdnthumblength>61558</cdnthumblength><cdnthumbheight>100</cdnthumbheight><cdnthumbwidth>100</cdnthumbwidth></appattach><weappinfo><pagepath>pages/index/index.html</pagepath><username>gh_c2b88a38c424@app</username><appid>wxc2edadc87077fa2a</appid><version>197</version><type>2</type><weappiconurl>http://wx.qlogo.cn/mmhead/Q3auHgzwzM4727n0NQ0ZIPQPlfp15m1WLsnrXbo1kLhFGcolgLyc0A/96</weappiconurl><appservicetype>0</appservicetype><shareId>1_wxc2edadc87077fa2a_29177e9a9b918cb9e75964f80bb8f32e_1677849476_0</shareId></weappinfo><websearch /></appmsg><fromusername>wxid_eob5qfcrv4zd22</fromusername><scene>0</scene><appinfo><version>1</version><appname /></appinfo><commenturl /></msg>";
|
||||
client.sendXml("filehelper", xml, "", 0x21);
|
||||
|
||||
// 发送表情消息,gif 必须要存在
|
||||
client.sendEmotion("C:\\Projs\\WeChatFerry\\emo.gif", "filehelper");
|
||||
|
||||
// 接收消息,并调用 printWxMsg 处理
|
||||
client.enableRecvMsg(100);
|
||||
Thread thread = new Thread(new Runnable() {
|
||||
public void run(){while(client.getIsReceivingMsg()){client.printWxMsg(client.getMsg());}}
|
||||
});
|
||||
thread.start();
|
||||
// client.diableRecvMsg(); // 需要停止时调用
|
||||
|
||||
client.keepRunning();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<!-- appender 的配置表示打印到控制台。 -->
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<!-- encoder 默认配置为 PatternLayoutEncoder -->
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="debug">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
|
||||
</configuration>
|
||||
@@ -0,0 +1,2 @@
|
||||
include wcferry/*.dll
|
||||
include wcferry/*.exe
|
||||
@@ -0,0 +1,157 @@
|
||||
# WeChatFerry Python 客户端
|
||||
[](https://pypi.python.org/pypi/wcferry) [](https://pypi.python.org/pypi/wcferry) [](https://wechatferry.readthedocs.io/zh/latest/?badge=latest)
|
||||
|
||||
|[📖 文档](https://wechatferry.readthedocs.io/)|[📺 视频教程](https://mp.weixin.qq.com/s/APdjGyZ2hllXxyG_sNCfXQ)|[🙋 FAQ](https://mp.weixin.qq.com/s/vAGpn1C9stI8Xzt1hUJhLA)|
|
||||
|:-:|:-:|:-:|
|
||||
|
||||
🤖示例机器人框架:[WeChatRobot](https://github.com/lich0821/WeChatRobot)。
|
||||
|
||||
## 快速开始
|
||||
```sh
|
||||
pip install --upgrade wcferry
|
||||
```
|
||||
|
||||
### Demo:
|
||||
```py
|
||||
#! /usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import logging
|
||||
from threading import Thread
|
||||
from time import sleep
|
||||
|
||||
from wcferry import Wcf
|
||||
|
||||
logging.basicConfig(level='DEBUG', format="%(asctime)s %(message)s")
|
||||
LOG = logging.getLogger("Demo")
|
||||
|
||||
|
||||
def process_msg(wcf: Wcf):
|
||||
"""处理接收到的消息"""
|
||||
while wcf.is_receiving_msg():
|
||||
try:
|
||||
msg = wcf.get_msg()
|
||||
except Exception as e:
|
||||
continue
|
||||
|
||||
LOG.info(msg) # 简单打印
|
||||
|
||||
|
||||
def main():
|
||||
LOG.info("Start demo...")
|
||||
wcf = Wcf(debug=True)
|
||||
|
||||
sleep(5) # 等微信加载好,以免信息显示异常
|
||||
LOG.info(f"已经登录: {True if wcf.is_login() else False}")
|
||||
LOG.info(f"wxid: {wcf.get_self_wxid()}")
|
||||
|
||||
# 允许接收消息
|
||||
# wcf.enable_recv_msg(LOG.info) # deprecated
|
||||
|
||||
# 允许接收消息
|
||||
wcf.enable_receiving_msg()
|
||||
Thread(target=process_msg, name="GetMessage", args=(wcf,), daemon=True).start()
|
||||
|
||||
# wcf.disable_recv_msg() # 当需要停止接收消息时调用
|
||||
sleep(5)
|
||||
ret = wcf.send_text("Hello world.", "filehelper")
|
||||
LOG.info(f"send_text: {ret}")
|
||||
|
||||
sleep(5)
|
||||
ret = wcf.send_image("TEQuant.jpeg", "filehelper") # 需要确保图片路径正确,建议使用绝对路径(使用双斜杠\\)
|
||||
LOG.info(f"send_image: {ret}")
|
||||
|
||||
sleep(5)
|
||||
ret = wcf.send_file("README.MD", "filehelper") # 需要确保文件路径正确,建议使用绝对路径(使用双斜杠\\)
|
||||
LOG.info(f"send_file: {ret}")
|
||||
|
||||
sleep(5)
|
||||
LOG.info(f"Message types:\n{wcf.get_msg_types()}")
|
||||
LOG.info(f"Contacts:\n{wcf.get_contacts()}")
|
||||
|
||||
sleep(5)
|
||||
LOG.info(f"DBs:\n{wcf.get_dbs()}")
|
||||
LOG.info(f"Tables:\n{wcf.get_tables('MicroMsg.db')}")
|
||||
LOG.info(f"Results:\n{wcf.query_sql('MicroMsg.db', 'SELECT * FROM Contact LIMIT 1;')}")
|
||||
|
||||
# 需要真正的 V3、V4 信息
|
||||
# wcf.accept_new_friend("v3", "v4")
|
||||
|
||||
# 添加群成员,填写正确的群 ID 和成员 wxid
|
||||
# ret = wcf.add_chatroom_members("chatroom id", "wxid1,wxid2,wxid3,...")
|
||||
# LOG.info(f"add_chatroom_members: {ret}")
|
||||
|
||||
# 删除群成员,填写正确的群 ID 和成员 wxid
|
||||
# ret = wcf.del_chatroom_members("chatroom id", "wxid1,wxid2,wxid3,...")
|
||||
# LOG.info(f"add_chatroom_members: {ret}")
|
||||
|
||||
# 一直运行
|
||||
wcf.keep_running()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
```
|
||||
|
||||
|||
|
||||
|:-:|:-:|
|
||||
|后台回复 `WeChatFerry` 加群交流|如果你觉得有用|
|
||||
|
||||
## 一起开发
|
||||
### 配置环境
|
||||
```sh
|
||||
# 创建虚拟环境
|
||||
python -m venv .env
|
||||
# 激活虚拟环境
|
||||
source .env/Scripts/activate
|
||||
# 升级 pip
|
||||
pip install --upgrade pip
|
||||
# 安装依赖包
|
||||
pip install grpcio-tools pynng
|
||||
```
|
||||
|
||||
### 重新生成 PB 文件
|
||||
```sh
|
||||
# CMD
|
||||
cd python\wcferry
|
||||
python -m grpc_tools.protoc --python_out=. --proto_path=..\..\rpc\proto\ wcf.proto
|
||||
|
||||
# GitBash
|
||||
cd python/wcferry
|
||||
python -m grpc_tools.protoc --python_out=. --proto_path=../../rpc/proto/ wcf.proto
|
||||
```
|
||||
|
||||
## 版本更新
|
||||
版本号:`w.x.y.z`。
|
||||
|
||||
其中:
|
||||
* `w` 是微信的大版本号,如 `37` (3.7.a.a), `38` (3.8.a.a), `39` (3.9.a.a)
|
||||
* `x` 是适配的微信的小版本号,从 0 开始
|
||||
* `y` 是 `WeChatFerry` 的版本,从 0 开始
|
||||
* `z` 是各客户端的版本,从 0 开始
|
||||
|
||||
### 39.0.0.1 (2023.07.15)
|
||||
修复不能 @ 问题。
|
||||
|
||||
功能:
|
||||
|
||||
* 检查登录状态
|
||||
* 获取登录账号的 wxid
|
||||
* 获取消息类型
|
||||
* 获取所有联系人
|
||||
* 获取所有好友
|
||||
* 获取数据库
|
||||
* 获取某数据库下的表
|
||||
* 获取用户信息
|
||||
* 发送文本消息(可 @)
|
||||
* 发送图片(Python 客户端支持网络路径)
|
||||
* 发送文件
|
||||
* 允许接收消息
|
||||
* 停止接收消息
|
||||
* 执行 SQL 查询
|
||||
* 接受好友申请
|
||||
* 添加群成员
|
||||
* 删除群成员
|
||||
* 解密图片
|
||||
* 某功能(Breaking Change)
|
||||
@@ -0,0 +1,79 @@
|
||||
#! /usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import logging
|
||||
from threading import Thread
|
||||
from time import sleep
|
||||
|
||||
from wcferry import Wcf
|
||||
|
||||
logging.basicConfig(level='DEBUG', format="%(asctime)s %(message)s")
|
||||
LOG = logging.getLogger("Demo")
|
||||
|
||||
|
||||
def process_msg(wcf: Wcf):
|
||||
"""处理接收到的消息"""
|
||||
while wcf.is_receiving_msg():
|
||||
try:
|
||||
msg = wcf.get_msg()
|
||||
except Exception as e:
|
||||
continue
|
||||
|
||||
LOG.info(msg) # 简单打印
|
||||
|
||||
|
||||
def main():
|
||||
LOG.info("Start demo...")
|
||||
wcf = Wcf(debug=True) # 默认连接本地服务
|
||||
# wcf = Wcf("tcp://127.0.0.1:10086") # 连接远端服务
|
||||
|
||||
sleep(5) # 等微信加载好,以免信息显示异常
|
||||
LOG.info(f"已经登录: {True if wcf.is_login() else False}")
|
||||
LOG.info(f"wxid: {wcf.get_self_wxid()}")
|
||||
|
||||
# 允许接收消息
|
||||
# wcf.enable_recv_msg(LOG.info) # deprecated
|
||||
|
||||
# 允许接收消息
|
||||
wcf.enable_receiving_msg()
|
||||
Thread(target=process_msg, name="GetMessage", args=(wcf,), daemon=True).start()
|
||||
|
||||
# wcf.disable_recv_msg() # 当需要停止接收消息时调用
|
||||
sleep(5)
|
||||
ret = wcf.send_text("Hello world.", "filehelper")
|
||||
LOG.info(f"send_text: {ret}")
|
||||
|
||||
sleep(5)
|
||||
ret = wcf.send_image("TEQuant.jpeg", "filehelper") # 需要确保图片路径正确,建议使用绝对路径(使用双斜杠\\)
|
||||
LOG.info(f"send_image: {ret}")
|
||||
|
||||
sleep(5)
|
||||
ret = wcf.send_file("README.MD", "filehelper") # 需要确保文件路径正确,建议使用绝对路径(使用双斜杠\\)
|
||||
LOG.info(f"send_file: {ret}")
|
||||
|
||||
sleep(5)
|
||||
LOG.info(f"Message types:\n{wcf.get_msg_types()}")
|
||||
LOG.info(f"Contacts:\n{wcf.get_contacts()}")
|
||||
|
||||
sleep(5)
|
||||
LOG.info(f"DBs:\n{wcf.get_dbs()}")
|
||||
LOG.info(f"Tables:\n{wcf.get_tables('db')}")
|
||||
LOG.info(f"Results:\n{wcf.query_sql('MicroMsg.db', 'SELECT * FROM Contact LIMIT 1;')}")
|
||||
|
||||
# 需要真正的 V3、V4 信息
|
||||
# wcf.accept_new_friend("v3", "v4")
|
||||
|
||||
# 添加群成员,填写正确的群 ID 和成员 wxid
|
||||
# ret = wcf.add_chatroom_members("chatroom id", "wxid1,wxid2,wxid3,...")
|
||||
# LOG.info(f"add_chatroom_members: {ret}")
|
||||
|
||||
# 删除群成员,填写正确的群 ID 和成员 wxid
|
||||
# ret = wcf.del_chatroom_members("chatroom id", "wxid1,wxid2,wxid3,...")
|
||||
# LOG.info(f"add_chatroom_members: {ret}")
|
||||
|
||||
# 一直运行
|
||||
wcf.keep_running()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,45 @@
|
||||
#! /usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
|
||||
from __future__ import print_function
|
||||
from setuptools import setup, find_packages
|
||||
|
||||
import wcferry
|
||||
|
||||
with open("README.md", "r", encoding="utf-8") as fh:
|
||||
long_description = fh.read()
|
||||
|
||||
|
||||
setup(
|
||||
name="wcferry",
|
||||
version=wcferry.__version__,
|
||||
author="Changhua",
|
||||
author_email="lichanghua0821@gmail.com",
|
||||
description="一个玩微信的工具",
|
||||
long_description=long_description,
|
||||
long_description_content_type="text/markdown",
|
||||
license="MIT",
|
||||
url="https://github.com/lich0821/WeChatFerry",
|
||||
python_requires=">=3.8",
|
||||
packages=find_packages(),
|
||||
include_package_data=True,
|
||||
install_requires=[
|
||||
"setuptools",
|
||||
"grpcio-tools",
|
||||
"pynng",
|
||||
"requests",
|
||||
],
|
||||
classifiers=[
|
||||
"Environment :: Win32 (MS Windows)",
|
||||
"Intended Audience :: Developers",
|
||||
"Intended Audience :: Customer Service",
|
||||
"Topic :: Communications :: Chat",
|
||||
"Operating System :: Microsoft :: Windows",
|
||||
"Programming Language :: Python",
|
||||
],
|
||||
project_urls={
|
||||
"Documentation": "https://wechatferry.readthedocs.io/zh/latest/index.html",
|
||||
"GitHub": "https://github.com/lich0821/WeChatFerry/",
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,4 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from wcferry.client import Wcf, __version__
|
||||
from wcferry.wxmsg import WxMsg
|
||||
@@ -0,0 +1,578 @@
|
||||
#! /usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
__version__ = "39.0.0.1"
|
||||
|
||||
import atexit
|
||||
import base64
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from queue import Queue
|
||||
from threading import Thread
|
||||
from time import sleep
|
||||
from typing import Callable, List, Optional
|
||||
|
||||
import pynng
|
||||
import requests
|
||||
from google.protobuf import json_format
|
||||
from wcferry import wcf_pb2
|
||||
from wcferry.wxmsg import WxMsg
|
||||
|
||||
|
||||
def _retry():
|
||||
def decorator(func):
|
||||
""" Retry the function """
|
||||
def wrapper(*args, **kwargs):
|
||||
def logerror(e):
|
||||
func_name = re.findall(r"func: (.*?)\n", str(args[1]))[-1]
|
||||
logging.getLogger("WCF").error(f"Call {func_name} failed: {e}")
|
||||
|
||||
try:
|
||||
ret = func(*args, **kwargs)
|
||||
except pynng.Timeout as _: # 如果超时,重试
|
||||
try:
|
||||
ret = func(*args, **kwargs)
|
||||
except Exception as e:
|
||||
logerror(e)
|
||||
ret = wcf_pb2.Response()
|
||||
except Exception as e: # 其他异常,退出
|
||||
logerror(e)
|
||||
sys.exit(-1)
|
||||
|
||||
return ret
|
||||
return wrapper
|
||||
return decorator
|
||||
|
||||
|
||||
class Wcf():
|
||||
"""WeChatFerry, 一个玩微信的工具。
|
||||
|
||||
Args:
|
||||
host (str): `wcferry` RPC 服务器地址,默认本地启动;也可以指定地址连接远程服务
|
||||
port (int): `wcferry` RPC 服务器端口,默认为 10086,接收消息会占用 `port+1` 端口
|
||||
debug (bool): 是否开启调试模式(仅本地启动有效)
|
||||
|
||||
Attributes:
|
||||
contacts (list): 联系人缓存,调用 `get_contacts` 后更新
|
||||
self_wxid (str): 登录账号 wxid
|
||||
"""
|
||||
|
||||
def __init__(self, host: str = None, port: int = 10086, debug: bool = True) -> None:
|
||||
self._local_mode = False
|
||||
self._is_running = False
|
||||
self._is_receiving_msg = False
|
||||
self._wcf_root = os.path.abspath(os.path.dirname(__file__))
|
||||
self.LOG = logging.getLogger("WCF")
|
||||
self.LOG.info(f"wcferry version: {__version__}")
|
||||
self.port = port
|
||||
self.host = host
|
||||
if host is None:
|
||||
self._local_mode = True
|
||||
self.host = "127.0.0.1"
|
||||
cmd = fr'"{self._wcf_root}\wcf.exe" start {self.port} {"debug" if debug else ""}'
|
||||
if os.system(cmd) != 0:
|
||||
self.LOG.error("初始化失败!")
|
||||
os._exit(-1)
|
||||
|
||||
self.cmd_url = f"tcp://{self.host}:{self.port}"
|
||||
|
||||
# 连接 RPC
|
||||
self.cmd_socket = pynng.Pair1() # Client --> Server,发送消息
|
||||
self.cmd_socket.send_timeout = 2000 # 发送 2 秒超时
|
||||
self.cmd_socket.recv_timeout = 2000 # 接收 2 秒超时
|
||||
try:
|
||||
self.cmd_socket.dial(self.cmd_url, block=True)
|
||||
except Exception as e:
|
||||
self.LOG.error(f"连接失败: {e}")
|
||||
os._exit(-2)
|
||||
|
||||
self.msg_socket = pynng.Pair1() # Server --> Client,接收消息
|
||||
self.msg_socket.send_timeout = 2000 # 发送 2 秒超时
|
||||
self.msg_socket.recv_timeout = 2000 # 接收 2 秒超时
|
||||
self.msg_url = self.cmd_url.replace(str(self.port), str(self.port + 1))
|
||||
|
||||
atexit.register(self.cleanup) # 退出的时候停止消息接收,防止资源占用
|
||||
while not self.is_login(): # 等待微信登录成功
|
||||
sleep(1)
|
||||
|
||||
self._is_running = True
|
||||
self.contacts = []
|
||||
self.msgQ = Queue()
|
||||
self._SQL_TYPES = {1: int, 2: float, 3: lambda x: x.decode("utf-8"), 4: bytes, 5: lambda x: None}
|
||||
self.self_wxid = self.get_self_wxid()
|
||||
|
||||
def __del__(self) -> None:
|
||||
self.cleanup()
|
||||
|
||||
def cleanup(self) -> None:
|
||||
"""关闭连接,回收资源"""
|
||||
if not self._is_running:
|
||||
return
|
||||
|
||||
self.disable_recv_msg()
|
||||
self.cmd_socket.close()
|
||||
|
||||
if self._local_mode:
|
||||
cmd = fr'"{self._wcf_root}\wcf.exe" stop'
|
||||
if os.system(cmd) != 0:
|
||||
self.LOG.error("退出失败!")
|
||||
return
|
||||
self._is_running = False
|
||||
|
||||
def keep_running(self):
|
||||
"""阻塞进程,让 RPC 一直维持连接"""
|
||||
try:
|
||||
while True:
|
||||
sleep(1)
|
||||
except Exception as e:
|
||||
self.cleanup()
|
||||
|
||||
@_retry()
|
||||
def _send_request(self, req: wcf_pb2.Request) -> wcf_pb2.Response:
|
||||
data = req.SerializeToString()
|
||||
self.cmd_socket.send(data)
|
||||
rsp = wcf_pb2.Response()
|
||||
rsp.ParseFromString(self.cmd_socket.recv_msg().bytes)
|
||||
return rsp
|
||||
|
||||
def is_receiving_msg(self) -> bool:
|
||||
"""是否已启动接收消息功能"""
|
||||
return self._is_receiving_msg
|
||||
|
||||
def is_login(self) -> bool:
|
||||
"""是否已经登录"""
|
||||
req = wcf_pb2.Request()
|
||||
req.func = wcf_pb2.FUNC_IS_LOGIN # FUNC_IS_LOGIN
|
||||
rsp = self._send_request(req)
|
||||
|
||||
return rsp.status == 1
|
||||
|
||||
def get_self_wxid(self) -> str:
|
||||
"""获取登录账户的 wxid"""
|
||||
req = wcf_pb2.Request()
|
||||
req.func = wcf_pb2.FUNC_GET_SELF_WXID # FUNC_GET_SELF_WXID
|
||||
rsp = self._send_request(req)
|
||||
|
||||
return rsp.str
|
||||
|
||||
def get_msg_types(self) -> dict:
|
||||
"""获取所有消息类型"""
|
||||
req = wcf_pb2.Request()
|
||||
req.func = wcf_pb2.FUNC_GET_MSG_TYPES # FUNC_GET_MSG_TYPES
|
||||
rsp = self._send_request(req)
|
||||
types = json_format.MessageToDict(rsp.types).get("types", {})
|
||||
types = {int(k): v for k, v in types.items()}
|
||||
|
||||
return dict(sorted(dict(types).items()))
|
||||
|
||||
def get_contacts(self) -> List[dict]:
|
||||
"""获取完整通讯录"""
|
||||
req = wcf_pb2.Request()
|
||||
req.func = wcf_pb2.FUNC_GET_CONTACTS # FUNC_GET_CONTACTS
|
||||
rsp = self._send_request(req)
|
||||
contacts = json_format.MessageToDict(rsp.contacts).get("contacts", [])
|
||||
|
||||
self.contacts.clear()
|
||||
for cnt in contacts:
|
||||
gender = cnt.get("gender", "")
|
||||
if gender == 1:
|
||||
gender = "男"
|
||||
elif gender == 2:
|
||||
gender = "女"
|
||||
else:
|
||||
gender = ""
|
||||
contact = {
|
||||
"wxid": cnt.get("wxid", ""),
|
||||
"code": cnt.get("code", ""),
|
||||
"remark": cnt.get("remark", ""),
|
||||
"name": cnt.get("name", ""),
|
||||
"country": cnt.get("country", ""),
|
||||
"province": cnt.get("province", ""),
|
||||
"city": cnt.get("city", ""),
|
||||
"gender": gender}
|
||||
self.contacts.append(contact)
|
||||
return self.contacts
|
||||
|
||||
def get_dbs(self) -> List[str]:
|
||||
"""获取所有数据库"""
|
||||
req = wcf_pb2.Request()
|
||||
req.func = wcf_pb2.FUNC_GET_DB_NAMES # FUNC_GET_DB_NAMES
|
||||
rsp = self._send_request(req)
|
||||
dbs = json_format.MessageToDict(rsp.dbs).get("names", [])
|
||||
|
||||
return dbs
|
||||
|
||||
def get_tables(self, db: str) -> List[dict]:
|
||||
"""获取 db 中所有表
|
||||
|
||||
Args:
|
||||
db (str): 数据库名(可通过 `get_dbs` 查询)
|
||||
|
||||
Returns:
|
||||
List[dict]: `db` 下的所有表名及对应建表语句
|
||||
"""
|
||||
req = wcf_pb2.Request()
|
||||
req.func = wcf_pb2.FUNC_GET_DB_TABLES # FUNC_GET_DB_TABLES
|
||||
req.str = db
|
||||
rsp = self._send_request(req)
|
||||
tables = json_format.MessageToDict(rsp.tables).get("tables", [])
|
||||
|
||||
return tables
|
||||
|
||||
def get_user_info(self) -> dict:
|
||||
"""获取登录账号个人信息"""
|
||||
req = wcf_pb2.Request()
|
||||
req.func = wcf_pb2.FUNC_GET_USER_INFO # FUNC_GET_USER_INFO
|
||||
rsp = self._send_request(req)
|
||||
ui = json_format.MessageToDict(rsp.ui)
|
||||
|
||||
return ui
|
||||
|
||||
def send_text(self, msg: str, receiver: str, aters: Optional[str] = "") -> int:
|
||||
"""发送文本消息
|
||||
|
||||
Args:
|
||||
msg (str): 要发送的消息,换行使用 `\\n`;如果 @ 人的话,需要带上跟 `aters` 里数量相同的 @
|
||||
receiver (str): 消息接收人,wxid 或者 roomid
|
||||
aters (str): 要 @ 的 wxid,多个用逗号分隔;`@所有人` 只需要 `notify@all`
|
||||
|
||||
Returns:
|
||||
int: 0 为成功,其他失败
|
||||
"""
|
||||
req = wcf_pb2.Request()
|
||||
req.func = wcf_pb2.FUNC_SEND_TXT # FUNC_SEND_TXT
|
||||
req.txt.msg = msg
|
||||
req.txt.receiver = receiver
|
||||
if aters:
|
||||
req.txt.aters = aters
|
||||
rsp = self._send_request(req)
|
||||
return rsp.status
|
||||
|
||||
def send_image(self, path: str, receiver: str) -> int:
|
||||
"""发送图片,非线程安全
|
||||
|
||||
Args:
|
||||
path (str): 图片路径,如:`C:/Projs/WeChatRobot/TEQuant.jpeg` 或 `https://raw.githubusercontent.com/lich0821/WeChatRobot/master/TEQuant.jpeg`
|
||||
receiver (str): 消息接收人,wxid 或者 roomid
|
||||
|
||||
Returns:
|
||||
int: 0 为成功,其他失败
|
||||
"""
|
||||
if path.startswith("http"):
|
||||
if not self._local_mode:
|
||||
self.LOG.error(f"只有本地模式才支持网络路径!")
|
||||
return -1
|
||||
try:
|
||||
headers = {
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36', }
|
||||
response = requests.get(path, headers=headers, stream=True)
|
||||
response.raw.decode_content = True
|
||||
|
||||
# 保存图片,不删除,等下次覆盖
|
||||
with open(f"{self._wcf_root}/.tmp.jpg", "wb") as of:
|
||||
of.write(response.content)
|
||||
|
||||
path = f"{self._wcf_root}/.tmp.jpg"
|
||||
except Exception as e:
|
||||
self.LOG.error(e)
|
||||
return -1
|
||||
|
||||
req = wcf_pb2.Request()
|
||||
req.func = wcf_pb2.FUNC_SEND_IMG # FUNC_SEND_IMG
|
||||
req.file.path = path
|
||||
req.file.receiver = receiver
|
||||
rsp = self._send_request(req)
|
||||
return rsp.status
|
||||
|
||||
def send_file(self, path: str, receiver: str) -> int:
|
||||
"""发送文件
|
||||
|
||||
Args:
|
||||
path (str): 本地文件路径,如:`C:/Projs/WeChatRobot/README.MD`
|
||||
receiver (str): 消息接收人,wxid 或者 roomid
|
||||
|
||||
Returns:
|
||||
int: 0 为成功,其他失败
|
||||
"""
|
||||
req = wcf_pb2.Request()
|
||||
req.func = wcf_pb2.FUNC_SEND_FILE # FUNC_SEND_FILE
|
||||
req.file.path = path
|
||||
req.file.receiver = receiver
|
||||
rsp = self._send_request(req)
|
||||
return rsp.status
|
||||
|
||||
def send_xml(self, receiver: str, xml: str, type: int, path: str = None) -> int:
|
||||
"""发送 XML
|
||||
|
||||
Args:
|
||||
receiver (str): 消息接收人,wxid 或者 roomid
|
||||
xml (str): xml 内容
|
||||
type (int): xml 类型,如:0x21 为小程序
|
||||
path (str): 封面图片路径
|
||||
|
||||
Returns:
|
||||
int: 0 为成功,其他失败
|
||||
"""
|
||||
raise Exception("Not implemented, yet")
|
||||
req = wcf_pb2.Request()
|
||||
req.func = wcf_pb2.FUNC_SEND_XML # FUNC_SEND_XML
|
||||
req.xml.receiver = receiver
|
||||
req.xml.content = xml
|
||||
req.xml.type = type
|
||||
if path:
|
||||
req.xml.path = path
|
||||
rsp = self._send_request(req)
|
||||
return rsp.status
|
||||
|
||||
def send_emotion(self, path: str, receiver: str) -> int:
|
||||
"""发送表情
|
||||
|
||||
Args:
|
||||
path (str): 本地表情路径,如:`C:/Projs/WeChatRobot/emo.gif`
|
||||
receiver (str): 消息接收人,wxid 或者 roomid
|
||||
|
||||
Returns:
|
||||
int: 0 为成功,其他失败
|
||||
"""
|
||||
raise Exception("Not implemented, yet")
|
||||
req = wcf_pb2.Request()
|
||||
req.func = wcf_pb2.FUNC_SEND_EMOTION # FUNC_SEND_EMOTION
|
||||
req.file.path = path
|
||||
req.file.receiver = receiver
|
||||
rsp = self._send_request(req)
|
||||
return rsp.status
|
||||
|
||||
def get_msg(self, block=True) -> WxMsg:
|
||||
"""从消息队列中获取消息
|
||||
|
||||
Args:
|
||||
block (bool): 是否阻塞,默认阻塞
|
||||
|
||||
Returns:
|
||||
WxMsg: 微信消息
|
||||
|
||||
Raises:
|
||||
Empty: 如果阻塞并且超时,抛出空异常,需要用户自行捕获
|
||||
"""
|
||||
return self.msgQ.get(block, timeout=1)
|
||||
|
||||
def enable_receiving_msg(self) -> bool:
|
||||
"""允许接收消息,成功后通过 `get_msg` 读取消息"""
|
||||
def listening_msg():
|
||||
rsp = wcf_pb2.Response()
|
||||
self.msg_socket.dial(self.msg_url, block=True)
|
||||
while self._is_receiving_msg:
|
||||
try:
|
||||
rsp.ParseFromString(self.msg_socket.recv_msg().bytes)
|
||||
except Exception as e:
|
||||
pass
|
||||
else:
|
||||
self.msgQ.put(WxMsg(rsp.wxmsg))
|
||||
|
||||
# 退出前关闭通信通道
|
||||
self.msg_socket.close()
|
||||
|
||||
if self._is_receiving_msg:
|
||||
return True
|
||||
|
||||
req = wcf_pb2.Request()
|
||||
req.func = wcf_pb2.FUNC_ENABLE_RECV_TXT # FUNC_ENABLE_RECV_TXT
|
||||
rsp = self._send_request(req)
|
||||
if rsp.status != 0:
|
||||
return False
|
||||
|
||||
self._is_receiving_msg = True
|
||||
# 阻塞,把控制权交给用户
|
||||
# self._rpc_get_message(callback)
|
||||
|
||||
# 不阻塞,启动一个新的线程来接收消息
|
||||
Thread(target=listening_msg, name="GetMessage", daemon=True).start()
|
||||
|
||||
return True
|
||||
|
||||
def enable_recv_msg(self, callback: Callable[[WxMsg], None] = None) -> bool:
|
||||
"""(不建议使用)设置接收消息回调,消息量大时可能会丢失消息
|
||||
|
||||
.. deprecated:: 3.7.0.30.13
|
||||
"""
|
||||
def listening_msg():
|
||||
rsp = wcf_pb2.Response()
|
||||
self.msg_socket.dial(self.msg_url, block=True)
|
||||
while self._is_receiving_msg:
|
||||
try:
|
||||
rsp.ParseFromString(self.msg_socket.recv_msg().bytes)
|
||||
except Exception as e:
|
||||
pass
|
||||
else:
|
||||
callback(WxMsg(rsp.wxmsg))
|
||||
# 退出前关闭通信通道
|
||||
self.msg_socket.close()
|
||||
|
||||
if self._is_receiving_msg:
|
||||
return True
|
||||
|
||||
if callback is None:
|
||||
return False
|
||||
|
||||
req = wcf_pb2.Request()
|
||||
req.func = wcf_pb2.FUNC_ENABLE_RECV_TXT # FUNC_ENABLE_RECV_TXT
|
||||
rsp = self._send_request(req)
|
||||
if rsp.status != 0:
|
||||
return False
|
||||
|
||||
self._is_receiving_msg = True
|
||||
# 阻塞,把控制权交给用户
|
||||
# listening_msg()
|
||||
|
||||
# 不阻塞,启动一个新的线程来接收消息
|
||||
Thread(target=listening_msg, name="GetMessage", daemon=True).start()
|
||||
|
||||
return True
|
||||
|
||||
def disable_recv_msg(self) -> int:
|
||||
"""停止接收消息"""
|
||||
if not self._is_receiving_msg:
|
||||
return 0
|
||||
|
||||
req = wcf_pb2.Request()
|
||||
req.func = wcf_pb2.FUNC_DISABLE_RECV_TXT # FUNC_DISABLE_RECV_TXT
|
||||
rsp = self._send_request(req)
|
||||
self._is_receiving_msg = False
|
||||
|
||||
return rsp.status
|
||||
|
||||
def query_sql(self, db: str, sql: str) -> List[dict]:
|
||||
"""执行 SQL,如果数据量大注意分页,以免 OOM
|
||||
|
||||
Args:
|
||||
db (str): 要查询的数据库
|
||||
sql (str): 要执行的 SQL
|
||||
|
||||
Returns:
|
||||
List[dict]: 查询结果
|
||||
"""
|
||||
result = []
|
||||
req = wcf_pb2.Request()
|
||||
req.func = wcf_pb2.FUNC_EXEC_DB_QUERY # FUNC_EXEC_DB_QUERY
|
||||
req.query.db = db
|
||||
req.query.sql = sql
|
||||
rsp = self._send_request(req)
|
||||
rows = json_format.MessageToDict(rsp.rows).get("rows", [])
|
||||
for r in rows:
|
||||
row = {}
|
||||
for f in r["fields"]:
|
||||
c = base64.b64decode(f.get("content", ""))
|
||||
row[f["column"]] = self._SQL_TYPES[f["type"]](c)
|
||||
result.append(row)
|
||||
return result
|
||||
|
||||
def accept_new_friend(self, v3: str, v4: str, scene: int = 30) -> int:
|
||||
"""通过好友申请
|
||||
|
||||
Args:
|
||||
v3 (str): 加密用户名 (好友申请消息里 v3 开头的字符串)
|
||||
v4 (str): Ticket (好友申请消息里 v4 开头的字符串)
|
||||
scene: 申请方式 (好友申请消息里的 scene); 为了兼容旧接口,默认为扫码添加 (30)
|
||||
|
||||
Returns:
|
||||
int: 1 为成功,其他失败
|
||||
"""
|
||||
req = wcf_pb2.Request()
|
||||
req.func = wcf_pb2.FUNC_ACCEPT_FRIEND # FUNC_ACCEPT_FRIEND
|
||||
req.v.v3 = v3
|
||||
req.v.v4 = v4
|
||||
req.v.scene = scene
|
||||
rsp = self._send_request(req)
|
||||
return rsp.status
|
||||
|
||||
def get_friends(self) -> List[dict]:
|
||||
"""获取好友列表"""
|
||||
not_friends = {
|
||||
"fmessage": "朋友推荐消息",
|
||||
"medianote": "语音记事本",
|
||||
"floatbottle": "漂流瓶",
|
||||
"filehelper": "文件传输助手",
|
||||
"newsapp": "新闻",
|
||||
}
|
||||
friends = []
|
||||
for cnt in self.get_contacts():
|
||||
if (cnt["wxid"].endswith("@chatroom") # 群聊
|
||||
or cnt["wxid"].startswith("gh_") # 公众号
|
||||
or cnt["wxid"] in not_friends.keys() # 其他杂号
|
||||
):
|
||||
continue
|
||||
friends.append(cnt)
|
||||
|
||||
return friends
|
||||
|
||||
def receive_transfer(self, wxid: str, transferid: str, transactionid: str) -> int:
|
||||
"""接收转账
|
||||
|
||||
Args:
|
||||
wxid (str): 转账消息里的发送人 wxid
|
||||
transferid (str): 转账消息里的 transferid
|
||||
transactionid (str): 转账消息里的 transactionid
|
||||
|
||||
Returns:
|
||||
int: 1 为成功,其他失败
|
||||
"""
|
||||
req = wcf_pb2.Request()
|
||||
req.func = wcf_pb2.FUNC_RECV_TRANSFER # FUNC_RECV_TRANSFER
|
||||
req.tf.wxid = wxid
|
||||
req.tf.tfid = transferid
|
||||
req.tf.taid = transactionid
|
||||
rsp = self._send_request(req)
|
||||
return rsp.status
|
||||
|
||||
def decrypt_image(self, src: str, dst: str) -> bool:
|
||||
"""解密图片:
|
||||
|
||||
Args:
|
||||
src (str): 加密的图片路径
|
||||
dst (str): 解密的图片路径
|
||||
|
||||
Returns:
|
||||
bool: 是否成功
|
||||
"""
|
||||
req = wcf_pb2.Request()
|
||||
req.func = wcf_pb2.FUNC_DECRYPT_IMAGE # FUNC_DECRYPT_IMAGE
|
||||
req.dec.src = src
|
||||
req.dec.dst = dst
|
||||
rsp = self._send_request(req)
|
||||
return rsp.status == 1
|
||||
|
||||
def add_chatroom_members(self, roomid: str, wxids: str) -> int:
|
||||
"""添加群成员
|
||||
|
||||
Args:
|
||||
roomid (str): 待加群的 id
|
||||
wxids (str): 要加到群里的 wxid,多个用逗号分隔
|
||||
|
||||
Returns:
|
||||
int: 1 为成功,其他失败
|
||||
"""
|
||||
req = wcf_pb2.Request()
|
||||
req.func = wcf_pb2.FUNC_ADD_ROOM_MEMBERS # FUNC_ADD_ROOM_MEMBERS
|
||||
req.m.roomid = roomid
|
||||
req.m.wxids = wxids
|
||||
rsp = self._send_request(req)
|
||||
return rsp.status
|
||||
|
||||
def del_chatroom_members(self, roomid: str, wxids: str) -> int:
|
||||
"""删除群成员
|
||||
|
||||
Args:
|
||||
roomid (str): 群的 id
|
||||
wxids (str): 要删除成员的 wxid,多个用逗号分隔
|
||||
|
||||
Returns:
|
||||
int: 1 为成功,其他失败
|
||||
"""
|
||||
req = wcf_pb2.Request()
|
||||
req.func = wcf_pb2.FUNC_DEL_ROOM_MEMBERS # FUNC_DEL_ROOM_MEMBERS
|
||||
req.m.roomid = roomid
|
||||
req.m.wxids = wxids.replace(" ", "")
|
||||
rsp = self._send_request(req)
|
||||
return rsp.status
|
||||
@@ -0,0 +1,74 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Generated by the protocol buffer compiler. DO NOT EDIT!
|
||||
# source: wcf.proto
|
||||
"""Generated protocol buffer code."""
|
||||
from google.protobuf.internal import builder as _builder
|
||||
from google.protobuf import descriptor as _descriptor
|
||||
from google.protobuf import descriptor_pool as _descriptor_pool
|
||||
from google.protobuf import symbol_database as _symbol_database
|
||||
# @@protoc_insertion_point(imports)
|
||||
|
||||
_sym_db = _symbol_database.Default()
|
||||
|
||||
|
||||
|
||||
|
||||
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\twcf.proto\x12\x03wcf\"\xc8\x02\n\x07Request\x12\x1c\n\x04\x66unc\x18\x01 \x01(\x0e\x32\x0e.wcf.Functions\x12\x1b\n\x05\x65mpty\x18\x02 \x01(\x0b\x32\n.wcf.EmptyH\x00\x12\r\n\x03str\x18\x03 \x01(\tH\x00\x12\x1b\n\x03txt\x18\x04 \x01(\x0b\x32\x0c.wcf.TextMsgH\x00\x12\x1c\n\x04\x66ile\x18\x05 \x01(\x0b\x32\x0c.wcf.PathMsgH\x00\x12\x1d\n\x05query\x18\x06 \x01(\x0b\x32\x0c.wcf.DbQueryH\x00\x12\x1e\n\x01v\x18\x07 \x01(\x0b\x32\x11.wcf.VerificationH\x00\x12\x1c\n\x01m\x18\x08 \x01(\x0b\x32\x0f.wcf.AddMembersH\x00\x12\x1a\n\x03xml\x18\t \x01(\x0b\x32\x0b.wcf.XmlMsgH\x00\x12\x1b\n\x03\x64\x65\x63\x18\n \x01(\x0b\x32\x0c.wcf.DecPathH\x00\x12\x1b\n\x02tf\x18\x0b \x01(\x0b\x32\r.wcf.TransferH\x00\x42\x05\n\x03msg\"\xab\x02\n\x08Response\x12\x1c\n\x04\x66unc\x18\x01 \x01(\x0e\x32\x0e.wcf.Functions\x12\x10\n\x06status\x18\x02 \x01(\x05H\x00\x12\r\n\x03str\x18\x03 \x01(\tH\x00\x12\x1b\n\x05wxmsg\x18\x04 \x01(\x0b\x32\n.wcf.WxMsgH\x00\x12\x1e\n\x05types\x18\x05 \x01(\x0b\x32\r.wcf.MsgTypesH\x00\x12$\n\x08\x63ontacts\x18\x06 \x01(\x0b\x32\x10.wcf.RpcContactsH\x00\x12\x1b\n\x03\x64\x62s\x18\x07 \x01(\x0b\x32\x0c.wcf.DbNamesH\x00\x12\x1f\n\x06tables\x18\x08 \x01(\x0b\x32\r.wcf.DbTablesH\x00\x12\x1b\n\x04rows\x18\t \x01(\x0b\x32\x0b.wcf.DbRowsH\x00\x12\x1b\n\x02ui\x18\n \x01(\x0b\x32\r.wcf.UserInfoH\x00\x42\x05\n\x03msg\"\x07\n\x05\x45mpty\"\xa0\x01\n\x05WxMsg\x12\x0f\n\x07is_self\x18\x01 \x01(\x08\x12\x10\n\x08is_group\x18\x02 \x01(\x08\x12\x0c\n\x04type\x18\x03 \x01(\x05\x12\n\n\x02id\x18\x04 \x01(\t\x12\x0b\n\x03xml\x18\x05 \x01(\t\x12\x0e\n\x06sender\x18\x06 \x01(\t\x12\x0e\n\x06roomid\x18\x07 \x01(\t\x12\x0f\n\x07\x63ontent\x18\x08 \x01(\t\x12\r\n\x05thumb\x18\t \x01(\t\x12\r\n\x05\x65xtra\x18\n \x01(\t\"7\n\x07TextMsg\x12\x0b\n\x03msg\x18\x01 \x01(\t\x12\x10\n\x08receiver\x18\x02 \x01(\t\x12\r\n\x05\x61ters\x18\x03 \x01(\t\")\n\x07PathMsg\x12\x0c\n\x04path\x18\x01 \x01(\t\x12\x10\n\x08receiver\x18\x02 \x01(\t\"G\n\x06XmlMsg\x12\x10\n\x08receiver\x18\x01 \x01(\t\x12\x0f\n\x07\x63ontent\x18\x02 \x01(\t\x12\x0c\n\x04path\x18\x03 \x01(\t\x12\x0c\n\x04type\x18\x04 \x01(\x05\"a\n\x08MsgTypes\x12\'\n\x05types\x18\x01 \x03(\x0b\x32\x18.wcf.MsgTypes.TypesEntry\x1a,\n\nTypesEntry\x12\x0b\n\x03key\x18\x01 \x01(\x05\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x87\x01\n\nRpcContact\x12\x0c\n\x04wxid\x18\x01 \x01(\t\x12\x0c\n\x04\x63ode\x18\x02 \x01(\t\x12\x0e\n\x06remark\x18\x03 \x01(\t\x12\x0c\n\x04name\x18\x04 \x01(\t\x12\x0f\n\x07\x63ountry\x18\x05 \x01(\t\x12\x10\n\x08province\x18\x06 \x01(\t\x12\x0c\n\x04\x63ity\x18\x07 \x01(\t\x12\x0e\n\x06gender\x18\x08 \x01(\x05\"0\n\x0bRpcContacts\x12!\n\x08\x63ontacts\x18\x01 \x03(\x0b\x32\x0f.wcf.RpcContact\"\x18\n\x07\x44\x62Names\x12\r\n\x05names\x18\x01 \x03(\t\"$\n\x07\x44\x62Table\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0b\n\x03sql\x18\x02 \x01(\t\"(\n\x08\x44\x62Tables\x12\x1c\n\x06tables\x18\x01 \x03(\x0b\x32\x0c.wcf.DbTable\"\"\n\x07\x44\x62Query\x12\n\n\x02\x64\x62\x18\x01 \x01(\t\x12\x0b\n\x03sql\x18\x02 \x01(\t\"8\n\x07\x44\x62\x46ield\x12\x0c\n\x04type\x18\x01 \x01(\x05\x12\x0e\n\x06\x63olumn\x18\x02 \x01(\t\x12\x0f\n\x07\x63ontent\x18\x03 \x01(\x0c\"%\n\x05\x44\x62Row\x12\x1c\n\x06\x66ields\x18\x01 \x03(\x0b\x32\x0c.wcf.DbField\"\"\n\x06\x44\x62Rows\x12\x18\n\x04rows\x18\x01 \x03(\x0b\x32\n.wcf.DbRow\"5\n\x0cVerification\x12\n\n\x02v3\x18\x01 \x01(\t\x12\n\n\x02v4\x18\x02 \x01(\t\x12\r\n\x05scene\x18\x03 \x01(\x05\"+\n\nAddMembers\x12\x0e\n\x06roomid\x18\x01 \x01(\t\x12\r\n\x05wxids\x18\x02 \x01(\t\"D\n\x08UserInfo\x12\x0c\n\x04wxid\x18\x01 \x01(\t\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x0e\n\x06mobile\x18\x03 \x01(\t\x12\x0c\n\x04home\x18\x04 \x01(\t\"#\n\x07\x44\x65\x63Path\x12\x0b\n\x03src\x18\x01 \x01(\t\x12\x0b\n\x03\x64st\x18\x02 \x01(\t\"4\n\x08Transfer\x12\x0c\n\x04wxid\x18\x01 \x01(\t\x12\x0c\n\x04tfid\x18\x02 \x01(\t\x12\x0c\n\x04taid\x18\x03 \x01(\t*\xee\x03\n\tFunctions\x12\x11\n\rFUNC_RESERVED\x10\x00\x12\x11\n\rFUNC_IS_LOGIN\x10\x01\x12\x16\n\x12\x46UNC_GET_SELF_WXID\x10\x10\x12\x16\n\x12\x46UNC_GET_MSG_TYPES\x10\x11\x12\x15\n\x11\x46UNC_GET_CONTACTS\x10\x12\x12\x15\n\x11\x46UNC_GET_DB_NAMES\x10\x13\x12\x16\n\x12\x46UNC_GET_DB_TABLES\x10\x14\x12\x16\n\x12\x46UNC_GET_USER_INFO\x10\x15\x12\x11\n\rFUNC_SEND_TXT\x10 \x12\x11\n\rFUNC_SEND_IMG\x10!\x12\x12\n\x0e\x46UNC_SEND_FILE\x10\"\x12\x11\n\rFUNC_SEND_XML\x10#\x12\x15\n\x11\x46UNC_SEND_EMOTION\x10$\x12\x18\n\x14\x46UNC_ENABLE_RECV_TXT\x10\x30\x12\x19\n\x15\x46UNC_DISABLE_RECV_TXT\x10@\x12\x16\n\x12\x46UNC_EXEC_DB_QUERY\x10P\x12\x16\n\x12\x46UNC_ACCEPT_FRIEND\x10Q\x12\x16\n\x12\x46UNC_RECV_TRANSFER\x10R\x12\x16\n\x12\x46UNC_DECRYPT_IMAGE\x10`\x12\x19\n\x15\x46UNC_ADD_ROOM_MEMBERS\x10p\x12\x19\n\x15\x46UNC_DEL_ROOM_MEMBERS\x10qB\r\n\x0b\x63om.iamteerb\x06proto3')
|
||||
|
||||
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
|
||||
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wcf_pb2', globals())
|
||||
if _descriptor._USE_C_DESCRIPTORS == False:
|
||||
|
||||
DESCRIPTOR._options = None
|
||||
DESCRIPTOR._serialized_options = b'\n\013com.iamteer'
|
||||
_MSGTYPES_TYPESENTRY._options = None
|
||||
_MSGTYPES_TYPESENTRY._serialized_options = b'8\001'
|
||||
_FUNCTIONS._serialized_start=1820
|
||||
_FUNCTIONS._serialized_end=2314
|
||||
_REQUEST._serialized_start=19
|
||||
_REQUEST._serialized_end=347
|
||||
_RESPONSE._serialized_start=350
|
||||
_RESPONSE._serialized_end=649
|
||||
_EMPTY._serialized_start=651
|
||||
_EMPTY._serialized_end=658
|
||||
_WXMSG._serialized_start=661
|
||||
_WXMSG._serialized_end=821
|
||||
_TEXTMSG._serialized_start=823
|
||||
_TEXTMSG._serialized_end=878
|
||||
_PATHMSG._serialized_start=880
|
||||
_PATHMSG._serialized_end=921
|
||||
_XMLMSG._serialized_start=923
|
||||
_XMLMSG._serialized_end=994
|
||||
_MSGTYPES._serialized_start=996
|
||||
_MSGTYPES._serialized_end=1093
|
||||
_MSGTYPES_TYPESENTRY._serialized_start=1049
|
||||
_MSGTYPES_TYPESENTRY._serialized_end=1093
|
||||
_RPCCONTACT._serialized_start=1096
|
||||
_RPCCONTACT._serialized_end=1231
|
||||
_RPCCONTACTS._serialized_start=1233
|
||||
_RPCCONTACTS._serialized_end=1281
|
||||
_DBNAMES._serialized_start=1283
|
||||
_DBNAMES._serialized_end=1307
|
||||
_DBTABLE._serialized_start=1309
|
||||
_DBTABLE._serialized_end=1345
|
||||
_DBTABLES._serialized_start=1347
|
||||
_DBTABLES._serialized_end=1387
|
||||
_DBQUERY._serialized_start=1389
|
||||
_DBQUERY._serialized_end=1423
|
||||
_DBFIELD._serialized_start=1425
|
||||
_DBFIELD._serialized_end=1481
|
||||
_DBROW._serialized_start=1483
|
||||
_DBROW._serialized_end=1520
|
||||
_DBROWS._serialized_start=1522
|
||||
_DBROWS._serialized_end=1556
|
||||
_VERIFICATION._serialized_start=1558
|
||||
_VERIFICATION._serialized_end=1611
|
||||
_ADDMEMBERS._serialized_start=1613
|
||||
_ADDMEMBERS._serialized_end=1656
|
||||
_USERINFO._serialized_start=1658
|
||||
_USERINFO._serialized_end=1726
|
||||
_DECPATH._serialized_start=1728
|
||||
_DECPATH._serialized_end=1763
|
||||
_TRANSFER._serialized_start=1765
|
||||
_TRANSFER._serialized_end=1817
|
||||
# @@protoc_insertion_point(module_scope)
|
||||
@@ -0,0 +1,65 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import re
|
||||
|
||||
from wcferry import wcf_pb2
|
||||
|
||||
|
||||
class WxMsg():
|
||||
"""微信消息
|
||||
|
||||
Attributes:
|
||||
type (int): 消息类型,可通过 `get_msg_types` 获取
|
||||
id (str): 消息 id
|
||||
xml (str): 消息 xml 部分
|
||||
sender (str): 消息发送人
|
||||
roomid (str): (仅群消息有)群 id
|
||||
content (str): 消息内容
|
||||
thumb (str): 视频或图片消息的缩略图路径
|
||||
extra (str): 视频或图片消息的路径
|
||||
"""
|
||||
|
||||
def __init__(self, msg: wcf_pb2.WxMsg) -> None:
|
||||
self._is_self = msg.is_self
|
||||
self._is_group = msg.is_group
|
||||
self.type = msg.type
|
||||
self.id = msg.id
|
||||
self.xml = msg.xml
|
||||
self.sender = msg.sender
|
||||
self.roomid = msg.roomid
|
||||
self.content = msg.content
|
||||
self.thumb = msg.thumb
|
||||
self.extra = msg.extra
|
||||
|
||||
def __str__(self) -> str:
|
||||
s = f"{'自己发的:' if self._is_self else ''}"
|
||||
s += f"{self.sender}[{self.roomid}]:{self.id}:{self.type}:{self.xml.replace(chr(10), '').replace(chr(9),'')}\n"
|
||||
s += self.content
|
||||
s += f"\n{self.thumb}" if self.thumb else ""
|
||||
s += f"\n{self.extra}" if self.extra else ""
|
||||
return s
|
||||
|
||||
def from_self(self) -> bool:
|
||||
"""是否自己发的消息"""
|
||||
return self._is_self == 1
|
||||
|
||||
def from_group(self) -> bool:
|
||||
"""是否群聊消息"""
|
||||
return self._is_group
|
||||
|
||||
def is_at(self, wxid) -> bool:
|
||||
"""是否被 @:群消息,在 @ 名单里,并且不是 @ 所有人"""
|
||||
if not self.from_group():
|
||||
return False # 只有群消息才能 @
|
||||
|
||||
if not re.findall(f"<atuserlist>.*({wxid}).*</atuserlist>", self.xml):
|
||||
return False # 不在 @ 清单里
|
||||
|
||||
if re.findall(r"@(?:所有人|all|All)", self.content):
|
||||
return False # 排除 @ 所有人
|
||||
|
||||
return True
|
||||
|
||||
def is_text(self) -> bool:
|
||||
"""是否文本消息"""
|
||||
return self.type == 1
|
||||
@@ -0,0 +1 @@
|
||||
测试方法在 wechat.rs 中
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "wcferry"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
tonic = "0.8.3"
|
||||
prost = "0.11.5"
|
||||
nng = "1.0.1"
|
||||
serde_json = "1.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
log = "0.4.17"
|
||||
|
||||
[build-dependencies]
|
||||
tonic-build = "0.8.4"
|
||||
@@ -0,0 +1,9 @@
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tonic_build::configure()
|
||||
.build_client(true)
|
||||
.build_server(false)
|
||||
.out_dir("src/proto")
|
||||
.compile(&["proto/wcf.proto"], &["."])
|
||||
.expect("failed to compile protos");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
将最新的 dll、exe 放入此文件夹下
|
||||
@@ -0,0 +1 @@
|
||||
将最新的 wcf.proto 放入此文件夹下
|
||||
@@ -0,0 +1,173 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package wcf;
|
||||
option java_package = "com.iamteer";
|
||||
|
||||
enum Functions {
|
||||
FUNC_RESERVED = 0x00;
|
||||
FUNC_IS_LOGIN = 0x01;
|
||||
FUNC_GET_SELF_WXID = 0x10;
|
||||
FUNC_GET_MSG_TYPES = 0x11;
|
||||
FUNC_GET_CONTACTS = 0x12;
|
||||
FUNC_GET_DB_NAMES = 0x13;
|
||||
FUNC_GET_DB_TABLES = 0x14;
|
||||
FUNC_GET_USER_INFO = 0x15;
|
||||
FUNC_SEND_TXT = 0x20;
|
||||
FUNC_SEND_IMG = 0x21;
|
||||
FUNC_SEND_FILE = 0x22;
|
||||
FUNC_SEND_XML = 0x23;
|
||||
FUNC_SEND_EMOTION = 0x24;
|
||||
FUNC_ENABLE_RECV_TXT = 0x30;
|
||||
FUNC_DISABLE_RECV_TXT = 0x40;
|
||||
FUNC_EXEC_DB_QUERY = 0x50;
|
||||
FUNC_ACCEPT_FRIEND = 0x51;
|
||||
FUNC_RECV_TRANSFER = 0x52;
|
||||
FUNC_DECRYPT_IMAGE = 0x60;
|
||||
FUNC_ADD_ROOM_MEMBERS = 0x70;
|
||||
FUNC_DEL_ROOM_MEMBERS = 0x71;
|
||||
}
|
||||
|
||||
message Request
|
||||
{
|
||||
Functions func = 1;
|
||||
oneof msg
|
||||
{
|
||||
Empty empty = 2;
|
||||
string str = 3;
|
||||
TextMsg txt = 4;
|
||||
PathMsg file = 5;
|
||||
DbQuery query = 6;
|
||||
Verification v = 7;
|
||||
AddMembers m = 8;
|
||||
XmlMsg xml = 9;
|
||||
DecPath dec = 10;
|
||||
Transfer tf = 11;
|
||||
}
|
||||
}
|
||||
|
||||
message Response
|
||||
{
|
||||
Functions func = 1;
|
||||
oneof msg
|
||||
{
|
||||
int32 status = 2; // Int 状态,通用
|
||||
string str = 3; // 字符串
|
||||
WxMsg wxmsg = 4; // 微信消息
|
||||
MsgTypes types = 5; // 消息类型
|
||||
RpcContacts contacts = 6; // 联系人
|
||||
DbNames dbs = 7; // 数据库列表
|
||||
DbTables tables = 8; // 表列表
|
||||
DbRows rows = 9; // 行列表
|
||||
UserInfo ui = 10; // 个人信息
|
||||
};
|
||||
}
|
||||
|
||||
message Empty { }
|
||||
|
||||
message WxMsg
|
||||
{
|
||||
bool is_self = 1; // 是否自己发送的
|
||||
bool is_group = 2; // 是否群消息
|
||||
int32 type = 3; // 消息类型
|
||||
string id = 4; // 消息 id
|
||||
string xml = 5; // 消息 xml
|
||||
string sender = 6; // 消息发送者
|
||||
string roomid = 7; // 群 id(如果是群消息的话)
|
||||
string content = 8; // 消息内容
|
||||
string thumb = 9; // 缩略图
|
||||
string extra = 10; // 附加内容
|
||||
}
|
||||
|
||||
message TextMsg
|
||||
{
|
||||
string msg = 1; // 要发送的消息内容
|
||||
string receiver = 2; // 消息接收人,当为群时可@
|
||||
string aters = 3; // 要@的人列表,逗号分隔
|
||||
}
|
||||
|
||||
message PathMsg
|
||||
{
|
||||
string path = 1; // 要发送的图片的路径
|
||||
string receiver = 2; // 消息接收人
|
||||
}
|
||||
|
||||
message XmlMsg
|
||||
{
|
||||
string receiver = 1; // 消息接收人
|
||||
string content = 2; // xml 内容
|
||||
string path = 3; // 图片路径
|
||||
int32 type = 4; // 消息类型
|
||||
}
|
||||
|
||||
message MsgTypes { map<int32, string> types = 1; }
|
||||
|
||||
message RpcContact
|
||||
{
|
||||
string wxid = 1; // 微信 id
|
||||
string code = 2; // 微信号
|
||||
string remark = 3; // 备注
|
||||
string name = 4; // 微信昵称
|
||||
string country = 5; // 国家
|
||||
string province = 6; // 省/州
|
||||
string city = 7; // 城市
|
||||
int32 gender = 8; // 性别
|
||||
}
|
||||
message RpcContacts { repeated RpcContact contacts = 1; }
|
||||
|
||||
message DbNames { repeated string names = 1; }
|
||||
|
||||
message DbTable
|
||||
{
|
||||
string name = 1; // 表名
|
||||
string sql = 2; // 建表 SQL
|
||||
}
|
||||
message DbTables { repeated DbTable tables = 1; }
|
||||
|
||||
message DbQuery
|
||||
{
|
||||
string db = 1; // 目标数据库
|
||||
string sql = 2; // 查询 SQL
|
||||
}
|
||||
|
||||
message DbField
|
||||
{
|
||||
int32 type = 1; // 字段类型
|
||||
string column = 2; // 字段名称
|
||||
bytes content = 3; // 字段内容
|
||||
}
|
||||
message DbRow { repeated DbField fields = 1; }
|
||||
message DbRows { repeated DbRow rows = 1; }
|
||||
|
||||
message Verification
|
||||
{
|
||||
string v3 = 1; // 加密的用户名
|
||||
string v4 = 2; // Ticket
|
||||
int32 scene = 3; // 添加方式:17 名片,30 扫码
|
||||
}
|
||||
|
||||
message AddMembers
|
||||
{
|
||||
string roomid = 1; // 要加的群ID
|
||||
string wxids = 2; // 要加群的人列表,逗号分隔
|
||||
}
|
||||
|
||||
message UserInfo
|
||||
{
|
||||
string wxid = 1; // 微信ID
|
||||
string name = 2; // 昵称
|
||||
string mobile = 3; // 手机号
|
||||
string home = 4; // 文件/图片等父路径
|
||||
}
|
||||
|
||||
message DecPath
|
||||
{
|
||||
string src = 1; // 源路径
|
||||
string dst = 2; // 目标路径
|
||||
}
|
||||
|
||||
message Transfer
|
||||
{
|
||||
string wxid = 1; // 转账人
|
||||
string tfid = 2; // 转账id transferid
|
||||
string taid = 3; // Transaction id
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
mod wechat;
|
||||
|
||||
fn main() {
|
||||
println!("Hello, wcferry!");
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct Request {
|
||||
#[prost(enumeration = "Functions", tag = "1")]
|
||||
pub func: i32,
|
||||
#[prost(oneof = "request::Msg", tags = "2, 3, 4, 5, 6, 7, 8, 9, 10, 11")]
|
||||
pub msg: ::core::option::Option<request::Msg>,
|
||||
}
|
||||
/// Nested message and enum types in `Request`.
|
||||
pub mod request {
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Oneof)]
|
||||
pub enum Msg {
|
||||
#[prost(message, tag = "2")]
|
||||
Empty(super::Empty),
|
||||
#[prost(string, tag = "3")]
|
||||
Str(::prost::alloc::string::String),
|
||||
#[prost(message, tag = "4")]
|
||||
Txt(super::TextMsg),
|
||||
#[prost(message, tag = "5")]
|
||||
File(super::PathMsg),
|
||||
#[prost(message, tag = "6")]
|
||||
Query(super::DbQuery),
|
||||
#[prost(message, tag = "7")]
|
||||
V(super::Verification),
|
||||
#[prost(message, tag = "8")]
|
||||
M(super::AddMembers),
|
||||
#[prost(message, tag = "9")]
|
||||
Xml(super::XmlMsg),
|
||||
#[prost(message, tag = "10")]
|
||||
Dec(super::DecPath),
|
||||
#[prost(message, tag = "11")]
|
||||
Tf(super::Transfer),
|
||||
}
|
||||
}
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct Response {
|
||||
#[prost(enumeration = "Functions", tag = "1")]
|
||||
pub func: i32,
|
||||
#[prost(oneof = "response::Msg", tags = "2, 3, 4, 5, 6, 7, 8, 9, 10")]
|
||||
pub msg: ::core::option::Option<response::Msg>,
|
||||
}
|
||||
/// Nested message and enum types in `Response`.
|
||||
pub mod response {
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Oneof)]
|
||||
pub enum Msg {
|
||||
/// Int 状态,通用
|
||||
#[prost(int32, tag = "2")]
|
||||
Status(i32),
|
||||
/// 字符串
|
||||
#[prost(string, tag = "3")]
|
||||
Str(::prost::alloc::string::String),
|
||||
/// 微信消息
|
||||
#[prost(message, tag = "4")]
|
||||
Wxmsg(super::WxMsg),
|
||||
/// 消息类型
|
||||
#[prost(message, tag = "5")]
|
||||
Types(super::MsgTypes),
|
||||
/// 联系人
|
||||
#[prost(message, tag = "6")]
|
||||
Contacts(super::RpcContacts),
|
||||
/// 数据库列表
|
||||
#[prost(message, tag = "7")]
|
||||
Dbs(super::DbNames),
|
||||
/// 表列表
|
||||
#[prost(message, tag = "8")]
|
||||
Tables(super::DbTables),
|
||||
/// 行列表
|
||||
#[prost(message, tag = "9")]
|
||||
Rows(super::DbRows),
|
||||
/// 个人信息
|
||||
#[prost(message, tag = "10")]
|
||||
Ui(super::UserInfo),
|
||||
}
|
||||
}
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct Empty {}
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct WxMsg {
|
||||
/// 是否自己发送的
|
||||
#[prost(bool, tag = "1")]
|
||||
pub is_self: bool,
|
||||
/// 是否群消息
|
||||
#[prost(bool, tag = "2")]
|
||||
pub is_group: bool,
|
||||
/// 消息类型
|
||||
#[prost(int32, tag = "3")]
|
||||
pub r#type: i32,
|
||||
/// 消息 id
|
||||
#[prost(string, tag = "4")]
|
||||
pub id: ::prost::alloc::string::String,
|
||||
/// 消息 xml
|
||||
#[prost(string, tag = "5")]
|
||||
pub xml: ::prost::alloc::string::String,
|
||||
/// 消息发送者
|
||||
#[prost(string, tag = "6")]
|
||||
pub sender: ::prost::alloc::string::String,
|
||||
/// 群 id(如果是群消息的话)
|
||||
#[prost(string, tag = "7")]
|
||||
pub roomid: ::prost::alloc::string::String,
|
||||
/// 消息内容
|
||||
#[prost(string, tag = "8")]
|
||||
pub content: ::prost::alloc::string::String,
|
||||
/// 缩略图
|
||||
#[prost(string, tag = "9")]
|
||||
pub thumb: ::prost::alloc::string::String,
|
||||
/// 附加内容
|
||||
#[prost(string, tag = "10")]
|
||||
pub extra: ::prost::alloc::string::String,
|
||||
}
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct TextMsg {
|
||||
/// 要发送的消息内容
|
||||
#[prost(string, tag = "1")]
|
||||
pub msg: ::prost::alloc::string::String,
|
||||
/// 消息接收人,当为群时可@
|
||||
#[prost(string, tag = "2")]
|
||||
pub receiver: ::prost::alloc::string::String,
|
||||
/// 要@的人列表,逗号分隔
|
||||
#[prost(string, tag = "3")]
|
||||
pub aters: ::prost::alloc::string::String,
|
||||
}
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct PathMsg {
|
||||
/// 要发送的图片的路径
|
||||
#[prost(string, tag = "1")]
|
||||
pub path: ::prost::alloc::string::String,
|
||||
/// 消息接收人
|
||||
#[prost(string, tag = "2")]
|
||||
pub receiver: ::prost::alloc::string::String,
|
||||
}
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct XmlMsg {
|
||||
/// 消息接收人
|
||||
#[prost(string, tag = "1")]
|
||||
pub receiver: ::prost::alloc::string::String,
|
||||
/// xml 内容
|
||||
#[prost(string, tag = "2")]
|
||||
pub content: ::prost::alloc::string::String,
|
||||
/// 图片路径
|
||||
#[prost(string, tag = "3")]
|
||||
pub path: ::prost::alloc::string::String,
|
||||
/// 消息类型
|
||||
#[prost(int32, tag = "4")]
|
||||
pub r#type: i32,
|
||||
}
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct MsgTypes {
|
||||
#[prost(map = "int32, string", tag = "1")]
|
||||
pub types: ::std::collections::HashMap<i32, ::prost::alloc::string::String>,
|
||||
}
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct RpcContact {
|
||||
/// 微信 id
|
||||
#[prost(string, tag = "1")]
|
||||
pub wxid: ::prost::alloc::string::String,
|
||||
/// 微信号
|
||||
#[prost(string, tag = "2")]
|
||||
pub code: ::prost::alloc::string::String,
|
||||
/// 备注
|
||||
#[prost(string, tag = "3")]
|
||||
pub remark: ::prost::alloc::string::String,
|
||||
/// 微信昵称
|
||||
#[prost(string, tag = "4")]
|
||||
pub name: ::prost::alloc::string::String,
|
||||
/// 国家
|
||||
#[prost(string, tag = "5")]
|
||||
pub country: ::prost::alloc::string::String,
|
||||
/// 省/州
|
||||
#[prost(string, tag = "6")]
|
||||
pub province: ::prost::alloc::string::String,
|
||||
/// 城市
|
||||
#[prost(string, tag = "7")]
|
||||
pub city: ::prost::alloc::string::String,
|
||||
/// 性别
|
||||
#[prost(int32, tag = "8")]
|
||||
pub gender: i32,
|
||||
}
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct RpcContacts {
|
||||
#[prost(message, repeated, tag = "1")]
|
||||
pub contacts: ::prost::alloc::vec::Vec<RpcContact>,
|
||||
}
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct DbNames {
|
||||
#[prost(string, repeated, tag = "1")]
|
||||
pub names: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
|
||||
}
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct DbTable {
|
||||
/// 表名
|
||||
#[prost(string, tag = "1")]
|
||||
pub name: ::prost::alloc::string::String,
|
||||
/// 建表 SQL
|
||||
#[prost(string, tag = "2")]
|
||||
pub sql: ::prost::alloc::string::String,
|
||||
}
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct DbTables {
|
||||
#[prost(message, repeated, tag = "1")]
|
||||
pub tables: ::prost::alloc::vec::Vec<DbTable>,
|
||||
}
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct DbQuery {
|
||||
/// 目标数据库
|
||||
#[prost(string, tag = "1")]
|
||||
pub db: ::prost::alloc::string::String,
|
||||
/// 查询 SQL
|
||||
#[prost(string, tag = "2")]
|
||||
pub sql: ::prost::alloc::string::String,
|
||||
}
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct DbField {
|
||||
/// 字段类型
|
||||
#[prost(int32, tag = "1")]
|
||||
pub r#type: i32,
|
||||
/// 字段名称
|
||||
#[prost(string, tag = "2")]
|
||||
pub column: ::prost::alloc::string::String,
|
||||
/// 字段内容
|
||||
#[prost(bytes = "vec", tag = "3")]
|
||||
pub content: ::prost::alloc::vec::Vec<u8>,
|
||||
}
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct DbRow {
|
||||
#[prost(message, repeated, tag = "1")]
|
||||
pub fields: ::prost::alloc::vec::Vec<DbField>,
|
||||
}
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct DbRows {
|
||||
#[prost(message, repeated, tag = "1")]
|
||||
pub rows: ::prost::alloc::vec::Vec<DbRow>,
|
||||
}
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct Verification {
|
||||
/// 加密的用户名
|
||||
#[prost(string, tag = "1")]
|
||||
pub v3: ::prost::alloc::string::String,
|
||||
/// Ticket
|
||||
#[prost(string, tag = "2")]
|
||||
pub v4: ::prost::alloc::string::String,
|
||||
/// 添加方式:17 名片,30 扫码
|
||||
#[prost(int32, tag = "3")]
|
||||
pub scene: i32,
|
||||
}
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct AddMembers {
|
||||
/// 要加的群ID
|
||||
#[prost(string, tag = "1")]
|
||||
pub roomid: ::prost::alloc::string::String,
|
||||
/// 要加群的人列表,逗号分隔
|
||||
#[prost(string, tag = "2")]
|
||||
pub wxids: ::prost::alloc::string::String,
|
||||
}
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct UserInfo {
|
||||
/// 微信ID
|
||||
#[prost(string, tag = "1")]
|
||||
pub wxid: ::prost::alloc::string::String,
|
||||
/// 昵称
|
||||
#[prost(string, tag = "2")]
|
||||
pub name: ::prost::alloc::string::String,
|
||||
/// 手机号
|
||||
#[prost(string, tag = "3")]
|
||||
pub mobile: ::prost::alloc::string::String,
|
||||
/// 文件/图片等父路径
|
||||
#[prost(string, tag = "4")]
|
||||
pub home: ::prost::alloc::string::String,
|
||||
}
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct DecPath {
|
||||
/// 源路径
|
||||
#[prost(string, tag = "1")]
|
||||
pub src: ::prost::alloc::string::String,
|
||||
/// 目标路径
|
||||
#[prost(string, tag = "2")]
|
||||
pub dst: ::prost::alloc::string::String,
|
||||
}
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct Transfer {
|
||||
/// 转账人
|
||||
#[prost(string, tag = "1")]
|
||||
pub wxid: ::prost::alloc::string::String,
|
||||
/// 转账id transferid
|
||||
#[prost(string, tag = "2")]
|
||||
pub tfid: ::prost::alloc::string::String,
|
||||
/// Transaction id
|
||||
#[prost(string, tag = "3")]
|
||||
pub taid: ::prost::alloc::string::String,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
|
||||
#[repr(i32)]
|
||||
pub enum Functions {
|
||||
FuncReserved = 0,
|
||||
FuncIsLogin = 1,
|
||||
FuncGetSelfWxid = 16,
|
||||
FuncGetMsgTypes = 17,
|
||||
FuncGetContacts = 18,
|
||||
FuncGetDbNames = 19,
|
||||
FuncGetDbTables = 20,
|
||||
FuncGetUserInfo = 21,
|
||||
FuncSendTxt = 32,
|
||||
FuncSendImg = 33,
|
||||
FuncSendFile = 34,
|
||||
FuncSendXml = 35,
|
||||
FuncSendEmotion = 36,
|
||||
FuncEnableRecvTxt = 48,
|
||||
FuncDisableRecvTxt = 64,
|
||||
FuncExecDbQuery = 80,
|
||||
FuncAcceptFriend = 81,
|
||||
FuncRecvTransfer = 82,
|
||||
FuncDecryptImage = 96,
|
||||
FuncAddRoomMembers = 112,
|
||||
FuncDelRoomMembers = 113,
|
||||
}
|
||||
impl Functions {
|
||||
/// String value of the enum field names used in the ProtoBuf definition.
|
||||
///
|
||||
/// The values are not transformed in any way and thus are considered stable
|
||||
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
|
||||
pub fn as_str_name(&self) -> &'static str {
|
||||
match self {
|
||||
Functions::FuncReserved => "FUNC_RESERVED",
|
||||
Functions::FuncIsLogin => "FUNC_IS_LOGIN",
|
||||
Functions::FuncGetSelfWxid => "FUNC_GET_SELF_WXID",
|
||||
Functions::FuncGetMsgTypes => "FUNC_GET_MSG_TYPES",
|
||||
Functions::FuncGetContacts => "FUNC_GET_CONTACTS",
|
||||
Functions::FuncGetDbNames => "FUNC_GET_DB_NAMES",
|
||||
Functions::FuncGetDbTables => "FUNC_GET_DB_TABLES",
|
||||
Functions::FuncGetUserInfo => "FUNC_GET_USER_INFO",
|
||||
Functions::FuncSendTxt => "FUNC_SEND_TXT",
|
||||
Functions::FuncSendImg => "FUNC_SEND_IMG",
|
||||
Functions::FuncSendFile => "FUNC_SEND_FILE",
|
||||
Functions::FuncSendXml => "FUNC_SEND_XML",
|
||||
Functions::FuncSendEmotion => "FUNC_SEND_EMOTION",
|
||||
Functions::FuncEnableRecvTxt => "FUNC_ENABLE_RECV_TXT",
|
||||
Functions::FuncDisableRecvTxt => "FUNC_DISABLE_RECV_TXT",
|
||||
Functions::FuncExecDbQuery => "FUNC_EXEC_DB_QUERY",
|
||||
Functions::FuncAcceptFriend => "FUNC_ACCEPT_FRIEND",
|
||||
Functions::FuncRecvTransfer => "FUNC_RECV_TRANSFER",
|
||||
Functions::FuncDecryptImage => "FUNC_DECRYPT_IMAGE",
|
||||
Functions::FuncAddRoomMembers => "FUNC_ADD_ROOM_MEMBERS",
|
||||
Functions::FuncDelRoomMembers => "FUNC_DEL_ROOM_MEMBERS",
|
||||
}
|
||||
}
|
||||
/// Creates an enum from field names used in the ProtoBuf definition.
|
||||
pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
|
||||
match value {
|
||||
"FUNC_RESERVED" => Some(Self::FuncReserved),
|
||||
"FUNC_IS_LOGIN" => Some(Self::FuncIsLogin),
|
||||
"FUNC_GET_SELF_WXID" => Some(Self::FuncGetSelfWxid),
|
||||
"FUNC_GET_MSG_TYPES" => Some(Self::FuncGetMsgTypes),
|
||||
"FUNC_GET_CONTACTS" => Some(Self::FuncGetContacts),
|
||||
"FUNC_GET_DB_NAMES" => Some(Self::FuncGetDbNames),
|
||||
"FUNC_GET_DB_TABLES" => Some(Self::FuncGetDbTables),
|
||||
"FUNC_GET_USER_INFO" => Some(Self::FuncGetUserInfo),
|
||||
"FUNC_SEND_TXT" => Some(Self::FuncSendTxt),
|
||||
"FUNC_SEND_IMG" => Some(Self::FuncSendImg),
|
||||
"FUNC_SEND_FILE" => Some(Self::FuncSendFile),
|
||||
"FUNC_SEND_XML" => Some(Self::FuncSendXml),
|
||||
"FUNC_SEND_EMOTION" => Some(Self::FuncSendEmotion),
|
||||
"FUNC_ENABLE_RECV_TXT" => Some(Self::FuncEnableRecvTxt),
|
||||
"FUNC_DISABLE_RECV_TXT" => Some(Self::FuncDisableRecvTxt),
|
||||
"FUNC_EXEC_DB_QUERY" => Some(Self::FuncExecDbQuery),
|
||||
"FUNC_ACCEPT_FRIEND" => Some(Self::FuncAcceptFriend),
|
||||
"FUNC_RECV_TRANSFER" => Some(Self::FuncRecvTransfer),
|
||||
"FUNC_DECRYPT_IMAGE" => Some(Self::FuncDecryptImage),
|
||||
"FUNC_ADD_ROOM_MEMBERS" => Some(Self::FuncAddRoomMembers),
|
||||
"FUNC_DEL_ROOM_MEMBERS" => Some(Self::FuncDelRoomMembers),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,939 @@
|
||||
use std::{env, path::PathBuf, process::Command, time::Duration, vec};
|
||||
|
||||
use log::{error, info, warn};
|
||||
use nng::options::{Options, RecvTimeout};
|
||||
use prost::Message;
|
||||
use std::collections::HashMap;
|
||||
|
||||
const DEFAULT_URL: &'static str = "tcp://127.0.0.1:10086";
|
||||
const LISTEN_URL: &'static str = "tcp://127.0.0.1:10087";
|
||||
|
||||
pub mod wcf {
|
||||
include!("proto/wcf.rs");
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct WeChat {
|
||||
pub url: String,
|
||||
pub wcf_path: PathBuf,
|
||||
pub debug: bool,
|
||||
pub socket: nng::Socket,
|
||||
pub listening: bool,
|
||||
pub enable_accept_firend: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct UserInfo {
|
||||
pub wxid: String,
|
||||
pub name: String,
|
||||
pub mobile: String,
|
||||
pub home: String,
|
||||
}
|
||||
|
||||
impl Default for WeChat {
|
||||
fn default() -> Self {
|
||||
WeChat::new(false)
|
||||
}
|
||||
}
|
||||
|
||||
impl WeChat {
|
||||
pub fn new(debug: bool) -> Self {
|
||||
let path = env::current_dir().unwrap().join("lib").join("wcf.exe");
|
||||
let _ = start(path.clone(), debug);
|
||||
let socket = connect(&DEFAULT_URL).unwrap();
|
||||
WeChat {
|
||||
url: String::from(DEFAULT_URL),
|
||||
wcf_path: path,
|
||||
debug,
|
||||
socket,
|
||||
listening: false,
|
||||
enable_accept_firend: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn start(wcf_path: PathBuf, debug: bool) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut args = vec!["start", "10086"];
|
||||
if debug {
|
||||
args.push("debug");
|
||||
}
|
||||
info!(
|
||||
"wcf_path: {}, debug: {}",
|
||||
wcf_path.clone().to_str().unwrap(),
|
||||
debug
|
||||
);
|
||||
let _ = match Command::new(wcf_path.to_str().unwrap()).args(args).output() {
|
||||
Ok(output) => output,
|
||||
Err(e) => {
|
||||
error!("命令行启动失败: {}", e);
|
||||
return Err("服务启动失败".into());
|
||||
}
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn stop(wechat: &mut WeChat) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let _ = disable_listen(wechat);
|
||||
wechat.socket.close();
|
||||
let output = Command::new(wechat.wcf_path.to_str().unwrap())
|
||||
.args(["stop"])
|
||||
.output();
|
||||
let _output = match output {
|
||||
Ok(output) => output,
|
||||
Err(e) => {
|
||||
error!("服务停止失败: {}", e);
|
||||
return Err("服务停止失败".into());
|
||||
}
|
||||
};
|
||||
info!("服务已停止: {}", wechat.url);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn connect(url: &str) -> Result<nng::Socket, Box<dyn std::error::Error>> {
|
||||
let client = match nng::Socket::new(nng::Protocol::Pair1) {
|
||||
Ok(client) => client,
|
||||
Err(e) => {
|
||||
error!("Socket创建失败: {}", e);
|
||||
return Err("连接服务失败".into());
|
||||
}
|
||||
};
|
||||
match client.set_opt::<RecvTimeout>(Some(Duration::from_millis(5000))) {
|
||||
Ok(()) => (),
|
||||
Err(e) => {
|
||||
error!("连接参数设置失败: {}", e);
|
||||
return Err("连接参数设置失败".into());
|
||||
}
|
||||
};
|
||||
match client.set_opt::<nng::options::SendTimeout>(Some(Duration::from_millis(5000))) {
|
||||
Ok(()) => (),
|
||||
Err(e) => {
|
||||
error!("连接参数设置失败: {}", e);
|
||||
return Err("连接参数设置失败".into());
|
||||
}
|
||||
};
|
||||
match client.dial(url) {
|
||||
Ok(()) => (),
|
||||
Err(e) => {
|
||||
error!("连接服务失败: {}", e);
|
||||
return Err("连接服务失败".into());
|
||||
}
|
||||
};
|
||||
Ok(client)
|
||||
}
|
||||
|
||||
fn send_cmd(
|
||||
wechat: &WeChat,
|
||||
req: wcf::Request,
|
||||
) -> Result<Option<wcf::response::Msg>, Box<dyn std::error::Error>> {
|
||||
let mut buf = Vec::with_capacity(req.encoded_len());
|
||||
match req.encode(&mut buf) {
|
||||
Ok(()) => (),
|
||||
Err(e) => {
|
||||
error!("序列化失败: {}", e);
|
||||
return Err("通信失败".into());
|
||||
}
|
||||
};
|
||||
let msg = nng::Message::from(&buf[..]);
|
||||
let _ = match wechat.socket.send(msg) {
|
||||
Ok(()) => {}
|
||||
Err(e) => {
|
||||
error!("Socket发送失败: {:?}, {}", e.0, e.1);
|
||||
return Err("通信失败".into());
|
||||
}
|
||||
};
|
||||
let mut msg = match wechat.socket.recv() {
|
||||
Ok(msg) => msg,
|
||||
Err(e) => {
|
||||
error!("Socket接收失败: {}", e);
|
||||
return Err("通信失败".into());
|
||||
}
|
||||
};
|
||||
// 反序列化为prost消息
|
||||
let response = match wcf::Response::decode(msg.as_slice()) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("反序列化失败: {}", e);
|
||||
return Err("通信失败".into());
|
||||
}
|
||||
};
|
||||
msg.clear();
|
||||
Ok(response.msg)
|
||||
}
|
||||
|
||||
pub fn is_login(wechat: &WeChat) -> Result<bool, Box<dyn std::error::Error>> {
|
||||
let req = wcf::Request {
|
||||
func: wcf::Functions::FuncIsLogin.into(),
|
||||
msg: None,
|
||||
};
|
||||
let response = match send_cmd(wechat, req) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("命令发送失败: {}", e);
|
||||
return Err("登录状态检查失败".into());
|
||||
}
|
||||
};
|
||||
if response.is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
match response.unwrap() {
|
||||
wcf::response::Msg::Status(status) => {
|
||||
return Ok(1 == status);
|
||||
}
|
||||
_ => {
|
||||
return Ok(false);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn get_self_wx_id(wechat: &mut WeChat) -> Result<Option<String>, Box<dyn std::error::Error>> {
|
||||
let req = wcf::Request {
|
||||
func: wcf::Functions::FuncGetSelfWxid.into(),
|
||||
msg: None,
|
||||
};
|
||||
let response = match send_cmd(wechat, req) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("命令发送失败: {}", e);
|
||||
return Err("获取微信ID失败".into());
|
||||
}
|
||||
};
|
||||
if response.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
match response.unwrap() {
|
||||
wcf::response::Msg::Str(wx_id) => {
|
||||
return Ok(Some(wx_id));
|
||||
}
|
||||
_ => {
|
||||
return Ok(None);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn get_user_info(wechat: &mut WeChat) -> Result<Option<UserInfo>, Box<dyn std::error::Error>> {
|
||||
let req = wcf::Request {
|
||||
func: wcf::Functions::FuncGetUserInfo.into(),
|
||||
msg: None,
|
||||
};
|
||||
let response = match send_cmd(wechat, req) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("命令发送失败: {}", e);
|
||||
return Err("获取用户信息失败".into());
|
||||
}
|
||||
};
|
||||
if response.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
match response.unwrap() {
|
||||
wcf::response::Msg::Ui(user_info) => {
|
||||
return Ok(Some(UserInfo {
|
||||
wxid: user_info.wxid,
|
||||
name: user_info.name,
|
||||
mobile: user_info.mobile,
|
||||
home: user_info.home,
|
||||
}));
|
||||
}
|
||||
_ => {
|
||||
return Ok(None);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn get_contacts(
|
||||
wechat: &mut WeChat,
|
||||
) -> Result<Option<wcf::RpcContacts>, Box<dyn std::error::Error>> {
|
||||
info!("获取联系人");
|
||||
let req = wcf::Request {
|
||||
func: wcf::Functions::FuncGetContacts.into(),
|
||||
msg: None,
|
||||
};
|
||||
let response = match send_cmd(wechat, req) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("命令发送失败: {}", e);
|
||||
return Err("获取微信联系人失败".into());
|
||||
}
|
||||
};
|
||||
if response.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
match response.unwrap() {
|
||||
wcf::response::Msg::Contacts(contact) => {
|
||||
return Ok(Some(contact));
|
||||
}
|
||||
_ => {
|
||||
return Ok(None);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn get_db_names(wechat: &mut WeChat) -> Result<Vec<String>, Box<dyn std::error::Error>> {
|
||||
let req = wcf::Request {
|
||||
func: wcf::Functions::FuncGetDbNames.into(),
|
||||
msg: None,
|
||||
};
|
||||
let response = match send_cmd(wechat, req) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("命令发送失败: {}", e);
|
||||
return Err("获取微信数据库失败".into());
|
||||
}
|
||||
};
|
||||
if response.is_none() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
match response.unwrap() {
|
||||
wcf::response::Msg::Dbs(dbs) => {
|
||||
return Ok(dbs.names);
|
||||
}
|
||||
_ => {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn get_db_tables(
|
||||
wechat: &mut WeChat,
|
||||
db: String,
|
||||
) -> Result<Vec<wcf::DbTable>, Box<dyn std::error::Error>> {
|
||||
let req = wcf::Request {
|
||||
func: wcf::Functions::FuncGetDbTables.into(),
|
||||
msg: Some(wcf::request::Msg::Str(db)),
|
||||
};
|
||||
let response = match send_cmd(wechat, req) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("命令发送失败: {}", e);
|
||||
return Err("获取数据库表失败".into());
|
||||
}
|
||||
};
|
||||
if response.is_none() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
match response.unwrap() {
|
||||
wcf::response::Msg::Tables(tables) => {
|
||||
let tables = tables.tables;
|
||||
return Ok(tables);
|
||||
}
|
||||
_ => {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn exec_db_query(
|
||||
wechat: &mut WeChat,
|
||||
db: String,
|
||||
sql: String,
|
||||
) -> Result<Vec<wcf::DbRow>, Box<dyn std::error::Error>> {
|
||||
let req = wcf::Request {
|
||||
func: wcf::Functions::FuncExecDbQuery.into(),
|
||||
msg: Some(wcf::request::Msg::Query(wcf::DbQuery { db, sql })),
|
||||
};
|
||||
let response = match send_cmd(wechat, req) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("命令发送失败: {}", e);
|
||||
return Err("执行SQL失败".into());
|
||||
}
|
||||
};
|
||||
if response.is_none() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
match response.unwrap() {
|
||||
wcf::response::Msg::Rows(rows) => {
|
||||
let rows = rows.rows;
|
||||
return Ok(rows);
|
||||
}
|
||||
_ => {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param msg: 消息内容(如果是 @ 消息则需要有跟 @ 的人数量相同的 @)
|
||||
* @param receiver: 消息接收人,私聊为 wxid(wxid_xxxxxxxxxxxxxx),群聊为
|
||||
* roomid(xxxxxxxxxx@chatroom)
|
||||
* @param aters: 群聊时要 @ 的人(私聊时为空字符串),多个用逗号分隔。@所有人 用
|
||||
* notify@all(必须是群主或者管理员才有权限)
|
||||
* @return int
|
||||
* @Description 发送文本消息
|
||||
* @author Changhua
|
||||
* @example sendText(" Hello @ 某人1 @ 某人2 ", " xxxxxxxx @ chatroom ",
|
||||
* "wxid_xxxxxxxxxxxxx1,wxid_xxxxxxxxxxxxx2");
|
||||
*/
|
||||
pub fn send_text(
|
||||
wechat: &mut WeChat,
|
||||
msg: String,
|
||||
receiver: String,
|
||||
aters: String,
|
||||
) -> Result<bool, Box<dyn std::error::Error>> {
|
||||
let text_msg = wcf::TextMsg {
|
||||
msg,
|
||||
receiver,
|
||||
aters,
|
||||
};
|
||||
let req = wcf::Request {
|
||||
func: wcf::Functions::FuncSendTxt.into(),
|
||||
msg: Some(wcf::request::Msg::Txt(text_msg)),
|
||||
};
|
||||
let response = match send_cmd(wechat, req) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("命令发送失败: {}", e);
|
||||
return Err("微信消息发送失败".into());
|
||||
}
|
||||
};
|
||||
if response.is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
return Ok(true);
|
||||
// match response.unwrap() {
|
||||
// wcf::response::Msg::Status(status) => {
|
||||
// return Ok(1 == status);
|
||||
// }
|
||||
// _ => {
|
||||
// return Ok(false);
|
||||
// }
|
||||
// };
|
||||
}
|
||||
|
||||
pub fn send_image(
|
||||
wechat: &mut WeChat,
|
||||
path: PathBuf,
|
||||
receiver: String,
|
||||
) -> Result<bool, Box<dyn std::error::Error>> {
|
||||
let image_msg = wcf::PathMsg {
|
||||
path: String::from(path.to_str().unwrap()),
|
||||
receiver,
|
||||
};
|
||||
let req = wcf::Request {
|
||||
func: wcf::Functions::FuncSendImg.into(),
|
||||
msg: Some(wcf::request::Msg::File(image_msg)),
|
||||
};
|
||||
let response = match send_cmd(wechat, req) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("命令发送失败: {}", e);
|
||||
return Err("图片发送失败".into());
|
||||
}
|
||||
};
|
||||
println!("{:?}", response);
|
||||
if response.is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
return Ok(true);
|
||||
// match response.unwrap() {
|
||||
// wcf::response::Msg::Status(status) => {
|
||||
// return Ok(1 == status);
|
||||
// }
|
||||
// _ => {
|
||||
// return Ok(false);
|
||||
// }
|
||||
// };
|
||||
}
|
||||
|
||||
pub fn send_file(
|
||||
wechat: &mut WeChat,
|
||||
path: PathBuf,
|
||||
receiver: String,
|
||||
) -> Result<bool, Box<dyn std::error::Error>> {
|
||||
let image_msg = wcf::PathMsg {
|
||||
path: String::from(path.to_str().unwrap()),
|
||||
receiver,
|
||||
};
|
||||
let req = wcf::Request {
|
||||
func: wcf::Functions::FuncSendFile.into(),
|
||||
msg: Some(wcf::request::Msg::File(image_msg)),
|
||||
};
|
||||
let response = match send_cmd(wechat, req) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("命令发送失败: {}", e);
|
||||
return Err("文件发送失败".into());
|
||||
}
|
||||
};
|
||||
if response.is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
match response.unwrap() {
|
||||
wcf::response::Msg::Status(status) => {
|
||||
return Ok(1 == status);
|
||||
}
|
||||
_ => {
|
||||
return Ok(false);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn send_xml(
|
||||
wechat: &mut WeChat,
|
||||
xml: String,
|
||||
path: PathBuf,
|
||||
receiver: String,
|
||||
xml_type: i32,
|
||||
) -> Result<bool, Box<dyn std::error::Error>> {
|
||||
let xml_msg = wcf::XmlMsg {
|
||||
content: xml,
|
||||
path: String::from(path.to_str().unwrap()),
|
||||
receiver,
|
||||
r#type: xml_type,
|
||||
};
|
||||
let req = wcf::Request {
|
||||
func: wcf::Functions::FuncSendXml.into(),
|
||||
msg: Some(wcf::request::Msg::Xml(xml_msg)),
|
||||
};
|
||||
let response = match send_cmd(wechat, req) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("命令发送失败: {}", e);
|
||||
return Err("微信XML消息发送失败".into());
|
||||
}
|
||||
};
|
||||
if response.is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
match response.unwrap() {
|
||||
wcf::response::Msg::Status(status) => {
|
||||
return Ok(1 == status);
|
||||
}
|
||||
_ => {
|
||||
return Ok(false);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn send_emotion(
|
||||
wechat: &mut WeChat,
|
||||
path: PathBuf,
|
||||
receiver: String,
|
||||
) -> Result<bool, Box<dyn std::error::Error>> {
|
||||
let image_msg = wcf::PathMsg {
|
||||
path: String::from(path.to_str().unwrap()),
|
||||
receiver,
|
||||
};
|
||||
let req = wcf::Request {
|
||||
func: wcf::Functions::FuncSendEmotion.into(),
|
||||
msg: Some(wcf::request::Msg::File(image_msg)),
|
||||
};
|
||||
let response = match send_cmd(wechat, req) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("命令发送失败: {}", e);
|
||||
return Err("微信表情发送失败".into());
|
||||
}
|
||||
};
|
||||
if response.is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
match response.unwrap() {
|
||||
wcf::response::Msg::Status(status) => {
|
||||
return Ok(1 == status);
|
||||
}
|
||||
_ => {
|
||||
return Ok(false);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn enable_listen(wechat: &mut WeChat) -> Result<nng::Socket, Box<dyn std::error::Error>> {
|
||||
if wechat.listening {
|
||||
return Err("消息接收服务已开启".into());
|
||||
}
|
||||
let req = wcf::Request {
|
||||
func: wcf::Functions::FuncEnableRecvTxt.into(),
|
||||
msg: None,
|
||||
};
|
||||
let response = match send_cmd(wechat, req) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("命令发送失败: {}", e);
|
||||
return Err("消息接收服务启动失败".into());
|
||||
}
|
||||
};
|
||||
if response.is_none() {
|
||||
return Err("消息接收服务启动失败".into());
|
||||
}
|
||||
let client = connect(LISTEN_URL).unwrap();
|
||||
wechat.listening = true;
|
||||
Ok(client)
|
||||
}
|
||||
|
||||
pub fn disable_listen(wechat: &mut WeChat) -> Result<bool, Box<dyn std::error::Error>> {
|
||||
if !wechat.listening {
|
||||
return Ok(true);
|
||||
}
|
||||
let req = wcf::Request {
|
||||
func: wcf::Functions::FuncDisableRecvTxt.into(),
|
||||
msg: None,
|
||||
};
|
||||
let response = match send_cmd(wechat, req) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("命令发送失败: {}", e);
|
||||
return Err("消息接收服务停止失败".into());
|
||||
}
|
||||
};
|
||||
if response.is_none() {
|
||||
return Err("消息接收服务停止失败".into());
|
||||
}
|
||||
wechat.listening = false;
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
pub fn recv_msg(client: &nng::Socket) -> Result<Option<wcf::WxMsg>, Box<dyn std::error::Error>> {
|
||||
let mut msg = match client.recv() {
|
||||
Ok(msg) => msg,
|
||||
Err(e) => {
|
||||
warn!("Socket消息接收失败: {}", e);
|
||||
return Ok(None);
|
||||
}
|
||||
};
|
||||
// 反序列化为prost消息
|
||||
let res = match wcf::Response::decode(msg.as_slice()) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("反序列化失败: {}", e);
|
||||
return Err("微信消息接收失败".into());
|
||||
}
|
||||
};
|
||||
msg.clear();
|
||||
let res_msg = res.msg;
|
||||
match res_msg {
|
||||
Some(wcf::response::Msg::Wxmsg(msg)) => {
|
||||
return Ok(Some(msg));
|
||||
}
|
||||
_ => {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取消息类型
|
||||
* {"47": "石头剪刀布 | 表情图片", "62": "小视频", "43": "视频", "1": "文字", "10002": "撤回消息", "40": "POSSIBLEFRIEND_MSG", "10000": "红包、系统消息", "37": "好友确认", "48": "位置", "42": "名片", "49": "共享实时位置、文件、转账、链接", "3": "图片", "34": "语音", "9999": "SYSNOTICE", "52": "VOIPNOTIFY", "53": "VOIPINVITE", "51": "微信初始化", "50": "VOIPMSG"}
|
||||
*/
|
||||
pub fn get_msg_types(
|
||||
wechat: &mut WeChat,
|
||||
) -> Result<HashMap<i32, String>, Box<dyn std::error::Error>> {
|
||||
let req = wcf::Request {
|
||||
func: wcf::Functions::FuncGetMsgTypes.into(),
|
||||
msg: None,
|
||||
};
|
||||
let response = match send_cmd(wechat, req) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("命令发送失败: {}", e);
|
||||
return Err("获取消息类型失败".into());
|
||||
}
|
||||
};
|
||||
if response.is_none() {
|
||||
return Ok(HashMap::default());
|
||||
}
|
||||
match response.unwrap() {
|
||||
wcf::response::Msg::Types(msg_types) => {
|
||||
let types = msg_types.types;
|
||||
return Ok(types);
|
||||
}
|
||||
_ => {
|
||||
return Ok(HashMap::default());
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn accept_new_friend(
|
||||
v3: String,
|
||||
v4: String,
|
||||
scene: i32,
|
||||
wechat: &mut WeChat,
|
||||
) -> Result<bool, Box<dyn std::error::Error>> {
|
||||
let req = wcf::Request {
|
||||
func: wcf::Functions::FuncAcceptFriend.into(),
|
||||
msg: Some(wcf::request::Msg::V(wcf::Verification { v3, v4, scene })),
|
||||
};
|
||||
let response = match send_cmd(wechat, req) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("命令发送失败: {}", e);
|
||||
return Err("同意加好友请求失败".into());
|
||||
}
|
||||
};
|
||||
if response.is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
match response.unwrap() {
|
||||
wcf::response::Msg::Status(status) => {
|
||||
return Ok(status == 1);
|
||||
}
|
||||
_ => {
|
||||
return Ok(false);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn add_chatroom_members(
|
||||
roomid: String,
|
||||
wxids: String,
|
||||
wechat: &mut WeChat,
|
||||
) -> Result<bool, Box<dyn std::error::Error>> {
|
||||
let req = wcf::Request {
|
||||
func: wcf::Functions::FuncAddRoomMembers.into(),
|
||||
msg: Some(wcf::request::Msg::M(wcf::AddMembers { roomid, wxids })),
|
||||
};
|
||||
let response = match send_cmd(wechat, req) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("命令发送失败: {}", e);
|
||||
return Err("微信群加人失败".into());
|
||||
}
|
||||
};
|
||||
if response.is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
match response.unwrap() {
|
||||
wcf::response::Msg::Status(status) => {
|
||||
return Ok(status == 1);
|
||||
}
|
||||
_ => {
|
||||
return Ok(false);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn del_chatroom_members(
|
||||
roomid: String,
|
||||
wxids: String,
|
||||
wechat: &mut WeChat,
|
||||
) -> Result<bool, Box<dyn std::error::Error>> {
|
||||
let req = wcf::Request {
|
||||
func: wcf::Functions::FuncDelRoomMembers.into(),
|
||||
msg: Some(wcf::request::Msg::M(wcf::AddMembers { roomid, wxids })),
|
||||
};
|
||||
let response = match send_cmd(wechat, req) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("命令发送失败: {}", e);
|
||||
return Err("微信群踢人失败".into());
|
||||
}
|
||||
};
|
||||
if response.is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
match response.unwrap() {
|
||||
wcf::response::Msg::Status(status) => {
|
||||
return Ok(status == 1);
|
||||
}
|
||||
_ => {
|
||||
return Ok(false);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn decrypt_image(
|
||||
src: String,
|
||||
dst: String,
|
||||
wechat: &mut WeChat,
|
||||
) -> Result<bool, Box<dyn std::error::Error>> {
|
||||
let req = wcf::Request {
|
||||
func: wcf::Functions::FuncDecryptImage.into(),
|
||||
msg: Some(wcf::request::Msg::Dec(wcf::DecPath { src, dst })),
|
||||
};
|
||||
let response = match send_cmd(wechat, req) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("命令发送失败: {}", e);
|
||||
return Err("图片解密失败".into());
|
||||
}
|
||||
};
|
||||
if response.is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
match response.unwrap() {
|
||||
wcf::response::Msg::Status(status) => {
|
||||
return Ok(status == 1);
|
||||
}
|
||||
_ => {
|
||||
return Ok(false);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn recv_transfer(
|
||||
wxid: String,
|
||||
transferid: String,
|
||||
transcationid: String,
|
||||
wechat: &mut WeChat,
|
||||
) -> Result<bool, Box<dyn std::error::Error>> {
|
||||
let req = wcf::Request {
|
||||
func: wcf::Functions::FuncRecvTransfer.into(),
|
||||
msg: Some(wcf::request::Msg::Tf(wcf::Transfer {
|
||||
wxid: wxid,
|
||||
taid: transferid,
|
||||
tfid: transcationid,
|
||||
})),
|
||||
};
|
||||
let response = match send_cmd(wechat, req) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
error!("命令发送失败: {}", e);
|
||||
return Err("接收转账失败".into());
|
||||
}
|
||||
};
|
||||
if response.is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
match response.unwrap() {
|
||||
wcf::response::Msg::Status(status) => {
|
||||
return Ok(status == 1);
|
||||
}
|
||||
_ => {
|
||||
return Ok(false);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
mod test {
|
||||
|
||||
#[test]
|
||||
fn test_start_stop() {
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
let mut wechat = crate::wechat::WeChat::new(false);
|
||||
thread::sleep(Duration::from_secs(20));
|
||||
let _ = crate::wechat::stop(&mut wechat);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_login() {
|
||||
let mut wechat = crate::wechat::WeChat::default();
|
||||
let is_login = crate::wechat::is_login(&mut wechat).unwrap();
|
||||
println!("IsLogin: {}", is_login);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_self_wx_id() {
|
||||
let mut wechat = crate::wechat::WeChat::default();
|
||||
let wx_id = crate::wechat::get_self_wx_id(&mut wechat).unwrap().unwrap();
|
||||
println!("WxId: {}", wx_id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_contacts() {
|
||||
let mut wechat = crate::wechat::WeChat::default();
|
||||
let contacts = crate::wechat::get_contacts(&mut wechat).unwrap().unwrap();
|
||||
println!("WxId: {:?}", contacts);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_send_text() {
|
||||
let mut wechat = crate::wechat::WeChat::default();
|
||||
let status = crate::wechat::send_text(
|
||||
&mut wechat,
|
||||
String::from("Hello, wcferry!"),
|
||||
String::from("filehelper"),
|
||||
String::from(""),
|
||||
)
|
||||
.unwrap();
|
||||
println!("Success: {}", status);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_send_image() {
|
||||
use std::path::PathBuf;
|
||||
|
||||
let mut wechat = crate::wechat::WeChat::default();
|
||||
let status = crate::wechat::send_image(
|
||||
&mut wechat,
|
||||
PathBuf::from("C:\\Users\\Administrator\\Pictures\\1.jpg"),
|
||||
String::from("filehelper"),
|
||||
)
|
||||
.unwrap();
|
||||
println!("Success: {}", status);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_recv_msg() {
|
||||
let mut wechat = crate::wechat::WeChat::default();
|
||||
let mut socket = crate::wechat::enable_listen(&mut wechat).unwrap();
|
||||
for _ in 1..5 {
|
||||
let msg = crate::wechat::recv_msg(&mut socket).unwrap();
|
||||
println!("WxMsg: {:?}", msg);
|
||||
}
|
||||
let _ = crate::wechat::disable_listen(&mut wechat);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_msg_types() {
|
||||
let mut wechat = crate::wechat::WeChat::default();
|
||||
let types = crate::wechat::get_msg_types(&mut wechat);
|
||||
println!("{:?}", types);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_accept_new_friend() {
|
||||
let mut wechat = crate::wechat::WeChat::default();
|
||||
let v3 = String::from("v3_020b3826fd03010000000000d65613e9435fd2000000501ea9a3dba12f95f6b60a0536a1adb6b4e20a513856625d11892e0635fe745d9c7ee96937f341a860c34107c6417414e5b41e427fc3d26a6af2590a1f@stranger");
|
||||
let v4 = String::from("v4_000b708f0b0400000100000000003c3767b326120d5b5795b98031641000000050ded0b020927e3c97896a09d47e6e9eac7eea28e4a39b49644b3b702b82268c1d40370261e3ae6eb543d231fbd29ee7a326598ba810316c10171871103ad967ca4d147d9f6dd8fa5ccd4986042520a1173c8138e5afe21f795ee50fecf58b4ac5269acd80028627dbf65fd17ca57c0e479fbe0392288a6f42@stranger");
|
||||
let status = crate::wechat::accept_new_friend(v3, v4, 17, &mut wechat).unwrap();
|
||||
println!("Status: {}", status);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_add_chatroom_members() {
|
||||
let mut wechat = crate::wechat::WeChat::default();
|
||||
let status = crate::wechat::add_chatroom_members(
|
||||
String::from("*****@chatroom"),
|
||||
String::from("****"),
|
||||
&mut wechat,
|
||||
)
|
||||
.unwrap();
|
||||
println!("Status: {}", status);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_del_chatroom_members() {
|
||||
let mut wechat = crate::wechat::WeChat::default();
|
||||
let status = crate::wechat::del_chatroom_members(
|
||||
String::from("34476879773@chatroom"),
|
||||
String::from("*******"),
|
||||
&mut wechat,
|
||||
)
|
||||
.unwrap();
|
||||
println!("Status: {}", status);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_user_info() {
|
||||
let mut wechat = crate::wechat::WeChat::default();
|
||||
let user_info = crate::wechat::get_user_info(&mut wechat).unwrap();
|
||||
println!("UserInfo: {:?}", user_info);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_recv_transfer() {
|
||||
let mut wechat = crate::wechat::WeChat::default();
|
||||
let status = crate::wechat::recv_transfer(
|
||||
String::from("****"),
|
||||
String::from("1000050001202306300415889890620"),
|
||||
String::from("100005000123063000081247810011296088"),
|
||||
&mut wechat,
|
||||
)
|
||||
.unwrap();
|
||||
println!("Status: {}", status);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_decrypt_image() {
|
||||
let mut wechat = crate::wechat::WeChat::default();
|
||||
let status = crate::wechat::decrypt_image(
|
||||
String::from("C:\\Users\\Administrator\\Documents\\WeChat Files\\****\\FileStorage\\MsgAttach\\c963b851e0578c320c2966c6fc49e35c\\Image\\2023-05\\c66044e188c64452e236e53eff73324b.dat"),
|
||||
String::from("C:\\foo"),
|
||||
&mut wechat,
|
||||
)
|
||||
.unwrap();
|
||||
println!("Status: {}", status);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user