图灵机器人和ichat

  • python API
    例:itchat
  1. 操作微信,给手机助手发信息
import itchat
# hotReload=True,会保留登陆状态,在短时间内重新登陆不用再次扫描二维码
# itchat.auto_login(hotReload=True)
itchat.auto_login()
# 1.给手机助手发送消息

itchat.send('hello',toUserName='filehelper')
itchat.send_file('/etc/passwd',toUserName='filehelper')

  1. 操作微信,统计你的好友的男女比例
import itchat
itchat.auto_login()
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)

  1. 自动回复机器人
import itchat
import requests

def get_tuling_reponse(_info):
    api_url = 'http://www.tuling123.com/openapi/api'
    data ={
        'key':'d6cdfe1757a044d7b6370927acebc297',#自行注册获得
        '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('给我讲个故事')
# 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()
  1. 操作微信在python中执行shell命令
import os
import itchat
# 1.第一种方式:可以判断命令是否执行成功;
# 返回值为0,执行成功
# 返回值不为0.执行是失败
os.system('ls')
res = os.system('hostnamess')
print(res)
2.第二种方式 用来保存命令的执行结果的
res = os.popen('hostname').read()
print(res)
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

itchat.auto_login(hotReload=True)
# 根据好友昵称查找好友的信息,返回值是一个列表,有多个元素
res = itchat.search_friends('ftzy')
#print(res)
# 通过索引获取该好友的详细信息
lz = res[0]['UserName']
itchat.send('python',toUserName=lz)

猜你喜欢

转载自blog.csdn.net/qq_41386300/article/details/85218938