|
| 1 | +#! /usr/bin/python |
| 2 | +# _*_ encode:utf-8_*_ |
| 3 | + |
| 4 | +""" |
| 5 | +图林机器人聊天 |
| 6 | +author: gxcuizy |
| 7 | +time: 2018-09-19 |
| 8 | +""" |
| 9 | + |
| 10 | +import json |
| 11 | +import socket |
| 12 | +import uuid |
| 13 | +from urllib.request import urlopen, Request |
| 14 | +from urllib.parse import urlencode |
| 15 | + |
| 16 | + |
| 17 | +class TuringChatMode(object): |
| 18 | + def __init__(self): |
| 19 | + # API接口地址 |
| 20 | + self.turing_url = 'http://www.tuling123.com/openapi/api?' |
| 21 | + |
| 22 | + def getTuringText(self, text): |
| 23 | + """获取聊天返回内容""" |
| 24 | + # 用户IP |
| 25 | + user_ip = self.getHostIp() |
| 26 | + # MAC地址 |
| 27 | + mac_id = self.getMacId() |
| 28 | + # 请求参数 |
| 29 | + turing_url_data = dict( |
| 30 | + # AppKey密钥 |
| 31 | + key='82622364a28142878dd8ad634eec401c', |
| 32 | + # 聊天请求内容 |
| 33 | + info=text, |
| 34 | + # 用户唯一标志(可以传IP地址或者MAC地址,或者其他的唯一标识) |
| 35 | + userid=mac_id |
| 36 | + ) |
| 37 | + # 发送聊天请求 |
| 38 | + request = Request(self.turing_url + urlencode(turing_url_data)) |
| 39 | + try: |
| 40 | + w_data = urlopen(request) |
| 41 | + except Exception as error_info: |
| 42 | + return error_info |
| 43 | + response_text = w_data.read().decode('utf-8') |
| 44 | + json_result = json.loads(response_text) |
| 45 | + return json_result['text'] |
| 46 | + |
| 47 | + def getHostIp(self): |
| 48 | + """获取用户IP""" |
| 49 | + socket_info = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 50 | + socket_info.connect(('8.8.8.8', 80)) |
| 51 | + ip = socket_info.getsockname()[0] |
| 52 | + return ip |
| 53 | + |
| 54 | + def getMacId(self): |
| 55 | + """获取MAC地址""" |
| 56 | + node = uuid.getnode() |
| 57 | + mac = uuid.UUID(int=node).hex[-12:] |
| 58 | + return mac |
| 59 | + |
| 60 | + |
| 61 | +# 聊天程序主入口 |
| 62 | +if __name__ == '__main__': |
| 63 | + print("您可以和机器人聊天了(退出请输入q)") |
| 64 | + turing = TuringChatMode() |
| 65 | + while True: |
| 66 | + msg = input("\n我:") |
| 67 | + # 设定输入q,退出聊天。 |
| 68 | + if msg == 'q': |
| 69 | + exit("聊天结束!") |
| 70 | + else: |
| 71 | + turing_data = turing.getTuringText(msg) |
| 72 | + print("机器人:", turing_data) |
0 commit comments