使用Pyhton+ItChat+图灵机器人扩展微信功能

教程使用到:

已经实现的功能:

  • 微信消息记录,撤回消息查看
  • 发送指令召唤机器人
  • 开关电脑、远程控制电脑拍照摄像并发送图像

将要实现的功能:

  • 在妹子起床的时候给妹子推送天气,问候晚安(部分实现)
  • 将聊天记录存入数据库(没时间弄完)
  • (给树莓派增加一种控制方式)控制树莓派端,然后通过树莓派上的UDP Server去广播控制指令到Arduino端,随后控制远程家用设备(窗帘、灯等等)
  • 更加颗粒化的配置

不废话上代码:

# main.py

#coding:utf-8
import itchat
from itchat.content import *
import control
import time
import sqlite3
import requests
import json
from urllib import parse
import schedule
import _thread

me = {}
ROBOT_NAME = "小x"
TULING_KEY = "tuling_key"
vips = []
robots = set()

def gen_db():
    conn = sqlite3.connect("wechat.db")
    print("Connect to database successfully.")
    c = conn.cursor()
    c.execute('''CREATE TABLE CHATS IF NOT EXISTS
        (id INT PRIMARY KEY NOT NULL autoincrement,
        msgId text not null,
        fromName char(70),
        toName char(70),
        time text,
        from text,
        to text,
        content text
        );''')

@itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING])
def text_reply(msg):
    # print(msg)
    fromUserName = itchat.search_friends(userName=msg.FromUserName)
    toUserName = itchat.search_friends(userName=msg.ToUserName)
    print("%s [%s] [%s -> %s]:%s"%(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(msg.CreateTime)),msg.type,get_name(fromUserName),get_name(toUserName),msg.text))
    if msg.type == TEXT and msg.FromUserName != me.userName:
        if msg.text.strip() == "%s"%(ROBOT_NAME) and msg.FromUserName not in robots:
            msg.user.send("恭喜你,成功召唤了我家机器人,你可以问TA任何事情(比如今天天气、讲个笑话鬼故事等等)\n回复 '%s再见' 就可以让TA滚蛋哟" % (ROBOT_NAME) )
            robots.add(msg.FromUserName)
        if msg.text == "%s再见"%(ROBOT_NAME) and msg.FromUserName in robots:
            msg.user.send("虽然我走了,但是我会永远爱你~")
            msg.user.send_image('./dady.jpg') # 随便发的一张暴漫表情
            robots.remove(msg.FromUserName)
    
    if msg.type == TEXT and msg.FromUserName in robots and  msg.FromUserName != me.userName:
        #处于ai聊天的用户
        tuling(msg)
    if msg.FromUserName == me.userName and msg.ToUserName == me.userName:
        #是自己    
        command(msg,msg.text)
    else:
        #不是自己对自己说
        pass
    # return msg.text

def get_name(user):
    return user.NickName if user.RemarkName == "" else user.RemarkName

def command(msg,text):
    if text.startswith(ROBOT_NAME):
        msg.user.send(control.cmd(itchat,msg,text[3:]))

def tuling(msg):
    params = parse.urlencode({'key':TULING_KEY,'info':msg.text})
    url = 'http://www.tuling123.com/openapi/api?'+params
    res = requests.get(url)
    res.encoding = 'utf-8'
    print("tuling:",res.text)
    jd = json.loads(res.text)
    msg.user.send(jd['text'])


def lc(): # 登陆成功执行
    print('finish logining')
    friends = itchat.get_friends(update=True)
    for f in friends:
        print(f)
        if f.RemarkName == "XXXX": 
            vips.append(f)
    global me
    me = itchat.search_friends()
    print(me)
    # _thread.start_new_thread( print_time,())

def ec():
    print('exit')

def job():
    print("定时任务开始执行.")
    
    for v in vips:
        msg = {
            'user':v,
            'text':v.City+'的天气'
        }
        print(msg)
        tuling(msg)

def print_time():
    schedule.every(1).seconds.do(job)
    while True:
        schedule.run_pending()
        time.sleep(1)

# itchat.auto_login(hotReload=True,loginCallback=lc, exitCallback=ec)
itchat.auto_login(hotReload=True,loginCallback=lc, exitCallback=ec)
itchat.run()
# schedule.every().day.at("20:32").do(job)

print("GAME OVER.")

# control.py

#coding:utf-8
import os
import cv2

def cmd(itchat,msg,data):
    data.strip()
    print("execute cmd:",data)
    # os.system(data)
    if data == "关机":
        os.system("shutdown -s -t 1000 -c 已经被微信机器人执行远程关机指令")
        return "执行成功,1000秒后关机"   
    elif data =="取消关机":
        os.system("shutdown -a")
        return "取消关机成功" 
    elif data == "拍照":
        f = capture()
        # msg.user.send_image(path)
        itchat.send_image(f)
        return "拍照成功"
    elif data == "录像":
        f = video()
        print(f)
        itchat.send_file(fileDir=f)
        # itchat.send_video("@vid@%s" % f)
        return "录像成功"
    return "未知指令"

def video():
    p = "e:/temp.mp4"
    cap = cv2.VideoCapture(0)
    cap.set(3,640)
    cap.set(4,480)
    cap.set(1, 10.0)
    fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
    out = cv2.VideoWriter(p, fourcc,10,(640,480))
    count = 0
    while True:
        ret,frame = cap.read()
        if ret == True:
            frame = cv2.flip(frame, 1)
            a = out.write(frame)
            print(".",end="")
            if count == 200: #1.2m & 20s
                print()
                break
        else:
            break
        count = count + 1
    cap.release()
    out.release()
    cv2.destroyAllWindows()
    return p

def capture():
    p  = "e:/temp.jpg"
    cap = cv2.VideoCapture(0)
    ret, frame = cap.read()
    cv2.imwrite(p, frame)
    cap.release()
    cv2.destroyAllWindows()
    return p

 执行:

python main.py

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值