python itchat 微信开发

使用itchat可以简单操作微信,进行好友和群消息的发送

安装:

pip install itchat

使用:

import itchat, time

# 登录
itchat.auto_login(hotReload=True)


def send_one_group(msg, g_name):
    """
    给某个组发送消息
    :param msg:
    :param g_name:
    :return:
    """
    rooms = itchat.search_chatrooms(g_name)
    if rooms is not None:
        user_name = rooms[0]['UserName']
        itchat.send(msg, toUserName=user_name)
    else:
        print("None group found")


def send_all_group(msg):
    """
    给所有组发送消息
    :param msg:
    :return:
    """
    rooms = itchat.get_chatrooms(update=True)
    if rooms is not None:
        for r in rooms:
            user_name = r['UserName']
            itchat.send(msg, toUserName=user_name)
        else:
            print("None group found")


def send_one_person(msg, p_name):
    """
    给某个人发消息
    :param msg:
    :param p_name:
    :return:
    """
    persons = itchat.search_friends(p_name)
    if persons is not None:
        user_name = persons[0]['UserName']
        itchat.send_msg(msg, toUserName=user_name)
    else:
        print("None person found")


def send_all_person(msg):
    """
    给所有人发消息
    :param msg:
    :return:
    """
    persons = itchat.get_friends()
    if persons is not None:
        for p in persons:
            user_name = p['UserName']
            itchat.send(msg, toUserName=user_name)
        else:
            print("None person found")


if __name__ == '__main__':
    send_one_person('测试123', "")
    # send_one_group('1','***学员群')

 小实例:

获取所有头像并保存和拼接到一个图片里面:

# -*- coding:utf-8 -*-
# 导入相关模块
import itchat
import os
import PIL.Image as Image
from os import listdir
import math

# 登录
itchat.auto_login(hotReload=True)
# 获取微信全部好友的信息
friends = itchat.get_friends(update=True)[0:]
# 获取自己的用户名
user = friends[0]["UserName"]
# 打印用户名
print(user)
# 建立文件夹用来装好友的头像
os.mkdir(user)

num = 0
# 遍历好友信息,将头像保存
for i in friends:
    img = itchat.get_head_img(userName=i["UserName"])
    fileImage = open(user + "/" + str(num) + ".jpg", 'wb')
    fileImage.write(img)
    fileImage.close()
    num += 1

pics = listdir(user)
numPic = len(pics)
print(numPic)
eachsize = int(math.sqrt(float(640 * 640) / numPic))
print(eachsize)
numline = int(640 / eachsize)
toImage = Image.new('RGBA', (640, 640))
print(numline)

x = 0
y = 0

for i in pics:
    try:
        # 打开图片
        img = Image.open(user + "/" + i)
    except IOError:
        print("Error: 没有找到文件或读取文件失败")
    else:
        # 缩小图片
        img = img.resize((eachsize, eachsize), Image.ANTIALIAS)
        # 拼接图片
        toImage.paste(img, (x * eachsize, y * eachsize))
        x += 1
        if x == numline:
            x = 0
            y += 1

# 保存拼接后的头像
toImage.save(user + ".BMP")
itchat.send_image(user + ".BMP", 'filehelper')
View Code

 

posted @ 2018-04-23 10:24  田云  阅读(879)  评论(0编辑  收藏  举报