├── README.md
├── dotnet
├── ChatterBotAPI.sln
├── ChatterBotAPI
│ ├── AssemblyInfo.cs
│ ├── ChatterBot.cs
│ ├── ChatterBotAPI.csproj
│ ├── ChatterBotFactory.cs
│ ├── ChatterBotSession.cs
│ ├── ChatterBotThought.cs
│ ├── ChatterBotType.cs
│ ├── Cleverbot.cs
│ ├── Pandorabots.cs
│ └── Utils.cs
├── ChatterBotAPITest
│ ├── AssemblyInfo.cs
│ ├── ChatterBotAPITest.csproj
│ └── Main.cs
└── ChatterBotAPITestVB
│ ├── Application.vb
│ ├── AssemblyInfo.vb
│ └── ChatterBotAPITestVB.vbproj
├── java
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── com
│ │ └── google
│ │ └── code
│ │ └── chatterbotapi
│ │ ├── ChatterBot.java
│ │ ├── ChatterBotFactory.java
│ │ ├── ChatterBotSession.java
│ │ ├── ChatterBotThought.java
│ │ ├── ChatterBotType.java
│ │ ├── Cleverbot.java
│ │ ├── Pandorabots.java
│ │ └── Utils.java
│ └── test
│ └── java
│ └── com
│ └── google
│ └── code
│ └── chatterbotapi
│ └── test
│ └── ChatterBotApiTest.java
├── lgpl-3.0.txt
├── php
├── ChatterBotApiTestOOP.php
├── chatterbotapi.php
├── chatterbotapitest.php
├── composer.json
├── phpunit.xml
├── src
│ └── ChatterBotApi
│ │ ├── AbstractBot.php
│ │ ├── AbstractSession.php
│ │ ├── ChatterBotFactory.php
│ │ ├── ChatterBotThought.php
│ │ ├── ChatterBotType.php
│ │ ├── IOException.php
│ │ ├── Implementation
│ │ ├── CleverBot
│ │ │ ├── CleverBot.php
│ │ │ └── Session.php
│ │ └── PandoraBots
│ │ │ ├── PandoraBots.php
│ │ │ └── Session.php
│ │ └── Utils.php
└── tests
│ └── ChatterBotApi
│ ├── ChatterBotFactoryTest.php
│ ├── ChatterBotThoughtTest.php
│ ├── ChatterBotTypeTest.php
│ ├── IOExceptionTest.php
│ └── UtilsTest.php
└── python
├── chatterbotapi.py
└── chatterbotapitest.py
/README.md:
--------------------------------------------------------------------------------
1 | # Chatter Bot API
2 |
3 | A Mono/.NET, JAVA, Python and PHP chatter bot API that supports [Cleverbot](http://www.cleverbot.com/), [JabberWacky](http://jabberwacky.com/) and [Pandorabots](http://www.pandorabots.com/).
4 |
5 | For a Ruby version, have a look at [Gabriele Cirulli cleverbot-api implementation](https://github.com/gabrielecirulli/cleverbot-api).
6 |
7 | If you are planing using the .NET version, maybe [this fork by Schumix](https://github.com/Schumix/ChatterBotApi) is worth looking at.
8 |
9 | ## News
10 |
11 | **2017-02-13**: This project's [v2 branch](https://github.com/pierredavidbelanger/chatter-bot-api/tree/v2#java) is an in progress refactor/cleanup effort. For now I have a working Java version that uses the new [Cleverbot official API](https://www.cleverbot.com/api/). No code breaking changes were required, except that you will now need an API Key when calling `factory.create(ChatterBotType.CLEVERBOT, "YOURAPIKEY")`.
12 |
13 | **2017-01-04**: Folks at [Existor](http://www.existor.com/) (the company behind [Cleverbot](http://www.cleverbot.com/)) have concerns because this project goes against their terms of usage.
14 | Indeed, their service costs money (to host their huge servers for example) and this project allows users to bypass their ads.
15 | I acknowledged that this project does not makes a fair use of their service.
16 | I would be the first to be mad if someone would make an unfair use of one of my project, so I understand their positions.
17 | We agreed on this: this project will send [a parameter](https://github.com/pierredavidbelanger/chatter-bot-api/blob/c196833f63f2b4d68805b66bd12382a1097dc9c9/java/src/main/java/com/google/code/chatterbotapi/ChatterBotFactory.java#L29) on each request that will uniquely identify the project itself.
18 | They will collect metrics, and let the project alone if they found that the project usage does not make a big difference for them.
19 |
20 | **2015-09-21**: Thanks to [S.R](https://github.com/urban48), the python version is now also compatible with python 3.
21 |
22 | **2014-10-17**: Merged a bunch of nicely arranged pull requests sent by [Csaba Jakosa](https://github.com/megax). Those include works done by [Christian Gärtner](https://github.com/ChristianGaertner) (for the PHP version), and [Arnaud Aliès](https://github.com/mouuff) (for the Python version).
23 |
24 | **2014-10-11**: Moved to GitHub!
25 |
26 | **2014-08-04**: The Java version is now on The Maven Central Repository. This is a request I get from time to time. I was too lazy to do it until now. But this time a user was kind enough, so I kick myself and did it (thanks Hardik!). [Just add this dependency to your pom file](#maven).
27 |
28 | **2014-03-31**: Cleverbot seems to stops working from time to time. You should expect it to be really unstable until I find a fix.
29 |
30 | **2014-02-02**: Cleverbot stops working. Thanks to Matthew to let me know.
31 |
32 | **2013-11-15**: Cleverbot stops working, they changed their API again. I am working on this.
33 |
34 | **2013-08-29**: There is a bug with Cleverbot in any language right now. I will fix it as soon as possible. A bug with Cleverbot is now fixed in the new 1.3 revision release. Enjoy! (Kevin, Alienmario, Rai: Thanks to you guys for letting me know)
35 |
36 | ## Download
37 |
38 | I encourage you to download a compiled version of the library (*TBA*), and try the example below in this page. I tried to keep all the libraries free from dependencies, so you do not need to download anything else.
39 |
40 | Be sure to always use the latest version of the library, as the Cleverbot/JabberWacky Web Service is changing over time. I suppose it is not meant to be public.
41 |
42 | ### Maven
43 |
44 | Just add this dependency to your pom file:
45 |
46 | ```xml
47 |
48 | ca.pjer
49 | chatter-bot-api
50 | 1.4.7
51 |
52 | ```
53 |
54 | ## Going further
55 |
56 | If you like what you see, browse and comment the source code. If you found a bug or something missing, consult the [Issues section](https://github.com/pierredavidbelanger/chatter-bot-api/issues) before posting a new defect or a new enhancement. Also I will gladly accept [Pull Requests](https://github.com/pierredavidbelanger/chatter-bot-api/pulls)
57 |
58 | ## Disclaimer
59 |
60 | I am not the owner of Cleverbot/JabberWacky nor Pandorabots.
61 |
62 | My work (the Cleverbot/JabberWacky part) is based on [pycleverbot](https://code.google.com/p/pycleverbot/), a Python bindings for the Cleverbot.
63 |
64 | ## Contact
65 |
66 | You can also let [me](https://github.com/pierredavidbelanger) know what you think.
67 |
68 | ## Examples
69 |
70 | ### Mono/.NET C#
71 |
72 | ```csharp
73 | using System;
74 |
75 | using ChatterBotAPI;
76 |
77 | namespace ChatterBotAPITest {
78 |
79 | class MainClass {
80 |
81 | public static void Main(string[] args) {
82 | ChatterBotFactory factory = new ChatterBotFactory();
83 |
84 | ChatterBot bot1 = factory.Create(ChatterBotType.CLEVERBOT);
85 | ChatterBotSession bot1session = bot1.CreateSession();
86 |
87 | ChatterBot bot2 = factory.Create(ChatterBotType.PANDORABOTS, "b0dafd24ee35a477");
88 | ChatterBotSession bot2session = bot2.CreateSession();
89 |
90 | string s = "Hi";
91 | while (true) {
92 |
93 | Console.WriteLine("bot1> " + s);
94 |
95 | s = bot2session.Think(s);
96 | Console.WriteLine("bot2> " + s);
97 |
98 | s = bot1session.Think(s);
99 | }
100 | }
101 | }
102 | }
103 | ```
104 |
105 | ### Mono/.NET VB
106 |
107 | ```vbnet
108 | Imports ChatterBotAPI
109 |
110 | Public Class Application
111 |
112 | Public Shared Sub Main()
113 | Dim factory As ChatterBotFactory = new ChatterBotFactory()
114 |
115 | Dim bot1 As ChatterBot = factory.Create(ChatterBotType.CLEVERBOT)
116 | Dim bot1session As ChatterBotSession = bot1.CreateSession()
117 |
118 | Dim bot2 As ChatterBot = factory.Create(ChatterBotType.PANDORABOTS, "b0dafd24ee35a477")
119 | Dim bot2session As ChatterBotSession = bot2.CreateSession()
120 |
121 | Dim s As String = "Hi"
122 | Do While true
123 |
124 | Console.WriteLine("bot1> " + s)
125 |
126 | s = bot2session.Think(s)
127 | Console.WriteLine("bot2> " + s)
128 |
129 | s = bot1session.Think(s)
130 | Loop
131 | End Sub
132 | End Class
133 | ```
134 |
135 | ### JAVA
136 |
137 | ```java
138 | package com.google.code.chatterbotapi.test;
139 |
140 | import com.google.code.chatterbotapi.*;
141 |
142 | public class ChatterBotApiTest {
143 |
144 | public static void main(String[] args) throws Exception {
145 | ChatterBotFactory factory = new ChatterBotFactory();
146 |
147 | ChatterBot bot1 = factory.create(ChatterBotType.CLEVERBOT);
148 | ChatterBotSession bot1session = bot1.createSession();
149 |
150 | ChatterBot bot2 = factory.create(ChatterBotType.PANDORABOTS, "b0dafd24ee35a477");
151 | ChatterBotSession bot2session = bot2.createSession();
152 |
153 | String s = "Hi";
154 | while (true) {
155 |
156 | System.out.println("bot1> " + s);
157 |
158 | s = bot2session.think(s);
159 | System.out.println("bot2> " + s);
160 |
161 | s = bot1session.think(s);
162 | }
163 | }
164 | }
165 | ```
166 |
167 | ### Python
168 |
169 | ```python
170 | from chatterbotapi import ChatterBotFactory, ChatterBotType
171 |
172 | factory = ChatterBotFactory()
173 |
174 | bot1 = factory.create(ChatterBotType.CLEVERBOT)
175 | bot1session = bot1.create_session()
176 |
177 | bot2 = factory.create(ChatterBotType.PANDORABOTS, 'b0dafd24ee35a477')
178 | bot2session = bot2.create_session()
179 |
180 | s = 'Hi'
181 | while (1):
182 |
183 | print 'bot1> ' + s
184 |
185 | s = bot2session.think(s);
186 | print 'bot2> ' + s
187 |
188 | s = bot1session.think(s);
189 | ```
190 |
191 | ### PHP
192 |
193 | ```php
194 | create(ChatterBotType::CLEVERBOT);
200 | $bot1session = $bot1->createSession();
201 |
202 | $bot2 = $factory->create(ChatterBotType::PANDORABOTS, 'b0dafd24ee35a477');
203 | $bot2session = $bot2->createSession();
204 |
205 | $s = 'Hi';
206 | while (1)
207 | {
208 | echo "bot1> $s\n";
209 |
210 | $s = $bot2session->think($s);
211 | echo "bot2> $s\n";
212 |
213 | $s = $bot1session->think($s);
214 | }
215 | ?>
216 | ```
217 |
--------------------------------------------------------------------------------
/dotnet/ChatterBotAPI.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 10.00
3 | # Visual Studio 2008
4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ChatterBotAPI", "ChatterBotAPI\ChatterBotAPI.csproj", "{2E624962-F155-432C-A90A-E1CE75DEE9EA}"
5 | EndProject
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ChatterBotAPITest", "ChatterBotAPITest\ChatterBotAPITest.csproj", "{DA59F247-C17B-4A92-BB03-CB458C6916F0}"
7 | EndProject
8 | Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "ChatterBotAPITestVB", "ChatterBotAPITestVB\ChatterBotAPITestVB.vbproj", "{4D5C5614-9C76-4464-AB6E-A4349784F123}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Any CPU = Debug|Any CPU
13 | Release|Any CPU = Release|Any CPU
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {2E624962-F155-432C-A90A-E1CE75DEE9EA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
17 | {2E624962-F155-432C-A90A-E1CE75DEE9EA}.Debug|Any CPU.Build.0 = Debug|Any CPU
18 | {2E624962-F155-432C-A90A-E1CE75DEE9EA}.Release|Any CPU.ActiveCfg = Release|Any CPU
19 | {2E624962-F155-432C-A90A-E1CE75DEE9EA}.Release|Any CPU.Build.0 = Release|Any CPU
20 | {4D5C5614-9C76-4464-AB6E-A4349784F123}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {4D5C5614-9C76-4464-AB6E-A4349784F123}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {4D5C5614-9C76-4464-AB6E-A4349784F123}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {4D5C5614-9C76-4464-AB6E-A4349784F123}.Release|Any CPU.Build.0 = Release|Any CPU
24 | {DA59F247-C17B-4A92-BB03-CB458C6916F0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
25 | {DA59F247-C17B-4A92-BB03-CB458C6916F0}.Debug|Any CPU.Build.0 = Debug|Any CPU
26 | {DA59F247-C17B-4A92-BB03-CB458C6916F0}.Release|Any CPU.ActiveCfg = Release|Any CPU
27 | {DA59F247-C17B-4A92-BB03-CB458C6916F0}.Release|Any CPU.Build.0 = Release|Any CPU
28 | EndGlobalSection
29 | GlobalSection(MonoDevelopProperties) = preSolution
30 | StartupItem = ChatterBotAPITestVB\ChatterBotAPITestVB.vbproj
31 | EndGlobalSection
32 | EndGlobal
33 |
--------------------------------------------------------------------------------
/dotnet/ChatterBotAPI/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 |
3 | /*
4 | ChatterBotAPI
5 | Copyright (C) 2011 pierredavidbelanger@gmail.com
6 |
7 | This program is free software: you can redistribute it and/or modify
8 | it under the terms of the GNU Lesser General Public License as published by
9 | the Free Software Foundation, either version 3 of the License, or
10 | (at your option) any later version.
11 |
12 | This program is distributed in the hope that it will be useful,
13 | but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | GNU Lesser General Public License for more details.
16 |
17 | You should have received a copy of the GNU Lesser General Public License
18 | along with this program. If not, see .
19 | */
20 |
21 | [assembly: AssemblyTitle("ChatterBotAPI")]
22 | [assembly: AssemblyDescription("")]
23 | [assembly: AssemblyConfiguration("")]
24 | [assembly: AssemblyCompany("")]
25 | [assembly: AssemblyProduct("")]
26 | [assembly: AssemblyCopyright("pierredavidbelanger")]
27 | [assembly: AssemblyTrademark("")]
28 | [assembly: AssemblyCulture("")]
29 | [assembly: AssemblyVersion("1.1.*")]
--------------------------------------------------------------------------------
/dotnet/ChatterBotAPI/ChatterBot.cs:
--------------------------------------------------------------------------------
1 | /*
2 | ChatterBotAPI
3 | Copyright (C) 2011 pierredavidbelanger@gmail.com
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Lesser General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Lesser General Public License for more details.
14 |
15 | You should have received a copy of the GNU Lesser General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | namespace ChatterBotAPI
20 | {
21 | public interface ChatterBot
22 | {
23 | ChatterBotSession CreateSession();
24 | }
25 | }
--------------------------------------------------------------------------------
/dotnet/ChatterBotAPI/ChatterBotAPI.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Debug
5 | AnyCPU
6 | 9.0.21022
7 | 2.0
8 | {2E624962-F155-432C-A90A-E1CE75DEE9EA}
9 | Library
10 | ChatterBotAPI
11 | ChatterBotAPI
12 | v2.0
13 |
14 |
15 | true
16 | full
17 | false
18 | bin\Debug
19 | DEBUG
20 | prompt
21 | 4
22 | false
23 |
24 |
25 | none
26 | false
27 | bin\Release
28 | prompt
29 | 4
30 | false
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/dotnet/ChatterBotAPI/ChatterBotFactory.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | /*
4 | ChatterBotAPI
5 | Copyright (C) 2011 pierredavidbelanger@gmail.com
6 |
7 | This program is free software: you can redistribute it and/or modify
8 | it under the terms of the GNU Lesser General Public License as published by
9 | the Free Software Foundation, either version 3 of the License, or
10 | (at your option) any later version.
11 |
12 | This program is distributed in the hope that it will be useful,
13 | but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | GNU Lesser General Public License for more details.
16 |
17 | You should have received a copy of the GNU Lesser General Public License
18 | along with this program. If not, see .
19 | */
20 |
21 | namespace ChatterBotAPI
22 | {
23 | public class ChatterBotFactory
24 | {
25 | public ChatterBot Create(ChatterBotType type)
26 | {
27 | return Create(type, null);
28 | }
29 |
30 | public ChatterBot Create(ChatterBotType type, object arg)
31 | {
32 | switch (type)
33 | {
34 | case ChatterBotType.CLEVERBOT:
35 | return new Cleverbot("http://www.cleverbot.com/", "http://www.cleverbot.com/webservicemin?uc=777&botapi=chatterbotapi", 26);
36 | case ChatterBotType.JABBERWACKY:
37 | return new Cleverbot("http://jabberwacky.com", "http://jabberwacky.com/webservicemin?botapi=chatterbotapi", 20);
38 | case ChatterBotType.PANDORABOTS:
39 | if (arg == null) throw new ApplicationException("PANDORABOTS needs a botid arg");
40 | return new Pandorabots(arg.ToString());
41 | }
42 | return null;
43 | }
44 | }
45 | }
--------------------------------------------------------------------------------
/dotnet/ChatterBotAPI/ChatterBotSession.cs:
--------------------------------------------------------------------------------
1 | /*
2 | ChatterBotAPI
3 | Copyright (C) 2011 pierredavidbelanger@gmail.com
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Lesser General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Lesser General Public License for more details.
14 |
15 | You should have received a copy of the GNU Lesser General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | namespace ChatterBotAPI
20 | {
21 | public interface ChatterBotSession
22 | {
23 | ChatterBotThought Think(ChatterBotThought thought);
24 | string Think(string text);
25 | }
26 | }
--------------------------------------------------------------------------------
/dotnet/ChatterBotAPI/ChatterBotThought.cs:
--------------------------------------------------------------------------------
1 | /*
2 | ChatterBotAPI
3 | Copyright (C) 2011 pierredavidbelanger@gmail.com
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Lesser General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Lesser General Public License for more details.
14 |
15 | You should have received a copy of the GNU Lesser General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | namespace ChatterBotAPI
20 | {
21 | public class ChatterBotThought
22 | {
23 | public string[] Emotions { get; set; }
24 | public string Text { get; set; }
25 | }
26 | }
--------------------------------------------------------------------------------
/dotnet/ChatterBotAPI/ChatterBotType.cs:
--------------------------------------------------------------------------------
1 | /*
2 | ChatterBotAPI
3 | Copyright (C) 2011 pierredavidbelanger@gmail.com
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Lesser General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Lesser General Public License for more details.
14 |
15 | You should have received a copy of the GNU Lesser General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | namespace ChatterBotAPI
20 | {
21 | public enum ChatterBotType
22 | {
23 | CLEVERBOT,
24 | JABBERWACKY,
25 | PANDORABOTS
26 | }
27 | }
--------------------------------------------------------------------------------
/dotnet/ChatterBotAPI/Cleverbot.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Net;
3 |
4 | /*
5 | ChatterBotAPI
6 | Copyright (C) 2011 pierredavidbelanger@gmail.com
7 |
8 | This program is free software: you can redistribute it and/or modify
9 | it under the terms of the GNU Lesser General Public License as published by
10 | the Free Software Foundation, either version 3 of the License, or
11 | (at your option) any later version.
12 |
13 | This program is distributed in the hope that it will be useful,
14 | but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | GNU Lesser General Public License for more details.
17 |
18 | You should have received a copy of the GNU Lesser General Public License
19 | along with this program. If not, see .
20 | */
21 |
22 | namespace ChatterBotAPI
23 | {
24 | internal class Cleverbot : ChatterBot
25 | {
26 | private readonly int endIndex;
27 | private readonly string baseUrl;
28 | private readonly string url;
29 |
30 | public Cleverbot(string baseUrl, string url, int endIndex)
31 | {
32 | this.baseUrl = baseUrl;
33 | this.url = url;
34 | this.endIndex = endIndex;
35 | }
36 |
37 | public ChatterBotSession CreateSession()
38 | {
39 | return new CleverbotSession(baseUrl, url, endIndex);
40 | }
41 | }
42 |
43 | internal class CleverbotSession : ChatterBotSession
44 | {
45 | private readonly int endIndex;
46 | private readonly string url;
47 | private readonly IDictionary vars;
48 | private readonly CookieCollection cookies;
49 |
50 | public CleverbotSession(string baseUrl, string url, int endIndex)
51 | {
52 | this.url = url;
53 | this.endIndex = endIndex;
54 | vars = new Dictionary();
55 | //vars["start"] = "y";
56 | vars["stimulus"] = "";
57 | vars["islearning"] = "1";
58 | vars["icognoid"] = "wsf";
59 | //vars["fno"] = "0";
60 | //vars["sub"] = "Say";
61 | //vars["cleanslate"] = "false";
62 | cookies = Utils.GetCookies(baseUrl);
63 | }
64 |
65 | public ChatterBotThought Think(ChatterBotThought thought)
66 | {
67 | vars["stimulus"] = thought.Text;
68 |
69 | var formData = Utils.ParametersToWWWFormURLEncoded(vars);
70 | var formDataToDigest = formData.Substring(9, endIndex);
71 | var formDataDigest = Utils.MD5(formDataToDigest);
72 | vars["icognocheck"] = formDataDigest;
73 |
74 | var response = Utils.Post(url, vars, cookies);
75 |
76 | var responseValues = response.Split('\r');
77 |
78 | //vars[""] = Utils.StringAtIndex(responseValues, 0); ??
79 | vars["sessionid"] = Utils.StringAtIndex(responseValues, 1);
80 | vars["logurl"] = Utils.StringAtIndex(responseValues, 2);
81 | vars["vText8"] = Utils.StringAtIndex(responseValues, 3);
82 | vars["vText7"] = Utils.StringAtIndex(responseValues, 4);
83 | vars["vText6"] = Utils.StringAtIndex(responseValues, 5);
84 | vars["vText5"] = Utils.StringAtIndex(responseValues, 6);
85 | vars["vText4"] = Utils.StringAtIndex(responseValues, 7);
86 | vars["vText3"] = Utils.StringAtIndex(responseValues, 8);
87 | vars["vText2"] = Utils.StringAtIndex(responseValues, 9);
88 | vars["prevref"] = Utils.StringAtIndex(responseValues, 10);
89 | //vars[""] = Utils.StringAtIndex(responseValues, 11); ??
90 | // vars["emotionalhistory"] = Utils.StringAtIndex(responseValues, 12);
91 | // vars["ttsLocMP3"] = Utils.StringAtIndex(responseValues, 13);
92 | // vars["ttsLocTXT"] = Utils.StringAtIndex(responseValues, 14);
93 | // vars["ttsLocTXT3"] = Utils.StringAtIndex(responseValues, 15);
94 | // vars["ttsText"] = Utils.StringAtIndex(responseValues, 16);
95 | // vars["lineRef"] = Utils.StringAtIndex(responseValues, 17);
96 | // vars["lineURL"] = Utils.StringAtIndex(responseValues, 18);
97 | // vars["linePOST"] = Utils.StringAtIndex(responseValues, 19);
98 | // vars["lineChoices"] = Utils.StringAtIndex(responseValues, 20);
99 | // vars["lineChoicesAbbrev"] = Utils.StringAtIndex(responseValues, 21);
100 | // vars["typingData"] = Utils.StringAtIndex(responseValues, 22);
101 | // vars["divert"] = Utils.StringAtIndex(responseValues, 23);
102 |
103 | var responseThought = new ChatterBotThought();
104 |
105 | responseThought.Text = Utils.StringAtIndex(responseValues, 0);
106 |
107 | return responseThought;
108 | }
109 |
110 | public string Think(string text)
111 | {
112 | return Think(new ChatterBotThought {Text = text}).Text;
113 | }
114 | }
115 | }
--------------------------------------------------------------------------------
/dotnet/ChatterBotAPI/Pandorabots.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | /*
5 | ChatterBotAPI
6 | Copyright (C) 2011 pierredavidbelanger@gmail.com
7 |
8 | This program is free software: you can redistribute it and/or modify
9 | it under the terms of the GNU Lesser General Public License as published by
10 | the Free Software Foundation, either version 3 of the License, or
11 | (at your option) any later version.
12 |
13 | This program is distributed in the hope that it will be useful,
14 | but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | GNU Lesser General Public License for more details.
17 |
18 | You should have received a copy of the GNU Lesser General Public License
19 | along with this program. If not, see .
20 | */
21 |
22 | namespace ChatterBotAPI
23 | {
24 | internal class Pandorabots : ChatterBot
25 | {
26 | private readonly string botid;
27 |
28 | public Pandorabots(string botid)
29 | {
30 | this.botid = botid;
31 | }
32 |
33 | public ChatterBotSession CreateSession()
34 | {
35 | return new PandorabotsSession(botid);
36 | }
37 | }
38 |
39 | internal class PandorabotsSession : ChatterBotSession
40 | {
41 | private readonly IDictionary vars;
42 |
43 | public PandorabotsSession(string botid)
44 | {
45 | vars = new Dictionary();
46 | vars["botid"] = botid;
47 | vars["custid"] = Guid.NewGuid().ToString();
48 | }
49 |
50 | public ChatterBotThought Think(ChatterBotThought thought)
51 | {
52 | vars["input"] = thought.Text;
53 |
54 | var response = Utils.Post("https://www.pandorabots.com/pandora/talk-xml", vars, null);
55 |
56 | var responseThought = new ChatterBotThought();
57 | responseThought.Text = Utils.XPathSearch(response, "//result/that/text()");
58 |
59 | return responseThought;
60 | }
61 |
62 | public string Think(string text)
63 | {
64 | return Think(new ChatterBotThought {Text = text}).Text;
65 | }
66 | }
67 | }
--------------------------------------------------------------------------------
/dotnet/ChatterBotAPI/Utils.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.IO;
3 | using System.Net;
4 | using System.Text;
5 | using System.Xml.XPath;
6 |
7 | /*
8 | ChatterBotAPI
9 | Copyright (C) 2011 pierredavidbelanger@gmail.com
10 |
11 | This program is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU Lesser General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | This program is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU Lesser General Public License for more details.
20 |
21 | You should have received a copy of the GNU Lesser General Public License
22 | along with this program. If not, see .
23 | */
24 |
25 | namespace ChatterBotAPI
26 | {
27 | internal static class Utils
28 | {
29 | public static string ParametersToWWWFormURLEncoded(IDictionary parameters)
30 | {
31 | string wwwFormUrlEncoded = null;
32 | foreach (var parameterKey in parameters.Keys)
33 | {
34 | var parameterValue = parameters[parameterKey];
35 | var parameter = string.Format("{0}={1}", System.Uri.EscapeDataString(parameterKey), System.Uri.EscapeDataString(parameterValue));
36 | if (wwwFormUrlEncoded == null)
37 | {
38 | wwwFormUrlEncoded = parameter;
39 | }
40 | else
41 | {
42 | wwwFormUrlEncoded = string.Format("{0}&{1}", wwwFormUrlEncoded, parameter);
43 | }
44 | }
45 | return wwwFormUrlEncoded;
46 | }
47 |
48 | public static string MD5(string input)
49 | {
50 | // step 1, calculate MD5 hash from input
51 | var md5 = System.Security.Cryptography.MD5.Create();
52 | var inputBytes = Encoding.ASCII.GetBytes(input);
53 | var hash = md5.ComputeHash(inputBytes);
54 |
55 | // step 2, convert byte array to hex string
56 | var sb = new StringBuilder();
57 | for (var i = 0; i < hash.Length; i++)
58 | {
59 | sb.Append(hash[i].ToString("X2"));
60 | }
61 | return sb.ToString();
62 |
63 | }
64 |
65 | public static CookieCollection GetCookies(string url)
66 | {
67 | CookieContainer container = new CookieContainer();
68 | var request = (HttpWebRequest)WebRequest.Create(url);
69 | request.Method = "GET";
70 | request.Headers.Add("UserAgent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0;");
71 | request.ContentType = "text/html";
72 | request.CookieContainer = container;
73 |
74 | var response = (HttpWebResponse)request.GetResponse();
75 | using (var responseStreamReader = new StreamReader(response.GetResponseStream()))
76 | {
77 | responseStreamReader.ReadToEnd ();
78 | }
79 |
80 | return container.GetCookies(request.RequestUri);
81 | }
82 |
83 | public static string Post(string url, IDictionary parameters, CookieCollection cookies)
84 | {
85 | var postData = ParametersToWWWFormURLEncoded(parameters);
86 | var postDataBytes = Encoding.ASCII.GetBytes(postData);
87 |
88 | var request = (HttpWebRequest)WebRequest.Create(url);
89 |
90 | if (cookies != null)
91 | {
92 | var container = new CookieContainer();
93 | container.Add(cookies);
94 | request.CookieContainer = container;
95 | }
96 |
97 |
98 | request.Method = "POST";
99 | request.ContentType = "application/x-www-form-urlencoded";
100 | request.ContentLength = postDataBytes.Length;
101 |
102 | using (var outputStream = request.GetRequestStream())
103 | {
104 | outputStream.Write(postDataBytes, 0, postDataBytes.Length);
105 | outputStream.Close();
106 |
107 | var response = (HttpWebResponse)request.GetResponse();
108 | using (var responseStreamReader = new StreamReader(response.GetResponseStream()))
109 | {
110 | return responseStreamReader.ReadToEnd().Trim();
111 | }
112 | }
113 | }
114 |
115 | public static string XPathSearch(string input, string expression)
116 | {
117 | var document = new XPathDocument(new MemoryStream(Encoding.ASCII.GetBytes(input)));
118 | var navigator = document.CreateNavigator();
119 | return navigator.SelectSingleNode(expression).Value.Trim();
120 | }
121 |
122 | public static string StringAtIndex(string[] strings, int index)
123 | {
124 | if (index >= strings.Length) return "";
125 | return strings[index];
126 | }
127 | }
128 | }
--------------------------------------------------------------------------------
/dotnet/ChatterBotAPITest/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 |
4 | /*
5 | ChatterBotAPI
6 | Copyright (C) 2011 pierredavidbelanger@gmail.com
7 |
8 | This program is free software: you can redistribute it and/or modify
9 | it under the terms of the GNU Lesser General Public License as published by
10 | the Free Software Foundation, either version 3 of the License, or
11 | (at your option) any later version.
12 |
13 | This program is distributed in the hope that it will be useful,
14 | but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | GNU Lesser General Public License for more details.
17 |
18 | You should have received a copy of the GNU Lesser General Public License
19 | along with this program. If not, see .
20 | */
21 |
22 | [assembly: AssemblyTitle("ChatterBotAPITest")]
23 | [assembly: AssemblyDescription("")]
24 | [assembly: AssemblyConfiguration("")]
25 | [assembly: AssemblyCompany("")]
26 | [assembly: AssemblyProduct("")]
27 | [assembly: AssemblyCopyright("pierredavidbelanger")]
28 | [assembly: AssemblyTrademark("")]
29 | [assembly: AssemblyCulture("")]
30 |
31 | [assembly: AssemblyVersion("1.0.*")]
--------------------------------------------------------------------------------
/dotnet/ChatterBotAPITest/ChatterBotAPITest.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Debug
5 | AnyCPU
6 | 9.0.21022
7 | 2.0
8 | {DA59F247-C17B-4A92-BB03-CB458C6916F0}
9 | Exe
10 | ChatterBotAPITest
11 | ChatterBotAPITest
12 | v2.0
13 |
14 |
15 | true
16 | full
17 | false
18 | bin\Debug
19 | DEBUG
20 | prompt
21 | 4
22 | false
23 |
24 |
25 | none
26 | false
27 | bin\Release
28 | prompt
29 | 4
30 | true
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 | {2E624962-F155-432C-A90A-E1CE75DEE9EA}
43 | ChatterBotAPI
44 |
45 |
46 |
--------------------------------------------------------------------------------
/dotnet/ChatterBotAPITest/Main.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | using ChatterBotAPI;
4 |
5 | /*
6 | ChatterBotAPI
7 | Copyright (C) 2011 pierredavidbelanger@gmail.com
8 |
9 | This program is free software: you can redistribute it and/or modify
10 | it under the terms of the GNU Lesser General Public License as published by
11 | the Free Software Foundation, either version 3 of the License, or
12 | (at your option) any later version.
13 |
14 | This program is distributed in the hope that it will be useful,
15 | but WITHOUT ANY WARRANTY; without even the implied warranty of
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 | GNU Lesser General Public License for more details.
18 |
19 | You should have received a copy of the GNU Lesser General Public License
20 | along with this program. If not, see .
21 | */
22 | namespace ChatterBotAPITest {
23 |
24 | class MainClass {
25 |
26 | public static void Main(string[] args) {
27 | ChatterBotFactory factory = new ChatterBotFactory();
28 |
29 | ChatterBot bot1 = factory.Create(ChatterBotType.CLEVERBOT);
30 | ChatterBotSession bot1session = bot1.CreateSession();
31 |
32 | ChatterBot bot2 = factory.Create(ChatterBotType.PANDORABOTS, "b0dafd24ee35a477");
33 | ChatterBotSession bot2session = bot2.CreateSession();
34 |
35 | string s = "Hi";
36 | while (true) {
37 |
38 | Console.WriteLine("bot1> " + s);
39 |
40 | s = bot2session.Think(s);
41 | Console.WriteLine("bot2> " + s);
42 |
43 | s = bot1session.Think(s);
44 | }
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/dotnet/ChatterBotAPITestVB/Application.vb:
--------------------------------------------------------------------------------
1 |
2 | Imports ChatterBotAPI
3 |
4 | ' ChatterBotAPI
5 | ' Copyright (C) 2011 pierredavidbelanger@gmail.com
6 | '
7 | ' This program is free software: you can redistribute it and/or modify
8 | ' it under the terms of the GNU Lesser General Public License as published by
9 | ' the Free Software Foundation, either version 3 of the License, or
10 | ' (at your option) any later version.
11 | '
12 | ' This program is distributed in the hope that it will be useful,
13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | ' GNU Lesser General Public License for more details.
16 | '
17 | ' You should have received a copy of the GNU Lesser General Public License
18 | ' along with this program. If not, see .
19 | Public Class Application
20 |
21 | Public Shared Sub Main()
22 | Dim factory As ChatterBotFactory = new ChatterBotFactory()
23 |
24 | Dim bot1 As ChatterBot = factory.Create(ChatterBotType.CLEVERBOT)
25 | Dim bot1session As ChatterBotSession = bot1.CreateSession()
26 |
27 | Dim bot2 As ChatterBot = factory.Create(ChatterBotType.PANDORABOTS, "b0dafd24ee35a477")
28 | Dim bot2session As ChatterBotSession = bot2.CreateSession()
29 |
30 | Dim s As String = "Hi"
31 | Do While true
32 |
33 | Console.WriteLine("bot1> " + s)
34 |
35 | s = bot2session.Think(s)
36 | Console.WriteLine("bot2> " + s)
37 |
38 | s = bot1session.Think(s)
39 | Loop
40 | End Sub
41 | End Class
42 |
43 |
--------------------------------------------------------------------------------
/dotnet/ChatterBotAPITestVB/AssemblyInfo.vb:
--------------------------------------------------------------------------------
1 | Imports System.Reflection
2 | Imports System.Runtime.CompilerServices
3 |
4 | ' ChatterBotAPI
5 | ' Copyright (C) 2011 pierredavidbelanger@gmail.com
6 | '
7 | ' This program is free software: you can redistribute it and/or modify
8 | ' it under the terms of the GNU Lesser General Public License as published by
9 | ' the Free Software Foundation, either version 3 of the License, or
10 | ' (at your option) any later version.
11 | '
12 | ' This program is distributed in the hope that it will be useful,
13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | ' GNU Lesser General Public License for more details.
16 | '
17 | ' You should have received a copy of the GNU Lesser General Public License
18 | ' along with this program. If not, see .
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/dotnet/ChatterBotAPITestVB/ChatterBotAPITestVB.vbproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Debug
5 | AnyCPU
6 | 9.0.21022
7 | 2.0
8 | {4D5C5614-9C76-4464-AB6E-A4349784F123}
9 | Exe
10 | ChatterBotAPITestVB
11 | ChatterBotAPITestVB
12 | v3.5
13 |
14 |
15 | true
16 | bin\Debug
17 | prompt
18 | false
19 | false
20 |
21 | false
22 |
23 |
24 | bin\Release
25 | prompt
26 | false
27 | false
28 |
29 | false
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 | {2E624962-F155-432C-A90A-E1CE75DEE9EA}
42 | ChatterBotAPI
43 |
44 |
45 |
--------------------------------------------------------------------------------
/java/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | 4.0.0
7 |
8 | ca.pjer
9 | chatter-bot-api
10 | 1.4.7
11 |
12 | Chatter Bot API
13 |
14 | A JAVA (also Mono/.NET, Python and PHP) chatter bot API
15 | that supports Cleverbot, JabberWacky and Pandorabots.
16 |
17 | https://code.google.com/p/chatter-bot-api/
18 |
19 |
20 | UTF-8
21 | 1.6
22 |
23 |
24 |
25 |
26 | GNU LESSER GENERAL PUBLIC LICENSE
27 | http://www.gnu.org/licenses/lgpl-3.0.txt
28 |
29 |
30 |
31 |
32 |
33 | Pierre-David Bélanger
34 | pierredavidbelanger@gmail.com
35 | PjEr.ca
36 | http://www.pjer.ca/
37 |
38 |
39 |
40 |
41 | scm:svn:https://chatter-bot-api.googlecode.com/svn/trunk/
42 | scm:svn:https://chatter-bot-api.googlecode.com/svn/trunk/
43 | https://chatter-bot-api.googlecode.com/svn/trunk/
44 |
45 |
46 |
47 |
48 | ossrh
49 | https://oss.sonatype.org/content/repositories/snapshots/
50 |
51 |
52 | ossrh
53 | https://oss.sonatype.org/service/local/staging/deploy/maven2/
54 |
55 |
56 |
57 |
58 |
59 |
60 | org.apache.maven.plugins
61 | maven-compiler-plugin
62 | 3.1
63 |
64 | 1.6
65 | 1.6
66 |
67 |
68 |
69 | org.apache.maven.plugins
70 | maven-source-plugin
71 | 2.2.1
72 |
73 |
74 | attach-sources
75 |
76 | jar-no-fork
77 |
78 |
79 |
80 |
81 |
82 | org.apache.maven.plugins
83 | maven-javadoc-plugin
84 | 2.9.1
85 |
86 |
87 | attach-javadocs
88 |
89 | jar
90 |
91 |
92 |
93 |
94 |
95 | org.apache.maven.plugins
96 | maven-gpg-plugin
97 | 1.5
98 |
99 |
100 | sign-artifacts
101 | verify
102 |
103 | sign
104 |
105 |
106 |
107 |
108 |
109 |
110 | org.sonatype.plugins
111 | nexus-staging-maven-plugin
112 | 1.6.2
113 | true
114 |
115 | ossrh
116 | https://oss.sonatype.org/
117 | true
118 |
119 |
120 |
121 |
122 |
123 |
--------------------------------------------------------------------------------
/java/src/main/java/com/google/code/chatterbotapi/ChatterBot.java:
--------------------------------------------------------------------------------
1 | package com.google.code.chatterbotapi;
2 |
3 | import java.util.Locale;
4 |
5 | /*
6 | chatter-bot-api
7 | Copyright (C) 2011 pierredavidbelanger@gmail.com
8 |
9 | This program is free software: you can redistribute it and/or modify
10 | it under the terms of the GNU Lesser General Public License as published by
11 | the Free Software Foundation, either version 3 of the License, or
12 | (at your option) any later version.
13 |
14 | This program is distributed in the hope that it will be useful,
15 | but WITHOUT ANY WARRANTY; without even the implied warranty of
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 | GNU Lesser General Public License for more details.
18 |
19 | You should have received a copy of the GNU Lesser General Public License
20 | along with this program. If not, see .
21 | */
22 | public interface ChatterBot {
23 |
24 | ChatterBotSession createSession(Locale... locales);
25 | }
--------------------------------------------------------------------------------
/java/src/main/java/com/google/code/chatterbotapi/ChatterBotFactory.java:
--------------------------------------------------------------------------------
1 | package com.google.code.chatterbotapi;
2 |
3 | /*
4 | chatter-bot-api
5 | Copyright (C) 2011 pierredavidbelanger@gmail.com
6 |
7 | This program is free software: you can redistribute it and/or modify
8 | it under the terms of the GNU Lesser General Public License as published by
9 | the Free Software Foundation, either version 3 of the License, or
10 | (at your option) any later version.
11 |
12 | This program is distributed in the hope that it will be useful,
13 | but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | GNU Lesser General Public License for more details.
16 |
17 | You should have received a copy of the GNU Lesser General Public License
18 | along with this program. If not, see .
19 | */
20 | public class ChatterBotFactory {
21 |
22 | public ChatterBot create(ChatterBotType type) throws Exception {
23 | return create(type, null);
24 | }
25 |
26 | public ChatterBot create(ChatterBotType type, Object arg) throws Exception {
27 | switch (type) {
28 | case CLEVERBOT:
29 | return new Cleverbot("http://www.cleverbot.com", "http://www.cleverbot.com/webservicemin?uc=777&botapi=chatterbotapi", 35);
30 | case JABBERWACKY:
31 | return new Cleverbot("http://jabberwacky.com", "http://jabberwacky.com/webservicemin?botapi=chatterbotapi", 29);
32 | case PANDORABOTS:
33 | if (arg == null) {
34 | throw new Exception("PANDORABOTS needs a botid arg");
35 | }
36 | return new Pandorabots(arg.toString());
37 | }
38 | return null;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/java/src/main/java/com/google/code/chatterbotapi/ChatterBotSession.java:
--------------------------------------------------------------------------------
1 | package com.google.code.chatterbotapi;
2 |
3 | /*
4 | chatter-bot-api
5 | Copyright (C) 2011 pierredavidbelanger@gmail.com
6 |
7 | This program is free software: you can redistribute it and/or modify
8 | it under the terms of the GNU Lesser General Public License as published by
9 | the Free Software Foundation, either version 3 of the License, or
10 | (at your option) any later version.
11 |
12 | This program is distributed in the hope that it will be useful,
13 | but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | GNU Lesser General Public License for more details.
16 |
17 | You should have received a copy of the GNU Lesser General Public License
18 | along with this program. If not, see .
19 | */
20 | public interface ChatterBotSession {
21 |
22 | ChatterBotThought think(ChatterBotThought thought) throws Exception;
23 |
24 | String think(String text) throws Exception;
25 | }
--------------------------------------------------------------------------------
/java/src/main/java/com/google/code/chatterbotapi/ChatterBotThought.java:
--------------------------------------------------------------------------------
1 | package com.google.code.chatterbotapi;
2 |
3 | /*
4 | chatter-bot-api
5 | Copyright (C) 2011 pierredavidbelanger@gmail.com
6 |
7 | This program is free software: you can redistribute it and/or modify
8 | it under the terms of the GNU Lesser General Public License as published by
9 | the Free Software Foundation, either version 3 of the License, or
10 | (at your option) any later version.
11 |
12 | This program is distributed in the hope that it will be useful,
13 | but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | GNU Lesser General Public License for more details.
16 |
17 | You should have received a copy of the GNU Lesser General Public License
18 | along with this program. If not, see .
19 | */
20 | public class ChatterBotThought {
21 | private String[] emotions;
22 | private String text;
23 |
24 | public String[] getEmotions() {
25 | return emotions;
26 | }
27 |
28 | public void setEmotions(String[] emotions) {
29 | this.emotions = emotions;
30 | }
31 |
32 | public String getText() {
33 | return text;
34 | }
35 |
36 | public void setText(String text) {
37 | this.text = text;
38 | }
39 | }
--------------------------------------------------------------------------------
/java/src/main/java/com/google/code/chatterbotapi/ChatterBotType.java:
--------------------------------------------------------------------------------
1 | package com.google.code.chatterbotapi;
2 |
3 | /*
4 | chatter-bot-api
5 | Copyright (C) 2011 pierredavidbelanger@gmail.com
6 |
7 | This program is free software: you can redistribute it and/or modify
8 | it under the terms of the GNU Lesser General Public License as published by
9 | the Free Software Foundation, either version 3 of the License, or
10 | (at your option) any later version.
11 |
12 | This program is distributed in the hope that it will be useful,
13 | but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | GNU Lesser General Public License for more details.
16 |
17 | You should have received a copy of the GNU Lesser General Public License
18 | along with this program. If not, see .
19 | */
20 | public enum ChatterBotType {
21 | CLEVERBOT,
22 | JABBERWACKY,
23 | PANDORABOTS
24 | }
--------------------------------------------------------------------------------
/java/src/main/java/com/google/code/chatterbotapi/Cleverbot.java:
--------------------------------------------------------------------------------
1 | package com.google.code.chatterbotapi;
2 |
3 | import java.util.LinkedHashMap;
4 | import java.util.Locale;
5 | import java.util.Map;
6 |
7 | /*
8 | chatter-bot-api
9 | Copyright (C) 2011 pierredavidbelanger@gmail.com
10 |
11 | This program is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU Lesser General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | This program is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU Lesser General Public License for more details.
20 |
21 | You should have received a copy of the GNU Lesser General Public License
22 | along with this program. If not, see .
23 | */
24 | class Cleverbot implements ChatterBot {
25 | private final String baseUrl;
26 | private final String serviceUrl;
27 | private int endIndex;
28 |
29 | public Cleverbot(String baseUrl, String serviceUrl, int endIndex) {
30 | this.baseUrl = baseUrl;
31 | this.serviceUrl = serviceUrl;
32 | this.endIndex = endIndex;
33 | }
34 |
35 | @Override
36 | public ChatterBotSession createSession(Locale... locales) {
37 | return new Session(locales);
38 | }
39 |
40 | private class Session implements ChatterBotSession {
41 | private final Map vars;
42 | private final Map headers;
43 | private final Map cookies;
44 |
45 | public Session(Locale... locales) {
46 | vars = new LinkedHashMap();
47 | //vars.put("start", "y");
48 | vars.put("stimulus", "");
49 | vars.put("islearning", "1");
50 | vars.put("icognoid", "wsf");
51 | //vars.put("fno", "0");
52 | //vars.put("sub", "Say");
53 | //vars.put("cleanslate", "false");
54 | headers = new LinkedHashMap();
55 | if (locales.length > 0)
56 | headers.put("Accept-Language", Utils.toAcceptLanguageTags(locales));
57 | cookies = new LinkedHashMap();
58 | try {
59 | Utils.request(baseUrl, headers, cookies, null);
60 | } catch (Exception e) {
61 | throw new RuntimeException(e);
62 | }
63 | }
64 |
65 | public ChatterBotThought think(ChatterBotThought thought) throws Exception {
66 | vars.put("stimulus", thought.getText());
67 |
68 | String formData = Utils.parametersToWWWFormURLEncoded(vars);
69 | String formDataToDigest = formData.substring(9, endIndex);
70 | String formDataDigest = Utils.md5(formDataToDigest);
71 | vars.put("icognocheck", formDataDigest);
72 |
73 | String response = Utils.request(serviceUrl, headers, cookies, vars);
74 |
75 | String[] responseValues = response.split("\r");
76 |
77 | //vars.put("", Utils.stringAtIndex(responseValues, 0)); ??
78 | vars.put("sessionid", Utils.stringAtIndex(responseValues, 1));
79 | vars.put("logurl", Utils.stringAtIndex(responseValues, 2));
80 | vars.put("vText8", Utils.stringAtIndex(responseValues, 3));
81 | vars.put("vText7", Utils.stringAtIndex(responseValues, 4));
82 | vars.put("vText6", Utils.stringAtIndex(responseValues, 5));
83 | vars.put("vText5", Utils.stringAtIndex(responseValues, 6));
84 | vars.put("vText4", Utils.stringAtIndex(responseValues, 7));
85 | vars.put("vText3", Utils.stringAtIndex(responseValues, 8));
86 | vars.put("vText2", Utils.stringAtIndex(responseValues, 9));
87 | vars.put("prevref", Utils.stringAtIndex(responseValues, 10));
88 | //vars.put("", Utils.stringAtIndex(responseValues, 11)); ??
89 | // vars.put("emotionalhistory", Utils.stringAtIndex(responseValues, 12));
90 | // vars.put("ttsLocMP3", Utils.stringAtIndex(responseValues, 13));
91 | // vars.put("ttsLocTXT", Utils.stringAtIndex(responseValues, 14));
92 | // vars.put("ttsLocTXT3", Utils.stringAtIndex(responseValues, 15));
93 | // vars.put("ttsText", Utils.stringAtIndex(responseValues, 16));
94 | // vars.put("lineRef", Utils.stringAtIndex(responseValues, 17));
95 | // vars.put("lineURL", Utils.stringAtIndex(responseValues, 18));
96 | // vars.put("linePOST", Utils.stringAtIndex(responseValues, 19));
97 | // vars.put("lineChoices", Utils.stringAtIndex(responseValues, 20));
98 | // vars.put("lineChoicesAbbrev", Utils.stringAtIndex(responseValues, 21));
99 | // vars.put("typingData", Utils.stringAtIndex(responseValues, 22));
100 | // vars.put("divert", Utils.stringAtIndex(responseValues, 23));
101 |
102 | ChatterBotThought responseThought = new ChatterBotThought();
103 |
104 | responseThought.setText(Utils.stringAtIndex(responseValues, 0));
105 |
106 | return responseThought;
107 | }
108 |
109 | public String think(String text) throws Exception {
110 | ChatterBotThought thought = new ChatterBotThought();
111 | thought.setText(text);
112 | return think(thought).getText();
113 | }
114 | }
115 | }
--------------------------------------------------------------------------------
/java/src/main/java/com/google/code/chatterbotapi/Pandorabots.java:
--------------------------------------------------------------------------------
1 | package com.google.code.chatterbotapi;
2 |
3 | import java.util.LinkedHashMap;
4 | import java.util.Locale;
5 | import java.util.Map;
6 | import java.util.UUID;
7 |
8 | /*
9 | chatter-bot-api
10 | Copyright (C) 2011 pierredavidbelanger@gmail.com
11 |
12 | This program is free software: you can redistribute it and/or modify
13 | it under the terms of the GNU Lesser General Public License as published by
14 | the Free Software Foundation, either version 3 of the License, or
15 | (at your option) any later version.
16 |
17 | This program is distributed in the hope that it will be useful,
18 | but WITHOUT ANY WARRANTY; without even the implied warranty of
19 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 | GNU Lesser General Public License for more details.
21 |
22 | You should have received a copy of the GNU Lesser General Public License
23 | along with this program. If not, see .
24 | */
25 | class Pandorabots implements ChatterBot {
26 | private final String botid;
27 |
28 | public Pandorabots(String botid) {
29 | this.botid = botid;
30 | }
31 |
32 | @Override
33 | public ChatterBotSession createSession(Locale... locales) {
34 | return new Session();
35 | }
36 |
37 | private class Session implements ChatterBotSession {
38 | private final Map vars;
39 |
40 | public Session() {
41 | vars = new LinkedHashMap();
42 | vars.put("botid", botid);
43 | vars.put("custid", UUID.randomUUID().toString());
44 | }
45 |
46 | public ChatterBotThought think(ChatterBotThought thought) throws Exception {
47 | vars.put("input", thought.getText());
48 |
49 | String response = Utils.request("https://www.pandorabots.com/pandora/talk-xml", null, null, vars);
50 |
51 | ChatterBotThought responseThought = new ChatterBotThought();
52 |
53 | responseThought.setText(Utils.xPathSearch(response, "//result/that/text()"));
54 |
55 | return responseThought;
56 | }
57 |
58 | public String think(String text) throws Exception {
59 | ChatterBotThought thought = new ChatterBotThought();
60 | thought.setText(text);
61 | return think(thought).getText();
62 | }
63 | }
64 | }
--------------------------------------------------------------------------------
/java/src/main/java/com/google/code/chatterbotapi/Utils.java:
--------------------------------------------------------------------------------
1 | package com.google.code.chatterbotapi;
2 |
3 | import org.w3c.dom.Document;
4 |
5 | import javax.xml.parsers.DocumentBuilder;
6 | import javax.xml.parsers.DocumentBuilderFactory;
7 | import javax.xml.xpath.XPath;
8 | import javax.xml.xpath.XPathConstants;
9 | import javax.xml.xpath.XPathExpression;
10 | import javax.xml.xpath.XPathFactory;
11 | import java.io.*;
12 | import java.math.BigInteger;
13 | import java.net.HttpCookie;
14 | import java.net.HttpURLConnection;
15 | import java.net.URL;
16 | import java.net.URLEncoder;
17 | import java.security.MessageDigest;
18 | import java.util.List;
19 | import java.util.Locale;
20 | import java.util.Map;
21 |
22 | /*
23 | chatter-bot-api
24 | Copyright (C) 2011 pierredavidbelanger@gmail.com
25 |
26 | This program is free software: you can redistribute it and/or modify
27 | it under the terms of the GNU Lesser General Public License as published by
28 | the Free Software Foundation, either version 3 of the License, or
29 | (at your option) any later version.
30 |
31 | This program is distributed in the hope that it will be useful,
32 | but WITHOUT ANY WARRANTY; without even the implied warranty of
33 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
34 | GNU Lesser General Public License for more details.
35 |
36 | You should have received a copy of the GNU Lesser General Public License
37 | along with this program. If not, see .
38 | */
39 | class Utils {
40 |
41 | public static String parametersToWWWFormURLEncoded(Map parameters) throws Exception {
42 | StringBuilder s = new StringBuilder();
43 | for (Map.Entry parameter : parameters.entrySet()) {
44 | if (s.length() > 0) {
45 | s.append("&");
46 | }
47 | s.append(URLEncoder.encode(parameter.getKey(), "UTF-8"));
48 | s.append("=");
49 | s.append(URLEncoder.encode(parameter.getValue(), "UTF-8"));
50 | }
51 | return s.toString();
52 | }
53 |
54 | public static String md5(String input) throws Exception {
55 | MessageDigest md5 = MessageDigest.getInstance("MD5");
56 | md5.update(input.getBytes("UTF-8"));
57 | BigInteger hash = new BigInteger(1, md5.digest());
58 | return String.format("%1$032X", hash);
59 | }
60 |
61 | public static String toAcceptLanguageTags(Locale... locales) {
62 | // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
63 | //
64 | // for example, if user ask for: Locale.CANADA_FRENCH, Locale.ENGLISH
65 | // then this method will render: fr-CA;q=1.0, fr;q=0.99, en;q=0.5
66 | //
67 | if (locales.length == 0)
68 | return "";
69 | float qf = 1f / (float) locales.length;
70 | float q = 1f;
71 | StringBuilder s = new StringBuilder();
72 | for (int i = 0; i < locales.length; i++) {
73 | Locale locale = locales[i];
74 | if (s.length() > 0)
75 | s.append(", ");
76 | if (!locale.getCountry().equals("")) {
77 | s.append(locale.getLanguage()).append("-").append(locale.getCountry());
78 | s.append(";q=" + q);
79 | s.append(", ");
80 | s.append(locale.getLanguage());
81 | s.append(";q=" + (q - 0.01));
82 | } else {
83 | s.append(locale.getLanguage());
84 | s.append(";q=" + q);
85 | }
86 | q -= qf;
87 | }
88 | return s.toString();
89 | }
90 |
91 | public static String request(String url, Map headers, Map cookies, Map parameters) throws Exception {
92 | HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
93 | connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36");
94 | if (headers != null) {
95 | for (Map.Entry header : headers.entrySet()) {
96 | connection.setRequestProperty(header.getKey(), header.getValue());
97 | }
98 | }
99 | if (cookies != null && !cookies.isEmpty()) {
100 | StringBuilder cookieHeader = new StringBuilder();
101 | for (String cookie : cookies.values()) {
102 | if (cookieHeader.length() > 0) {
103 | cookieHeader.append(";");
104 | }
105 | cookieHeader.append(cookie);
106 | }
107 | connection.setRequestProperty("Cookie", cookieHeader.toString());
108 | }
109 | connection.setDoInput(true);
110 | if (parameters != null && !parameters.isEmpty()) {
111 | connection.setDoOutput(true);
112 | OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
113 | osw.write(parametersToWWWFormURLEncoded(parameters));
114 | osw.flush();
115 | osw.close();
116 | }
117 | if (cookies != null) {
118 | for (Map.Entry> headerEntry : connection.getHeaderFields().entrySet()) {
119 | if (headerEntry != null && headerEntry.getKey() != null && headerEntry.getKey().equalsIgnoreCase("Set-Cookie")) {
120 | for (String header : headerEntry.getValue()) {
121 | for (HttpCookie httpCookie : HttpCookie.parse(header)) {
122 | cookies.put(httpCookie.getName(), httpCookie.toString());
123 | }
124 | }
125 | }
126 | }
127 | }
128 | Reader r = new BufferedReader(new InputStreamReader(connection.getInputStream()));
129 | StringWriter w = new StringWriter();
130 | char[] buffer = new char[1024];
131 | int n = 0;
132 | while ((n = r.read(buffer)) != -1) {
133 | w.write(buffer, 0, n);
134 | }
135 | r.close();
136 | return w.toString();
137 | }
138 |
139 | public static String xPathSearch(String input, String expression) throws Exception {
140 | DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
141 | XPath xPath = XPathFactory.newInstance().newXPath();
142 | XPathExpression xPathExpression = xPath.compile(expression);
143 | Document document = documentBuilder.parse(new ByteArrayInputStream(input.getBytes("UTF-8")));
144 | String output = (String) xPathExpression.evaluate(document, XPathConstants.STRING);
145 | return output == null ? "" : output.trim();
146 | }
147 |
148 | public static String stringAtIndex(String[] strings, int index) {
149 | if (index >= strings.length) return "";
150 | return strings[index];
151 | }
152 | }
--------------------------------------------------------------------------------
/java/src/test/java/com/google/code/chatterbotapi/test/ChatterBotApiTest.java:
--------------------------------------------------------------------------------
1 | package com.google.code.chatterbotapi.test;
2 |
3 | import com.google.code.chatterbotapi.*;
4 |
5 | /*
6 | chatter-bot-api
7 | Copyright (C) 2011 pierredavidbelanger@gmail.com
8 |
9 | This program is free software: you can redistribute it and/or modify
10 | it under the terms of the GNU Lesser General Public License as published by
11 | the Free Software Foundation, either version 3 of the License, or
12 | (at your option) any later version.
13 |
14 | This program is distributed in the hope that it will be useful,
15 | but WITHOUT ANY WARRANTY; without even the implied warranty of
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 | GNU Lesser General Public License for more details.
18 |
19 | You should have received a copy of the GNU Lesser General Public License
20 | along with this program. If not, see .
21 | */
22 | public class ChatterBotApiTest {
23 |
24 | public static void main(String[] args) throws Exception {
25 | ChatterBotFactory factory = new ChatterBotFactory();
26 |
27 | ChatterBot bot1 = factory.create(ChatterBotType.CLEVERBOT);
28 | ChatterBotSession bot1session = bot1.createSession();
29 |
30 | ChatterBot bot2 = factory.create(ChatterBotType.PANDORABOTS, "b0dafd24ee35a477");
31 | ChatterBotSession bot2session = bot2.createSession();
32 |
33 | String s = "Hi";
34 | while (true) {
35 |
36 | System.out.println("bot1> " + s);
37 |
38 | s = bot2session.think(s);
39 | System.out.println("bot2> " + s);
40 |
41 | s = bot1session.think(s);
42 | }
43 | }
44 | }
--------------------------------------------------------------------------------
/lgpl-3.0.txt:
--------------------------------------------------------------------------------
1 | GNU LESSER GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 |
9 | This version of the GNU Lesser General Public License incorporates
10 | the terms and conditions of version 3 of the GNU General Public
11 | License, supplemented by the additional permissions listed below.
12 |
13 | 0. Additional Definitions.
14 |
15 | As used herein, "this License" refers to version 3 of the GNU Lesser
16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU
17 | General Public License.
18 |
19 | "The Library" refers to a covered work governed by this License,
20 | other than an Application or a Combined Work as defined below.
21 |
22 | An "Application" is any work that makes use of an interface provided
23 | by the Library, but which is not otherwise based on the Library.
24 | Defining a subclass of a class defined by the Library is deemed a mode
25 | of using an interface provided by the Library.
26 |
27 | A "Combined Work" is a work produced by combining or linking an
28 | Application with the Library. The particular version of the Library
29 | with which the Combined Work was made is also called the "Linked
30 | Version".
31 |
32 | The "Minimal Corresponding Source" for a Combined Work means the
33 | Corresponding Source for the Combined Work, excluding any source code
34 | for portions of the Combined Work that, considered in isolation, are
35 | based on the Application, and not on the Linked Version.
36 |
37 | The "Corresponding Application Code" for a Combined Work means the
38 | object code and/or source code for the Application, including any data
39 | and utility programs needed for reproducing the Combined Work from the
40 | Application, but excluding the System Libraries of the Combined Work.
41 |
42 | 1. Exception to Section 3 of the GNU GPL.
43 |
44 | You may convey a covered work under sections 3 and 4 of this License
45 | without being bound by section 3 of the GNU GPL.
46 |
47 | 2. Conveying Modified Versions.
48 |
49 | If you modify a copy of the Library, and, in your modifications, a
50 | facility refers to a function or data to be supplied by an Application
51 | that uses the facility (other than as an argument passed when the
52 | facility is invoked), then you may convey a copy of the modified
53 | version:
54 |
55 | a) under this License, provided that you make a good faith effort to
56 | ensure that, in the event an Application does not supply the
57 | function or data, the facility still operates, and performs
58 | whatever part of its purpose remains meaningful, or
59 |
60 | b) under the GNU GPL, with none of the additional permissions of
61 | this License applicable to that copy.
62 |
63 | 3. Object Code Incorporating Material from Library Header Files.
64 |
65 | The object code form of an Application may incorporate material from
66 | a header file that is part of the Library. You may convey such object
67 | code under terms of your choice, provided that, if the incorporated
68 | material is not limited to numerical parameters, data structure
69 | layouts and accessors, or small macros, inline functions and templates
70 | (ten or fewer lines in length), you do both of the following:
71 |
72 | a) Give prominent notice with each copy of the object code that the
73 | Library is used in it and that the Library and its use are
74 | covered by this License.
75 |
76 | b) Accompany the object code with a copy of the GNU GPL and this license
77 | document.
78 |
79 | 4. Combined Works.
80 |
81 | You may convey a Combined Work under terms of your choice that,
82 | taken together, effectively do not restrict modification of the
83 | portions of the Library contained in the Combined Work and reverse
84 | engineering for debugging such modifications, if you also do each of
85 | the following:
86 |
87 | a) Give prominent notice with each copy of the Combined Work that
88 | the Library is used in it and that the Library and its use are
89 | covered by this License.
90 |
91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license
92 | document.
93 |
94 | c) For a Combined Work that displays copyright notices during
95 | execution, include the copyright notice for the Library among
96 | these notices, as well as a reference directing the user to the
97 | copies of the GNU GPL and this license document.
98 |
99 | d) Do one of the following:
100 |
101 | 0) Convey the Minimal Corresponding Source under the terms of this
102 | License, and the Corresponding Application Code in a form
103 | suitable for, and under terms that permit, the user to
104 | recombine or relink the Application with a modified version of
105 | the Linked Version to produce a modified Combined Work, in the
106 | manner specified by section 6 of the GNU GPL for conveying
107 | Corresponding Source.
108 |
109 | 1) Use a suitable shared library mechanism for linking with the
110 | Library. A suitable mechanism is one that (a) uses at run time
111 | a copy of the Library already present on the user's computer
112 | system, and (b) will operate properly with a modified version
113 | of the Library that is interface-compatible with the Linked
114 | Version.
115 |
116 | e) Provide Installation Information, but only if you would otherwise
117 | be required to provide such information under section 6 of the
118 | GNU GPL, and only to the extent that such information is
119 | necessary to install and execute a modified version of the
120 | Combined Work produced by recombining or relinking the
121 | Application with a modified version of the Linked Version. (If
122 | you use option 4d0, the Installation Information must accompany
123 | the Minimal Corresponding Source and Corresponding Application
124 | Code. If you use option 4d1, you must provide the Installation
125 | Information in the manner specified by section 6 of the GNU GPL
126 | for conveying Corresponding Source.)
127 |
128 | 5. Combined Libraries.
129 |
130 | You may place library facilities that are a work based on the
131 | Library side by side in a single library together with other library
132 | facilities that are not Applications and are not covered by this
133 | License, and convey such a combined library under terms of your
134 | choice, if you do both of the following:
135 |
136 | a) Accompany the combined library with a copy of the same work based
137 | on the Library, uncombined with any other library facilities,
138 | conveyed under the terms of this License.
139 |
140 | b) Give prominent notice with the combined library that part of it
141 | is a work based on the Library, and explaining where to find the
142 | accompanying uncombined form of the same work.
143 |
144 | 6. Revised Versions of the GNU Lesser General Public License.
145 |
146 | The Free Software Foundation may publish revised and/or new versions
147 | of the GNU Lesser General Public License from time to time. Such new
148 | versions will be similar in spirit to the present version, but may
149 | differ in detail to address new problems or concerns.
150 |
151 | Each version is given a distinguishing version number. If the
152 | Library as you received it specifies that a certain numbered version
153 | of the GNU Lesser General Public License "or any later version"
154 | applies to it, you have the option of following the terms and
155 | conditions either of that published version or of any later version
156 | published by the Free Software Foundation. If the Library as you
157 | received it does not specify a version number of the GNU Lesser
158 | General Public License, you may choose any version of the GNU Lesser
159 | General Public License ever published by the Free Software Foundation.
160 |
161 | If the Library as you received it specifies that a proxy can decide
162 | whether future versions of the GNU Lesser General Public License shall
163 | apply, that proxy's public statement of acceptance of any version is
164 | permanent authorization for you to choose that version for the
165 | Library.
166 |
--------------------------------------------------------------------------------
/php/ChatterBotApiTestOOP.php:
--------------------------------------------------------------------------------
1 | .
18 | */
19 |
20 | /**
21 | * This tests were written by:
22 | * Christian Gärtner
23 | */
24 |
25 | require 'vendor/autoload.php';
26 |
27 |
28 | use ChatterBotApi\ChatterBotType;
29 | use ChatterBotApi\ChatterBotThought;
30 | use ChatterBotApi\ChatterBotFactory;
31 |
32 | $bot1 = ChatterBotFactory::create(ChatterBotType::CLEVERBOT);
33 | $bot1session = $bot1->createSession();
34 |
35 | $bot2 = ChatterBotFactory::create(ChatterBotType::PANDORABOTS, ChatterBotType::PANDORABOTS_DEFAULT_ID);
36 | $bot2session = $bot2->createSession();
37 |
38 | $th = ChatterBotThought::make('Hi');
39 |
40 | while (1)
41 | {
42 | echo "bot1> $th\n";
43 |
44 | try {
45 | $th = $bot2session->think($th->message());
46 | } catch (IOException $e) {
47 | echo $e;
48 | } catch (Exception $e) {
49 | // Ignore these
50 | }
51 |
52 | echo "bot2> $th\n";
53 |
54 | try {
55 | $th = $bot1session->think($th->message());
56 | } catch (IOException $e) {
57 | echo $e;
58 | } catch (Exception $e) {
59 | // Ignore these
60 | }
61 |
62 | }
--------------------------------------------------------------------------------
/php/chatterbotapi.php:
--------------------------------------------------------------------------------
1 | .
18 | */
19 |
20 | #################################################
21 | # API
22 | #################################################
23 |
24 | class ChatterBotType
25 | {
26 | const CLEVERBOT = 1;
27 | const JABBERWACKY = 2;
28 | const PANDORABOTS = 3;
29 | }
30 |
31 | class ChatterBotFactory
32 | {
33 | public function create($type, $arg = null)
34 | {
35 | switch ($type)
36 | {
37 | case ChatterBotType::CLEVERBOT:
38 | {
39 | return new _Cleverbot('http://www.cleverbot.com', 'http://www.cleverbot.com/webservicemin?uc=777&botapi=chatterbotapi', 26);
40 | }
41 | case ChatterBotType::JABBERWACKY:
42 | {
43 | return new _Cleverbot('http://jabberwacky.com', 'http://jabberwacky.com/webservicemin?botapi=chatterbotapi', 20);
44 | }
45 | case ChatterBotType::PANDORABOTS:
46 | {
47 | if ($arg == null) {
48 | throw new Exception('PANDORABOTS needs a botid arg');
49 | }
50 | return new _Pandorabots($arg);
51 | }
52 | }
53 | }
54 | }
55 |
56 | abstract class ChatterBot
57 | {
58 | public function createSession($lang = 'en')
59 | {
60 | return null;
61 | }
62 | }
63 |
64 | abstract class ChatterBotSession
65 | {
66 | public function thinkThought($thought)
67 | {
68 | return $thought;
69 | }
70 |
71 | public function think($text)
72 | {
73 | $thought = new ChatterBotThought();
74 | $thought->setText($text);
75 | return $this->thinkThought($thought)->getText();
76 | }
77 | }
78 |
79 | class ChatterBotThought
80 | {
81 | private $text;
82 |
83 | public function getText()
84 | {
85 | return $this->text;
86 | }
87 |
88 | public function setText($text)
89 | {
90 | $this->text = $text;
91 | }
92 | }
93 |
94 | #################################################
95 | # Cleverbot impl
96 | #################################################
97 |
98 | class _Cleverbot extends ChatterBot
99 | {
100 | private $baseUrl;
101 | private $serviceUrl;
102 | private $endIndex;
103 |
104 | public function __construct($baseUrl, $serviceUrl, $endIndex)
105 | {
106 | $this->baseUrl = $baseUrl;
107 | $this->serviceUrl = $serviceUrl;
108 | $this->endIndex = $endIndex;
109 | }
110 |
111 | public function getBaseUrl()
112 | {
113 | return $this->baseUrl;
114 | }
115 |
116 | public function getServiceUrl()
117 | {
118 | return $this->serviceUrl;
119 | }
120 |
121 | public function getEndIndex()
122 | {
123 | return $this->endIndex;
124 | }
125 |
126 | public function setEndIndex($endIndex)
127 | {
128 | $this->endIndex = $endIndex;
129 | }
130 |
131 | public function createSession($lang = 'en')
132 | {
133 | return new _CleverbotSession($this, $lang);
134 | }
135 | }
136 |
137 | class _CleverbotSession extends ChatterBotSession
138 | {
139 | private $bot;
140 | private $headers;
141 | private $cookies;
142 | private $vars;
143 |
144 | public function __construct($bot, $lang)
145 | {
146 | $this->bot = $bot;
147 | $this->headers = array();
148 | $this->headers['Accept-Language'] = "$lang;q=1.0";
149 | $this->vars = array();
150 | //$this->vars['start'] = 'y';
151 | $this->vars['stimulus'] = '';
152 | $this->vars['islearning'] = '1';
153 | $this->vars['icognoid'] = 'wsf';
154 | //$this->vars['fno'] = '0';
155 | //$this->vars['sub'] = 'Say';
156 | //$this->vars['cleanslate'] = 'false';
157 | $this->cookies = array();
158 | _utils_request($this->bot->getBaseUrl(), $this->cookies, null, $this->headers);
159 | }
160 |
161 | public function thinkThought($thought)
162 | {
163 | $this->vars['stimulus'] = $thought->getText();
164 | $data = http_build_query($this->vars);
165 | $dataToDigest = substr($data, 9, $this->bot->getEndIndex());
166 | $dataDigest = md5($dataToDigest);
167 | $this->vars['icognocheck'] = $dataDigest;
168 | $response = _utils_request($this->bot->getServiceUrl(), $this->cookies, $this->vars, $this->headers);
169 | $responseValues = explode("\r", $response);
170 | //self.vars['??'] = _utils_string_at_index($responseValues, 0);
171 | $this->vars['sessionid'] = _utils_string_at_index($responseValues, 1);
172 | $this->vars['logurl'] = _utils_string_at_index($responseValues, 2);
173 | $this->vars['vText8'] = _utils_string_at_index($responseValues, 3);
174 | $this->vars['vText7'] = _utils_string_at_index($responseValues, 4);
175 | $this->vars['vText6'] = _utils_string_at_index($responseValues, 5);
176 | $this->vars['vText5'] = _utils_string_at_index($responseValues, 6);
177 | $this->vars['vText4'] = _utils_string_at_index($responseValues, 7);
178 | $this->vars['vText3'] = _utils_string_at_index($responseValues, 8);
179 | $this->vars['vText2'] = _utils_string_at_index($responseValues, 9);
180 | $this->vars['prevref'] = _utils_string_at_index($responseValues, 10);
181 | //$this->vars['??'] = _utils_string_at_index($responseValues, 11);
182 | // $this->vars['emotionalhistory'] = _utils_string_at_index($responseValues, 12);
183 | // $this->vars['ttsLocMP3'] = _utils_string_at_index($responseValues, 13);
184 | // $this->vars['ttsLocTXT'] = _utils_string_at_index($responseValues, 14);
185 | // $this->vars['ttsLocTXT3'] = _utils_string_at_index($responseValues, 15);
186 | // $this->vars['ttsText'] = _utils_string_at_index($responseValues, 16);
187 | // $this->vars['lineRef'] = _utils_string_at_index($responseValues, 17);
188 | // $this->vars['lineURL'] = _utils_string_at_index($responseValues, 18);
189 | // $this->vars['linePOST'] = _utils_string_at_index($responseValues, 19);
190 | // $this->vars['lineChoices'] = _utils_string_at_index($responseValues, 20);
191 | // $this->vars['lineChoicesAbbrev'] = _utils_string_at_index($responseValues, 21);
192 | // $this->vars['typingData'] = _utils_string_at_index($responseValues, 22);
193 | // $this->vars['divert'] = _utils_string_at_index($responseValues, 23);
194 | $responseThought = new ChatterBotThought();
195 | $text = _utils_string_at_index($responseValues, 0);
196 | if (!is_null($text))
197 | {
198 | $text = preg_replace_callback(
199 | '/\|([01234567890ABCDEF]{4})/',
200 | function ($matches) {
201 | return iconv('UCS-4LE', 'UTF-8', pack('V', hexdec($matches[0])));
202 | },
203 | $text);
204 | }
205 | else
206 | {
207 | $text = '';
208 | }
209 | $responseThought->setText($text);
210 | return $responseThought;
211 | }
212 | }
213 |
214 | #################################################
215 | # Pandorabots impl
216 | #################################################
217 |
218 | class _Pandorabots extends ChatterBot
219 | {
220 | private $botid;
221 |
222 | public function __construct($botid)
223 | {
224 | $this->botid = $botid;
225 | }
226 |
227 | public function getBotid()
228 | {
229 | return $this->botid;
230 | }
231 |
232 | public function setBotid($botid)
233 | {
234 | $this->botid = $botid;
235 | }
236 |
237 | public function createSession($lang = 'en')
238 | {
239 | return new _PandorabotsSession($this);
240 | }
241 | }
242 |
243 | class _PandorabotsSession extends ChatterBotSession
244 | {
245 | private $vars;
246 |
247 | public function __construct($bot)
248 | {
249 | $this->vars = array();
250 | $this->vars['botid'] = $bot->getBotid();
251 | $this->vars['custid'] = uniqid();
252 | }
253 |
254 | public function thinkThought($thought)
255 | {
256 | $this->vars['input'] = $thought->getText();
257 | $dummy = NULL;
258 | $response = _utils_request('https://www.pandorabots.com/pandora/talk-xml', $dummy, $this->vars);
259 | $element = new SimpleXMLElement($response);
260 | $result = $element->xpath('//result/that/text()');
261 | $responseThought = new ChatterBotThought();
262 | if (isset($result[0][0]))
263 | {
264 | $responseThought->setText(trim($result[0][0]));
265 | }
266 | else
267 | {
268 | $responseThought->setText("");
269 | }
270 | return $responseThought;
271 | }
272 | }
273 |
274 | #################################################
275 | # Utils
276 | #################################################
277 |
278 | function _utils_request($url, &$cookies, $params, $headers = null)
279 | {
280 | $contextParams = array();
281 | $contextParams['http'] = array();
282 | if ($params)
283 | {
284 | $contextParams['http']['method'] = 'POST';
285 | $contextParams['http']['content'] = http_build_query($params);
286 | $contextParams['http']['header'] = "Content-type: application/x-www-form-urlencoded\r\n";
287 | }
288 | else
289 | {
290 | $contextParams['http']['method'] = 'GET';
291 | }
292 | if (!is_null($cookies) && count($cookies) > 0)
293 | {
294 | $cookieHeader = "Cookie: ";
295 | foreach ($cookies as $cookieName => $cookie)
296 | {
297 | $cookieHeader .= $cookie . ";";
298 | }
299 | $cookieHeader .= "\r\n";
300 | if (isset($contextParams['http']['header']))
301 | {
302 | $contextParams['http']['header'] .= $cookieHeader;
303 | }
304 | else
305 | {
306 | $contextParams['http']['header'] = $cookieHeader;
307 | }
308 | }
309 | if (!is_null($headers))
310 | {
311 | foreach ($headers as $headerName => $headerValue)
312 | {
313 | if (isset($contextParams['http']['header']))
314 | {
315 | $contextParams['http']['header'] .= "$headerName: $headerValue\r\n";
316 | }
317 | else
318 | {
319 | $contextParams['http']['header'] = "$headerName: $headerValue\r\n";
320 | }
321 | }
322 | }
323 | $context = stream_context_create($contextParams);
324 | $fp = fopen($url, 'rb', false, $context);
325 | $response = stream_get_contents($fp);
326 | if (!is_null($cookies))
327 | {
328 | foreach ($http_response_header as $header)
329 | {
330 | if (preg_match('@Set-Cookie: (([^=]+)=[^;]+)@i', $header, $matches))
331 | {
332 | $cookies[$matches[2]] = $matches[1];
333 | }
334 | }
335 | }
336 | fclose($fp);
337 | return $response;
338 | }
339 |
340 | function _utils_string_at_index($strings, $index)
341 | {
342 | if (count($strings) > $index)
343 | {
344 | return $strings[$index];
345 | }
346 | else
347 | {
348 | return '';
349 | }
350 | }
351 | ?>
352 |
--------------------------------------------------------------------------------
/php/chatterbotapitest.php:
--------------------------------------------------------------------------------
1 | .
18 | */
19 |
20 | require 'chatterbotapi.php';
21 |
22 | $factory = new ChatterBotFactory();
23 |
24 | $bot1 = $factory->create(ChatterBotType::CLEVERBOT);
25 | $bot1session = $bot1->createSession();
26 |
27 | $bot2 = $factory->create(ChatterBotType::PANDORABOTS, 'b0dafd24ee35a477');
28 | $bot2session = $bot2->createSession();
29 |
30 | $s = 'Hi';
31 | while (1)
32 | {
33 | echo "bot1> $s\n";
34 |
35 | $s = $bot2session->think($s);
36 | echo "bot2> $s\n";
37 |
38 | $s = $bot1session->think($s);
39 | }
40 | ?>
--------------------------------------------------------------------------------
/php/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "autoload": {
3 | "psr-0": {
4 | "ChatterBotApi\\": "src/"
5 | }
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/php/phpunit.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
14 |
15 |
16 |
17 |
18 | ./vendor
19 |
20 |
21 |
22 |
23 |
24 | ./tests/
25 |
26 |
27 |
--------------------------------------------------------------------------------
/php/src/ChatterBotApi/AbstractBot.php:
--------------------------------------------------------------------------------
1 | .
19 | */
20 |
21 | /**
22 | * Abstract for all ChatterBots
23 | */
24 | abstract class AbstractBot
25 | {
26 | /**
27 | * Create the session
28 | * @return \ChatterBotApi\ChatterBotSession The new session instance
29 | */
30 | public function createSession()
31 | {
32 | return null;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/php/src/ChatterBotApi/AbstractSession.php:
--------------------------------------------------------------------------------
1 | .
19 | */
20 |
21 | /**
22 | * Abstract for all ChatterBot Sessions
23 | */
24 | abstract class AbstractSession
25 | {
26 | /**
27 | * Return new thought based on given thought
28 | * @param \ChatterBotApi\ChatterBotThought $thought The previous thought
29 | * @return \ChatterBotApi\ChatterBotThought The new thought.
30 | */
31 | public function thinkThought(ChatterBotThought $thought)
32 | {
33 | return $thought;
34 | }
35 |
36 | /**
37 | * Return a new thought based on given string
38 | * @param string $text The text
39 | *
40 | * @return \ChatterBotApi\ChatterBotThought The new thought.
41 | */
42 | public function think($text)
43 | {
44 | $thought = ChatterBotThought::make($text);
45 | return $this->thinkThought($thought);
46 | }
47 | }
--------------------------------------------------------------------------------
/php/src/ChatterBotApi/ChatterBotFactory.php:
--------------------------------------------------------------------------------
1 | .
19 | */
20 |
21 | use Exception;
22 | use InvalidArgumentException;
23 | use ChatterBotApi\Implementation\CleverBot\CleverBot;
24 | use ChatterBotApi\Implementation\PandoraBots\PandoraBots;
25 |
26 | /**
27 | * The ChatterBotFactory
28 | */
29 | class ChatterBotFactory
30 | {
31 | /**
32 | * Create a new a ChatterBot
33 | * @param int $type The ChatterBotType (hint: use the ChatterBotType constants)
34 | * @param string $arg BotId (only needed when using a PandoraBot)
35 | *
36 | * @return \ChatterBotApi\ChatterBot The new Bot instance
37 | *
38 | * @throws \Exception When type not recognized or no BotId bassed to the PandoraBot
39 | */
40 | public static function create($type, $arg = null)
41 | {
42 | switch ($type) {
43 | case ChatterBotType::CLEVERBOT:
44 | return new Cleverbot('http://www.cleverbot.com/webservicemin');
45 |
46 |
47 | case ChatterBotType::JABBERWACKY:
48 | return new Cleverbot('http://jabberwacky.com/webservicemin');
49 |
50 | case ChatterBotType::PANDORABOTS:
51 | if ($arg == null) {
52 | throw new Exception('PANDORABOTS needs a botid arg');
53 | }
54 | return new PandoraBots($arg);
55 |
56 | default:
57 | throw new InvalidArgumentException('Type not recognized');
58 |
59 | }
60 | }
61 | }
--------------------------------------------------------------------------------
/php/src/ChatterBotApi/ChatterBotThought.php:
--------------------------------------------------------------------------------
1 | .
19 | */
20 |
21 | /**
22 | * A ChatterBot thought
23 | */
24 | class ChatterBotThought
25 | {
26 | /**
27 | * The associated Text
28 | * @var string
29 | */
30 | private $text;
31 |
32 | /**
33 | * Factory Method.
34 | * @param string $text [description]
35 | * @return \ChatterBotApi\ChatterBotThought The new instance
36 | */
37 | public static function make($text = '')
38 | {
39 | return new static($text);
40 | }
41 |
42 | /**
43 | * Contructor.
44 | * @param string $text The text
45 | */
46 | public function __construct($text = '')
47 | {
48 | $this->setText($text);
49 | }
50 |
51 | /**
52 | * Magic Method __toString
53 | * @return string The text
54 | */
55 | public function __toString()
56 | {
57 | return (string) $this->text;
58 | }
59 |
60 | /**
61 | * Wrapper for getText()
62 | * @uses getText()
63 | * @return string The text
64 | */
65 | public function message()
66 | {
67 | return $this->getText();
68 | }
69 |
70 | /**
71 | * Get the text of this thought
72 | * @return string The text
73 | */
74 | public function getText()
75 | {
76 | return $this->text;
77 | }
78 |
79 | /**
80 | * Set the text of this thought
81 | * @param string $text The text
82 | */
83 | public function setText($text)
84 | {
85 | $this->text = $text;
86 | }
87 | }
--------------------------------------------------------------------------------
/php/src/ChatterBotApi/ChatterBotType.php:
--------------------------------------------------------------------------------
1 | .
19 | */
20 |
21 | /**
22 | * The ChatterBot type
23 | */
24 | class ChatterBotType
25 | {
26 | /**
27 | * CleverBot
28 | * @var int 1
29 | */
30 | const CLEVERBOT = 1;
31 |
32 | /**
33 | * JabberWacky
34 | * @var int 2
35 | */
36 | const JABBERWACKY = 2;
37 |
38 | /**
39 | * PandoraBot
40 | * @var int 3
41 | */
42 | const PANDORABOTS = 3;
43 |
44 | /**
45 | * A "good" bot ID
46 | * @var string
47 | */
48 | const PANDORABOTS_DEFAULT_ID = 'b0dafd24ee35a477';
49 | }
--------------------------------------------------------------------------------
/php/src/ChatterBotApi/IOException.php:
--------------------------------------------------------------------------------
1 | .
20 | */
21 |
22 | use Exception;
23 |
24 | /**
25 | * An IO Exception
26 | * @author Christian Gärtner
27 | */
28 | class IOException extends Exception
29 | {
30 | private $path;
31 |
32 | public function __construct($message, $code = 0, $path = null, Exception $previous = null)
33 | {
34 | if ($path === '' && $path !== null) {
35 | $path = '';
36 | }
37 | $this->path = $path;
38 | parent::__construct($message, $code, $previous);
39 | }
40 |
41 | /**
42 | * Magic Function. __toString
43 | * @return string The exception message
44 | * @Override
45 | */
46 | public function __toString()
47 | {
48 | return __CLASS__ . ": [{$this->code}]: {$this->message}\nIO path: {$this->path}\n";
49 | }
50 |
51 | /**
52 | * Returns the path of this IOException
53 | * @return string The path
54 | */
55 | public function getPath()
56 | {
57 | return $this->path;
58 | }
59 | }
--------------------------------------------------------------------------------
/php/src/ChatterBotApi/Implementation/CleverBot/CleverBot.php:
--------------------------------------------------------------------------------
1 | .
19 | */
20 |
21 | use ChatterBotApi\AbstractBot;
22 |
23 | /**
24 | * A cleverbot
25 | */
26 | class CleverBot extends AbstractBot
27 | {
28 | /**
29 | * The url for this chatterbot
30 | * @var string
31 | */
32 | private $url;
33 |
34 | /**
35 | * Constructor.
36 | * @param string $url The url for this chatterbot
37 | */
38 | public function __construct($url)
39 | {
40 | $this->url = $url;
41 | }
42 |
43 | /**
44 | * Get the url of this chatterbot
45 | * @return string The url
46 | */
47 | public function getUrl()
48 | {
49 | return $this->url;
50 | }
51 |
52 | /**
53 | * Set the url for this chatterbot
54 | * @param string $url The url
55 | */
56 | public function setUrl($url)
57 | {
58 | $this->url = $url;
59 | }
60 |
61 | /**
62 | * Create a new Session for this bot
63 | * @return \ChatterBotApi\Implementation\CleverBot\Session The new Session
64 | */
65 | public function createSession()
66 | {
67 | return new Session($this);
68 | }
69 | }
--------------------------------------------------------------------------------
/php/src/ChatterBotApi/Implementation/CleverBot/Session.php:
--------------------------------------------------------------------------------
1 | .
19 | */
20 |
21 | use Exception;
22 | use ChatterBotApi\Utils;
23 | use ChatterBotApi\AbstractSession;
24 | use ChatterBotApi\ChatterBotThought;
25 |
26 | class Session extends AbstractSession
27 | {
28 | /**
29 | * The assoc. bot of this session
30 | * @var \ChatterBotApi\Implementation\CleverBot\CleverBot
31 | */
32 | private $bot;
33 |
34 | /**
35 | * Varibales used for creating the request
36 | * @var array
37 | */
38 | private $vars;
39 |
40 | /**
41 | * Constructor.
42 | * @param \ChatterBotApi\Implementation\CleverBot\CleverBot $bot The bot
43 | */
44 | public function __construct(CleverBot $bot)
45 | {
46 | $this->bot = $bot;
47 | $this->vars = array();
48 | $this->vars['start'] = 'y';
49 | $this->vars['icognoid'] = 'wsf';
50 | $this->vars['fno'] = '0';
51 | $this->vars['sub'] = 'Say';
52 | $this->vars['islearning'] = '1';
53 | $this->vars['cleanslate'] = 'false';
54 | }
55 |
56 | /**
57 | * Return new thought based on given thought
58 | * @param \ChatterBotApi\ChatterBotTought $thought The previous thought
59 | * @return \ChatterBotApi\ChatterBotTought The new thought.
60 | */
61 | public function thinkThought(ChatterBotThought $thought)
62 | {
63 | $this->vars['stimulus'] = $thought->getText();
64 |
65 | $data = http_build_query($this->vars);
66 |
67 | $dataToDigest = substr($data, 9, 20);
68 |
69 | $dataDigest = md5($dataToDigest);
70 |
71 | $this->vars['icognocheck'] = $dataDigest;
72 |
73 | $response = Utils::post($this->bot->getUrl(), $this->vars);
74 |
75 | $responseValues = explode("\r", $response);
76 |
77 | // $this->vars['??'] = Utils::stringAtIndex($responseValues, 0);
78 | $this->vars['sessionid'] = Utils::stringAtIndex($responseValues, 1);
79 | $this->vars['logurl'] = Utils::stringAtIndex($responseValues, 2);
80 | $this->vars['vText8'] = Utils::stringAtIndex($responseValues, 3);
81 | $this->vars['vText7'] = Utils::stringAtIndex($responseValues, 4);
82 | $this->vars['vText6'] = Utils::stringAtIndex($responseValues, 5);
83 | $this->vars['vText5'] = Utils::stringAtIndex($responseValues, 6);
84 | $this->vars['vText4'] = Utils::stringAtIndex($responseValues, 7);
85 | $this->vars['vText3'] = Utils::stringAtIndex($responseValues, 8);
86 | $this->vars['vText2'] = Utils::stringAtIndex($responseValues, 9);
87 | $this->vars['prevref'] = Utils::stringAtIndex($responseValues, 10);
88 | // $this->vars['??'] = Utils::stringAtIndex($responseValues, 11);
89 | $this->vars['emotionalhistory'] = Utils::stringAtIndex($responseValues, 12);
90 | $this->vars['ttsLocMP3'] = Utils::stringAtIndex($responseValues, 13);
91 | $this->vars['ttsLocTXT'] = Utils::stringAtIndex($responseValues, 14);
92 | $this->vars['ttsLocTXT3'] = Utils::stringAtIndex($responseValues, 15);
93 | $this->vars['ttsText'] = Utils::stringAtIndex($responseValues, 16);
94 | $this->vars['lineRef'] = Utils::stringAtIndex($responseValues, 17);
95 | $this->vars['lineURL'] = Utils::stringAtIndex($responseValues, 18);
96 | $this->vars['linePOST'] = Utils::stringAtIndex($responseValues, 19);
97 | $this->vars['lineChoices'] = Utils::stringAtIndex($responseValues, 20);
98 | $this->vars['lineChoicesAbbrev'] = Utils::stringAtIndex($responseValues, 21);
99 | $this->vars['typingData'] = Utils::stringAtIndex($responseValues, 22);
100 | $this->vars['divert'] = Utils::stringAtIndex($responseValues, 23);
101 |
102 | if ('' == Utils::stringAtIndex($responseValues, 16)) {
103 | throw new Exception('Empty Response');
104 | }
105 | return ChatterBotThought::make(Utils::stringAtIndex($responseValues, 16));
106 | }
107 | }
--------------------------------------------------------------------------------
/php/src/ChatterBotApi/Implementation/PandoraBots/PandoraBots.php:
--------------------------------------------------------------------------------
1 | .
19 | */
20 |
21 | use ChatterBotApi\AbstractBot;
22 |
23 | /**
24 | * A Pandora Bot
25 | */
26 | class PandoraBots extends AbstractBot
27 | {
28 | /**
29 | * The BotID
30 | * @var string
31 | */
32 | private $botid;
33 |
34 | /**
35 | * Constructor.
36 | * @param string $botid The Bot ID
37 | */
38 | public function __construct($botid)
39 | {
40 | $this->botid = $botid;
41 | }
42 |
43 | /**
44 | * Returns the bot ID
45 | * @return string The bot ID
46 | */
47 | public function getId()
48 | {
49 | return $this->botid;
50 | }
51 |
52 | /**
53 | * Set the bot ID
54 | * @param string $botid The bot ID
55 | */
56 | public function setId($botid)
57 | {
58 | $this->botid = $botid;
59 | }
60 |
61 | /**
62 | * Create a new Session for this bot
63 | * @return \ChatterBotApi\Implementation\PandoraBots\Session The new Session
64 | */
65 | public function createSession()
66 | {
67 | return new Session($this);
68 | }
69 | }
--------------------------------------------------------------------------------
/php/src/ChatterBotApi/Implementation/PandoraBots/Session.php:
--------------------------------------------------------------------------------
1 | .
19 | */
20 |
21 | use Exception;
22 | use SimpleXMLElement;
23 | use ChatterBotApi\Utils;
24 | use ChatterBotApi\AbstractSession;
25 | use ChatterBotApi\ChatterBotThought;
26 |
27 | class Session extends AbstractSession
28 | {
29 | /**
30 | * Varibales used for creating the request
31 | * @var array
32 | */
33 | private $vars;
34 |
35 | /**
36 | * Constructor.
37 | * @param \ChatterBotApi\Implementation\PandoraBots $bot The bot
38 | */
39 | public function __construct(PandoraBots $bot)
40 | {
41 | $this->vars = array();
42 | $this->vars['botid'] = $bot->getId();
43 | $this->vars['custid'] = uniqid();
44 | }
45 |
46 | /**
47 | * Return new thought based on given thought
48 | * @param \ChatterBotApi\ChatterBotTought $thought The previous thought
49 | * @return \ChatterBotApi\ChatterBotTought The new thought.
50 | *
51 | * @throws \Exception If response is empty (when input string is empty)
52 | */
53 | public function thinkThought(ChatterBotThought $thought)
54 | {
55 | $this->vars['input'] = $thought->getText();
56 |
57 |
58 | $response = Utils::post('http://www.pandorabots.com/pandora/talk-xml', $this->vars);
59 |
60 | $element = new SimpleXMLElement($response);
61 |
62 | $result = $element->xpath('//result/that/text()');
63 |
64 | if (isset($result[0][0])) {
65 | return ChatterBotThought::make($result[0][0]);
66 | } else {
67 | throw new Exception('Empty Response');
68 |
69 | }
70 | }
71 | }
--------------------------------------------------------------------------------
/php/src/ChatterBotApi/Utils.php:
--------------------------------------------------------------------------------
1 | .
19 | */
20 |
21 | /**
22 | * Utils class
23 | */
24 | class Utils
25 | {
26 | /**
27 | * Post to the given URL
28 | * @param string $url The target url
29 | * @param array $params The parameters
30 | * @return string The response
31 | */
32 | public static function post($url, $params)
33 | {
34 | $contextParams = array();
35 | $contextParams['http'] = array();
36 | $contextParams['http']['method'] = 'POST';
37 | $contextParams['http']['content'] = http_build_query($params);
38 | $contextParams['http']['header'] = "Content-Type: application/x-www-form-urlencoded\r\n";
39 | $context = stream_context_create($contextParams);
40 | $fp = @fopen($url, 'rb', false, $context);
41 | if (!$fp) {
42 | throw new IOException('Connection refused', 0, $url);
43 | }
44 |
45 | $response = @stream_get_contents($fp);
46 |
47 | if ($response === false || $response === null) {
48 | throw new IOException('Cannot grab data', 0, $url);
49 | }
50 | fclose($fp);
51 | return $response;
52 | }
53 |
54 | /**
55 | * Returns the string at the given index
56 | * @param array $strings The strings
57 | * @param int $index The index
58 | * @return string The string | ''
59 | */
60 | public static function stringAtIndex($strings, $index)
61 | {
62 | if (count($strings) > $index && isset($strings[$index])) {
63 | return $strings[$index];
64 | } else {
65 | return '';
66 | }
67 | }
68 | }
--------------------------------------------------------------------------------
/php/tests/ChatterBotApi/ChatterBotFactoryTest.php:
--------------------------------------------------------------------------------
1 | .
18 | */
19 |
20 | use ChatterBotApi\ChatterBotFactory;
21 |
22 | /**
23 | * PHPUnit Test
24 | */
25 | class ChatterBotFactoryTest extends PHPUnit_Framework_TestCase
26 | {
27 | /**
28 | * @dataProvider createData
29 | */
30 | public function testCreate($type, $arg, $exp)
31 | {
32 | $this->assertInstanceOf($exp, ChatterBotFactory::create($type, $arg));
33 | }
34 |
35 | public function createData()
36 | {
37 | return array(
38 | array(1, null, 'ChatterBotApi\\Implementation\\CleverBot\\CleverBot'),
39 | array(1, null, 'ChatterBotApi\\AbstractBot'),
40 |
41 | array(2, null, 'ChatterBotApi\\Implementation\\CleverBot\\CleverBot'),
42 | array(2, null, 'ChatterBotApi\\AbstractBot'),
43 |
44 | array(3, 'b0dafd24ee35a477', 'ChatterBotApi\\Implementation\\PandoraBots\\PandoraBots'),
45 | array(3, 'b0dafd24ee35a477', 'ChatterBotApi\\AbstractBot')
46 | );
47 | }
48 |
49 | /**
50 | * @expectedException Exception
51 | */
52 | public function testCreateException()
53 | {
54 | ChatterBotFactory::create(3);
55 | }
56 |
57 | /**
58 | * @expectedException InvalidArgumentException
59 | */
60 | public function testCreateInvalidArgumentException()
61 | {
62 | ChatterBotFactory::create('Foo');
63 | }
64 | }
--------------------------------------------------------------------------------
/php/tests/ChatterBotApi/ChatterBotThoughtTest.php:
--------------------------------------------------------------------------------
1 | .
18 | */
19 |
20 | use ChatterBotApi\ChatterBotThought;
21 |
22 | /**
23 | * PHPUnit Test
24 | */
25 | class ChatterBotThoughtTest extends PHPUnit_Framework_TestCase
26 | {
27 | public function testMake()
28 | {
29 | $this->assertInstanceOf('ChatterBotApi\ChatterBotThought', ChatterBotThought::make());
30 | }
31 |
32 | /**
33 | * @dataProvider constructData
34 | */
35 | public function testConstruct($text, $exp)
36 | {
37 | if ($text === null) {
38 | $t = new ChatterBotThought();
39 | } else {
40 | $t = new ChatterBotThought($text);
41 | }
42 |
43 | $rp = new ReflectionProperty($t, 'text');
44 | $rp->setAccessible(true);
45 |
46 | $this->assertEquals($exp, $rp->getValue($t));
47 |
48 | }
49 |
50 | public function constructData()
51 | {
52 | return array(
53 | array(null, ''),
54 | array('Foo', 'Foo')
55 | );
56 | }
57 |
58 | public function testToString()
59 | {
60 | $t = ChatterBotThought::make('Foo');
61 |
62 | $this->assertEquals('Foo', (string) $t);
63 | }
64 |
65 | public function testGetText()
66 | {
67 | $t = ChatterBotThought::make('Foo');
68 |
69 | $this->assertEquals('Foo', $t->getText());
70 | }
71 |
72 | public function testSetText()
73 | {
74 | $t = ChatterBotThought::make('Foo');
75 | $t->setText('Bar');
76 | $this->assertEquals('Bar', $t->getText());
77 | }
78 |
79 | public function testMessage()
80 | {
81 | $t = ChatterBotThought::make('Foo');
82 |
83 | $this->assertEquals('Foo', $t->message());
84 | }
85 | }
--------------------------------------------------------------------------------
/php/tests/ChatterBotApi/ChatterBotTypeTest.php:
--------------------------------------------------------------------------------
1 | .
18 | */
19 |
20 | use ChatterBotApi\ChatterBotType;
21 |
22 | /**
23 | * PHPUnit Test
24 | */
25 | class ChatterBotTypeTest extends PHPUnit_Framework_TestCase
26 | {
27 | public function testCleverbot()
28 | {
29 | $this->assertEquals(1, ChatterBotType::CLEVERBOT);
30 | }
31 |
32 | public function testJabberWacky()
33 | {
34 | $this->assertEquals(2, ChatterBotType::JABBERWACKY);
35 | }
36 |
37 | public function testPandoraBots()
38 | {
39 | $this->assertEquals(3, ChatterBotType::PANDORABOTS);
40 | }
41 |
42 | public function testPandoraBotsID()
43 | {
44 | $this->assertEquals('b0dafd24ee35a477', ChatterBotType::PANDORABOTS_DEFAULT_ID);
45 | }
46 | }
--------------------------------------------------------------------------------
/php/tests/ChatterBotApi/IOExceptionTest.php:
--------------------------------------------------------------------------------
1 | .
18 | */
19 |
20 | use ChatterBotApi\IOException;
21 |
22 | /**
23 | * PHPUnit Test
24 | */
25 | class IOExceptionTest extends PHPUnit_Framework_TestCase
26 | {
27 | /**
28 | * @dataProvider contructData
29 | */
30 | public function testContruct($path, $exp)
31 | {
32 | $e = new IOException('Foo', 1, $path);
33 |
34 | $rp = new ReflectionProperty($e, 'path');
35 | $rp->setAccessible(true);
36 |
37 | $this->assertEquals($exp, $rp->getValue($e));
38 | }
39 |
40 | public function contructData()
41 | {
42 | return array(
43 | array('foo/bar', 'foo/bar'),
44 | array('', ''),
45 | array(null, null),
46 | );
47 | }
48 |
49 | public function testGetpath()
50 | {
51 | $e = new IOException('Foo', 1, 'foo/bar');
52 |
53 | $this->assertEquals('foo/bar', $e->getPath());
54 | }
55 |
56 | public function testToString()
57 | {
58 | $e = new IOException('Foo', 1, 'foo/bar');
59 |
60 | $this->assertEquals("ChatterBotApi\IOException: [1]: Foo\nIO path: foo/bar\n", (string) $e);
61 | }
62 | }
--------------------------------------------------------------------------------
/php/tests/ChatterBotApi/UtilsTest.php:
--------------------------------------------------------------------------------
1 | .
18 | */
19 |
20 | use ChatterBotApi\Utils;
21 |
22 | /**
23 | * PHPUnit Test
24 | */
25 | class UtilsTest extends PHPUnit_Framework_TestCase
26 | {
27 | /**
28 | * @dataProvider stringAtIndexData
29 | */
30 | public function testStringAtIndex($strings, $index, $exp)
31 | {
32 | $this->assertEquals($exp, Utils::stringAtIndex($strings, $index));
33 | }
34 |
35 | public function stringAtIndexData()
36 | {
37 | return array(
38 | array(
39 | array('Foo', 'Bar', 'Baz'),
40 | 0,
41 | 'Foo'
42 | ),
43 | array(
44 | array('Foo', 'Bar', 'Baz'),
45 | 1,
46 | 'Bar'
47 | ),
48 | array(
49 | array('Foo', 'Bar', 'Baz'),
50 | 2,
51 | 'Baz'
52 | ),
53 | array(
54 | array('Foo', 'Bar', 'Baz'),
55 | 8,
56 | ''
57 | ),
58 | );
59 | }
60 | }
--------------------------------------------------------------------------------
/python/chatterbotapi.py:
--------------------------------------------------------------------------------
1 | import re
2 | import sys
3 | import hashlib
4 |
5 | if sys.version_info >= (3, 0):
6 | from urllib.request import build_opener, HTTPCookieProcessor, urlopen
7 | from urllib.parse import urlencode
8 | import http.cookiejar as cookielib
9 |
10 | else:
11 | from urllib import urlencode, urlopen
12 | from urllib2 import build_opener, HTTPCookieProcessor
13 | import cookielib
14 |
15 | from collections import OrderedDict
16 |
17 | import uuid
18 | import xml.dom.minidom
19 |
20 | """
21 | chatterbotapi
22 | Copyright (C) 2011 pierredavidbelanger@gmail.com
23 |
24 | This program is free software: you can redistribute it and/or modify
25 | it under the terms of the GNU Lesser General Public License as published by
26 | the Free Software Foundation, either version 3 of the License, or
27 | (at your option) any later version.
28 |
29 | This program is distributed in the hope that it will be useful,
30 | but WITHOUT ANY WARRANTY; without even the implied warranty of
31 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
32 | GNU Lesser General Public License for more details.
33 |
34 | You should have received a copy of the GNU Lesser General Public License
35 | along with this program. If not, see .
36 | """
37 |
38 | #################################################
39 | # API
40 | #################################################
41 |
42 | class ChatterBotType:
43 |
44 | CLEVERBOT = 1
45 | JABBERWACKY = 2
46 | PANDORABOTS = 3
47 |
48 | class ChatterBotFactory:
49 |
50 | def create(self, type, arg = None):
51 | if type == ChatterBotType.CLEVERBOT:
52 | return _Cleverbot('http://www.cleverbot.com', 'http://www.cleverbot.com/webservicemin?uc=777&botapi=chatterbotapi', 35)
53 | elif type == ChatterBotType.JABBERWACKY:
54 | return _Cleverbot('http://jabberwacky.com', 'http://jabberwacky.com/webservicemin?botapi=chatterbotapi', 29)
55 | elif type == ChatterBotType.PANDORABOTS:
56 | if arg == None:
57 | raise Exception('PANDORABOTS needs a botid arg')
58 | return _Pandorabots(arg)
59 | return None
60 |
61 | class ChatterBot:
62 |
63 | def create_session(self):
64 | return None
65 |
66 | class ChatterBotSession:
67 |
68 | def think_thought(self, thought):
69 | return thought
70 |
71 | def think(self, text):
72 | thought = ChatterBotThought()
73 | thought.text = text
74 | return self.think_thought(thought).text
75 |
76 | class ChatterBotThought:
77 |
78 | pass
79 |
80 | #################################################
81 | # Cleverbot impl
82 | #################################################
83 |
84 | class _Cleverbot(ChatterBot):
85 |
86 | def __init__(self, baseUrl, serviceUrl, endIndex):
87 | self.baseUrl = baseUrl
88 | self.serviceUrl = serviceUrl
89 | self.endIndex = endIndex
90 |
91 | def create_session(self):
92 | return _CleverbotSession(self)
93 |
94 | class _CleverbotSession(ChatterBotSession):
95 |
96 | def __init__(self, bot):
97 | self.bot = bot
98 | self.vars = OrderedDict()
99 | #self.vars['start'] = 'y'
100 | self.vars['stimulus'] = ''
101 | self.vars['islearning'] = '1'
102 | self.vars['icognoid'] = 'wsf'
103 | #self.vars['fno'] = '0'
104 | #self.vars['sub'] = 'Say'
105 | #self.vars['cleanslate'] = 'false'
106 | self.cookieJar = cookielib.CookieJar()
107 | self.opener = build_opener(HTTPCookieProcessor(self.cookieJar))
108 | self.opener.open(self.bot.baseUrl)
109 |
110 | def think_thought(self, thought):
111 | self.vars['stimulus'] = thought.text
112 | data = urlencode(self.vars)
113 | data_to_digest = data[9:self.bot.endIndex]
114 | data_digest = hashlib.md5(data_to_digest.encode('utf-8')).hexdigest()
115 | data = data + '&icognocheck=' + data_digest
116 | url_response = self.opener.open(self.bot.serviceUrl, data.encode('utf-8'))
117 | response = str(url_response.read())
118 | response_values = re.split(r'\\r|\r', response)
119 | #self.vars['??'] = _utils_string_at_index(response_values, 0)
120 | self.vars['sessionid'] = _utils_string_at_index(response_values, 1)
121 | self.vars['logurl'] = _utils_string_at_index(response_values, 2)
122 | self.vars['vText8'] = _utils_string_at_index(response_values, 3)
123 | self.vars['vText7'] = _utils_string_at_index(response_values, 4)
124 | self.vars['vText6'] = _utils_string_at_index(response_values, 5)
125 | self.vars['vText5'] = _utils_string_at_index(response_values, 6)
126 | self.vars['vText4'] = _utils_string_at_index(response_values, 7)
127 | self.vars['vText3'] = _utils_string_at_index(response_values, 8)
128 | self.vars['vText2'] = _utils_string_at_index(response_values, 9)
129 | self.vars['prevref'] = _utils_string_at_index(response_values, 10)
130 | #self.vars['??'] = _utils_string_at_index(response_values, 11)
131 | # self.vars['emotionalhistory'] = _utils_string_at_index(response_values, 12)
132 | # self.vars['ttsLocMP3'] = _utils_string_at_index(response_values, 13)
133 | # self.vars['ttsLocTXT'] = _utils_string_at_index(response_values, 14)
134 | # self.vars['ttsLocTXT3'] = _utils_string_at_index(response_values, 15)
135 | # self.vars['ttsText'] = _utils_string_at_index(response_values, 16)
136 | # self.vars['lineRef'] = _utils_string_at_index(response_values, 17)
137 | # self.vars['lineURL'] = _utils_string_at_index(response_values, 18)
138 | # self.vars['linePOST'] = _utils_string_at_index(response_values, 19)
139 | # self.vars['lineChoices'] = _utils_string_at_index(response_values, 20)
140 | # self.vars['lineChoicesAbbrev'] = _utils_string_at_index(response_values, 21)
141 | # self.vars['typingData'] = _utils_string_at_index(response_values, 22)
142 | # self.vars['divert'] = _utils_string_at_index(response_values, 23)
143 | response_thought = ChatterBotThought()
144 | response_thought.text = _utils_string_at_index(response_values, 0)
145 | return response_thought
146 |
147 | #################################################
148 | # Pandorabots impl
149 | #################################################
150 |
151 | class _Pandorabots(ChatterBot):
152 |
153 | def __init__(self, botid):
154 | self.botid = botid
155 |
156 | def create_session(self):
157 | return _PandorabotsSession(self)
158 |
159 | class _PandorabotsSession(ChatterBotSession):
160 |
161 | def __init__(self, bot):
162 | self.vars = {}
163 | self.vars['botid'] = bot.botid
164 | self.vars['custid'] = uuid.uuid1()
165 |
166 | def think_thought(self, thought):
167 | self.vars['input'] = thought.text
168 | data = urlencode(self.vars)
169 | url_response = urlopen('https://www.pandorabots.com/pandora/talk-xml', data)
170 | response = url_response.read()
171 | response_dom = xml.dom.minidom.parseString(response)
172 | response_thought = ChatterBotThought()
173 | that_elements = response_dom.getElementsByTagName('that')
174 | if that_elements is None or len(that_elements) == 0 or that_elements[0] is None:
175 | return ''
176 | that_elements_child_nodes = that_elements[0].childNodes
177 | if that_elements_child_nodes is None or len(that_elements_child_nodes) == 0 or that_elements_child_nodes[0] is None:
178 | return ''
179 | that_elements_child_nodes_data = that_elements_child_nodes[0].data
180 | if that_elements_child_nodes_data is None:
181 | return ''
182 | response_thought.text = that_elements_child_nodes_data.strip()
183 | return response_thought
184 |
185 | #################################################
186 | # Utils
187 | #################################################
188 |
189 | def _utils_string_at_index(strings, index):
190 | if len(strings) > index:
191 | return strings[index]
192 | else:
193 | return ''
--------------------------------------------------------------------------------
/python/chatterbotapitest.py:
--------------------------------------------------------------------------------
1 | from chatterbotapi import ChatterBotFactory, ChatterBotType
2 |
3 | """
4 | chatterbotapi
5 | Copyright (C) 2011 pierredavidbelanger@gmail.com
6 |
7 | This program is free software: you can redistribute it and/or modify
8 | it under the terms of the GNU Lesser General Public License as published by
9 | the Free Software Foundation, either version 3 of the License, or
10 | (at your option) any later version.
11 |
12 | This program is distributed in the hope that it will be useful,
13 | but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | GNU Lesser General Public License for more details.
16 |
17 | You should have received a copy of the GNU Lesser General Public License
18 | along with this program. If not, see .
19 | """
20 |
21 | factory = ChatterBotFactory()
22 |
23 | bot1 = factory.create(ChatterBotType.CLEVERBOT)
24 | bot1session = bot1.create_session()
25 |
26 | bot2 = factory.create(ChatterBotType.PANDORABOTS, 'b0dafd24ee35a477')
27 | bot2session = bot2.create_session()
28 |
29 | s = 'Hi'
30 | while (1):
31 |
32 | print 'bot1> ' + s
33 |
34 | s = bot2session.think(s);
35 | print 'bot2> ' + s
36 |
37 | s = bot1session.think(s);
38 |
--------------------------------------------------------------------------------