python wxpy模块学习

python wxpy 微信机器人

itchat 模块 教学文档:itchat.
wxpy 模块 教学文档 : wxpy.

基础阶段

wxpy模块 的安装
命令行安装:
pip install wxpy
pycharm 安装:
File -> Settings ->Project : xx x ->project Interpreter -> + -> wxpy -> install

1.给自己的微信助手发送消息

#机器人对象,给自己微信的文件传输助手发送消息
from wxpy import *
bot = Bot(cache_path=True)
#机器人账号自身
#myself = bot.self
#想文件传输助手发送消息
bot.file_helper.send('Goodbye of world')

2.基础测试

from wxpy import *
bot = Bot(cache_path=True)
聊天对象puid
bot.enable_puid('wxpy_puid.pkl')
my_friend = bot.friends().search('好友备注')[0]   #wxpy教程文档的 “获取聊天对象”
my_group = bot.groups().search('群昵称')[0]
print('this ID'+my_friend.puid)
my_friend.send('在吗?')
my_friend.send_image('u0.jpg') #可以将image改成其他的文件发送

pkl文件是python的储存文件格式
打开方式:

import pickle
t = open('wxpy_puid.pkl','rb')
data = pickle.load(t)
print(data)

测是好友是否在某个群中

if my_friend in my_group:
    print('yes,{}在{}中!'.format(my_friend.name,my_group.name))

输出某个群中人所有好友语句

for name in my_group:
    print(name)

实际类
好友 Friend
群聊 Group
群成员 Member
公众号 MP

3.小实战

1.将群中的某个好友发言转发给文件助手

from wxpy import *
bot = Bot(cache_path=True)
my_group = ensure_one(bot.groups().search('群名称'))
my_friend = ensure_one(friend_group.search('群名称'))
@bot.register(my_group)
def forward_pan_message(msg):
    if msg.member == my_friend:
        msg.forwad(bot.file_helper,prefix='xx说')
embed()  # 堵塞线程

附:@bot.register(my_group)
预先将特定聊天对象的特定类型消息,注册到对应的处理函数,以实现自动回复等功能。

# 打印所有*群聊*对象中的*文本*消息
@bot.register(Group, TEXT)
def print_group_msg(msg):
    print(msg)

2.忽略 “某个群” 的所有消息
回复好友 “xx” 和其他群聊中被 @ 的 TEXT 类消息
打印所有其他消息

from wxpy import *
bot = Bot(cache_path=True)
my_friend = bot.friends().search('好友备注')[0]
my_group = bot.groups().search('群名称')[0]
@bot.register()
def just_print(msg):
    # 打印消息
    print(msg)
@bot.register([my_friend, Group], TEXT)
def auto_reply(msg):
    # 如果是群聊,但没有被 @,则不回复
    if isinstance(msg.chat, Group) and not msg.is_at:
        return
    else:
        # 回复消息内容和类型
        return '收到消息: {} ({})'.format(msg.text, msg.type)

@bot.register(my_group)
def ignore(msg):
    # 啥也不做
    return
embed()

3.输出自己微信好友的一些信息并统计相关情况

from wxpy import *
# 初始化机器人,扫码登录
# cache_path保持登录,Bot初始化中可以加入参数:console_qr是否在控制台显示二维码
bot = Bot(cache_path=True)
print('登录成功')
# bot.join()
bot.enable_puid('wxpy_puid.pkl')
friends = bot.friends()
sex_male = 0
sex_female = 0
unkown = 0
for i in range(len(friends)):
    print('friends[i]:\t',friends[i])
    print('nick_name:\t', friends[i].nick_name)   # 微信好友的微信昵称
    print('name:\t', friends[i].name)     # 扫码用户对该微信好友的备注
    print('remark_name:\t', friends[i].remark_name)  
    print('bot:\t',friends[i].bot)# 机器人对象 格式为:<Bot: 备注名称>
    print('raw:\t', friends[i].raw) # 微信好友对应的用户详细信息json数据
    print('puid:\t', friends[i].puid)  # 微信好友对应的puid值
    print('Nickname:\t', friends[i].raw['NickName'])  # 打印备注信息
    print('Province:\t', friends[i].raw['Province'])   # 打印好友所在的省份
    print('City:\t\t\t', friends[i].raw['City'])
    print('性别:\t', friends[i].raw['Sex'])

    if friends[i].raw['Sex'] == 1:
        sex_male += 1
    elif friends[i].raw['Sex'] == 2:
        sex_female += 1
    else:
        unkown += 1
print('count of male is:', sex_male, 'count os female is:', sex_female,'不知道性别的共:', unkown)
print('共有好友:', len(friends))
# bot.logout()
# print('退出登录')

4.找到好友列表中昵称为“xx”的好友,监控聊天,打印该好友发来的文本消息,监控群聊消息,打印群聊中的文本消息

from wxpy import *
# 初始化机器人,扫码登录
# cache_path保持登录,Bot初始化中可以加入参数:console_qr是否在控制台显示二维码
bot = Bot(cache_path=True)
print('登录成功')
myfriend = bot.friends().search(u'马萌妹')[0]
@bot.register(myfriend, TEXT)
def print_msg1(msg1):
    print(msg1)
# 监控群聊消息
@bot.register(Group, TEXT)
def print_msg(msg):
    print(msg)
bot.join()

5.自动回复,图灵网站的api

from wxpy import *
bot = Bot(cache_path=True, console_qr=False)
tuling = Tuling(api_key='你在tuling网站申请的api_key')
myfriend = bot.friends().search(u'好友备注')[0]
myfriend1 = bot.self
print(myfriend)
@bot.register()
def reply_msg(msg):
    sender_username = msg.sender.raw['UserName']
    # 输出发送信息的好友或者群聊中的人员信息
    print(sender_username)
    # 判断是否和我设置的想要自动恢复到人一致如果一致调用tuling进行消息回复
    if sender_username == myfriend.raw['UserName']:
        # 输出或得到的消息
        print(msg)
        # 调用tuling机器人回复消息,并将消息赋值给message
        message = tuling.do_reply(msg)
        # 输出回复消息的内容
        print(message)
# 阻塞进程
bot.join()

6.定时自动发送

from __future__ import unicode_literals
from threading import Timer
from wxpy import *
import requests
import random
bot = Bot(cache_path=True)
def get_news():    #网络爬虫
    url = "http://open.iciba.com/dsapi/"
    r = requests.get(url)
    content = r.json()['content']
    note = r.json()['note']
    return content, note
def send_news():
    try:
        contents = get_news()
    # 你朋友的微信名称,不是备注,也不是微信帐号。
    my_friend = bot.friends().search(u'月微凉')[0]
    my_friend.send(contents[0])
    my_friend.send(contents[1])
    my_friend.send(u"晚安")
    # 可以设置每86400秒(1天),发送1次
    t = Timer(300, send_news)
    # 为了防止时间太固定,于是决定对其加上随机数
    ran_int = random.randint(0, 100)
    t = Timer(300 + ran_int, send_news)
    t.start()
    except:
    # 你的微信名称,不是微信帐号。
    my_friend = bot.friends().search('Hhhh')[0]
    my_friend.send(u"哦豁,今天消息发送失败了")
if __name__ == "__main__":
    send_news()
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值