Intelligent chatbot implementation (source code + resolution) and chatbot source code

Source: Internet
Author: User

Intelligent chatbot implementation (source code + resolution) and chatbot source code
Preface:

I wrote a beautiful image collector (source code + resolution), which was supported by many friends. I found this series of tutorials quite popular and encouraged me to continue writing.

As mentioned in that article, beauty image collection is only a feature of my previous complete APP. There are several other interesting ones that are not yet open-source, I will write a tutorial one by one later.

Today we bring about the implementation of intelligent chatbots (source code + resolution). Like in the previous tutorial, when you don't have a girlfriend, you can use it to pass the time. The API here is provided by the Turing robot to implement a very powerful robot.

Specific functions include:

• Supports chat and intelligent Q &
• Rich functions such as jokes, weather, and public transportation
• Support for natural language processing and semantic understanding
• Billions of knowledge bases

Running effect:

Download source code:

The source code has been uploaded to git. Download and learn.

Download link: https://github.com/colin1994/tulingIOS


Source code parsing:


I. Imitation Interface


The interface of this demo is imitation. It's just a simplified version, including emoticons and voices.

I will not introduce this part of the interface here, because it is not the main content of this tutorial. After all, this interface must be customized in your actual project.

Here is a brief introduction.

This interface is divided into two parts:

1. UITableView: displays the chat list, where the robot answers the questions on the left and the questions on the right.

In addition, each cell in the list consists of an avatar and text. This cell is customized. You can view the source code for details.

Add list:

//add UItableView    self.tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 44, self.view.frame.size.width, self.view.frame.size.height-88) style:UITableViewStylePlain];    [self.tableView registerClass:[ChartCell class] forCellReuseIdentifier:cellIdentifier];    self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;    self.tableView.allowsSelection = NO;    self.tableView.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"chat_bg_default.jpg"]];    self.tableView.dataSource=self;    self.tableView.delegate=self;    [self.view addSubview:self.tableView];

2. KeyBordVIew: Custom UIView, used to display custom keyboard views.

Add keyboard:

    //add keyBorad    self.keyBordView=[[KeyBordVIew alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height-44, self.view.frame.size.width, 44)];    self.keyBordView.delegate=self;    [self.view addSubview:self.keyBordView];


In addition, the keyboard involves the pop-up and collapse operations. Before loading the view, register the notification and respond to the related operations.

1. Registration notification

// Register the notification and collapse the keyboard. [[nsnotifcenter center defacenter center] addObserver: self selector: @ selector (keyboardShow :) name: UIKeyboardWillShowNotification object: nil]; [NSNotificationCenter defacenter center] addObserver: self selector: @ selector (keyboardHide :) name: UIKeyboardWillHideNotification object: nil];

2. response operation

// Keyboard pop-up response-(void) keyboardShow :( NSNotification *) note {CGRect keyBoardRect = [note. userInfo [UIKeyboardFrameEndUserInfoKey] CGRectValue]; CGFloat deltaY = keyBoardRect. size. height; [UIView animateWithDuration: [note. userInfo [UIKeyboardAnimationDurationUserInfoKey] floatValue] animations: ^ {self. view. transform = CGAffineTransformMakeTranslation (0,-deltaY);}];} // keyboard collapse response-(void) keyboardHide :( NSNotification *) note {[UIView animateWithDuration: [note. userInfo [UIKeyboardAnimationDurationUserInfoKey] floatValue] animations: ^ {self. view. transform = CGAffineTransformIdentity;}];}


II. Turing key acquisition


If you have used some third-party APIs, you must register them as their users before obtaining the corresponding key to call the API.

Turing is no exception. You need to register as a Turing user first, and then have relevant tutorials to teach you how to get your key and the correct URL. We will not repeat it here. Link to the Turing robot Official Website

For example, the key in my demo is 6c2cfaf7a7f088e843b550b0c5b89c26.

The corresponding API is: http://www.tuling123.com/openapi/api? Key = 6c2cfaf7a7f088e843b550b0c5b89c26 & info =% @

Therefore, you only need to replace the key here with your own.



3. Use of Turing API


Third-party network request library ASI and json format data parsing library JsonKit are used here.

When importing ASI, if your project is ARC, set the corresponding file to support ARC. (-Fno-objc-arc)

In addition, you need to import some frameworks

SystemConfiguration. framework
MobileCoreServices. framework
CFNetwork. framework
Libz. dylib


Then we can use ASI to call the Turing API and use jsonkit to parse the returned data.

The specific implementation is as follows:

// After the problem is edited, // 1. display your problem messageType = 1 // 2. call the API and return the result-(void) KeyBordView :( KeyBordVIew *) keyBoardView textFiledReturn :( UITextField *) textFiled {// display your issue ChartCellFrame * cellFrame = [[ChartCellFrame alloc] init]; chartMessage * chartMessage = [[ChartMessage alloc] init]; chartMessage. icon = @ "icon01.png"; chartMessage. messageType = 1; chartMessage. content = textFiled. text; cellFrame. chartMessage = chartMessage; [self. CellFrames addObject: cellFrame]; [self. tableView reloadData]; // scroll to the current row [self tableViewScrollCurrentIndexPath]; // query result using user problems // API request format. For the specific format, see the Turing official website // 6c2cfaf7a7f088e843b550b0c5b89c26 and replace it with the key you applied for. NSString * urlString = [NSString stringWithFormat: @ "http://www.tuling123.com/openapi/api? Key = 6c2cfaf7a7f088e843b550b0c5b89c26 & info = % @ ", textFiled. text]; // NSUTF8StringEncoding encoding. Avoid Chinese errors urlString = [urlString failed: Failed]; // call api nsurl * url = [NSURL URLWithString: urlString]; testRequest = [ASIHTTPRequest requestWithURL: url]; [testRequest setDelegate: self]; [testRequest startAsynchronous]; textFiled. text = @ ""; myTextField = textFiled;} # pragma mark-returned robot answer // After the API is called, the result of Turing's answer is returned // 1. collapse the keyboard // 2. show answer content-(void) requestFinished :( ASIHTTPRequest *) request {// collapse the keyboard [myTextField resignFirstResponder]; // use this method when reading the returned content in text format // parse the returned json data NSString * responseString = [request responseString]; self. testDic = [responseString objectFromJSONString]; self. testArr = [testDic objectForKey: @ "text"]; // display the answer content ChartCellFrame * cellFrame = [[ChartCellFrame alloc] init]; chartMessage * chartMessage = [[ChartMessage alloc] init]; chartMessage. icon = @ "icon02.png"; chartMessage. messageType = 0; chartMessage. content = [NSString stringWithFormat: @ "% @", self. testArr]; cellFrame. chartMessage = chartMessage; [self. cellFrames addObject: cellFrame]; [self. tableView reloadData]; // scroll to the current row [self tableViewScrollCurrentIndexPath];} // API request failed-(void) requestFailed :( ASIHTTPRequest *) request {NSError * error = [request error]; NSLog (@ "error --- % @", error); UIAlertView * alert _ = [[UIAlertView alloc] initWithTitle: @ "prompt" message: @ "No network available, please check the network status" delegate: self cancelButtonTitle: @ "know" otherButtonTitles: nil]; [alert _ show];}



On the way to learning, I will share with you

An automatic Chat Robot with better source code

I own a QQ auto-reply robot system .....

I wrote it in PHP... the QQ bound to this robot is 465749449.

In the past few days, my robot functions are being maintained and are temporarily unavailable. I will give you a QQ number of a robot with the same system as I have used ------ 869936432

A simple chatbot source code that needs to be compiled in C ++

It depends on what functions the chatbot has to offer.
Generally, you must be able to analyze sentences, distinguish between nouns and adjectives, and remember the set relationship.
Then the answer is random.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.