用Python写的一个多线程机器人聊天程序

本人是从事php开发的, 近来想通过php实现即时通讯(兼容windows)。后来发现实现起来特别麻烦, 就想到python。听说这家伙在什么地方都能发挥作用。所以想用python来做通讯模块。。。所以主要学习pythonn的多线程和tcp连接。

 

但是没有用过python, 所有在学习python的同时写个小小的程序 -》 和机器人聊天

 

本程序机器人由【图灵机器人 http://www.tuling123.com】提供, 把编写的例子发了出来供初学python的朋友们学习和熟悉。

 

注意:python版本必须为3.x +, 不兼容2.x版本的python

 

文件列表: 

 

main_server.py: 服务端程序,用于接收客户端的信息, 并返回Jinko回答的话

 1 # tcp server
 2 import socket;
 3 import time;
 4 import threading;
 5 from JinkoRobot import *;
 6 
 7 #应用程序入口类
 8 class ApplicationServer:
 9 
10     #构造函数初始化 socket 
11     def __init__(self, host="localhost", port=8005):
12         self.connList = [];
13         self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
14         self.socket.bind((host, port));
15         self.socket.listen(100);
16         print("我是Jinko, 我来自[图灵机器人:http://www.tuling123.com]");
17         print("");
18         print("赶紧打开客户端和我聊天吧!");
19         self.accept();
20 
21     #多线程接受用户请求
22     def accept(self):
23         while True:
24             connection, address = self.socket.accept();
25             # print('connect')
26             thread = ChatThread(connection);
27             thread.start();
28 
29 #聊天线程
30 class ChatThread(threading.Thread):
31 
32     def __init__(self, conn):
33         threading.Thread.__init__(self);
34         self.__connection = conn;
35 
36     def run(self):
37         while True:
38             try:
39                 recv = self.__connection.recv(8192);
40             except:
41                 break;
42 
43             # print("收到:" + recv.decode('utf-8'))
44             rebot = JinkoRobot();
45             rebot.listenFor(recv.decode('utf-8'));
46             answer = rebot.answer();
47             # print('say:' + answer)
48             self.__connection.send(answer.encode('utf-8'));
49 
50 ApplicationServer();

 

main_client.py: 客户端程序, 用于和Jinko发起聊天

 1 import socket;
 2 import time;
 3 
 4 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
 5 print("正在和Jinko连线...");
 6 sock.connect(('localhost', 8005));
 7 print("");
 8 
 9 
10 while True:
11     speak = input("和Jinko说点什么:");
12 
13     if speak == "quit":
14         break;
15 
16     if speak == "":
17         continue;
18 
19     # print("发送中..." + "("+ speak +")")
20     sock.send(speak.encode('utf-8'));
21     # print("已发送")
22 
23     print("Jinko在思考...");
24     answer = sock.recv(8192);
25     print("Jinko回复你:" + answer.decode('utf-8'));
26     print("");
27 
28 sock.close();

 

JinkoRobot.py: 它就是Jinko啦啦啦~~

 1 #Jinko Robot
 2 import json;
 3 import urllib.request;
 4 import urllib.parse;
 5 
 6 class JinkoRobot:
 7     
 8     __answer = '';
 9 
10     def __init__(self):
11         pass;
12 
13     #倾听话语
14     def listenFor(self, string):
15         self.__answer = self.thinking(string);
16 
17     # 思考着
18     def thinking(self, string):
19         says = urllib.parse.quote_plus(string);
20         f = urllib.request.urlopen("http://www.tuling123.com/openapi/api?key=4bc32d41c10be18627438ae45eb839ac&info=" + says);
21         json_str = f.read();
22         thinkdata = json.loads(json_str.decode('utf-8'));
23         f.close();
24         
25         if(thinkdata['code'] > 40000 and thinkdata['code'] < 40010):
26             return "今天Jinko被你问得有点累了, 过会再问吧!";
27 
28         if(thinkdata['code'] == 200000):
29             return thinkdata['text'] + ", 猛戳这里>>" +  thinkdata['url'];
30 
31         if(thinkdata['code'] == 302000) :
32             info = thinkdata['text'];
33 
34             for content in thinkdata['list']:
35                 info += "\n\n>" + content['article'] \
36                         + "  来源于" + content['source'] \
37                         + "  详细信息请猛戳这里>>" + content['detailurl'];
38             
39             return info;
40 
41         if(thinkdata['code'] == 305000):
42             info = thinkdata['text'];
43 
44             for key in thinkdata['list']:
45                 info += "\n\n>" + key + ": 车次>" + content['trainnum'] \
46                         + "" + content['start'] + "" + content['terminal'] \
47                         + "  发车时间:" + content['starttime'] \
48                         + "  到达时间:" + content['endtime'] \
49                         + "  详细信息请猛戳这里>>" + content['detailurl'];
50             
51             return info;
52 
53         return thinkdata['text'];
54 
55     #和你交流回答
56     def answer(self):
57         return self.__answer;

 

运行效果图:

 

最后我想说下, 我只是python的初学者,没啥python经验哈

 

顺便提供下zip下载包:https://files.cnblogs.com/files/JinkoWu/ChatWithRobot.zip

posted @ 2015-12-16 17:56  Jinko  阅读(4259)  评论(0编辑  收藏  举报