教程使用到:
已經(jīng)實現(xiàn)的功能:
- 微信消息記錄志珍,撤回消息查看
- 發(fā)送指令召喚機器人
- 開關(guān)電腦、遠程控制電腦拍照攝像并發(fā)送圖像
將要實現(xiàn)的功能:
- 在妹子起床的時候給妹子推送天氣胚股,問候晚安(部分實現(xiàn))
- 將聊天記錄存入數(shù)據(jù)庫(沒時間弄完)
- (給樹莓派增加一種控制方式)控制樹莓派端,然后通過樹莓派上的UDP Server去廣播控制指令到Arduino端,隨后控制遠程家用設(shè)備(窗簾、燈等等)
- 更加顆梁凡化的配置
不廢話上代碼:
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回復(fù) '%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') # 隨便發(fā)的一張暴漫表情
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(): # 登陸成功執(zhí)行
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("定時任務(wù)開始執(zhí)行.")
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 == "關(guān)機":
os.system("shutdown -s -t 1000 -c 已經(jīng)被微信機器人執(zhí)行遠程關(guān)機指令")
return "執(zhí)行成功廊蜒,1000秒后關(guān)機"
elif data =="取消關(guān)機":
os.system("shutdown -a")
return "取消關(guān)機成功"
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
執(zhí)行:
python main.py