Itchat基本操作 - littleboy12580/learning_python GitHub Wiki

简介

itchat是一个开源的微信个人号接口,使用python来进行调用

操作

安装

使用pip install itchat命令进行安装

登录

调用auto_login方法来实现登录,其中若传入参数hotReload=True,可以实现热启动,不需要每次运行文件都扫描一次二维码;当然也可以自定义登录过程,itchat提供了微信登录帐号的每个操作步骤对应的方法

获取二维码uuid

使用get_QRuuid()方法,成功返回uuid,失败返回None

获取二维码

使用get_QR()方法,参数为上一步返回的uuid,成功返回True,失败返回False

判断是否已登录成功

使用check_login()方法,参数为uuid,若登录成功返回状态码200,已扫描二维码返回状态码201,二维码失效返回状态码408,未获取到信息返回0

获取初始化数据

使用web_init()方法获取用户信息以及心跳所需数据

获取微信通讯录

使用get_friends()方法获取好友信息列表

更新微信手机登录状态

使用show_mobile_login()方法在手机上显示登录状态

循环扫描新信息

使用start_receiving()方法循环扫描新信息

示例代码

itchat自带的auto_login()的实现如下:

import itchat, time, sys

def output_info(msg):
    print('[INFO] %s' % msg)

def open_QR():
    for get_count in range(10):
        output_info('Getting uuid')
        uuid = itchat.get_QRuuid()
        while uuid is None: uuid = itchat.get_QRuuid();time.sleep(1)
        output_info('Getting QR Code')
        if itchat.get_QR(uuid): break
        elif get_count >= 9:
            output_info('Failed to get QR Code, please restart the program')
            sys.exit()
    output_info('Please scan the QR Code')
    return uuid

uuid = open_QR()
waitForConfirm = False
while 1:
    status = itchat.check_login(uuid)
    if status == '200':
        break
    elif status == '201':
        if waitForConfirm:
            output_info('Please press confirm')
            waitForConfirm = True
    elif status == '408':
        output_info('Reloading QR Code')
        uuid = open_QR()
        waitForConfirm = False
userInfo = itchat.web_init()
itchat.show_mobile_login()
itchat.get_friends(True)
output_info('Login successfully as %s'%userInfo['NickName'])
itchat.start_receiving()

# Start auto-replying
@itchat.msg_register
def simple_reply(msg):
    if msg['Type'] == 'Text':
        return 'I received: %s' % msg['Content']
itchat.run()

注册消息

itchat会根据接收到的消息类型寻找对应的已注册方法,若一个消息类型没有对应的注册方法,该消息将被舍弃

注册

有两种方法来注册消息,如下:

import itchat
from itchat.content import *

# 不带具体对象注册,将注册为普通消息的回复方法
@itchat.msg_register(TEXT)
def simple_reply(msg):
    return 'I received: %s' % msg['Text']

# 带对象参数注册,对应消息对象将调用该方法
@itchat.msg_register(TEXT, isFriendChat=True, isGroupChat=True, isMpChat=True)
def text_reply(msg):
    itchat.send('%s: %s' % (msg['Type'], msg['Text']), msg['FromUserName'])

消息类型

itchat.content中包含所有的消息类型参数,内容如下表所示:

参数 类型 Text键值
TEXT 文本 文本内容
MAP 地图 位置文本
CARD 名片 推荐人字典
NOTE 通知 通知文本
SHARING 分享 分享名称
PICTURE 图片/表情 下载方法
RECORDING 语音 下载方法
ATTACHMENT 附件 下载方法
VIDEO 小视频 下载方法
FRIENDS 好友邀请 添加好友所需参数
Useless 无用信息 'UselessMsg'

其中,群消息新增了三个键值,isAt判断是否是@本号,ActualNickName表示实际的NickName,Content表明实际的Content;
对于注册消息的优先级,规定后注册消息优先级高于先注册消息,带参数消息优先级高于不带参数消息

回复

itchat提供五种回复方法,一般直接使用send方法即可

send

示例如下:

send(msg='Text Message', toUserName=None)

所需参数有:

  • msg:消息内容
  • '@fil@文件地址'将会被识别为传送文件,'@img@图片地址'将会被识别为传送图片,'@vid@视频地址'将会被识别为小视频
  • toUserName:发送对象,如果留空将会发送给自己

示例如下:

#coding=utf8
import itchat

itchat.auto_login()
itchat.send('Hello world!')
# 请确保该程序目录下存在:gz.gif以及xlsx.xlsx
itchat.send('@img@%s' % 'gz.gif')
itchat.send('@fil@%s' % 'xlsx.xlsx')
itchat.send('@vid@%s' % 'demo.mp4')

send_msg

示例如下:

send_msg(msg='Text Message', toUserName=None)

所需参数有:

  • msg:消息内容
  • toUserName:发送对象,如果留空将会发送给自己

示例如下:

import itchat

itchat.auto_login()
itchat.send_msg('Hello world')

send_file

示例如下:

send_file(fileDir, toUserName=None)

所需参数有:

  • fileDir:文件路径(不存在该文件时将打印无此文件的提醒)
  • toUserName:发送对象,如果留空将会发送给自己

示例如下:

#coding=utf8
import itchat

itchat.auto_login()
# 请确保该程序目录下存在:xlsx.xlsx
itchat.send_file('xlsx.xlsx')

send_img

示例如下:

send_file(fileDir, toUserName=None)

所需参数有:

  • fileDir:文件路径(不存在该文件时将打印无此文件的提醒)
  • toUserName:发送对象,如果留空将会发送给自己

示例如下:

#coding=utf8
import itchat

itchat.auto_login()
# 请确保该程序目录下存在:demo.mp4
itchat.send_file('demo.mp4')

send_video

示例如下:

send_file(fileDir, toUserName=None)

所需参数有:

  • fileDir:文件路径(不存在该文件时将打印无此文件的提醒)
  • toUserName:发送对象,如果留空将会发送给自己

示例如下:

#coding=utf8
import itchat

itchat.auto_login()
# 请确保该程序目录下存在:demo.mp4
itchat.send_file('demo.mp4')
⚠️ **GitHub.com Fallback** ⚠️