itchat是一个开源的微信个人号接口,使用python调用微信从未如此简单。
使用不到三十行的代码,你就可以完成一个能够处理所有信息的微信机器人。
当然,该api的使用远不止一个机器人,更多的功能等着你来发现,比如这些。
该接口与公众号接口itchatmp共享类似的操作方式,学习一次掌握两个工具。
如今微信已经成为了个人社交的很大一部分,希望这个项目能够帮助你扩展你的个人的微信号、方便自己的生活。
官方文档:http://itchat.readthedocs.io
itchat的仓库地址:https://github.com/littlecodersh/ItChat
安装:
pip install itchat
代码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import itchat
import os
import cv2
from PIL import ImageGrab
usageMsg = u"使用方法:\n1.运行CMD命令:cmd xxx (xxx为命令)\n" \
u"例如关机命令:\ncmd shutdown -s -t 0 \n" \
u"2.获取摄像头并拍照:cap\n" \
u"2.获取屏幕截屏:pc\n" \
@itchat.msg_register('Text')
def handler_receive_msg(msg): # 处理收到的消息
message = msg['Text']
to_name = msg['ToUserName']
path = 'E:/sample/temp.jpg' # 临时保存截屏图片地址
if to_name == "filehelper":
if message == "cap": # 拍照
# 要使用摄像头,需要使用cv2.VideoCapture(0)创建VideoCapture对象,
# 参数:0指的是摄像头的编号。如果你电脑上有两个摄像头的话,访问第2个摄像头就可以传入1
cap = cv2.VideoCapture(0)
ret, img = cap.read() # 获取一帧
cv2.imwrite("temp.jpg", img)
itchat.send('@img@%s' % u'temp.jpg', 'filehelper')
cap.release() # 释放资源
elif message[0:3] == "cmd": # 处理cmd命令
os.system(message.strip(message[0:4]))
elif message == "pc": # 截图
im = ImageGrab.grab() # 实现截屏功能
im.save(path, 'JPEG') # 设置保存路径和图片格式
itchat.send_image(path, 'filehelper')
else:
return msg['Text']
if __name__ == '__main__':
itchat.auto_login(hotReload=True) # 退出程序后暂存登陆状态
# itchat.auto_login()
itchat.send(usageMsg, "filehelper")
itchat.run()
# 大部分代码为转载,侵告删
(注意:如果安装CV2时出现异常,请参考:Python安装CV2)
如果你想在后台无界面运行,参考:运行bat时隐藏cmd窗口
如果需要做一个聊天机器人,可对接图灵机器人,教程可自行查询,这里不在叙述
参考:https://blog.csdn.net/m0_38106923/article/details/81978279
https://blog.csdn.net/sixkery/article/details/81674684
https://blog.csdn.net/weixin_37557902/article/details/82740593
https://blog.csdn.net/wangxiao7474/article/details/80050730
https://itchat.readthedocs.io/zh/latest/tutorial/tutorial0/
https://www.cnblogs.com/dongxiaodong/p/10490563.html
https://www.cnblogs.com/wang-li/p/9744502.html
侵告删