Python之第三方模块itchat

Python之第三方模块itchat

  • 什么是API

API(Application Programming Interface,应用程序编程接口)是一些预先定义的函数,目的是提供应用程序与开发人员基于某软件或硬件得以访问一组例程的能力,而又无需访问源码,或理解内部工作机制的细节。

在linux中,用户编程接口API遵循了UNIX中最流行的应用编程界面标准—POSIX标准。POSIX标准是由IEEE和ISO/IEC共同开发的标准系统。该标准基于当时现有的UNIX实践和经验,描述了操作系统的系统调用编程接口API,用于保证应用程序可以在源程序一级上在多种操作系统上移植运行。这些系统调用编程接口主要是通过C库(LIBC)来实现的。

  • 什么是itchat模块

itchat是微信提供给python的一个接口包,其主要实现微信的基本功能,包括接发消息、获取好友个人资料等,要说有趣的东西,当然是注册图灵机器人,实现自动回复,其次还可以基于好友资料信息,做一些可视化的工作,包括签名的词云,性别的比例,好友的全国分布等

可自行下载了解:itchat
安装:

../bin/pip install itchat
  • itchat模块的应用示例

1.给手机助手发送消息

import itchat
import time
hotReload = True # 会保留登陆状态,在短时间内不用重新登陆
itchat.auto_login()
while True:
# 给微信手机助手发消息
itchat.send('hello',toUserName='filehelper')
itchat.send_file('/etc/passwd',toUserName='filehelper')
time.sleep(1)

2.统计微信的男女比例

import itchat
import time
hotReload = True 
itchat.auto_login()

iends = 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)

3.用图灵机器人工智能回复消息(需自行创建图灵机器人并复制api)

import itchat
import requests

def get_tuling_reponse(_info):
    print(_info)
    api_url = 'http://www.tuling123.com/openapi/api'
    data = {
        'key':'28a1d488a7fe47b5b637b750a6f3d66b',
        'info':_info,
        'userid':'haha'
    }
    # 发送数据到指定的网址,获取网址返回的数据
    res = requests.post(api_url,data).json()
    #print(res,type(res))
    # 给用户返回的内容
    print(res['text'])
    return (res['text'])

# get_tuling_reponse('给我讲个笑话')
# get_tuling_reponse('不好笑')

# 时刻监控好友发送的文本信息,并且给与一个回复
@itchat.msg_register(itchat.content.TEXT,isFriendChat=True)
def text_repky(msg):
    # 获取好友发送的文本信息
    # 返回文本信息
    content = msg['Content']
    # 将好友的消息发送给机器人去处理,处理的结果就是返回给好友的信息
    returnContent = get_tuling_reponse(content)
    return returnContent

itchat.auto_login()
itchat.run()

4.在微信端可使用linux系统命令

mport os
import itchat
@itchat.msg_register(itchat.content.TEXT,isFriendChat=True)
def text_reply(msg):
    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()

5.在python中执行shell命令

# 1.可以判断命令是否执行成功
# 返回值是0 执行成功
# 返回值不为0 执行不成功
import os
print(os.system('ls'))
res = os.system('hostnameeeee')
print(res)

# 2.用来保存命令的执行结果
res = os.popen('hostname').read()
print(res)
  • END

猜你喜欢

转载自blog.csdn.net/weixin_44828950/article/details/91472642