用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下載包:http://files.cnblogs.com/files/JinkoWu/ChatWithRobot.zip


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM