第三方模块
1.官方(例:time、math)
2.从网上下载(例:itchat)
itchat
1.安装itchat模块
pip install itchat
2.给微信助手发送消息或者文件
import itchat
hotReload=True#会保留登陆状态,在短时间内重新登陆不用
# 再次扫描二维码
itchat.auto_login()
itchat.send('hello',toUserName='filehelper')
itchat.send_file('/etc/passwd',toUserName='filehelper')
第三行报错是因为安装的画图软件打开不了
3.统计男女好友比例
friends = itchat.get_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)
4.和机器人交流
import itchat
import requests
def get_tuling_reponse(_info):
#机器人网址
api_url = 'http://www.tuling123.com/openapi/api'
#给机器人发送数据
#将api粘贴到key中
data ={
'key':'31c7db31e5e74c35b750172c00659bf9',
'info':_info,
'userid':'haha'
}
# 发送数据到指定网址,获取网址返回的数据
res = requests.post(api_url,data).json()
# 给用户返回的内容
print(res['text'])
return res['text']
get_tuling_reponse('给我讲个故事')
5.用机器人进行自动回复
# 时刻监控好友发送的文本消息,并且给予一个回复
# isGroupChat=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()
6.给电脑发送shell命令
import os
import itchat
# 在python中执行shell命令
# 1.第一种方式:可以判断命令是否执行成功;
# 返回值为0,执行成功
# 返回值不为0.执行是失败
# os.system('ls')
# res = os.system('hostnamess')
# print(res)
# 2.第二种方式 用来保存命令的执行结果的
# res = os.popen('hostname').read()
# print(res)
@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()
7.
import itchat
itchat.auto_login(hotReload=True)
res = itchat.search_friends('顾泽波')
x = res[0]['UserName']
while True: #最好不要加while True: 被微信检测到会被禁止发送消息
itchat.send('感受过绝望吗?',toUserName=x)