使用不到三十行的代码,你就可以完成一个能够处理所有信息的微信机器人。
当然,该api的使用远不止一个机器人,更多的功能等着你来发现.
1. 实现微信消息的获取
import itchat
@itchat.msg_register(itchat.content.TEXT)
def print_content(msg):
print(msg['Text'])
itchat.auto_login()
itchat.run()
2. 实现微信消息的发送
import itchat
itchat.auto_login(hotReload=True)
# 注意实验楼环境的中文输入切换
itchat.send(u'测试消息发送', 'filehelper')
如果接收到TEXT类型的消息,则执行以下的方法,msg是收到的消息,return msg.text是返回收到的消息的内容,实际效果是别人发给你什么,程序自动返回给他什么。
import itchat
from itchat.content import TEXT
@itchat.msg_register
def simple_reply(msg):
if msg['Type'] == TEXT:
return 'I received: %s' % msg['Content']
itchat.auto_login()
itchat.run()
3.使用itchat统计你的微信好友
import itchat
import matplotlib.pyplot as plt
itchat.auto_login(hotReload=True) #itchat.auto_login()自动登陆命令
# #hotReload为热加载即是否缓存
# 统计你的好友的男女比例
# friends是一个类似列表的数据类型, 其中第一个是自己的信息, 除了第一个之外是你的好友信息.
friends = itchat.get_friends()
info = {} # 'male':1, 'female':, 'other': #存储信息
for friend in friends[1:]: #获取好友信息
#以用此句print查看好友的微信名、备注名、性别、省份、个性签名(1:男 2:女 0:性别不详)
print(friend['NickName'],friend['RemarkName'],friend['Sex'],friend['Province'],friend['Signature'])
if friend['Sex'] == 1: #判断好友性别,1为男性,2为女性,0为其他。
info['male'] = info.get('male', 0) + 1
elif friend['Sex'] == 2:
info['female'] = info.get('female', 0) + 1
else:
info['other'] = info.get('other', 0) + 1
print(info) #{'male': 263, 'other': 77, 'female': 165}
# 柱状图展示
for i, key in enumerate(info):
plt.bar(key, info[key])
plt.show()
4.获取微信群聊信息
import itchat
itchat.auto_login(hotReload=True) #itchat.auto_login()自动登陆命令
# #hotReload为热加载即是否缓存
chatrooms = itchat.get_chatrooms(update=True)
for i in chatrooms:
print(i['NickName'])
5.下载好友头像图片
import itchat
itchat.auto_login(True)
friend = itchat.get_friends(update=True)[0:]
for count, f in enumerate(friends):
# 根据userName获取头像
img = itchat.get_head_img(userName=f["UserName"])
imgFile = open("img/" + str(count) + ".jpg", "wb")
imgFile.write(img)
imgFile.close()
6.微信好友头像拼接图
x = 0
y = 0
imgs = os.listdir("img")
random.shuffle(imgs) #打乱顺序
# 创建640*640的图片用于填充各小图片
newImg = Image.new('RGBA', (640, 640))
# 以640*640来拼接图片,math.sqrt()开平方根计算每张小图片的宽高,
width = int(math.sqrt(640 * 640 / len(imgs)))
# 每行图片数
numLine = int(640 / width)
for i in imgs:
img = Image.open("img/" + i)
# 缩小图片
img = img.resize((width, width), Image.ANTIALIAS)
# 拼接图片,一行排满,换行拼接
newImg.paste(img, (x * width, y * width))
x += 1
if x >= numLine:
x = 0
y += 1
newImg.save("all.png")
7.自动回复消息
微信和QQ最大的不同就是不知晓是否在线,发送的消息不知道是否及时能看到。如果能及时处理或自动回复消息,则避免了误解。下面这个可以完成回复所有文本信息(包括群聊@自己的消息,可以设置成和QQ离线消息一样的功能)。
import itchat
import requests
def get_tuling_response(_info):
print(_info)
#图灵机器人网址
## 构造了要发送给服务器的数据
api_url = "http://www.tuling123.com/openapi/api"
data = {
'key' : '824073e601264a22ba160d11988458e0',
'info' : _info,
'userid' : 'villa'
}
##其中userId是用户的标志
##Key来告诉图灵服务器你有权和他对话
##info接收的信息
res = requests.post(api_url,data).json()
# 字典的get方法在字典没有'text'值的时候会返回None而不会抛出异常
print(res['text'])
return res['text']
#时刻监控好友发送的文本消息,并且给予一回复
# isGroupChat=True接收群聊消息中的文本信息, 并让图灵机器人自动回复;
# isMapChat=True接收群聊消息中的文本信息, 并让图灵机器人自动回复;
@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
#获取好友发送消息的内容
content = msg['Content']
#将好友的消息发送给机器人处理,处理结果就是返回给好友的消息
returnContent = get_tuling_response(content)
return returnContent
# if __name__ == "__main__":
itchat.auto_login(hotReload=True)
itchat.run()