基于ITChat库实现的微信消息与微软小冰的自动转发
itchat库是基于微信Web版本实现的微信控制
2019年后微信Web版本已因安全问题下架,无法再使用
替代的产品是itchat-uos,使用方法和itchat如出一辙
以下代码是基于itchat-uos实现的功能
将目标对象的消息
和小冰的消息
进行相互转发
# encoding = utf-8
import itchat
ICE_USERNAME = "@9e00411451af853d612b0ca9ad4f7cad" # 小冰的UserName缓存
Target_USERNAME = "@对方的UserName非昵称,需通过下面方法获取" # 目标对象的UserName缓存
class WeChatUtils:
@staticmethod
def login():
itchat.auto_login(hotReload=True)
@staticmethod
def username_by_nickname(nick_name):
friends = itchat.search_friends(nickName=nick_name)
user_name = friends["UserName"]
return user_name
@staticmethod
def username_by_mpsname(nick_name):
mps = itchat.search_mps(name=nick_name)
user_name = mps[0]["UserName"]
return user_name
@staticmethod
def send_message(message, target):
itchat.send_msg(message, target)
@itchat.msg_register(itchat.content.TEXT, isFriendChat=True, isMpChat=True)
def on_receive_message(content):
message = content["Text"]
if Target_USERNAME is not None or Target_USERNAME != "":
# 收到target消息,转发给小冰,否则转发给Target
if content["FromUserName"] == Target_USERNAME:
print("target:"+message)
WeChatUtils.send_message(message, ICE_USERNAME)
elif content["FromUserName"] == ICE_USERNAME:
print("语义分析完毕,回复:"+message)
WeChatUtils.send_message(message, Target_USERNAME)
if __name__ == '__main__':
print("准备登录")
WeChatUtils.login()
print("登录完毕,检查TARGET的USERNAME")
if Target_USERNAME is None or Target_USERNAME == "":
#这一步是为了通过昵称获取目标方的UserName
result = WeChatUtils.username_by_nickname("对方的昵称")
Target_USERNAME = result
print("登录完毕,检查ICE的USERNAME")
if ICE_USERNAME is None or ICE_USERNAME == "":
#这一步是为了通过昵称获取微软小冰的UserName
result = WeChatUtils.username_by_mpsname("AI小冰")
ICE_USERNAME = result
print("开始监听消息")
itchat.run()
网友评论