Skip to content

Commit

Permalink
添加使用例子
Browse files Browse the repository at this point in the history
  • Loading branch information
smallevilbeast committed Aug 23, 2022
1 parent ab8995f commit be10cf4
Show file tree
Hide file tree
Showing 15 changed files with 273 additions and 4 deletions.
Empty file added examples/__init__.py
Empty file.
32 changes: 32 additions & 0 deletions examples/auto_accept_friend_request.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# -*- coding: utf-8 -*-
import sys
import ntchat
import xml.dom.minidom

wechat = ntchat.WeChat()

# 打开pc微信, smart: 是否管理已经登录的微信
wechat.open(smart=False)


# 注册消息回调
@wechat.msg_register(ntchat.MT_RECV_FRIEND_MSG)
def on_recv_text_msg(wechat_instance: ntchat.WeChat, message):
xml_content = message["data"]["raw_msg"]
dom = xml.dom.minidom.parseString(xml_content)

# 从xml取相关参数
encryptusername = dom.documentElement.getAttribute("encryptusername")
ticket = dom.documentElement.getAttribute("ticket")
scene = dom.documentElement.getAttribute("scene")

# 自动同意好友申请
wechat_instance.accept_friend_request(encryptusername, ticket, int(scene))


try:
while True:
pass
except KeyboardInterrupt:
ntchat.exit_()
sys.exit()
28 changes: 28 additions & 0 deletions examples/echo_bot_msg_register.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# -*- coding: utf-8 -*-
import sys
import ntchat

wechat = ntchat.WeChat()

# 打开pc微信, smart: 是否管理已经登录的微信
wechat.open(smart=False)


# 注册消息回调
@wechat.msg_register(ntchat.MT_RECV_TEXT_MSG)
def on_recv_text_msg(wechat_instance: ntchat.WeChat, message):
data = message["data"]
from_wxid = data["from_wxid"]
self_wxid = wechat_instance.get_login_info()["wxid"]

# 判断消息不是自己发的,并回复对方
if from_wxid != self_wxid:
wechat_instance.send_text(to_wxid=from_wxid, content=f"你发送的消息是: {data['msg']}")


try:
while True:
pass
except KeyboardInterrupt:
ntchat.exit_()
sys.exit()
29 changes: 29 additions & 0 deletions examples/echo_bot_on.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# -*- coding: utf-8 -*-
import sys
import ntchat

wechat = ntchat.WeChat()

# 打开pc微信, smart: 是否管理已经登录的微信
wechat.open(smart=False)


def on_recv_text_msg(wechat_instance: ntchat.WeChat, message):
data = message["data"]
from_wxid = data["from_wxid"]
self_wxid = wechat_instance.get_login_info()["wxid"]

# 判断消息不是自己发的,并回复对方
if from_wxid != self_wxid:
wechat_instance.send_text(to_wxid=from_wxid, content=f"你发送的消息是: {data['msg']}")


# 监听接收文本消息
wechat.on(ntchat.MT_RECV_TEXT_MSG, on_recv_text_msg)

try:
while True:
pass
except KeyboardInterrupt:
ntchat.exit_()
sys.exit()
25 changes: 25 additions & 0 deletions examples/get_contacts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# -*- coding: utf-8 -*-
import sys
import ntchat

wechat = ntchat.WeChat()

# 打开pc微信, smart: 是否管理已经登录的微信
wechat.open(smart=False)

# 等待登录
wechat.wait_login()

# 获取联系人列表并输出
contacts = wechat.get_contacts()

print("联系人列表: ")
print(contacts)


try:
while True:
pass
except KeyboardInterrupt:
ntchat.exit_()
sys.exit()
25 changes: 25 additions & 0 deletions examples/get_rooms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# -*- coding: utf-8 -*-
import sys
import ntchat

wechat = ntchat.WeChat()

# 打开pc微信, smart: 是否管理已经登录的微信
wechat.open(smart=False)

# 等待登录
wechat.wait_login()

# 获取联系人列表并输出
rooms = wechat.get_rooms()

print("群列表: ")
print(rooms)


try:
while True:
pass
except KeyboardInterrupt:
ntchat.exit_()
sys.exit()
9 changes: 9 additions & 0 deletions examples/multi_open.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# -*- coding: utf-8 -*-
import sys
import ntchat

# 多开3个微信
for i in range(3):
wechat = ntchat.WeChat()
wechat.open()

16 changes: 16 additions & 0 deletions examples/resources/send_text_ui.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--炫彩界面库-窗口布局文件-->
<head>
<bindJsFile value="" />
</head>
<windowUI center="true" content="ntchat界面演示" enableLayout="true" layout.horizon="true" padding="5,5,5,5" rect="20,20,761,571" windowStyle="2031" showT="true">
<editUI drawBorder="true" layout.height="fill" layout.width=":1" multiLine="true" name="edit_log" rect="246,187,100,20" scrollBarShowH="false" scrollBarShowV="true" showT="true" expandT="true" />
<elementUI layout.float="true" layout.height="fill" rect="219,85,200,100" transparent="true" showT="true" expandT="true">
<editUI content="filehelper" name="edit_wxid" rect="65,106,116,27" showT="true" expandT="true" />
<editUI content="消息来自ntchat" name="edit_content" rect="65,151,116,27" showT="true" expandT="true" />
<shapeText content="wxid" layout.height="20" layout.width="auto" rect="18,110,61,20" showT="true" expandT="true" />
<shapeText content="消息" layout.height="20" layout.width="auto" rect="20,156,61,20" showT="true" expandT="true" />
<buttonUI content="发送消息" name="btn_send" rect="93,192,60,25" showT="true" expandT="true" />
<buttonUI content="打开微信" name="btn_open" rect="47,31,120,25" showT="true" expandT="true" />
</elementUI>
</windowUI>
16 changes: 16 additions & 0 deletions examples/resources/warn.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
24 changes: 24 additions & 0 deletions examples/send_text.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# -*- coding: utf-8 -*-
import sys
import ntchat

wechat = ntchat.WeChat()

# 打开pc微信, smart: 是否管理已经登录的微信
wechat.open(smart=False)

# 等待登录
wechat.wait_login()

# 向文件助手发送一条消息
wechat.send_text(to_wxid="filehelper", content="hello, filehelper")

try:
while True:
pass
except KeyboardInterrupt:
ntchat.exit_()
sys.exit()



53 changes: 53 additions & 0 deletions examples/send_text_ui.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import xcgui
import ntchat
from xcgui import XApp, XWindow


class NtChatWindow(XWindow):
def __init__(self):
super(NtChatWindow, self).__init__()
self.loadLayout("resources\\send_text_ui.xml")
self.setMinimumSize(600, 500)

btn: xcgui.XButton = self.findObjectByName("btn_open")
btn.regEvent(xcgui.XE_BNCLICK, self.on_btn_open_clicked)

btn: xcgui.XButton = self.findObjectByName("btn_send")
btn.regEvent(xcgui.XE_BNCLICK, self.on_btn_send_clicked)

self.edit_wxid: xcgui.XEdit = self.findObjectByName("edit_wxid")
self.edit_content: xcgui.XEdit = self.findObjectByName("edit_content")
self.edit_log: xcgui.XEdit = self.findObjectByName("edit_log")
self.edit_log.enableAutoWrap(True)

self.wechat_instance: ntchat.WeChat = None

def on_btn_open_clicked(self, sender, _):
self.wechat_instance = ntchat.WeChat()
self.wechat_instance.open()
self.wechat_instance.on(ntchat.MT_ALL, self.on_recv_message)

def on_btn_send_clicked(self, sender, _):
if not self.wechat_instance.login_status:
svg = xcgui.XSvg.loadFile("resources\\warn.svg")
svg.setSize(16, 16)
self.notifyMsgWindowPopup(xcgui.position_flag_top, "警告", "请先打开并登录微信",
xcgui.XImage.loadSvg(svg), xcgui.notifyMsg_skin_warning)
else:
self.wechat_instance.send_text(self.edit_wxid.getText(), self.edit_content.getText())

def on_recv_message(self, wechat, message):
text = self.edit_log.getText()
text += "\n"
text += str(message)
self.edit_log.setText(text)
self.redraw()


if __name__ == '__main__':
app = XApp()
window = NtChatWindow()
window.showWindow()
app.run()
ntchat.exit_()
app.exit()
8 changes: 8 additions & 0 deletions examples/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import xml.dom.minidom

content = "<msg fromusername=\"houshao55\" encryptusername=\"v3_020b3826fd03010000000000e1b4234fe9f149000000501ea9a3dba12f95f6b60a0536a1adb6b8611b62b0df6381d864972ef3e95c0a10c1a9d455c8adf40eb8b2ba8bc7f156d6253929391104861ffa18287b@stranger\" fromnickname=\"pony\" content=\"我是小邪\" fullpy=\"pony\" shortpy=\"PONY\" imagestatus=\"3\" scene=\"6\" country=\"CN\" province=\"Chongqing\" city=\"Yongchuan\" sign=\"紧急情况,暂不联系\" percard=\"1\" sex=\"1\" alias=\"\" weibo=\"\" albumflag=\"0\" albumstyle=\"0\" albumbgimgid=\"\" snsflag=\"273\" snsbgimgid=\"http://szmmsns.qpic.cn/mmsns/2HibCL9x8HGxjfnzSK4zEiblwegh91AYYxBhnjALCHHctG3M5FrWyiaMVjLs40nopBThPpwtb0roCY/0\" snsbgobjectid=\"13330254115216625842\" mhash=\"0f3d85bd036c653100b5daf3cb1ab030\" mfullhash=\"0f3d85bd036c653100b5daf3cb1ab030\" bigheadimgurl=\"http://wx.qlogo.cn/mmhead/ver_1/RV52ICEKwkLzDs6KndnljtBfYSxnTT9nxD68GAvdOGXbjLxS0XUBYjNfk4VpDVazAKRuvAB3w9z4oMQT6QgPqw/0\" smallheadimgurl=\"http://wx.qlogo.cn/mmhead/ver_1/RV52ICEKwkLzDs6KndnljtBfYSxnTT9nxD68GAvdOGXbjLxS0XUBYjNfk4VpDVazAKRuvAB3w9z4oMQT6QgPqw/96\" ticket=\"v4_000b708f0b040000010000000000d9712677ef696796e9ae327e04631000000050ded0b020927e3c97896a09d47e6e9effc42d6c4f20c96254081b9aa8fe92a45be60783e3a024d97fdd10ac346452a96a122ca0005ff86a0f796a18811964682d051fed83fe1bbc85e0853b5ed10c4a9c333eba81bcd1fe932bb7e6b273471c810815c8e16422b1510453d423e7d0c4d0aea84f018283561a@stranger\" opcode=\"2\" googlecontact=\"\" qrticket=\"\" chatroomusername=\"\" sourceusername=\"\" sourcenickname=\"\" sharecardusername=\"\" sharecardnickname=\"\" cardversion=\"\" extflag=\"0\"><brandlist count=\"0\" ver=\"774271408\"></brandlist></msg>"
dom = xml.dom.minidom.parseString(content)
encryptusername = dom.documentElement.getAttribute("encryptusername")
ticket = dom.documentElement.getAttribute("ticket")
scene = dom.documentElement.getAttribute("scene")
print(dom.documentElement.getAttribute("encryptusername"))
2 changes: 1 addition & 1 deletion ntchat/const/wx_type.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@

MT_ALL = 11000
MT_READY_MSG = 11024
MT_USER_LOGIN_MSG = 11025
MT_USER_LOGOUT_MSG = 11026
Expand Down
8 changes: 6 additions & 2 deletions ntchat/core/wechat.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,21 +69,25 @@ def wrapper(f):
return wrapper

def on_recv(self, message):
log.debug("on recv message: %s", message)
msg_type = message["type"]
extend = message.get("extend", None)
if msg_type == wx_type.MT_USER_LOGIN_MSG:
self.login_status = False
self.login_status = True
self.__wait_login_event.set()
self.__login_info = message.get("data", {})
log.info("login success, wxid: %s, nickname: %s", self.__login_info["wxid"], self.__login_info["nickname"])
elif msg_type == wx_type.MT_USER_LOGOUT_MSG:
self.login_status = False
log.info("logout, pid: %d", self.pid)

if extend is not None and extend in self.__req_data_cache:
req_data = self.__req_data_cache[extend]
req_data.on_response(message)
del self.__req_data_cache[extend]
else:
self.__msg_event_emitter.emit(str(msg_type), self, message)
self.__msg_event_emitter.emit(str(wx_type.MT_ALL), self, message)

def wait_login(self, timeout=None):
log.info("wait login...")
Expand Down Expand Up @@ -114,7 +118,7 @@ def __send(self, msg_type, data=None, extend=None):
if extend is not None:
message["extend"] = extend
message_json = json.dumps(message)
log.debug("communicate wechat pid:%d, data: %s", self.pid, message)
log.debug("communicate wechat pid: %d, data: %s", self.pid, message)
return wcprobe.send(self.client_id, message_json)

def __send_sync(self, msg_type, data=None, timeout=10):
Expand Down
2 changes: 1 addition & 1 deletion ntchat/utils/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def get_logger(name: str) -> logging.Logger:

filepath = f'{base_dir}/log-{time_now.strftime(time_format)}.txt'

file_handler = logging.FileHandler(filepath, 'a')
file_handler = logging.FileHandler(filepath, 'a', encoding='utf-8')
file_handler.setLevel(NTCHAT_LOG)
file_handler.setFormatter(log_formatter)
logger.addHandler(file_handler)
Expand Down

0 comments on commit be10cf4

Please sign in to comment.