(19) 树莓派发送微信消息

API https://itchat.readthedocs.io/zh/latest/api/

教程  https://www.yahboom.com/build.html?id=1999&cid=257

项目地址  https://github.com/revotu/ItChat

更多使用  https://www.cnblogs.com/jiaoyu121/p/6944398.html

重要文件传输 :  视频 图片 语音 文字

https://www.cnblogs.com/dongxiaodong/p/10490563.html

音乐交互

https://itchat.readthedocs.io/zh/latest/tutorial/tutorial2/

说明:  这玩意相当于网页版微信,所以登陆了会挤掉电脑端。手机也会提示网页微信已经登陆,手机通知关闭,但是手机仍然可以接收消息(所以和手机不冲突喽??)。

1安装

首先使用pip安装itchat:

Windows用户可以直接打开cmd输入:

pip install itchat

Mac用户由于没有对anaconda的python配置环境变量,需要先在终端输入:

curl https://bootstrap.pypa.io/get-pip.py | python3

树莓派版本无需下载pip,直接下载itchat输入:

pip install itchat

pip命令和pip3的区别是:pip3可以直接下载适合python3 使用的package。对于树莓派,我们可以根据spyder中python的版本使用pip2或pip3下载itchat:

pip2 install itchat

  

2使用基本例程

首先解决问题,报错找不到 itchart

https://blog.csdn.net/lockelk/article/details/85296818

可以先查看是否已安装及安装的版本

2-1shell下:

pip list

解决:

先查看wxpy的安装路径

pip show itchat

然后将路径添加

python 进入>>>

>>>import sys

>>>sys.path.append("/home/pi/.local/lib/python2.7/site-packages")

其中括号内的为上一步实际查出的安装路径。
>>>sys.path  查看已安装的

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import sys
sys.path.append("/home/pi/.local/lib/python2.7/site-packages")
import itchat


#登陆 扫描图片二维码,一次登陆永久记录
itchat.auto_login(hotReload=True)


#给文件出书助手,发送一条消息
itchat.send(u'你好', 'filehelper')

#给指定用户发消息
users=itchat.search_friends("育铃")
userName= users[0]['UserName']
print(userName)
itchat.send('你好,姚宝贝蛋',toUserName=userName)


#程序不停运行
itchat.run()


  

  

 2-2 win10下修正错误

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import sys
sys.path.append("F:/dongdong/0tool/python/Anaconda3/Lib/site-packages")
import itchat
itchat.auto_login(hotReload=True)

  

3 基本使用

3-1 itchat给指定联系人发消息

https://blog.csdn.net/Lynn_coder/article/details/79436539

import itchat
itchat.auto_login()
itchat.send('Hello, filehelper', toUserName='filehelper')

  

这段代码意思是给filehelper发送一个hello,filehelper就是文件助手。

那么我们想给指定的人发消息,并不是把filehelper改掉这么简单

users=itchat.search_friends("老王")
userName= users[0]['UserName']
print(userName)
itchat.send('你好老王',toUserName=userName)

  

如果我们想给老王发消息,就先使用itchat.search方法,会把所有备注名为老王的联系人全都找出来。

之后我们选取第一个(如果你的联系人列表里只有一个老王,那么就只会搜出来一个)

users[0]取到的是一个联系人对象,他里面有个key叫UserName,它就是真正的用户的username

之后我们再使用itchat.send方法,就可以成功向老王发送消息了

 完整例程

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import sys
sys.path.append("F:/dongdong/0tool/python/Anaconda3/Lib/site-packages")
import itchat

#注册程序打开和关闭函数
def lc():
    print('finish login')
    itchat.send(u'设备连线', 'filehelper')
def ec():
    itchat.send(u'设备离线', 'filehelper')


    

# 注册打印出来消息的来源者函数
@itchat.msg_register(itchat.content.TEXT)
def _(msg):
    # equals to print(msg['FromUserName'])
    print(msg.fromUserName)

    
#登陆 图片二维码扫描 一次登陆之后不用重新扫描
itchat.auto_login(loginCallback=lc, exitCallback=ec,hotReload=True)

#给文件出书助手,发送一条消息
itchat.send(u'你好', 'filehelper')

users=itchat.search_friends("育铃")
userName= users[0]['UserName']
print(userName)
itchat.send('你好,姚宝贝蛋',toUserName=userName)


#程序不停运行
itchat.run()

#程序停止
#itchat.logout()

  

发现图片

这个图片发送很奇怪,我开始死活发不出去,后来把图片搞小了一点发出去了,后来再用原来分辨率,又可以了,难道是当时我网速慢???

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import sys
sys.path.append("F:/dongdong/0tool/python/Anaconda3/Lib/site-packages")
import itchat

#注册程序打开和关闭函数
def lc():
    print('finish login')
    itchat.send(u'设备连线', 'filehelper')
def ec():
    itchat.send(u'设备离线', 'filehelper')


    

# 注册打印出来消息的来源者函数
@itchat.msg_register(itchat.content.TEXT)
def _(msg):
    # equals to print(msg['FromUserName'])
    print(msg.fromUserName)

    
#登陆 图片二维码扫描 一次登陆之后不用重新扫描
itchat.auto_login(loginCallback=lc, exitCallback=ec,hotReload=True)

#给文件出书助手,发送一条消息
itchat.send(u'你好', 'filehelper')

#找到指定用户
users=itchat.search_friends("育铃")#微信备注
userName= users[0]['UserName']
print(userName)
itchat.send('哇,姚宝贝蛋',toUserName=userName)

f="F:/dongdong/1.jpg"  #图片地址
try:
    itchat.send_image(f,toUserName=userName)  #如果是其他文件可以直接send_file  
    print("success")
except:
    print("fail")


#程序不停运行
itchat.run()

#程序停止
#itchat.logout()

  

各种消息发送

消息分类:

图片或表情(PICTURE)、录制(RECORDING)、附件(ATTACHMENT)、小视频(VIDEO)、文本(TEXT),地图(MAP),名片(CARD),通知(NOTE),分享(SHARING),好友邀请(FRIENDS)、语音(RECORDING)、系统消息(SYSTEM)

https://www.cnblogs.com/lizm166/p/9670033.html

可接受监听的数据类型

图片或表情(PICTURE)、录制(RECORDING)、附件(ATTACHMENT)、小视频(VIDEO)、文本(TEXT),地图(MAP),名片(CARD),通知(NOTE),分享(SHARING),好友邀请(FRIENDS)、语音(RECORDING)、系统消息(SYSTEM)

控制电脑

https://github.com/BossBobxuan/WeChatToCommand/blob/master/chatToCommand.py

本项目的具体需求是:树莓派启动微信服务和OpenCV服务,OpenCV对摄像头实时视频监控,当检测到人脸后后拍照,将拍摄到的照片通过微信发送给用户的个人好友。

Python3 itchat实现微信定时发送群消息

 https://www.cnblogs.com/dongxiaodong/p/10490563.html

查找群失败的问题

https://www.jianshu.com/p/c8b164b840db

使用 user_info = itchat.search_chatrooms(name='XXX') 查找群的时候,有时会遇到找不到的情况,需要在群设置选择-保存到通讯录,才能被查找到

群发助手过年特定发消息    微信作为智能家居入口

https://itchat.readthedocs.io/zh/latest/tutorial/tutorial2/

通过微信获取城市PM2.5的状态

https://blog.csdn.net/weixin_33998125/article/details/85077561

自动回复(从Excel读取配置)

https://www.alphayan.cn/index.php/2018/03/17/itchat_01/

智能机器人

 https://itchat.readthedocs.io/zh/latest/tutorial/tutorial0/#_5

词云图

https://blog.csdn.net/xiaoxianerqq/article/details/81428054

全国好友分布地址

https://blog.csdn.net/xiaoxianerqq/article/details/81428054

二、py库

1,itchat:这个是主要的工具,用于连接微信个人账号接口。以下是一些相关的知识点网站。

2,xlrd:这个是用来读Excel文件的工具。

3,apscheduler:这个是用来定时调度时间的工具。

本项目中,对于微信的操作,我们需要用到的API是itchat。 itchat是一个微信对于python封装的api,它的功能非常强大,我们可以使用它和python对自己微信的很多信息进行爬取。

 image.png

  

综合示例

######################################### 程序说明 ########################################
# 功能:
#       集合了接收消息处理,主动发送消息处理
# 使用:
#       1运行后,第一次扫描二维码登陆,可以图片形式,也可以命令行形式显示二维码
#       2注册接收消息和文件处理函数
#         2-1 个人用户或者群给自己发的消息,图片,文件,视频,保存等机制
#         2-2 自己通过文件助手给自己发的消息
#       3主动给别人发消息
#         3-1 自己给普通用户或者群发消息,各种文件,图片,视频
#         3-2 自己给文件助手发送消息,相当于给自己发消息,用来控制设备,发送文件给设备等
#
###########################################################################################
#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import sys
sys.path.append("F:/dongdong/0tool/python/Anaconda3/Lib/site-packages")
import itchat


#各类型消息的注册
from itchat.content import *
from datetime import datetime
#from itchat.content import PICTURE, RECORDING, ATTACHMENT, VIDEO,TEXT


######################################### 消息发送函数 ########################################

#1-1注册程序打开和关闭函数
def lc():
    print('finish login')
    itchat.send(u'设备连线', 'filehelper')
def ec():
    itchat.send(u'设备离线', 'filehelper')


#1-2给普通用户发送图片
def send_pic(picpath,toUserName):
    try:
        itchat.send_image(picpath,toUserName)  #第一种通用发送方式 如果是其他文件可以直接send_file
        #itchat.send('@img@%s' % picpath, toUserName)       #第二种指定类型发送方式
        print("success_jpg")
    except:
        print("fail_jpg")


#1-3给普通用户发送文件
def send_file(filepath,toUserName):
    try:
        #itchat.send('@fil@%s' % './filex/tt.txt', toUserName=msg['FromUserName'])
        itchat.send_file(filepath, toUserName)  # txt如果是空的就不会发送
        print("success_file")
    except:
        print("fail_file")
    

#1-4给普通用户发送视频
def send_video(videopath,toUserName):
    try:
        #itchat.send('@vid@%s' % './filex/videox.mp4', toUserName=msg['FromUserName'])
        itchat.send_video(videopath, toUserName)
        print("success_video")
    except:
        print("fail_video")


#1-5给群发消息

def SentChatRoomsMsg(chatroomName ,context):
    itchat.get_chatrooms(update=True)
    chatrooms = itchat.search_chatrooms(name=chatroomName)

  #有时会遇到找不到的情况,需要在该群设置选择-保存到通讯录,才能被查找到
    if len(chatrooms)==0 :
        print('没有找到群聊:' + chatroomName)
       # exit(0)
    else:
        print(chatrooms[0]['UserName'])#输出群聊标识符
        itchat.send_msg(context, toUserName=chatrooms[0]['UserName'])#发送消息


######################################### 消息处理回调函数 ########################################
# 消息分类:
# 图片或表情(PICTURE)、录制(RECORDING)、附件(ATTACHMENT)、小视频(VIDEO)、文本(TEXT)
# 地图(MAP),名片(CARD),通知(NOTE),分享(SHARING),好友邀请(FRIENDS)、语音(RECORDING)、系统消息(SYSTEM)    

# 1-3 文本消息接收和处理

# 1自己发给文件助手的
# 2别人发给己的  
#@itchat.msg_register(itchat.content.TEXT,isGroupChat=True)                                     # 2-1只针对群消息
#@itchat.msg_register(itchat.content.TEXT)                                                      # 2-2自针对普通用户消息
@itchat.msg_register(itchat.content.TEXT, isFriendChat=True, isGroupChat=True, isMpChat=True)   # 2-3针对所有人消息
def text_reply(msg):
    #if msg['ToUserName'] != 'filehelper': return           # 过滤掉不是文件助手的消息
    #print(msg)                                             # 打印消息 所以的信息
    #print(msg["Text"])                                     # 收到的消息是什么
    #print(msg["ToUserName"])                               # 发给谁的

    rebacktxt_msg=  "收到:"+msg["Text"] 
    #判断是否是@本人
    #if msg["Text"].find(usermsgx["RemarkName"])== '育铃': 
    if msg["ToUserName"].find("filehelper")==0:              # 如果是给文件助手发的
        itchat.send(rebacktxt_msg, 'filehelper')
    return rebacktxt_msg                                     # 回复除了自己以外人的消息



#1-4文件下载---存在同级filex目录下 
    #1别人发给自己的消息
    #2自己发给文件助手的
@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
def download_files(msg):
   filedpx="./filex/"+msg["FileName"]                        # 得到文件路径+名字  目录需要手动创建
   msg.download(filedpx)
   
   rebackfile_msg="收到文件类型"+msg['Type']+"  保存地址为:filex/"+msg.fileName
   
   if msg["ToUserName"].find("filehelper")==0:               # 1如果是给文件助手发的,发个提醒
        itchat.send(rebackfile_msg, 'filehelper')
        
   return rebackfile_msg                                     # 2如果是别人发给自己的,直接回复对方




    

    
######################################### 主函数函数 ########################################
    
#1登陆 
itchat.auto_login(hotReload=True,loginCallback=lc, exitCallback=ec)    #图片二维码扫描 登陆之后一段时间内不用重新扫描,注册打开和结束回调函数

#2-1找到自己的名字
usermsgx=itchat.search_friends()                      #得到当前用户的信息 首位是自己
#print(usermsgx)                                      #我的微信ID
#print(usermsgx["NickName"])                          #我的备注名字

#2-2找到昵称为“”的用户
users=itchat.search_friends("育铃")                   #按照昵称查找 
#itchat.search_friends(userName='@abcdefg1234567')    #按照ID查找
userName= users[0]['UserName']
#print(userName)

 
#3-1-1给文件助手,发送一条消息
itchat.send(u'你好文件助手,这是一条文本测试消息', 'filehelper')

#3-1-2给个人用户,发送一条消息
#itchat.send('东小东: 这是一个来自树莓派的测试',toUserName=userName)


#3-3给个人用户, 发送图片
pic_file_name='./filex/1.txt'                        #图片相对路径地址
#send_pic("F:/dongdong/1.jpg",'filehelper')          #图片绝对路径地址



#3-4发送文件
#send_file('./filex/1.txt','filehelper')

    
#3-5发送视频
#send_video('./filex/1.mp4','filehelper')


#3-6群名向群里发送内容
#SentChatRoomsMsg('温县独霸', '你好')


#程序保持运行
itchat.run()

#程序停止
#itchat.logout()

  

原文地址:https://www.cnblogs.com/kekeoutlook/p/11123647.html