python版wobot

#-*- coding: UTF-8 -*-
import pyglet
import os
import random
import hashlib
import time
import urllib.request
from urllib.request import quote
import os.path
log=None;#False,None
tok='24.6a0ecfcf511a91e5fb6c9f9ef980b0d6.2592000.1462188570.282335-7953574'#你的token,一个月一授权
##############以下是一堆问题的答案,可以定期维护
dict={}
dict["hello"] = "你好,很高兴见到你。"
dict["who"] = "我是leo的小兄弟heo。"
dict["name"] = "我是leo的小兄弟heo。"
dict["eee"] = "鹅鹅鹅, 曲项向天歌。 白毛浮绿水, 红掌拨清波。"



#####################以下是函数代码
def downmp3(txt):
    h5 = hashlib.md5()   
    h5.update(txt.encode('utf-8'))   
    m5=h5.hexdigest()
    
    if os.path.exists(m5+'.mp3'):
        return m5+'.mp3'
    else:
        if(log):
            print('need interface:'+m5+'.mp3')
        url='http://tsn.baidu.com/text2audio?tex='+quote(txt)+'&lan=zh&cuid=1qazxsw23edcvfr4&ctp=1&tok='+tok
        
        request = urllib.request.Request(url)  
        response = urllib.request.urlopen(request)
        savePath=m5+'.mp3'#此文件保存最新下载的
        f = open(savePath,'wb')
        f.write(response.read())
        f.close()
        
        return savePath 

def exit_callback(dt):
    pyglet.app.exit()

def answer(atxt):
    #pyglet.resource.reindex()
    mp3file=downmp3(atxt)
    try:
        music = pyglet.media.load(mp3file)
        #music = pyglet.resource.media(mp3file)
    except Exception  as e:  
        print('except:', e)  
        print(mp3file+"文件是否存在:"+str(os.path.exists(mp3file))+","+str(os.path.getsize(mp3file)))
        time.sleep(3)
        music = pyglet.resource.media(mp3file)
    music.play()
    pyglet.clock.schedule_once(exit_callback, music.duration)   
    pyglet.app.run()
    
    
def randAnswer():
    ans = ["你问的问题我不知道哪","没听明白你说的","我搞不懂你说的哪","不清楚","不知道"]#没有匹配答案的时候,显示这个 
    #ans = ["50","51","52"]#没有匹配答案的时候,显示这个 
    rans=ans[random.randint(0, len(ans)-1)]
    if(log):
        print(rans)
    return rans
    
##########正式对话开始
print("I'm wobot,欢迎和我随便聊点什么。")
question = input("你说:")
while (question!='exit'):
    if(question in dict):
        answer(dict[question])
    else:
        #answer('你说什么')
        answer(randAnswer())
    question = input("你说:")

猜你喜欢

转载自mushme.iteye.com/blog/2292428
今日推荐