首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >用wxpy玩转微信

用wxpy玩转微信

作者头像
DC童生
发布2019-01-28 11:15:28
1.5K0
发布2019-01-28 11:15:28
举报
文章被收录于专栏:机器学习原理机器学习原理

模拟登陆

from wxpy import *
bot = Bot()

寻找聊天对象

通过机器人对象 Botchats(), friends()groups(), mps() 方法, 可分别获取到当前机器人的 所有聊天对象、好友、群聊,以及公众号列表。

from wxpy import *
bot = Bot()
#获取公众号列表
my_friend = bot.mps()
print(my_friend)

获取之后可以用send方法进行发送消息

# 发送文本
my_friend.send('Hello, WeChat!')
# 发送图片
my_friend.send_image('my_picture.png')
# 发送视频
my_friend.send_video('my_video.mov')
# 发送文件
my_friend.send_file('my_file.zip')
# 以动态的方式发送图片
my_friend.send('@img@my_picture.png')

获取聊天对象之后你可以查看你微信圈里好友的性别、年龄、地点等属性, 可以做成统计图如下:

image.png

消息处理

每当机器人接收到消息时,会自动执行以下两个步骤

  • 将消息保存到 Bot.messages 中
  • 查找消息预先注册的函数,并执行(若有匹配的函数)
#将公司老板的群里面的重要发言转发出来
from wxpy import *

bot = Bot()

# 定位公司群
company_group = ensure_one(bot.groups().search('公司微信群'))

# 定位老板
boss = ensure_one(company_group.search('老板大名'))

# 将老板的消息转发到文件传输助手
@bot.register(company_group)
def forward_boss_message(msg):
    if msg.member == boss:
        msg.forward(bot.file_helper, prefix='老板发言')

# 堵塞线程
embed()

实现自动回复功能

if __name__ =="__main__":
    SourceSavePath = './RecieveFile/'

    bot = Bot(cache_path=True)
    myFriend = bot.friends()  # 被处理消息的对象或对象集合


    # myFriend += bot.groups().search('GroupName') #添加群

    @bot.register(myFriend)  # 注册消息处理方法
    def Del_GroupMsg(msg):
        print(msg.sender.name, ':', msg.text, 'Msg Type:', msg.type)
        msg.sender.mark_as_read()
        if msg.type == TEXT:  
            return aiqa(msg.text)
        elif msg.type == PICTURE:  # 如果接受到图片,就自动回复同样的图片
            print('this is PICTURE:{}'.format(msg.file_name))
            savaPath = SourceSavePath + msg.file_name
            msg.get_file(savaPath)
            msg.reply_image(savaPath)
        else:  # 其它的就转发回给发送人
            msg.forward(msg.sender)
    embed()

用微信监控你的程序

微信中建立一个群聊,并在里面加入需要关注这些日志的人员。然后把这个群作为接收者。

from wxpy import get_wechat_logger

# 获得一个专用 Logger
# 当不设置 `receiver` 时,会将日志发送到随后扫码登陆的微信的"文件传输助手"
logger = get_wechat_logger()

# 发送警告
logger.warning('这是一条 WARNING 等级的日志,你收到了吗?')

# 接收捕获的异常
try:
    1 / 0
except:
    logger.exception('现在你又收到了什么?')
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.01.18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 模拟登陆
  • 寻找聊天对象
  • 消息处理
  • 用微信监控你的程序
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档