Demo simple respones to group @ message

This commit is contained in:
Changhua
2022-09-25 19:15:20 +08:00
parent 71b3a14e15
commit 7d0ffbac15
14 changed files with 158 additions and 2 deletions

65
robot/base_robot.py Normal file
View File

@@ -0,0 +1,65 @@
# -*- coding: utf-8 -*-
import re
import logging
class BaseRobot(object):
def __init__(self, sdk, config) -> None:
self.sdk = sdk
self.config = config
self.LOG = logging.getLogger("Robot")
def onMsg(self, msg) -> int:
try:
self.processMsg(msg)
except Exception as e:
self.LOG.error(e)
self.printRawMsg(msg)
return 0
def initSDK(self):
if self.sdk.WxInitSDK() != 0:
self.LOG.error("初始化失败")
exit(-1)
self.LOG.info("初始化成功")
self.wxid = self.sdk.WxGetSelfWxid()
def enableRecvMsg(self):
self.sdk.WxEnableRecvMsg(self.onMsg)
def sendTextMsg(self, receiver, msg, at_list=""):
# msg 中需要有 @ 名单中一样数量的 @
ats = ""
if at_list:
# 这里只简单补全数量,后续可以补充群昵称(通过 SQL 获取)
ats = " @" * len(at_list.split(","))
self.sdk.WxSendTextMsg(receiver, f"{msg}{ats}", at_list)
def isGroupChat(self, msg):
return msg.source == 1
def isAt(self, msg, exclude_at_all=True):
atall = []
atuserlist = re.findall(f"<atuserlist>.*({self.wxid}).*</atuserlist>", msg.xml)
if exclude_at_all:
atall = re.findall(f"@所有人", msg.content) # 排除@所有人
return (len(atuserlist) > 0) and (len(atall) == 0)
def printRawMsg(self, msg) -> None:
rmsg = {}
rmsg["id"] = msg.id
rmsg["self"] = msg.self
rmsg["wxId"] = msg.wxId
rmsg["roomId"] = msg.roomId
rmsg["type"] = msg.type
rmsg["source"] = msg.source
rmsg["xml"] = msg.xml
rmsg["content"] = msg.content
self.LOG.info(rmsg)
def processMsg(self, msg) -> None:
raise NotImplementedError("Method [processMsg] should be implemented.")

29
robot/configuration.py Normal file
View File

@@ -0,0 +1,29 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import yaml
import logging.config
class Config(object):
def __init__(self) -> None:
self.reload()
def _load_config(self) -> dict:
pwd = os.path.dirname(os.path.abspath(__file__))
try:
with open(f"{pwd}/config.yaml", "rb") as fp:
yconfig = yaml.safe_load(fp)
except FileNotFoundError:
with open(f"{pwd}/../config.yaml.template", "rb") as fp:
yconfig = yaml.safe_load(fp)
with open(f"{pwd}/config.yaml", "w+") as yf:
yaml.dump(yconfig, yf, default_flow_style=False)
return yconfig
def reload(self):
yconfig = self._load_config()
logging.config.dictConfig(yconfig["logging"])
self.GROUPS = yconfig["groups"]["enable"]

BIN
robot/sdk/App.exe Normal file

Binary file not shown.

84
robot/sdk/App.py Normal file
View File

@@ -0,0 +1,84 @@
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import time
import wcferry as sdk
def main():
help(sdk) # 查看SDK支持的方法和属性
# 初始化SDK如果成功返回0否则失败
status = sdk.WxInitSDK()
if status != 0:
print("初始化失败")
exit(-1)
print("初始化成功")
WxMsgTypes = sdk.WxGetMsgTypes() # 获取消息类型
print(WxMsgTypes) # 查看消息类型
time.sleep(2)
print("打印通讯录......")
contacts = sdk.WxGetContacts()
for k, v in contacts.items():
print(k, v.wxCode, v.wxName, v.wxCountry, v.wxProvince, v.wxCity, v.wxGender)
time.sleep(2)
print("发送文本消息......")
sdk.WxSendTextMsg("filehelper", "message from WeChatFerry...") # 往文件传输助手发消息
# sdk.WxSendTextMsg("xxxx@chatroom", "message from WeChatFerry...") # 往群里发消息(需要改成正确的 ID下同
# sdk.WxSendTextMsg("xxxx@chatroom", "message from WeChatFerry... @ ", "wxid_xxxxxxxxxxxx") # 往群里发消息,@某人
# sdk.WxSendTextMsg("xxxx@chatroom", "message from WeChatFerry... @ ", "notify@all") # 往群里发消息,@所有人
time.sleep(2)
print("发送图片消息......")
sdk.WxSendImageMsg("filehelper", "test.jpg")
dbs = sdk.WxGetDbNames()
for db in dbs:
print(db)
tables = sdk.WxGetDbTables(dbs[0])
for t in tables:
print(f"{t.table}\n{t.sql}\n\n")
# 接收消息。先定义消息处理回调
def OnTextMsg(msg: sdk.WxMessage):
def getName(id):
contact = contacts.get(id)
if contact is None:
return id
return contact.wxName
s = "收到"
if msg.self == 1: # 忽略自己发的消息
s += f"来自自己的消息"
print(f"\n{s}")
return 0
msgType = WxMsgTypes.get(msg.type, '未知类型')
nickName = getName(msg.wxId)
if msg.source == 1:
groupName = getName(msg.roomId)
s += f"来自群[{groupName}]的[{nickName}]的{msgType}消息:"
else:
s += f"来自[{nickName}]的{msgType}消息:"
s += f"\r\n{msg.content}"
if msg.type != 0x01:
s += f"\r\n{msg.xml}"
print(f"\n{s}")
return 0
print("Message: 接收通知中......")
sdk.WxEnableRecvMsg(OnTextMsg) # 设置回调,接收消息
while True:
time.sleep(1)
if __name__ == '__main__':
main()

BIN
robot/sdk/SDK.dll Normal file

Binary file not shown.

BIN
robot/sdk/Spy.dll Normal file

Binary file not shown.

BIN
robot/sdk/test.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 399 KiB

BIN
robot/sdk/wcferry.pyd Normal file

Binary file not shown.