Loading... ## 聊天机器人-图灵机器人 看到之前的课程上,有简短的示例代码,可以与机器人进行对话,但只能聊三毛钱的,聊完就要重新开始。于是我将其稍微改进了一下。 1、增加循环,可以无限制聊天,输入关键词退出 2、虽然可以无限制聊天,但受限于免费版key的调用次数,一个key一天调用100次,转瞬即逝,于是增加4个key,循环使用,达到400次 代码如下: ``` python # -*- coding: utf-8 -*- """ Created on Thu Jun 4 11:15:06 2020 @author: erek """ import requests, json, time, random wel = '''Hello!我是你的聊天机器人 我有问必答,你可以问“今天南京天气怎么样?”,也可以问“你喜欢夏天吗?” 快来问我问题呀,欢迎来撩! 【温馨提示】 1、如果要停止对话,请说‘再见’ 2、机器人未必智能,不可攻击它哦! 3、如果提示请求次数超限制,可继续尝试,如果一直超出限制,第二天再试噢!(每天约400次请求) 4、功能:笑话、故事、数字计算、中英互译、星座、脑筋急转弯、绕口令、天气查询、日期查询、快递查询等 ''' print(wel) apikey1 = '填写你自己的KEY' apikey2 = '填写你自己的KEY' apikey3 = '填写你自己的KEY' apikey4 = '填写你自己的KEY' tag = 0 apikey = apikey1 time.sleep(1) while True: feature_text = '说点什么:' user1 = input(feature_text) if user1 != '再见': userid = str(random.randint(1, 1000000000000000000000)) tulingdata1 = json.dumps({ "perception": { "inputText": { "text": user1 }, }, "userInfo": { "apiKey": apikey, "userId": userid } }) if tag == 0: apikey = apikey1 tag = 1 elif tag == 1: apikey = apikey2 tag = 2 elif tag == 2: apikey = apikey3 tag = 3 else: apikey = apikey4 tag = 0 robot1 = requests.post('http://openapi.tuling123.com/openapi/api/v2', tulingdata1) jsrobot1 = json.loads(robot1.text)['results'][0]['values']['text'] print(jsrobot1) time.sleep(1) continue else: print('\n我走啦,下次见!') break ``` 这样一个“智能”聊天机器人就完成了,很简单的小程序,利用图灵机器人提供的API,即可完成接入。 ## 打包exe,让每个人都可以运行 ### 安装PyInstaller 通过命令`pip install PyInstaller`,成功安装后即可对py程序进行打包。 ### 通过控制台进行打包 通过cd切换到`.py`文件所在路径,使用`pyinstaller -F Test.py`命令进行打包,随后该目录下会生成dist文件夹,里面exe的文件双击即可打开。 运行如下图所示,快来试试看吧!  <hr class="content-copyright" style="margin-top:50px" /><blockquote class="content-copyright" style="font-style:normal"><p class="content-copyright">版权属于:Erek</p><p class="content-copyright">本文链接:<a class="content-copyright" href="https://erek.top/archives/9.html">https://erek.top/archives/9.html</a></p><p class="content-copyright">转载时须注明出处及本声明</p></blockquote> 最后修改:2020 年 12 月 23 日 08 : 59 PM © 允许规范转载 赞赏 如果觉得我的文章对你有用,请随意赞赏 ×Close 赞赏作者 扫一扫支付 支付宝支付 微信支付