钉钉+图灵+语音播报+爬虫+自动化测试

本想着要考研了,以后就玩不成了,就最后给自己做一个每天都定时提醒自己目标的程序然后部署到服务器上,理想很丰满,现实是做了一个本地的,而且还是发到钉钉上,害我除了QQ,微信外又下载了一个钉钉办公软件...一言难尽,先记录一点是一点吧

首先我把我的目标放在了石墨文档中

 然后我要将其获取下来,利用 selenium 一个浏览器自动化测试工具,使用这个工具需要又对应的浏览器驱动,比如我用的是Google Chrome浏览器,就需要下载谷歌浏览器驱动(这里需要注意下载的版本要和浏览器一样),下载完成之后还要将其添加到环境变量中,为了方便直接将其放在python安装目录即可

shimo.py

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from lxml import etree
import time
import voice

class Remind(object):
    def __init__(self):
        self.usr = "你的账号"
        self.password = "你的密码"
        self.browser = webdriver.Chrome()
        self.wait = WebDriverWait(self.browser, 10)

    def quit_brower(self):
        self.browser.quit()

    def login(self):
        login_url = r"https://shimo.im/login"
        self.browser.get(login_url)

        usrInput = self.wait.until(
            EC.presence_of_element_located((By.XPATH,
                    "//*[@id='root']/div/div[2]/div/div/div/div[2]/div/div/div[1]/div[1]/div/input")))
        passwordInput = self.wait.until(
            EC.presence_of_element_located((By.XPATH,
                    "//*[@id='root']/div/div[2]/div/div/div/div[2]/div/div/div[1]/div[2]/div/input")))
        submit = self.wait.until(
            EC.element_to_be_clickable((By.XPATH,
                    "//*[@id='root']/div/div[2]/div/div/div/div[2]/div/div/div[1]/button")))

        usrInput.clear()
        usrInput.send_keys(self.usr)
        passwordInput.clear()
        passwordInput.send_keys(self.password)
        submit.click()

    def get_newyear_mission(self, _url):
        self.browser.get(_url)
        #time.sleep(10)
        self.wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="editor"]/div[2]')))
        html = self.browser.page_source
        s = etree.HTML(html)
        missionList = s.xpath('//*[@id="editor"]/div[2]/p/span/text()')
        missionToDo = []
        for mission in missionList:
            missionToDo.append(mission)
            print(mission)
        return missionToDo

def entrance():
    remind = Remind()
    m_voice = voice.Voice()
    remind.login()
    time.sleep(3)
    missions = remind.get_newyear_mission("要爬取的网页链接")
    remind.quit_brower()
    current_mp3_name = m_voice.synthetic(missions)
    m_voice.play_mp3(current_mp3_name)
    return missions

ok,得到想要的信息了,怎么将其发送到手机端呢,无非是微信和QQ,然而我的微信号不能登录网页版,QQ也被限制了,怎么办,只好用钉钉了,安状 DingtalkChatbot 模块,在网上找了以下用法

dingding.py

from dingtalkchatbot.chatbot import DingtalkChatbot
import shimo
import random
import tuling
import sys
import os


class Dingding():
    def __init__(self):
        super(Dingding, self).__init__()
        self.webhook = '你的webhook'
        self.tuling_robot = tuling.Robot()

    def sendmsg(self, data):
        text = ''
        if "考研" in data or "目标" in data or 'target' in data or "上岸" in data:
            missions = shimo.entrance()
            missions = '\n\n'.join(missions)
            num = random.randint(1, 100)
            text = '# [2020考研](https://shimo.im/docs/P3wpWH3G8vwDKgTt)\n{}\n\
            > ![美女](https://www.plmm.com.cn/images/{}.jpg)'.format(missions, num)
        elif "exit" == data:
            try:
                sys.exit(0)
            except:
                pass
            finally:
                os._exit(0)
        else:
            missions = self.tuling_robot.response(data)
            missions = '\n\n'.join(missions)
            num = random.randint(1, 100)
            text = '# [2020考研]\n{}\n\
                   > ![美女](https://www.plmm.com.cn/images/{}.jpg)'.format(missions, num)
        dd = DingtalkChatbot(self.webhook)
        dd.send_markdown(title="2020考研", text=text)

这样只要sengmsg又输入考研或者目标什么的手机端就可以收到你的目标了并且还会附上一张美女图片

最后发现这有点单调,能让它显示其他内容就好了,说做就做,这里使用图灵机器人是实现对话的效果

tuling.py

import requests
import json
import voice

class Robot():
    def __init__(self):
        super(Robot, self).__init__()

        self.url = '这三个字符串在你注册图灵的时候会给你'
        self.TULIN_API_KEY = '网上很多详细教程'
        self.userId = '这里不再赘述'

        self.m_voice = voice.Voice()



    def response(self, data):

        data_dict = {
            "reqType": 0,
            "perception": {
                "inputText": {
                    "text": data
                },
                "inputImage": {
                    "url": "https://www.plmm.com.cn/images/1.jpg"
                },
                "selfInfo": {
                    "location": {
                        "city": "xx",
                        "province": "xx",
                        "street": "xx"
                    }
                }
            },
            "userInfo": {
                "apiKey": self.TULIN_API_KEY,
                "userId": self.userId
            }
        }

        result = requests.post(self.url, json=data_dict)
        content = (result.content).decode('utf-8')
        string = json.loads(content)
        mp3_content = string['results'][0]['values']['text']

        print('小研:', mp3_content)
        current_mp3_name = self.m_voice.synthetic(mp3_content)
        self.m_voice.play_mp3(current_mp3_name)
        return mp3_content
#
# if __name__ == '__main__':
#     robot = Robot()
#     while(True):
#         data  =input('你:')
#         robot.response(data)

具体消息格式可以参考官方给的,稍稍修改一下即可

测试过后已经可以简单对话了,需要注意每天机器人只能回复100条(穷人说的)

对话就要有对话的样子,没有声音怎么行呢,加上语音播放的功能

安装baidu-aip模块,使用其文字转.wav的功能,再使用pygame播放.wav

voice.py

from aip import AipSpeech
import random
import time
import os
import wave
import pygame


class Voice():
    def __init__(self):
        super(Voice, self).__init__()

        self.AppID = '注册会有'
        self.API_Key = '注册会有'
        self.Secret_Key = '注册会有'
        #定义数据流块
        self.CHUNK = 1024

        self.client = AipSpeech(self.AppID, self.API_Key, self.Secret_Key)
    def synthetic(self,data):
        result = self.client.synthesis(data, 'zh', 1, {'vol':5, 'per':103, 'aue':6})
        filename = str(random.randint(1, 99999))+str(int(time.time()))+ '.wav'
         # 识别正确返回语音二进制 错误则返回dict 参照下面错误码
        if not isinstance(result, dict):
            with open('./mp3/'+filename, 'wb') as f:
                f.write(result)
                return filename
        else:
            return None

    def play_mp3(self, file_name):
        fhandle = wave.open('./mp3/'+file_name, "rb")
        params = fhandle.getparams()
        nchannels, sampwidth, framerate, nframes = params[:4]
        fhandle.close()
        pygame.mixer.init(framerate)
        pygame.mixer.music.load('./mp3/'+file_name)
        pygame.mixer.music.play()
        playTime = nframes / float(framerate)
        time.sleep(playTime)
        pygame.mixer.music.stop()

        #播放完毕之后删除指定文件
        try:
            os.remove('./mp3/'+file_name)
        except Exception as reason:
            pass
            #print("出错了:"+str(reason))

# if __name__ == '__main__':
#     voice = Voice()
#     while(True):
#         data = input()
#         current_mp3_name = voice.synthetic(data)
#
#         print(current_mp3_name)
#         voice.play_mp3(current_mp3_name)

这里没有实现播放完毕就删除mp3的功能,错误是文件被占用,只好每次打开程序把上一次的cache删除掉,就当带保存数据的了

main.py

from tuling import Robot
import os
import dingding


def del_file(path):
    file_list = os.listdir(path)
    for i in file_list:
        c_path = os.path.join(path, i)
        if os.path.isdir(c_path):
            del_file(c_path)
        else:
            os.remove(c_path)

if __name__ == '__main__':
    del_file(r'./mp3')
    ding = dingding.Dingding()
    while(True):
        data  =input('你:')
        ding.sendmsg(data)

一共是5个py文件

运行一下试一试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值