Python__itchat模块实现微信小功能

–itchat是一个开源的微信个人号接口,使用python调用微信从未如此简单。使用不到三十行的代码,你就可以完成一个能够处理所有信息的微信机器人。
使用命令安装itchat模块

pip install itchat

或者如果使用pyCharm的话,可以直接搜索itchat模块安装即可。
安装完成后下面我们来实现简单的几个功能
1、自动向微信文件助手消息

# _*_coding:utf-8_*_
import itchat
import time
import random
import os
ichat.auto_login()

while True:
    #1.给手机助手发送消息     itchat.send('hello',toUserName='filehelper')
    time.sleep(random.randint(1,3))

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)

3、需求:给文件助手发送消息,执行发送的内容
1.如果执行成功,显示执行结果
2.如果执行失败,显示执行失败

@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
    if msg['ToUserName'] == 'filehelper':
        #获取要执行命令的内容
        command = msg['Content']
        print(command)
        #让电脑执行命令代码
        #如果执行成功,返回值为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()

猜你喜欢

转载自blog.csdn.net/weixin_43314056/article/details/86659750