Python微信机器人

Stella981
• 阅读 672

Python微信机器人

本文目录

  • 一 简介
  • 二 登录微信
  • 三 微信好友男女比例
  • 四 微信好友地域分布
  • 五 微信聊天机器人

一 简介

wxpy基于itchat,使用了 Web 微信的通讯协议,,通过大量接口优化提升了模块的易用性,并进行丰富的功能扩展。实现了微信登录、收发消息、搜索好友、数据统计等功能。

总而言之,可用来实现各种微信个人号的自动化操作。

安装:wxpy 支持 Python 3.4-3.6,以及 2.7 版本

pip3 install  wxpy

安装 pillow模块

pip3 install pillow

安装 pyecharts模块

pip3 install pyecharts

二 登录微信

1 、 扫码登录微信

from wxpy import *

bot = Bot()

2、cache_path=True

运行上面的程序,会弹出二维码,用手机微信扫一扫即可实现登录。

但上面的程序有一个缺点,每次运行都要扫二维码。不过wxpy非常贴心地提供了缓存的选项,用于将登录信息保存下来,就不用每次都扫二维码,如下

bot = Bot(cache_path=True) # 必须先登录过一次以后才可以使用缓存

三 微信好友男女比例

Python微信机器人

from wxpy import *
from pyecharts import Pie
import webbrowser
bot=Bot(cache_path=True) #注意手机确认登录

friends=bot.friends()
#拿到所有朋友对象,放到列表里
attr=['男朋友','女朋友','性别不详']
value=[0,0,0]
for friend in friends:
    if friend.sex == 1: # 等于1代表男性
        value[0]+=1
    elif friend.sex == 2: #等于2代表女性
        value[1]+=1
    else:
        value[2]+=1


pie = Pie("朋友男女比例")
pie.add("", attr, value, is_label_show=True)
#图表名称str,属性名称list,属性所对应的值list,is_label_show是否显示标签
pie.render('sex.html')#生成html页面
# 打开浏览器
webbrowser.open("sex.html")

Python微信机器人

Python微信机器人

四 微信好友地域分布

显示中国地图,需要装中国地图模块:

全球国家地图: echarts-countries-pypkg (1.9MB): 世界地图和 213 个国家,包括中国地图
中国省级地图: echarts-china-provinces-pypkg (730KB):23 个省,5 个自治区
中国市级地图: echarts-china-cities-pypkg (3.8MB):370 个中国城市
中国县区级地图: echarts-china-counties-pypkg (4.1MB):2882 个中国县·区
中国区域地图: echarts-china-misc-pypkg (148KB):11 个中国区域地图,比如华南、华北。

特别注明,中国地图在 echarts-countries-pypkg 里。需要这些地图的朋友,可以装 pip 命令行:

pip3 install echarts-countries-pypkgpip3 install echarts-china-provinces-pypkgpip3 install echarts-china-cities-pypkgpip3 install echarts-china-counties-pypkgpip3 install echarts-china-misc-pypkg

Python微信机器人

from wxpy import *
from pyecharts import Map
import webbrowser
bot=Bot(cache_path=True)

friends=bot.friends()


area_dic={}#定义一个字典,用来存放省市以及省市人数
for friend in friends:
    if friend.province not in area_dic:
        area_dic[friend.province]=1
    else:
        area_dic[friend.province]+=1

attr = area_dic.keys()
value = area_dic.values()



map = Map("好朋友们的地域分布", width=1200, height=600)
map.add(
    "好友地域分布",
    attr,
    value,
    maptype='china',
    is_visualmap=True, #结合体VisualMap

)
#is_visualmap -> bool 是否使用视觉映射组件
#
map.render('area.html')


webbrowser.open("area.html")

Python微信机器人

五 微信聊天机器人

1、为微信传输助手传送消息

这里的file_helper就是微信的文件传输助手,我们给文件传输助手发送一条消息,可以在手机端的文件传输助手中收到括号内的消息

bot.file_helper.send('lqz say hello')

2、收发消息@bot.register()

Python微信机器人

from wxpy import *
bot=Bot(cache_path=True)

@bot.register()
def recv_send_msg(recv_msg):
    print('收到的消息:',recv_msg.text) # recv_msg.text取得文本
    return '自动回复:%s' %recv_msg.text

# 进入Python命令行,让程序保持运行
embed()

Python微信机器人

3、自动给老婆回复信息

当你在网吧吃着鸡,操作骚出天际时,你老婆打电话让你回家吃饭,此时你怎么办。。。

Python微信机器人

from wxpy import *
bot=Bot(cache_path=True)

girl_friend=bot.search('刘刘刘')[0]
print(girl_friend)

@bot.register() # 接收从指定好友发来的消息,发送者即recv_msg.sender为指定好友girl_friend
def recv_send_msg(recv_msg):
    print('收到的消息:',recv_msg.text) # recv_msg.text取得文本
    if recv_msg.sender == girl_friend:
        recv_msg.forward(bot.file_helper,prefix='老婆留言: ') #在文件传输助手里留一份,方便自己忙完了回头查看
        ms='老婆最美丽,我对老婆的爱如滔滔江水,连绵不绝'
        print('>>>给老婆回复的:', ms)
        return  ms#给老婆回一份

embed()

Python微信机器人

4、从微信群里定位好友之拍老板马屁

Python微信机器人

from wxpy import *
bot=Bot(cache_path=True)

company_group=bot.groups().search('群名字')[0]

boss=company_group.search('老板名字')[0]


@bot.register(chats=company_group) #接收从指定群发来的消息,发送者即recv_msg.sender为组
def recv_send_msg(recv_msg):
    print('收到的消息:',recv_msg.text)
    if recv_msg.member == boss:
        #这里不用recv_msg.render 因为render是群的名字
        recv_msg.forward(bot.file_helper,prefix='老板发言: ')
        return '老板说的好有道理,深受启发'

embed()

Python微信机器人

5、聊天机器人****

给所有人自动回复

Python微信机器人

import json
import requests
from wxpy import *
bot = Bot(cache_path=True)

# 调用图灵机器人API,发送消息并获得机器人的回复
def auto_reply(text):
    url = "http://www.tuling123.com/openapi/api"
    api_key = "9df516a74fc443769b233b01e8536a42"
    payload = {
        "key": api_key,
        "info": text,
    }
    r = requests.post(url, data=json.dumps(payload))
    result = json.loads(r.content)
    return "[来自智能机器人] " + result["text"]


@bot.register()
def forward_message(msg):
    return auto_reply(msg.text)

embed()

Python微信机器人

给指定的群回复

Python微信机器人

import json
import requests
from wxpy import *
bot = Bot(cache_path=False)

group=bot.groups().search('群名字')[0]
print(group)

# 调用图灵机器人API,发送消息并获得机器人的回复
def auto_reply(text):
    url = "http://www.tuling123.com/openapi/api"
    api_key = "9d602fe417464cd18beb2083d064bee6"
    payload = {
        "key": api_key,
        "info": text,
    }
    r = requests.post(url, data=json.dumps(payload))
    result = json.loads(r.content)
    return "[来自智能机器人] " + result["text"]


@bot.register(chats=group)
def forward_message(msg):
    return auto_reply(msg.text)

embed()

Python微信机器人

给指定的人回复

Python微信机器人

import requests
from wxpy import *
bot = Bot( cache_path=True)

girl_friend=bot.search('名字r')[0]

# 调用图灵机器人API,发送消息并获得机器人的回复
def auto_reply(text):
    url = "http://www.tuling123.com/openapi/api"
    api_key = "申请图灵机器人获取key值放到这里"
    payload = {
        "key": api_key,
        "info": text,
    }
    r = requests.post(url, data=json.dumps(payload))
    result = json.loads(r.content)
    return "[微信测试,请忽略] " + result["text"]


@bot.register()
def forward_message(msg):
    if msg.sender == girl_friend:
        return auto_reply(msg.text)

embed()
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
梦
3年前
微信小程序new Date()转换时间异常问题
微信小程序苹果手机页面上显示时间异常,安卓机正常问题image(https://imghelloworld.osscnbeijing.aliyuncs.com/imgs/b691e1230e2f15efbd81fe11ef734d4f.png)错误代码vardate'2021030617:00:00'vardateT
Easter79 Easter79
2年前
thinkcmf+jsapi 实现微信支付
首先从小程序端接收订单号、金额等参数,然后后台进行统一下单,把微信支付的订单号返回,在把订单号发送给前台,前台拉起支付,返回参数后更改支付状态。。。回调publicfunctionnotify(){$wechatDb::name('wechat')where('status',1)find();
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这