Python操作WeChat

准备工作
因对于WeChat本身也开放了Python SDK,但基于此我们借助了强大的wxpy来操作WeChat,因此我们需要用到wxpy模块,它能登陆和操作微信账号,涵盖大部分 Web 微信的功能。

初始化/登陆

1
2
3
from wxpy import *
#终端下执行时会弹出二维码图片进行微信授权登录,请使用微信扫描
bot = Bot()

好友操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#1、添加好友,添加名为SS的好友,并发送验证信息
bot.add_friend('SS', verify_content='我是你的好友XXX')
# 接受用户为好友
bot.accept_friend('SS', verify_content='我是你的好友XXX')
# 自动接受好友请求代码如下
# 注册好友请求类消息
@bot.register(msg_types=FRIENDS)
# 自动接受验证信息中包含 'hanggecrazy' 的好友请求
def auto_accept_friends(msg):
# 判断好友请求中的验证文本
if 'hanggecrazy' in msg.text.lower():
# 接受好友 (msg.card 为该请求的用户对象)
new_friend = bot.accept_friend(msg.card)
# 或 new_friend = msg.card.accept()
# 向新的好友发送消息
new_friend.send('您好,我已经接受了您的好友请求,谢谢!')
#2、获取好友
bf = bot.friends()
# 统计好友或群成员的性别和地区分布
bf.stats_text()
#3、用户查找,查找在四川成都用户名为SS的女性好友
friend = bf.search('SS', sex=FEMALE, province='四川', city='成都')[0]
#4、向好友发送消息,文本/图片/视频/文件/动图等
friend.send('Hello, WeChat!')
friend.send_image('my_picture.png')
friend.send_video('my_video.mov')
friend.send_file('my_file.zip')
friend.send('@img@my_picture.png')

群组操作

1
2
3
4
5
6
7
8
#1、创建群组,将好友SS1和SS2添加到名为"兴趣组"的群组中
bot.create_group(users=["SS1","SS2"],topic="兴趣组")
#2、获取群组
bg = bot.groups()
# 群组查询,查找名为"兴趣组"的群组
group = bg.search('兴趣组')[0]
#3、向群组发送消息,文本/图片/视频/文件/动图等,操作和好友消息一致
group.send('Hello, WeChat!')

公众号操作

1
2
3
4
5
6
7
8
#1、添加公众号,添加名为SS的公众号
bot.add_mp('SS')
#2、获取关注公众号
bm = bot.mps()
#3、公众号查询,查找名为SS的公众号
mps = bm.search('SS')[0]
#4、向公众号发送消息,文本/图片/视频/文件/动图等,操作和好友消息一致
mps.send('Hello, WeChat!')

最近消息操作

1
2
3
4
#1、获取最近发过消息的好友/公众号/群组等
bc = bot.chats()
#2、查找最近聊天的好友并发送消息,操作和上述好友群组公众号一致
bc = bot.chats().search('SS')[0].send('Hello, WeChat!')

监听WeChat消息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 打印来自其他好友、群聊和公众号的消息
@bot.register()
def print_others(msg):
print(msg)
# 回复 friend 的消息 (优先匹配后注册的函数!)
@bot.register(friend)
def reply_my_friend(msg):
return 'received: {} ({})'.format(msg.text, msg.type)
# 进入Python 命令行,让程序保持运行,接受消息
embed()
# 或者仅仅堵塞线程
bot.join()

(The End)

坚持原创技术分享,您的支持将鼓励我继续创作!