itchat模块实现微信消息撤回功能的方法
发布时间:2023-12-27 07:20:37
itchat是一个基于网页微信的开源模块,可以实现微信的批量登陆、消息获取和发送等功能。但是,itchat并没有提供原生的消息撤回功能。要实现微信消息撤回功能,需要在itchat的基础上进行一些扩展。
下面是实现微信消息撤回功能的方法及使用示例。
1. 导入itchat和time模块
import itchat import time
2. 登陆微信
itchat.auto_login(hotReload=True)
3. 监听消息
@itchat.msg_register([itchat.content.TEXT, itchat.content.PICTURE, itchat.content.RECORDING, itchat.content.ATTACHMENT])
def receive_msg(msg):
# 处理收到的消息
print("收到消息:", msg)
4. 撤回消息函数
def recall_msg(msg_id):
# 调用itchat原生的撤回消息接口
itchat.delete_msg(msg_id)
print("消息已撤回")
5. 监听撤回消息
@itchat.msg_register(itchat.content.FRIENDS)
def receive_recall(msg):
# 处理撤回的消息
if "撤回了一条消息" in msg['Content']:
old_msg = itchat.search_msg(msg_id=msg['MsgId'])
recall_msg(old_msg[0]['NewMsgId'])
6. 运行itchat
itchat.run()
现在,我们可以使用以上代码来实现微信消息撤回功能。当有新的消息发送到微信上时,监听消息函数会被调用。如果收到了撤回消息,监听撤回消息函数会被调用,并通过调用 recall_msg() 函数来撤回消息。
完整的使用例子如下:
import itchat
import time
itchat.auto_login(hotReload=True)
@itchat.msg_register([itchat.content.TEXT, itchat.content.PICTURE, itchat.content.RECORDING, itchat.content.ATTACHMENT])
def receive_msg(msg):
# 处理收到的消息
print("收到消息:", msg)
def recall_msg(msg_id):
# 调用itchat原生的撤回消息接口
itchat.delete_msg(msg_id)
print("消息已撤回")
@itchat.msg_register(itchat.content.FRIENDS)
def receive_recall(msg):
# 处理撤回的消息
if "撤回了一条消息" in msg['Content']:
old_msg = itchat.search_msg(msg_id=msg['MsgId'])
recall_msg(old_msg[0]['NewMsgId'])
itchat.run()
以上就是使用itchat模块实现微信消息撤回功能的方法及使用例子。通过扩展itchat的功能,并在监听消息的基础上添加撤回消息的逻辑,我们可以实现微信消息的撤回功能。
