第三方模块
官方第三方模块
第三方库---->模块(从网上下载)
API
API: 应用程序编程接口
是一些预先定义的函数,目的是提供应用程序与开发人员基于某软件或硬件得以访问一组例程的能力,而又无需访问源码,或理解内部工作机制的细节
实现编程访问微信
----导入itchat模块
import itchat
# 1.给手机助手发送消息
itchat.auto_login()
itchat.send('hello',toUserName='filehelper')
itchat.send_file('/etc/passwd',toUserName='filehelper')
# 2.统计好友的男女比例
friends = itchat.get_friends()
# print(friends)
info={}
for friend in friends[1:]:
if friend['Sex'] == 1:
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)
使用图灵机器人对好友消息进行自动回复
在图灵机器人官网上注册一个账号,并创建一个机器人
import itchat
import requests
def get_tuling_reponse(info):
api_url = 'http://www.tuling123.com/openapi/api'
data = {
'key':'2643b47d222644809174e95a8925f01f',
'info':info,
'userid':'Chung'
}
# 发送数据到指定网址,获取网址返回的数据
res = requests.post(api_url,data).json()
# 给用户返回的内容
print(res['text'])
return res['text']
# 测试机器人的自动回复
get_tuling_reponse('给我讲个笑话')
get_tuling_reponse('cat')
# 时刻监控好友发送的文本消息,并且给予一个回复
# isGroupChat=True:接收群聊消息 isFriendChat=True:接受好友消息
# 注册响应事件,消息类型为itchat.content.TEXT,即文本消息
@itchat.msg_register(itchat.content.TEXT,isFriendChat=True)
def text_reply(msg):
# 获取好友发送的文本消息
# 返回同样的文本消息
content = msg['Content']
# 将好友的消息发送给机器人去处理,处理的结果就是返回给好友的消息
returnContent = get_tuling_reponse(content)
return returnContent
itchat.auto_login()
itchat.run()
运行程序生成二维码,扫描二维码即可对好友消息进行自动回复
在微信上远程运行shell命令
在python中执行shell命令
import os
# 1.第一种方式:可以判断命令是否执行成功
# 返回值为0,执行成功
# 返回值不为0,执行失败
os.system('ls')
res = os.system('hostnamess')
print(res)
# 2.第二种方式:用来保存命令的执行结果的
res = os.popen('hostname').read()
print(res)
微信上运行shell命令
import os
import itchat
@itchat.msg_register(itchat.content.TEXT,isFriendChat=True)
def text_reply(msg):
"""
需求:当我们的文件助手发送消息的时候,执发送的内容
1.如果执行成功,显示执行结果
2.如果执行失败,显示执行失败
:param msg:
:return:
"""
if msg['ToUserName'] == 'filehelper':
# 获取要执行的命令的内容
command = msg['Content']
# 让电脑执行命令代码
# 如果命令执行成功,返回值是0
if os.system(command) == 0:
res = os.popen(command).read()
result = '[返回值]-命令执行成功,执行结果:\n' + res
itchat.send(result,'filehelper')
# 如果命令执行失败
else:
result = '[返回值]-命令%s执行失败,请重试' %(command)
itchat.send(result,'filehelper')
itchat.auto_login()
itchat.run()
给指定好友发送消息
import itchat
# hotReload=True:会保留登陆状态,在短时间内重新登陆不用再次扫描二维码
itchat.auto_login(hotReload=True)
# 根据好友昵称查找好友的信息,返回值是一个列表,有多个元素
res = itchat.search_friends('张珉')
# 通过索引获取该好友的详细信息
ly = res[0]['UserName']
while True:
itchat.send('python',toUserName=ly)