前言
itchat是一个开源的微信个人号接口,使用python调用微信从未如此简单。使用不到三十行的代码,你就可以完成一个能够处理所有信息的微信机器人。当然,该api的使用远不止一个机器人,更多的功能等着你来发现,比如这些。该接口与公众号接口itchatmp共享类似的操作方式,学习一次掌握两个工具。如今微信已经成为了个人社交的很大一部分,希望这个项目能够帮助你扩展你的个人的微信号、方便自己的生活。
安装
sudo pip install itchat
登录
itchat.auto_login() 这种方法将会通过微信扫描二维码登录,但是这种登录的方式确实短时间的登录,并不会保留登录的状态,也就是下次登录时还是需要扫描二维码,如果加上hotReload==True,那么就会保留登录的状态,至少在后面的几次登录过程中不会再次扫描二维码,该参数生成一个静态文件itchat.pkl用于存储登录状态
退出及登录完成后调用的特定的方法
这里主要使用的是灰调函数的方法,登录完成后的方法需要赋值在 loginCallback 中退出后的方法,需要赋值在 exitCallback 中.若不设置 loginCallback 的值, 将会自动删除二维码图片并清空命令行显示.
import itchat, timedef lc(): print("Finash Login!")def ec(): print("exit")itchat.auto_login(loginCallback=lc, exitCallback=ec)time.sleep()itchat.logout() #强制退出登录
回复消息
send
send(msg="Text Message", toUserName=None)
参数:
msg : 文本消息内容
@fil@path_to_file : 发送文件
@img@path_to_img : 发送图片
@vid@path_to_video : 发送视频
toUserName : 发送对象, 如果留空, 将发送给自己.
返回值
True or False
实例代码
# coding-utf-8import itchatitchat.auto_login()itchat.send("Hello World!")ithcat.send("@fil@%s" % '/tmp/test.text')ithcat.send("@img@%s" % '/tmp/test.png')ithcat.send("@vid@%s" % '/tmp/test.mkv')
send_msg
send_msg(msg='Text Message', toUserName=None),其中的的msg是要发送的文本,toUserName是发送对象, 如果留空, 将发送给自己,返回值为True或者False
实例代码
import itchatitchat.auto_login()itchat.send_msg("hello world.")
send_file
send_file(fileDir, toUserName=None) fileDir是文件路径, 当文件不存在时, 将打印无此文件的提醒,返回值为True或者False
实例代码
import itchatitchat.auto_login()itchat.send_file("/tmp/test.txt")
send_image
send_image(fileDir, toUserName=None) 参数同上
新闻热点
疑难解答