Chatbot_Integration - Version 0.0.15

Version Notes

First stable version.

Download this release

Release Info

Developer Pablo
Extension Chatbot_Integration
Version 0.0.15
Comparing to
See all releases


Code changes from version 0.0.9 to 0.0.15

Files changed (30) hide show
  1. app/code/community/Werules/Chatbot/Block/Commands.php +7 -1
  2. app/code/community/Werules/Chatbot/Block/MatchMode.php +22 -0
  3. app/code/community/Werules/Chatbot/Block/Messenger.php +5 -0
  4. app/code/community/Werules/Chatbot/Block/Replies.php +54 -8
  5. app/code/community/Werules/Chatbot/Helper/Data.php +469 -1
  6. app/code/community/Werules/Chatbot/Model/Api/Facebook/Handler.php +1427 -980
  7. app/code/community/Werules/Chatbot/Model/Api/Facebook/Messenger.php +54 -2
  8. app/code/community/Werules/Chatbot/Model/Api/Telegram/Handler.php +1452 -1002
  9. app/code/community/Werules/Chatbot/Model/Api/witAI/witAI.php +33 -11
  10. app/code/community/Werules/Chatbot/Model/Chatdata.php +166 -394
  11. app/code/community/Werules/Chatbot/Model/MatchMode.php +21 -0
  12. app/code/community/Werules/Chatbot/Model/Mysql4/Chatdata.php +1 -1
  13. app/code/community/Werules/Chatbot/Model/Options.php +2 -2
  14. app/code/community/Werules/Chatbot/Model/ReplyMode.php +3 -6
  15. app/code/community/Werules/Chatbot/controllers/SettingsController.php +17 -2
  16. app/code/community/Werules/Chatbot/etc/config.xml +8 -1
  17. app/code/community/Werules/Chatbot/etc/system.xml +237 -42
  18. app/code/community/Werules/Chatbot/sql/chatbot_setup/{mysql4-install-0.0.9.php → mysql4-install-0.0.15.php} +21 -0
  19. app/code/community/Werules/Chatbot/sql/chatbot_setup/mysql4-upgrade-0.0.9-0.0.15.php +32 -0
  20. app/design/adminhtml/default/default/layout/werules_chatbot.xml +9 -0
  21. app/design/frontend/base/default/layout/werules_chatbot.xml +11 -5
  22. app/design/frontend/base/default/template/werules_chatbot_config.phtml +20 -21
  23. app/design/frontend/base/default/template/werules_chatbot_messenger_box.phtml +103 -0
  24. app/design/frontend/base/default/template/werules_chatbot_view.phtml +4 -3
  25. app/locale/en_US/Werules_Chatbot.csv +121 -0
  26. app/locale/pt_BR/Werules_Chatbot.csv +121 -0
  27. js/werules/chatbot/chatbot.js +39 -0
  28. package.xml +9 -2
  29. skin/adminhtml/base/default/css/werules_chatbot/chatbot.css +11 -0
  30. skin/frontend/base/default/images/werules_chatbot/messenger-icon.png +0 -0
app/code/community/Werules/Chatbot/Block/Commands.php CHANGED
@@ -16,7 +16,13 @@ class Werules_Chatbot_Block_Commands extends Mage_Adminhtml_Block_System_Config_
16
  ));
17
  $this->addColumn('command_code', array(
18
  'label' => Mage::helper('core')->__('Command Code'),
19
- 'style' => 'width: 100%'
 
 
 
 
 
 
20
  ));
21
 
22
  $this->_addAfter = false;
16
  ));
17
  $this->addColumn('command_code', array(
18
  'label' => Mage::helper('core')->__('Command Code'),
19
+ 'style' => 'width: 100%',
20
+ 'class' => 'validate-no-html-tags'
21
+ ));
22
+ $this->addColumn('command_alias_list', array(
23
+ 'label' => Mage::helper('core')->__('Command Alias (Separated by Comma)'),
24
+ 'style' => 'width: 100%',
25
+ 'class' => 'validate-no-html-tags'
26
  ));
27
 
28
  $this->_addAfter = false;
app/code/community/Werules/Chatbot/Block/MatchMode.php ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Werules_Chatbot_Block_MatchMode extends Mage_Core_Block_Html_Select
3
+ {
4
+ public function _toHtml()
5
+ {
6
+ $options = Mage::getSingleton('chatbot/matchMode')->toOptionArray();
7
+ if (!$this->getOptions())
8
+ {
9
+ foreach ($options as $option)
10
+ {
11
+ $this->addOption($option['value'], $option['label']);
12
+ }
13
+ }
14
+
15
+ return parent::_toHtml();
16
+ }
17
+
18
+ public function setInputName($value)
19
+ {
20
+ return $this->setName($value);
21
+ }
22
+ }
app/code/community/Werules/Chatbot/Block/Messenger.php ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
1
+ <?php
2
+ class Werules_Chatbot_Block_Messenger extends Mage_Core_Block_Template
3
+ {
4
+ // nd
5
+ }
app/code/community/Werules/Chatbot/Block/Replies.php CHANGED
@@ -3,12 +3,18 @@ class Werules_Chatbot_Block_Replies extends Mage_Adminhtml_Block_System_Config_F
3
  {
4
  protected $_itemRendererEnableCase;
5
  protected $_itemRendererEnableProcessing;
 
6
  protected $_itemRendererReplyMode;
 
7
 
8
  public function _prepareToRender()
9
  {
 
 
 
 
10
  $this->addColumn('match_sintax', array(
11
- 'label' => Mage::helper('core')->__('Match Text or Regular Expression'),
12
  'style' => 'width: 250px'
13
  ));
14
  $this->addColumn('match_case', array(
@@ -19,10 +25,6 @@ class Werules_Chatbot_Block_Replies extends Mage_Adminhtml_Block_System_Config_F
19
  'label' => Mage::helper('core')->__('Stop Processing'),
20
  'renderer' => $this->_getRendererEnableProcessing()
21
  ));
22
- $this->addColumn('reply_mode', array(
23
- 'label' => Mage::helper('core')->__('Reply Mode'),
24
- 'renderer' => $this->_getRendererReplyMode()
25
- ));
26
  $this->addColumn('similarity', array(
27
  'label' => Mage::helper('core')->__('Similarity (%)'),
28
  'style' => 'width: 100%',
@@ -30,10 +32,18 @@ class Werules_Chatbot_Block_Replies extends Mage_Adminhtml_Block_System_Config_F
30
  //'maxlength' => '3',
31
  'class' => 'input-number validate-number validate-number-range number-range-1-100'
32
  ));
 
 
 
 
33
  $this->addColumn('reply_phrase', array(
34
- 'label' => Mage::helper('core')->__('Reply'),
35
  'style' => 'width: 250px'
36
  ));
 
 
 
 
37
 
38
  $this->_addAfter = false;
39
  $this->_addButtonLabel = Mage::helper('core')->__('Add');
@@ -72,15 +82,43 @@ class Werules_Chatbot_Block_Replies extends Mage_Adminhtml_Block_System_Config_F
72
  if (!$this->_itemRendererReplyMode)
73
  {
74
  $this->_itemRendererReplyMode = $this->getLayout()->createBlock(
75
- //'werules_chatbot/enable',
76
  'werules_chatbot/replyMode',
77
  '',
78
  array('is_render_to_js_template' => true)
79
- )->setExtraParams("style='width: auto;'");
 
80
  }
81
  return $this->_itemRendererReplyMode;
82
  }
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  protected function _prepareArrayRow(Varien_Object $row)
85
  {
86
  $row->setData(
@@ -91,6 +129,14 @@ class Werules_Chatbot_Block_Replies extends Mage_Adminhtml_Block_System_Config_F
91
  'option_extra_attr_' . $this->_getRendererEnableProcessing()->calcOptionHash($row->getData('stop_processing')),
92
  'selected="selected"'
93
  );
 
 
 
 
 
 
 
 
94
  $row->setData(
95
  'option_extra_attr_' . $this->_getRendererReplyMode()->calcOptionHash($row->getData('reply_mode')),
96
  'selected="selected"'
3
  {
4
  protected $_itemRendererEnableCase;
5
  protected $_itemRendererEnableProcessing;
6
+ protected $_itemRendererMatchMode;
7
  protected $_itemRendererReplyMode;
8
+ protected $_itemRendererCommandCode;
9
 
10
  public function _prepareToRender()
11
  {
12
+ $this->addColumn('match_mode', array(
13
+ 'label' => Mage::helper('core')->__('Match Mode'),
14
+ 'renderer' => $this->_getRendererMatchMode()
15
+ ));
16
  $this->addColumn('match_sintax', array(
17
+ 'label' => Mage::helper('core')->__('Match Text, Regex or wit.ai entity'),
18
  'style' => 'width: 250px'
19
  ));
20
  $this->addColumn('match_case', array(
25
  'label' => Mage::helper('core')->__('Stop Processing'),
26
  'renderer' => $this->_getRendererEnableProcessing()
27
  ));
 
 
 
 
28
  $this->addColumn('similarity', array(
29
  'label' => Mage::helper('core')->__('Similarity (%)'),
30
  'style' => 'width: 100%',
32
  //'maxlength' => '3',
33
  'class' => 'input-number validate-number validate-number-range number-range-1-100'
34
  ));
35
+ $this->addColumn('reply_mode', array(
36
+ 'label' => Mage::helper('core')->__('Reply Mode'),
37
+ 'renderer' => $this->_getRendererReplyMode()
38
+ ));
39
  $this->addColumn('reply_phrase', array(
40
+ 'label' => Mage::helper('core')->__('Reply Text'),
41
  'style' => 'width: 250px'
42
  ));
43
+ $this->addColumn('command_id', array(
44
+ 'label' => Mage::helper('core')->__('Command'),
45
+ 'renderer' => $this->_getRendererCommandCode()
46
+ ));
47
 
48
  $this->_addAfter = false;
49
  $this->_addButtonLabel = Mage::helper('core')->__('Add');
82
  if (!$this->_itemRendererReplyMode)
83
  {
84
  $this->_itemRendererReplyMode = $this->getLayout()->createBlock(
 
85
  'werules_chatbot/replyMode',
86
  '',
87
  array('is_render_to_js_template' => true)
88
+ )->setExtraParams("style='width: 140px;'");
89
+ $this->_itemRendererReplyMode->setExtraParams("onChange='werulesTogleReplyMode(this)'");
90
  }
91
  return $this->_itemRendererReplyMode;
92
  }
93
 
94
+ protected function _getRendererCommandCode()
95
+ {
96
+ if (!$this->_itemRendererCommandCode)
97
+ {
98
+ $this->_itemRendererCommandCode = $this->getLayout()->createBlock(
99
+ 'werules_chatbot/commandsSelect',
100
+ '',
101
+ array('is_render_to_js_template' => true)
102
+ )->setExtraParams("disabled='true'");
103
+ }
104
+ return $this->_itemRendererCommandCode;
105
+ }
106
+
107
+ protected function _getRendererMatchMode()
108
+ {
109
+ if (!$this->_itemRendererMatchMode)
110
+ {
111
+ $this->_itemRendererMatchMode = $this->getLayout()->createBlock(
112
+ //'werules_chatbot/enable',
113
+ 'werules_chatbot/matchMode',
114
+ '',
115
+ array('is_render_to_js_template' => true)
116
+ )->setExtraParams("style='width: auto;'");
117
+ $this->_itemRendererMatchMode->setExtraParams("onChange='werulesTogleMatchMode(this)'");
118
+ }
119
+ return $this->_itemRendererMatchMode;
120
+ }
121
+
122
  protected function _prepareArrayRow(Varien_Object $row)
123
  {
124
  $row->setData(
129
  'option_extra_attr_' . $this->_getRendererEnableProcessing()->calcOptionHash($row->getData('stop_processing')),
130
  'selected="selected"'
131
  );
132
+ $row->setData(
133
+ 'option_extra_attr_' . $this->_getRendererMatchMode()->calcOptionHash($row->getData('match_mode')),
134
+ 'selected="selected"'
135
+ );
136
+ $row->setData(
137
+ 'option_extra_attr_' . $this->_getRendererCommandCode()->calcOptionHash($row->getData('command_id')),
138
+ 'selected="selected"'
139
+ );
140
  $row->setData(
141
  'option_extra_attr_' . $this->_getRendererReplyMode()->calcOptionHash($row->getData('reply_mode')),
142
  'selected="selected"'
app/code/community/Werules/Chatbot/Helper/Data.php CHANGED
@@ -1,5 +1,473 @@
1
  <?php
2
  class Werules_Chatbot_Helper_Data extends Mage_Core_Helper_Abstract
3
  {
4
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  }
1
  <?php
2
  class Werules_Chatbot_Helper_Data extends Mage_Core_Helper_Abstract
3
  {
4
+ // ----- CONSTANTS ----------
5
+
6
+ // STRINGS
7
+ public $_tgBot = "telegram";
8
+ public $_fbBot = "facebook";
9
+ public $_wappBot = "whatsapp";
10
+ public $_wechatBot = "wechat";
11
+
12
+ // CONVERSATION STATES
13
+ public $_startState = 0;
14
+ public $_listCategoriesState = 1;
15
+ public $_listProductsState = 2;
16
+ public $_searchState = 3;
17
+ public $_loginState = 4;
18
+ public $_listOrdersState = 5;
19
+ public $_reorderState = 6;
20
+ public $_add2CartState = 7;
21
+ public $_checkoutState = 9;
22
+ public $_trackOrderState = 10;
23
+ public $_supportState = 11;
24
+ public $_sendEmailState = 12;
25
+ public $_clearCartState = 13;
26
+
27
+ // ADMIN STATES
28
+ public $_replyToSupportMessageState = 14;
29
+
30
+ // COMMANDS
31
+ public $_cmdList =
32
+ "
33
+ start,
34
+ list_categories,
35
+ search,
36
+ login,
37
+ list_orders,
38
+ reorder,
39
+ add2cart,
40
+ checkout,
41
+ clear_cart,
42
+ track_order,
43
+ support,
44
+ send_email,
45
+ cancel,
46
+ help,
47
+ about,
48
+ logout,
49
+ register
50
+ ";
51
+ public $_startCmd = array();
52
+ public $_listCategoriesCmd = array();
53
+ public $_searchCmd = array();
54
+ public $_loginCmd = array();
55
+ public $_listOrdersCmd = array();
56
+ public $_reorderCmd = array();
57
+ public $_add2CartCmd = array();
58
+ public $_checkoutCmd = array();
59
+ public $_clearCartCmd = array();
60
+ public $_trackOrderCmd = array();
61
+ public $_supportCmd = array();
62
+ public $_sendEmailCmd = array();
63
+ public $_cancelCmd = array();
64
+ public $_helpCmd = array();
65
+ public $_aboutCmd = array();
66
+ public $_logoutCmd = array();
67
+ public $_registerCmd = array();
68
+
69
+ // admin cmds
70
+ // protected $adminCmdList =
71
+ // "
72
+ // messagetoall,
73
+ // endsupport,
74
+ // blocksupport
75
+ // ";
76
+ public $_admSendMessage2AllCmd = "messagetoall";
77
+ public $_admEndSupportCmd = "endsupport";
78
+ public $_admBlockSupportCmd = "blocksupport";
79
+ public $_admEnableSupportCmd = "enablesupport";
80
+ public $_admEnableBotCmd = "enablebot";
81
+ public $_admDisableBotCmd = "disablebot";
82
+ public $_admListCmds = "admincommands";
83
+
84
+ // REGEX
85
+ public $_unallowedCharacters = "/[^A-Za-z0-9 _]/";
86
+
87
+ // DEFAULT MESSAGES
88
+ public $_errorMessage = "";
89
+ public $_cancelMessage = "";
90
+ public $_canceledMessage = "";
91
+ public $_loginFirstMessage = "";
92
+ public $_positiveMessages = array();
93
+
94
+ // URLS
95
+ public $_tgUrl = "https://t.me/";
96
+ public $_fbUrl = "https://m.me/";
97
+ // protected $_wappUrl = "";
98
+ // protected $_wechatUrl = "";
99
+
100
+ // public function transcribeAudio()
101
+ // {
102
+ // $googleSpeechURL = "https://speech.googleapis.com/v1beta1/speech:syncrecognize?key=xxxxxxxxxxxx";
103
+ // $upload = file_get_contents("1.wav");
104
+ // $fileData = base64_encode($upload);
105
+ //
106
+ // $data = array(
107
+ // "config" => array(
108
+ // "encoding" => "LINEAR16",
109
+ // "sample_rate" => 16000,
110
+ // "language_code" => "pt-BR"
111
+ // ),
112
+ // "audio" => array(
113
+ // "content" => base64_encode($fileData)
114
+ // )
115
+ // );
116
+ //
117
+ // $dataString = json_encode($data);
118
+ //
119
+ // $ch = curl_init($googleSpeechURL);
120
+ // curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
121
+ // curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
122
+ // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
123
+ // curl_setopt($ch, CURLOPT_HTTPHEADER, array(
124
+ // 'Content-Type: application/json',
125
+ // 'Content-Length: ' . strlen($dataString))
126
+ // );
127
+ //
128
+ // $result = curl_exec($ch);
129
+ //
130
+ // return json_decode($result, true);
131
+ // }
132
+
133
+ public function getContent($url)
134
+ {
135
+ $ch = curl_init();
136
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
137
+ curl_setopt($ch, CURLOPT_URL, $url);
138
+ $data = curl_exec($ch);
139
+ curl_close($ch);
140
+ if ($data)
141
+ return $data;
142
+
143
+ return null;
144
+ }
145
+
146
+ public function convertOggToMp3($filePath, $fileName)
147
+ {
148
+ // install ffmpeg by typoing sudo apt-get install ffmpeg
149
+ $output = $filePath . "output.mp3";
150
+ if (!file_exists($filePath . $fileName))
151
+ return null;
152
+
153
+ $ffmpeg = exec('which ffmpeg');
154
+ $ffmpegCmd = $ffmpeg . " -i " . $filePath . $fileName . " -acodec libmp3lame " . $output;
155
+ exec($ffmpegCmd);
156
+
157
+ if (!file_exists($output))
158
+ return null;
159
+
160
+ return $output;
161
+ }
162
+
163
+ // excerpt text
164
+ public function excerpt($text, $size)
165
+ {
166
+ if (strlen($text) > $size)
167
+ {
168
+ $text = substr($text, 0, $size);
169
+ $text = substr($text, 0, strrpos($text, " "));
170
+ $etc = " ...";
171
+ $text = $text . $etc;
172
+ }
173
+ return $text;
174
+ }
175
+
176
+ // get a value from a command, eg.: /add_product123 -> 123 is the ID of the product
177
+ public function getCommandValue($text, $cmd)
178
+ {
179
+ if (strlen($text) > strlen($cmd))
180
+ return substr($text, strlen($cmd), strlen($text));
181
+ return null;
182
+ }
183
+
184
+ // check if the message sent by the customer is a valid/enabled command
185
+ public function checkCommand($text, $cmd)
186
+ {
187
+ if ($cmd['command'])
188
+ {
189
+ $t = strtolower($text);
190
+ if ($t == $cmd['command'])
191
+ return true;
192
+ else if ($cmd['alias'])
193
+ {
194
+ //$alias = explode(",", $cmd['alias']);
195
+ $alias = $cmd['alias'];
196
+ if (is_array($alias))
197
+ {
198
+ foreach ($alias as $al)
199
+ {
200
+ if (!empty($al))
201
+ if (strpos($t, $al) !== false)
202
+ return true;
203
+ }
204
+ }
205
+ }
206
+ }
207
+
208
+ return false;
209
+ }
210
+
211
+ // check if a message starts with something
212
+ public function startsWith($haystack, $needle)
213
+ {
214
+ if ($needle)
215
+ return substr($haystack, 0, strlen($needle)) == $needle;
216
+ return false;
217
+ }
218
+
219
+ // check if a message ends with something
220
+ public function endsWith($haystack, $needle)
221
+ {
222
+ $length = strlen($needle);
223
+ if ($length == 0)
224
+ return true;
225
+
226
+ return (substr($haystack, -$length) === $needle);
227
+ }
228
+
229
+ // return all orders id from a customer id
230
+ public function getOrdersIdsFromCustomer($customerId)
231
+ {
232
+ $ids = array();
233
+ $orders = Mage::getResourceModel('sales/order_collection')
234
+ ->addFieldToSelect('*')
235
+ ->addFieldToFilter('customer_id', $customerId) // not a problem if customer dosen't exist
236
+ ->setOrder('created_at', 'desc');
237
+ foreach ($orders as $_order)
238
+ {
239
+ array_push($ids, $_order->getId());
240
+ }
241
+ if ($ids)
242
+ return $ids;
243
+ return false;
244
+ }
245
+
246
+ // return all ids from a product search by text
247
+ public function getProductIdsBySearch($searchString)
248
+ {
249
+ // Code to Search Product by $searchstring and get Product IDs
250
+ $productCollection = Mage::getResourceModel('catalog/product_collection')
251
+ ->addAttributeToSelect('*')
252
+ ->addAttributeToFilter('visibility', 4)
253
+ ->addAttributeToFilter('type_id', 'simple')
254
+ ->addAttributeToFilter(
255
+ array(
256
+ array('attribute' => 'sku', 'like' => '%' . $searchString .'%'),
257
+ array('attribute' => 'name', 'like' => '%' . $searchString .'%')
258
+ )
259
+ );
260
+ //->getAllIds();
261
+ Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($productCollection);
262
+ $productIDs = $productCollection->getAllIds();
263
+
264
+ if (!empty($productIDs))
265
+ return $productIDs;
266
+
267
+ return false;
268
+ }
269
+
270
+ // return image content to be sent as message
271
+ public function loadImageContent($productID)
272
+ {
273
+ $imagepath = Mage::getModel('catalog/product')->load($productID)->getSmallImage();
274
+ if ($imagepath && $imagepath != "no_selection")
275
+ {
276
+ $absolutePath =
277
+ Mage::getBaseDir('media') .
278
+ DS . "catalog" . DS . "product" .
279
+ $imagepath;
280
+
281
+ return curl_file_create($absolutePath, 'image/jpg');
282
+ }
283
+ return null;
284
+ }
285
+
286
+ // TELEGRAM FUNCTIONS
287
+ public function getTelegramBotUsername()
288
+ {
289
+ $tgUsername = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_bot_username');
290
+ if (!empty($tgUsername))
291
+ return $tgUsername;
292
+
293
+ $tgApiKey = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_api_key');
294
+ if (!empty($tgApiKey))
295
+ {
296
+ $getMe = "https://api.telegram.org/bot" . $tgApiKey . "/getMe";
297
+ $response = json_decode(file_get_contents($getMe), true);
298
+ if (isset($response["ok"]))
299
+ return $response["result"]["username"];
300
+ }
301
+
302
+ return null;
303
+ }
304
+
305
+ public function prepareTelegramOrderMessages($orderID) // TODO add link to product name
306
+ {
307
+ $order = Mage::getModel('sales/order')->load($orderID);
308
+ if ($order->getId())
309
+ {
310
+ $message = Mage::helper('core')->__("Order") . " # " . $order->getIncrementId() . "\n\n";
311
+ $items = $order->getAllVisibleItems();
312
+ foreach($items as $item)
313
+ {
314
+ $message .= (int)$item->getQtyOrdered() . "x " .
315
+ $item->getName() . "\n" .
316
+ Mage::helper('core')->__("Price") . ": " . Mage::helper('core')->currency($item->getPrice(), true, false) . "\n\n";
317
+ }
318
+ $message .= Mage::helper('core')->__("Total") . ": " . Mage::helper('core')->currency($order->getGrandTotal(), true, false) . "\n" .
319
+ Mage::helper('core')->__("Zipcode") . ": " . $order->getShippingAddress()->getPostcode();
320
+ return $message;
321
+ }
322
+ return null;
323
+ }
324
+
325
+ public function prepareTelegramProdMessages($productID) // TODO add link to product name
326
+ {
327
+ $product = Mage::getModel('catalog/product')->load($productID);
328
+ if ($product->getId())
329
+ {
330
+ if ($product->getStockItem()->getIsInStock() > 0)
331
+ {
332
+ $mageHelper = Mage::helper('core');
333
+ $chatbotHelper = Mage::helper('werules_chatbot');
334
+ $message = $product->getName() . "\n" .
335
+ $mageHelper->__("Price") . ": " . Mage::helper('core')->currency($product->getPrice(), true, false) . "\n" .
336
+ $chatbotHelper->excerpt($product->getShortDescription(), 60);
337
+ return $message;
338
+ }
339
+ }
340
+ return null;
341
+ }
342
+
343
+ // check if it's a valid Telegram command
344
+ public function validateTelegramCmd($cmd)
345
+ {
346
+ if ($cmd == "/")
347
+ return null;
348
+ return $cmd;
349
+ }
350
+
351
+ // FACEBOOK FUNCTIONS
352
+ public function getFacebookPageChatID()
353
+ {
354
+ $fbUsername = Mage::getStoreConfig('chatbot_enable/facebook_config/facebook_page_username');
355
+ if (!empty($fbUsername))
356
+ return $fbUsername;
357
+
358
+ $fbApiKey = Mage::getStoreConfig('chatbot_enable/facebook_config/facebook_api_key');
359
+ if (!empty($fbApiKey))
360
+ {
361
+ $getMe = "https://graph.facebook.com/v2.8/me?access_token=" . $fbApiKey;
362
+ $response = json_decode(file_get_contents($getMe), true);
363
+ if (!empty($response))
364
+ return $response["id"];
365
+ }
366
+
367
+ return null;
368
+ }
369
+
370
+ public function prepareFacebookProdMessages($productID) // TODO add link to product name
371
+ {
372
+ $product = Mage::getModel('catalog/product')->load($productID);
373
+ if ($product->getId())
374
+ {
375
+ if ($product->getStockItem()->getIsInStock() > 0)
376
+ {
377
+ $chatbotHelper = Mage::helper('werules_chatbot');
378
+ $message = $product->getName() . "\n" .
379
+ $chatbotHelper->excerpt($product->getShortDescription(), 60);
380
+ return $message;
381
+ }
382
+ }
383
+ return null;
384
+ }
385
+
386
+ // public function prepareFacebookOrderMessages($orderID) // TODO add link to product name
387
+ // {
388
+ // $order = Mage::getModel('sales/order')->load($orderID);
389
+ // if ($order->getId())
390
+ // {
391
+ // $message = Mage::helper('core')->__("Order") . " # " . $order->getIncrementId() . "\n\n";
392
+ // $items = $order->getAllVisibleItems();
393
+ // foreach($items as $item)
394
+ // {
395
+ // $message .= (int)$item->getQtyOrdered() . "x " .
396
+ // $item->getName() . "\n" .
397
+ // Mage::helper('core')->__("Price") . ": " . Mage::helper('core')->currency($item->getPrice(), true, false) . "\n\n";
398
+ // }
399
+ // $message .= Mage::helper('core')->__("Total") . ": " . Mage::helper('core')->currency($order->getGrandTotal(), true, false) . "\n" .
400
+ // Mage::helper('core')->__("Zipcode") . ": " . $order->getShippingAddress()->getPostcode();
401
+ //
402
+ // return $message;
403
+ // }
404
+ // return null;
405
+ // }
406
+
407
+ public function prepareFacebookOrderPayload($orderID) // TODO add link to product name
408
+ {
409
+ $order = Mage::getModel('sales/order')->load($orderID);
410
+ if ($order->getId())
411
+ {
412
+ $chatbotHelper = Mage::helper('werules_chatbot');
413
+ $orderNumber = $order->getIncrementId();
414
+ $customerName = $order->getCustomerName();
415
+ $orderUrl = Mage::getUrl('sales/order/view', array('order_id' => $orderNumber));
416
+ $currency = $order->getOrderCurrencyCode();
417
+ $createdAt = strtotime($order->getCreatedAt());
418
+ $elements = array();
419
+ $items = $order->getAllVisibleItems();
420
+ foreach($items as $item)
421
+ {
422
+ $product = Mage::getModel('catalog/product')->load($item->getProductId());
423
+ $element = array(
424
+ 'title' => $item->getName(),
425
+ 'subtitle' => $chatbotHelper->excerpt($item->getShortDescription(), 30),
426
+ 'quantity' => (int)$item->getQtyOrdered(),
427
+ 'price' => $item->getPrice(),
428
+ 'currency' => $currency,
429
+ 'image_url' => $product->getSmallImageUrl()
430
+ );
431
+ array_push($elements, $element);
432
+ }
433
+
434
+ $shippingAddress = $order->getShippingAddress();
435
+ $streetOne = $shippingAddress->getStreet()[0];
436
+ $streetTwo = "";
437
+ if (count($shippingAddress->getStreet()) > 1)
438
+ $streetTwo = $shippingAddress->getStreet()[1];
439
+ $address = array(
440
+ 'street_1' => $streetOne,
441
+ 'street_2' => $streetTwo,
442
+ 'city' => $shippingAddress->getCity(),
443
+ 'postal_code' => $shippingAddress->getPostcode(),
444
+ 'state' => $shippingAddress->getRegion(),
445
+ 'country' => $shippingAddress->getCountryId()
446
+ );
447
+
448
+ $summary = array(
449
+ 'subtotal' => $order->getSubtotal(),
450
+ 'shipping_cost' => $order->getShippingAmount(),
451
+ 'total_tax' => $order->getTaxAmount(),
452
+ 'total_cost' => $order->getGrandTotal()
453
+ );
454
+
455
+ $payload = array(
456
+ 'template_type' => 'receipt',
457
+ 'recipient_name' => $customerName,
458
+ 'order_number' => $orderNumber,
459
+ 'currency' => $currency,
460
+ 'payment_method' => $order->getPayment()->getMethodInstance()->getTitle(),
461
+ 'order_url' => $orderUrl,
462
+ 'timestamp' => $createdAt,
463
+ 'elements' => $elements,
464
+ 'address' => $address,
465
+ 'summary' => $summary,
466
+ );
467
+
468
+ return $payload;
469
+ }
470
+
471
+ return null;
472
+ }
473
  }
app/code/community/Werules/Chatbot/Model/Api/Facebook/Handler.php CHANGED
@@ -1,54 +1,72 @@
1
  <?php
2
- include("Messenger.php");
 
3
  //$api_path = Mage::getModuleDir('', 'Werules_Chatbot') . DS . "Model" . DS . "Api" . DS . "witAI" . DS;
4
- //include($api_path . "witAI.php");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
  class Werules_Chatbot_Model_Api_Facebook_Handler extends Werules_Chatbot_Model_Chatdata
7
  {
 
 
8
  public function _construct()
9
  {
10
  //parent::_construct();
11
  //$this->_init('chatbot/api_facebook_handler'); // this is location of the resource file.
 
 
 
12
  }
13
 
14
- public function foreignMessageFromSupport($chat_id, $text)
15
  {
 
 
 
16
  // Instances the model class
17
  $chatdata = Mage::getModel('chatbot/chatdata');
18
- $chatdata->load($chat_id, 'facebook_chat_id');
19
- $chatdata->_apiType = $chatdata->_fbBot;
20
 
21
  if (is_null($chatdata->getFacebookChatId()))
22
  { // should't happen
23
  return false;
24
  }
25
 
26
- // mage helper
27
- $mageHelper = Mage::helper('core');
28
-
29
- $apiKey = $chatdata->getApikey($chatdata->_apiType); // get facebook bot api
30
- if ($apiKey)
31
  {
32
- $facebook = new Messenger($apiKey);
33
- $message = $mageHelper->__("Message from support") . ":\n" . $text;
34
- $facebook->sendMessage($chat_id, $message);
35
  return true;
36
  }
37
 
38
  return false;
39
  }
40
 
41
- public function facebookHandler($apiKey)
42
  {
43
- if (empty($apiKey)) // if no apiKey available, break proccess
44
- return "";
45
-
46
  // Instances the Facebook class
47
- $facebook = new Messenger($apiKey);
48
 
49
- // Instances the witAI class
50
- // $witapi = Mage::getStoreConfig('chatbot_enable/witai_config/enable_witai');
51
- // $witai = new witAI($witapi);
52
 
53
  // hub challenge
54
  $hubToken = Mage::getStoreConfig('chatbot_enable/general_config/your_custom_key');
@@ -57,677 +75,623 @@
57
  return $verify;
58
 
59
  // Take text and chat_id from the message
60
- $originalText = $facebook->Text();
61
- $chatId = $facebook->ChatID();
62
- $messageId = $facebook->MessageID();
63
  $isEcho = $facebook->getEcho();
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  // configs
66
- //$enable_witai = Mage::getStoreConfig('chatbot_enable/witai_config/enable_witai');
67
  $enabledBot = Mage::getStoreConfig('chatbot_enable/facebook_config/enable_bot');
68
  $enableReplies = Mage::getStoreConfig('chatbot_enable/facebook_config/enable_default_replies');
69
  $enablePredict = Mage::getStoreConfig('chatbot_enable/facebook_config/enable_predict_commands');
70
- $enableLog = Mage::getStoreConfig('chatbot_enable/general_config/enable_post_log');
71
  $enableEmptyCategoriesListing = Mage::getStoreConfig('chatbot_enable/general_config/list_empty_categories');
72
  $enableFinalMessage2Support = Mage::getStoreConfig('chatbot_enable/general_config/enable_support_final_message');
73
  $supportGroupId = Mage::getStoreConfig('chatbot_enable/facebook_config/facebook_support_group');
74
  $showMore = 0;
75
  $moreOrders = false;
 
76
  $listingLimit = 5;
77
  $listMoreCategories = "show_more_list_cat_";
78
  $listMoreSearch = "show_more_search_prod_";
79
  $listMoreOrders = "show_more_order_";
80
  $replyToCustomerMessage = "reply_to_message";
 
 
 
81
 
82
- if ($enableLog == "1") // log all posts
83
- Mage::log("Post Data:\n" . var_export($facebook->RawData(), true) . "\n\n", null, 'chatbot_facebook.log');
84
-
85
- // checking for payload
86
- $isPayload = false;
87
- $payloadContent = $facebook->getPayload();
88
- if ($payloadContent && empty($originalText))
89
- {
90
- $isPayload = true;
91
- $originalText = $payloadContent;
92
- $messageId = $facebook->getMessageTimestamp();
93
- }
94
 
95
- if (!empty($originalText) && !empty($chatId) && $isEcho != "true")
96
- {
97
- // Instances facebook user details
98
- $userData = $facebook->UserData($chatId);
99
- $username = null;
100
- if (!empty($userData))
101
- $username = $userData['first_name'];
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
- $text = strtolower($originalText);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
- // Instances the model class
106
- $chatdata = Mage::getModel('chatbot/chatdata')->load($chatId, 'facebook_chat_id');
107
- $chatdata->_apiType = $chatdata->_fbBot;
108
 
109
- if ($messageId == $chatdata->getFacebookMessageId()) // prevents to reply the same request twice
110
- return $facebook->respondSuccess();
111
- else if ($chatdata->getFacebookChatId())
112
- $chatdata->updateChatdata('facebook_message_id', $messageId); // if this fails, it may send the same message twice
 
 
 
 
 
113
 
114
- // bot enabled/disabled
115
- if ($enabledBot != "1")
116
  {
117
- $disabledMessage = Mage::getStoreConfig('chatbot_enable/facebook_config/disabled_message');
118
- if (!empty($disabledMessage))
119
- $facebook->sendMessage($chatId, $disabledMessage);
120
- return $facebook->respondSuccess();
 
121
  }
 
122
 
123
- // send feedback to user
124
- $facebook->sendChatAction($chatId, "typing_on");
 
 
 
 
 
 
 
 
 
 
 
 
 
125
 
126
- // payload handler, may change the conversation state
127
- if ($chatdata->getFacebookConvState() == $chatdata->_listProductsState || $chatdata->getFacebookConvState() == $chatdata->_listOrdersState) // listing products
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  {
129
- if ($chatdata->startsWith($text, $listMoreCategories)) // old checkCommandWithValue
130
  {
131
- if ($chatdata->updateChatdata('facebook_conv_state', $chatdata->_listCategoriesState))
132
- {
133
- $value = $this->getCommandValue($text, $listMoreCategories);
134
- $arr = explode(",", $value);
135
- $text = $arr[0];
136
- $showMore = (int)$arr[1];
137
- }
138
  }
139
- else if ($chatdata->startsWith($text, $listMoreSearch)) // old checkCommandWithValue
 
 
 
140
  {
141
- if ($chatdata->updateChatdata('facebook_conv_state', $chatdata->_searchState))
142
- {
143
- $value = $this->getCommandValue($text, $listMoreSearch);
144
- $arr = explode(",", $value);
145
- $text = $arr[0];
146
- $showMore = (int)$arr[1];
147
- }
148
  }
149
- else if ($chatdata->startsWith($text, $listMoreOrders)) // old checkCommandWithValue
 
 
 
150
  {
151
- if ($chatdata->updateChatdata('facebook_conv_state', $chatdata->_listOrdersState))
152
- {
153
- $value = $this->getCommandValue($text, $listMoreOrders);
154
- $showMore = (int)$value; // get where listing stopped
155
- $moreOrders = true;
156
- }
157
  }
158
- // else
159
- // $chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState);
160
  }
 
 
 
161
 
162
- // instances conversation state
163
- $conversationState = $chatdata->getFacebookConvState();
164
 
165
- // mage helper
166
- $mageHelper = Mage::helper('core');
167
 
168
- // handle admin stuff
169
- //$isAdmin = $chatdata->getIsAdmin();
170
- // if it's the admin chat id
171
- if ($chatId == $supportGroupId)// || $isAdmin == "1")
172
- {
173
  // if ($isAdmin == "0") // set user as admin
174
  // $chatdata->updateChatdata('is_admin', "1");
175
 
176
- if ($conversationState == $chatdata->_replyToSupportMessageState) // check if admin is replying to a customer
 
 
 
177
  {
178
- $customerChatId = $chatdata->getFacebookSupportReplyChatId(); // get customer chat id
179
- if (!empty($customerChatId))
180
- {
181
- $chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState); // set admin to _startState
182
- $customerData = Mage::getModel('chatbot/chatdata')->load($customerChatId, 'facebook_chat_id'); // load chatdata model
183
 
184
- if ($customerData->getFacebookConvState() != $chatdata->_supportState) // if user isn't on support, switch to support
185
- {
186
- // TODO IMPORTANT remember to switch off all other supports
187
- $customerData->updateChatdata('facebook_conv_state', $chatdata->_supportState);
188
- $facebook->sendMessage($customerChatId, $mageHelper->__("You're now on support mode."));
189
- }
190
- $facebook->sendMessage($customerChatId, $mageHelper->__("Message from support") . ":\n" . $text); // send message to customer TODO
191
- $facebook->sendMessage($chatId, $mageHelper->__("Message sent."));
192
  }
193
- return $facebook->respondSuccess();
 
194
  }
195
- else if ($chatdata->startsWith($text, $chatdata->_admSendMessage2AllCmd)) // old checkCommandWithValue
 
 
 
 
 
196
  {
197
- $message = trim($chatdata->getCommandValue($text, $chatdata->_admSendMessage2AllCmd));
198
- if (!empty($message))
199
  {
200
- $chatbotcollection = Mage::getModel('chatbot/chatdata')->getCollection();
201
- foreach($chatbotcollection as $chatbot)
202
- {
203
- $fbChatId = $chatbot->getFacebookChatId();
204
- if ($fbChatId)
205
- $facebook->sendMessage($fbChatId, $message); // $magehelper->__("Message from support") . ":\n" .
206
- }
207
- $facebook->sendMessage($chatId, $mageHelper->__("Message sent."));
208
  }
209
- else
210
- $facebook->sendMessage($chatId, $mageHelper->__("Please use") . ' "' . $chatdata->_admSendMessage2AllCmd . " " . $mageHelper->__("your message here.") . '"');
211
  }
212
- else if ($isPayload)
 
 
 
 
 
213
  {
214
- if ($chatdata->startsWith($text, $chatdata->_admEndSupportCmd)) // finish customer support // old checkCommandWithValue
215
- {
216
- $customerChatId = trim($chatdata->getCommandValue($text, $chatdata->_admEndSupportCmd)); // get customer chatId from payload
217
- $customerData = Mage::getModel('chatbot/chatdata')->load($customerChatId, 'facebook_chat_id'); // load chatdata model
218
- $customerData->updateChatdata('facebook_conv_state', $chatdata->_startState); // update conversation state
219
 
220
- $facebook->sendMessage($chatId, $mageHelper->__("Done. The customer is no longer on support."));
221
- $facebook->sendMessage($customerChatId, $mageHelper->__("Support ended."));
 
 
 
222
  }
223
- else if ($chatdata->startsWith($text, $chatdata->_admBlockSupportCmd)) // block user from using support // old checkCommandWithValue
 
 
 
 
 
 
 
224
  {
225
- $customerChatId = trim($chatdata->getCommandValue($text, $chatdata->_admBlockSupportCmd)); // get customer chatId from payload
226
- $customerData = Mage::getModel('chatbot/chatdata')->load($customerChatId, 'facebook_chat_id'); // load chatdata model
227
  if ($customerData->getEnableSupport() == "1")
228
  {
229
  $customerData->updateChatdata('enable_support', "0"); // disable support
230
- $facebook->sendMessage($chatId, $mageHelper->__("Done. The customer is no longer able to enter support."));
231
  }
232
  else //if ($customerData->getEnableSupport() == "0")
233
  {
234
  $customerData->updateChatdata('enable_support', "1"); // enable support
235
- $facebook->sendMessage($chatId, $mageHelper->__("Done. The customer is now able to enter support."));
236
  }
237
-
238
  }
239
- else if ($chatdata->startsWith($text, $replyToCustomerMessage)) // old checkCommandWithValue
240
- {
241
- $customerChatId = trim($chatdata->getCommandValue($text, $replyToCustomerMessage)); // get customer chatId from payload
242
- $chatdata->updateChatdata('facebook_support_reply_chat_id', $customerChatId);
243
- $chatdata->updateChatdata('facebook_conv_state', $chatdata->_replyToSupportMessageState);
244
 
245
- $facebook->sendMessage($chatId, $mageHelper->__("Ok, send me the message and I'll forward it to the customer."));
246
- }
247
- else if ($chatdata->checkCommand($text, $chatdata->_admSendMessage2AllCmd)) // TODO
248
- {
 
 
 
 
 
 
 
 
 
249
 
 
 
 
 
 
 
 
 
 
 
 
 
250
  }
 
 
 
 
 
251
 
252
- return $facebook->respondSuccess();
253
  }
 
 
254
  }
 
255
 
256
- // ALL CUSTOMER HANDLERS GOES AFTER HERE
257
 
258
- if ($chatdata->getIsLogged() == "1") // check if customer is logged
 
 
259
  {
260
- if (Mage::getModel('customer/customer')->load((int)$chatdata->getCustomerId())->getId()) // if is a valid customer id
261
  {
262
- if ($chatdata->getEnableFacebook() != "1")
263
- {
264
- $facebook->sendMessage($chatId, $mageHelper->__("To talk with me, please enable Facebook Messenger on your account chatbot settings."));
265
- $facebook->sendChatAction($chatId, "typing_off");
266
- return $facebook->respondSuccess();
267
- }
268
  }
269
  }
 
270
 
271
- $blockerStates = (
272
- $conversationState == $chatdata->_listCategoriesState ||
273
- $conversationState == $chatdata->_searchState ||
274
- $conversationState == $chatdata->_supportState ||
275
- $conversationState == $chatdata->_sendEmailState ||
276
- $conversationState == $chatdata->_trackOrderState
277
- );
278
 
279
- // handle default replies
280
- if ($enableReplies == "1" && !$blockerStates)
 
 
 
281
  {
282
- $defaultReplies = Mage::getStoreConfig('chatbot_enable/facebook_config/default_replies');
283
- if ($defaultReplies)
284
- {
285
- $replies = unserialize($defaultReplies);
286
- if (is_array($replies))
287
- {
288
- foreach($replies as $reply)
289
- {
290
- // MODES
291
- // 0 =>'Similarity'
292
- // 1 =>'Starts With'
293
- // 2 =>'Ends With'
294
- // 3 =>'Contains'
295
- // 4 =>'Match Regular Expression'
296
- // 5 =>'Equals to'
297
-
298
- $matched = false;
299
- $match = $reply["match_sintax"];
300
- $mode = $reply["reply_mode"];
301
-
302
- if ($reply["match_case"] == "0")
303
- {
304
- $match = strtolower($match);
305
- $textToMatch = strtolower($text);
306
- }
307
- else
308
- $textToMatch = $text;
309
-
310
- if ($mode == "0") // Similarity
311
- {
312
- $similarity = $reply["similarity"];
313
- if (is_numeric($similarity))
314
- {
315
- if (!($similarity >= 1 && $similarity <= 100))
316
- $similarity = 100;
317
- }
318
- else
319
- $similarity = 100;
320
-
321
- similar_text($textToMatch, $match, $percent);
322
- if ($percent >= $similarity)
323
- $matched = true;
324
- }
325
- else if ($mode == "1") // Starts With
326
- {
327
- if ($chatdata->startsWith($textToMatch, $match))
328
- $matched = true;
329
- }
330
- else if ($mode == "2") // Ends With
331
- {
332
- if ($chatdata->endsWith($textToMatch, $match))
333
- $matched = true;
334
- }
335
- else if ($mode == "3") // Contains
336
- {
337
- if (strpos($textToMatch, $match) !== false)
338
- $matched = true;
339
- }
340
- else if ($mode == "4") // Match Regular Expression
341
- {
342
- // if ($match[0] != "/")
343
- // $match = "/" . $match;
344
- // if ((substr($match, -1) != "/") && ($match[strlen($match) - 2] != "/"))
345
- // $match .= "/";
346
- if (preg_match($match, $textToMatch))
347
- $matched = true;
348
- }
349
- else if ($mode == "5") // Equals to
350
- {
351
- if ($textToMatch == $match)
352
- $matched = true;
353
- }
354
-
355
- if ($matched)
356
- {
357
- $facebook->sendMessage($chatId, $reply["reply_phrase"]);
358
- if ($reply["stop_processing"] == "1")
359
- return $facebook->respondSuccess();
360
- break;
361
- }
362
- }
363
- }
364
- }
365
  }
366
-
367
- // user isnt registred HERE
368
- if (is_null($chatdata->getFacebookChatId())) // if user isn't registred
369
  {
370
- $message = Mage::getStoreConfig('chatbot_enable/facebook_config/facebook_welcome_msg'); // TODO
371
- if ($message) // TODO
372
- $facebook->sendMessage($chatId, $message);
373
- try
374
- {
375
- $hash = substr(md5(uniqid($chatId, true)), 0, 150); // TODO
376
- $chatdata // using magento model to insert data into database the proper way
377
- ->setFacebookChatId($chatId)
378
- ->setHashKey($hash) // TODO
379
- ->setCreatedAt(date('Y-m-d H:i:s'))
380
- ->save();
381
- //$chatdata->updateChatdata('facebook_chat_id', $chat_id);
382
- //$chatdata->updateChatdata('hash_key', $hash);
383
- }
384
- catch (Exception $e)
385
- {
386
- $facebook->sendMessage($chatId, $chatdata->_errorMessage); // TODO
387
- }
388
- //$facebook->sendChatAction($chatId, "typing_off");
389
- //return $facebook->respondSuccess(); // commented to keep processing the message
390
  }
391
-
392
- // init commands
393
- //$chatdata->_startCmd['command'] = "Start";
394
- $chatdata->_listCategoriesCmd = $chatdata->getCommandString(1);
395
- $chatdata->_searchCmd = $chatdata->getCommandString(2);
396
- $chatdata->_loginCmd = $chatdata->getCommandString(3);
397
- $chatdata->_listOrdersCmd = $chatdata->getCommandString(4);
398
- $chatdata->_reorderCmd = $chatdata->getCommandString(5);
399
- $chatdata->_add2CartCmd = $chatdata->getCommandString(6);
400
- $chatdata->_checkoutCmd = $chatdata->getCommandString(7);
401
- $chatdata->_clearCartCmd = $chatdata->getCommandString(8);
402
- $chatdata->_trackOrderCmd = $chatdata->getCommandString(9);
403
- $chatdata->_supportCmd = $chatdata->getCommandString(10);
404
- $chatdata->_sendEmailCmd = $chatdata->getCommandString(11);
405
- $chatdata->_cancelCmd = $chatdata->getCommandString(12);
406
- $chatdata->_helpCmd = $chatdata->getCommandString(13);
407
- $chatdata->_aboutCmd = $chatdata->getCommandString(14);
408
- $chatdata->_logoutCmd = $chatdata->getCommandString(15);
409
- $chatdata->_registerCmd = $chatdata->getCommandString(16);
410
- if (!$chatdata->_cancelCmd['command']) $chatdata->_cancelCmd['command'] = "cancel"; // it must always have a cancel command
411
-
412
- // init messages
413
- $chatdata->_errorMessage = $mageHelper->__("Something went wrong, please try again.");
414
- $chatdata->_cancelMessage = $mageHelper->__("To cancel, send") . ' "' . $chatdata->_cancelCmd['command'] . '"';
415
- $chatdata->_canceledMessage = $mageHelper->__("Ok, canceled.");
416
- $chatdata->_loginFirstMessage = $mageHelper->__("Please login first.");
417
- array_push($chatdata->_positiveMessages, $mageHelper->__("Ok"), $mageHelper->__("Okay"), $mageHelper->__("Cool"), $mageHelper->__("Awesome"));
418
- // $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)]
419
-
420
- if ($enablePredict == "1" && !$isPayload) // prediction is enabled and itsn't payload
421
  {
422
- if ($conversationState == $chatdata->_startState)
423
- {
424
- $cmdarray = array(
425
- $chatdata->_startCmd['command'],
426
- $chatdata->_listCategoriesCmd['command'],
427
- $chatdata->_searchCmd['command'],
428
- $chatdata->_loginCmd['command'],
429
- $chatdata->_listOrdersCmd['command'],
430
- $chatdata->_reorderCmd['command'],
431
- $chatdata->_add2CartCmd['command'],
432
- $chatdata->_checkoutCmd['command'],
433
- $chatdata->_clearCartCmd['command'],
434
- $chatdata->_trackOrderCmd['command'],
435
- $chatdata->_supportCmd['command'],
436
- $chatdata->_sendEmailCmd['command'],
437
- $chatdata->_cancelCmd['command'],
438
- $chatdata->_helpCmd['command'],
439
- $chatdata->_aboutCmd['command'],
440
- $chatdata->_logoutCmd['command'],
441
- $chatdata->_registerCmd['command']
442
- );
443
-
444
- foreach ($cmdarray as $cmd)
445
- {
446
- if (strpos($text, $cmd) !== false)
447
- {
448
- $text = $cmd;
449
- break;
450
- }
451
- }
452
- }
453
  }
 
 
 
454
 
455
- // cancel command
456
- if ($chatdata->checkCommand($text, $chatdata->_cancelCmd))
 
 
 
457
  {
458
- if ($conversationState == $chatdata->_listCategoriesState)
459
- {
460
- $message = $chatdata->_canceledMessage;
461
- }
462
- else if ($conversationState == $chatdata->_supportState)
463
- {
464
- $message = $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("exiting support mode.");
465
- }
466
- else if ($conversationState == $chatdata->_searchState)
467
- {
468
- $message = $chatdata->_canceledMessage;
469
- }
470
- else if ($conversationState == $chatdata->_sendEmailState)
471
- {
472
- $message = $chatdata->_canceledMessage;
473
- }
474
- else if ($conversationState == $chatdata->_listProductsState)
475
- {
476
- $message = $chatdata->_canceledMessage;
477
- }
478
- else if ($conversationState == $chatdata->_listOrdersState)
479
- {
480
- $message = $chatdata->_canceledMessage;
481
- }
482
- else
483
- $message = $chatdata->_errorMessage;
484
-
485
- if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState))
486
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
487
- else
488
- $facebook->sendMessage($chatId, $message);
489
- $facebook->sendChatAction($chatId, "typing_off");
490
- return $facebook->respondSuccess();
491
  }
 
 
 
492
 
493
- // add2cart commands
494
- if ($chatdata->startsWith($text, $chatdata->_add2CartCmd['command'])) // ignore alias // old checkCommandWithValue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
495
  {
496
- $errorFlag = false;
497
- $notInStock = false;
498
- $cmdvalue = $chatdata->getCommandValue($text, $chatdata->_add2CartCmd['command']);
499
- if ($cmdvalue) // TODO
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
500
  {
501
- $product = Mage::getModel('catalog/product')->load($cmdvalue);
502
- if ($product->getId())
503
  {
504
- $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getIsInStock();
505
- if ($stock > 0)
506
- {
507
- $productName = $product->getName();
508
- if (empty($productName))
509
- $productName = $mageHelper->__("this product");
510
- $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("adding %s to your cart.", $productName));
511
- $facebook->sendChatAction($chatId, "typing_on");
512
- if ($chatdata->addProd2Cart($cmdvalue))
513
- $facebook->sendMessage($chatId, $mageHelper->__("Added. To checkout send") . ' "' . $chatdata->_checkoutCmd['command'] . '"');
514
- else
515
- $errorFlag = true;
516
- }
517
- else
518
- $notInStock = true;
519
  }
520
- else
521
- $errorFlag = true;
522
  }
523
- else
524
- $errorFlag = true;
525
-
526
- if ($errorFlag)
527
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
528
- else if ($notInStock)
529
- $facebook->sendMessage($chatId, $mageHelper->__("This product is not in stock."));
530
-
531
- return $facebook->respondSuccess();
532
  }
533
-
534
- // help command
535
- if ($chatdata->checkCommand($text, $chatdata->_helpCmd))
 
 
 
 
536
  {
537
- $message = Mage::getStoreConfig('chatbot_enable/facebook_config/facebook_help_msg'); // TODO
538
- if (!empty($message)) // TODO
 
539
  {
540
- $facebook->sendMessage($chatId, $message);
541
- $cmdListing = Mage::getStoreConfig('chatbot_enable/facebook_config/enable_help_command_list');
542
- if ($cmdListing == "1")
543
- {
544
- $content = $chatdata->listFacebookCommandsMessage();
545
- $facebook->sendQuickReply($chatId, $content[0], $content[1]);
546
- }
547
  }
548
-
549
- $facebook->sendChatAction($chatId, "typing_off");
550
- return $facebook->respondSuccess();
551
  }
552
 
553
- // about command
554
- if ($chatdata->checkCommand($text, $chatdata->_aboutCmd))
555
- {
556
- $message = Mage::getStoreConfig('chatbot_enable/facebook_config/facebook_about_msg'); // TODO
557
- if (!empty($message))
558
- $facebook->sendMessage($chatId, $message);
559
 
560
- $facebook->sendChatAction($chatId, "typing_off");
561
- return $facebook->respondSuccess();
562
- }
 
 
 
563
 
564
- // states
565
- if ($conversationState == $chatdata->_listCategoriesState) // TODO show only in stock products
 
 
 
 
 
 
566
  {
567
- if ($showMore == 0) // show only in the first time
568
- $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("please wait while I gather all products from %s for you.", $text));
569
- else
570
- $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("listing more."));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
571
 
572
- $facebook->sendChatAction($chatId, "typing_on");
573
- $_category = Mage::getModel('catalog/category')->loadByAttribute('name', $text);
574
- $errorFlag = false;
575
- if ($_category) // check if variable isn't false/empty
 
 
 
 
 
 
 
 
 
 
 
 
 
 
576
  {
577
- if ($_category->getId()) // check if is a valid category
 
578
  {
579
- $noProductFlag = false;
580
- $productCollection = $_category->getProductCollection()
581
- ->addAttributeToSelect('*')
582
- ->addAttributeToFilter('visibility', 4)
583
- ->addAttributeToFilter('type_id', 'simple');
584
- Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($productCollection);
585
- $productIDs = $productCollection->getAllIds();
586
-
587
- $elements = array();
588
- if ($productIDs)
589
- {
590
- $i = 0;
591
- $total = count($productIDs);
592
-
593
- if ($showMore < $total)
594
- {
595
- if ($showMore == 0)
596
- {
597
- if ($total == 1)
598
- $facebook->sendMessage($chatId, $mageHelper->__("Done. This category has only one product."));
599
- else
600
- $facebook->sendMessage($chatId, $mageHelper->__("Done. This category has %s products.", $total));
601
- }
602
-
603
- $placeholder = Mage::getSingleton("catalog/product_media_config")->getBaseMediaUrl() . DS . "placeholder" . DS . Mage::getStoreConfig("catalog/placeholder/thumbnail_placeholder");
604
- foreach ($productIDs as $productID)
605
- {
606
- if ($i >= $showMore)
607
- {
608
- $product = Mage::getModel('catalog/product')->load($productID);
609
- $productUrl = $product->getProductUrl();
610
- $productImage = $product->getImageUrl();
611
- if (empty($productImage))
612
- $productImage = $placeholder;
613
-
614
- $button = array(
615
- array(
616
- 'type' => 'postback',
617
- 'title' => $mageHelper->__("Add to cart"),
618
- 'payload' => $chatdata->_add2CartCmd['command'] . $productID
619
- ),
620
- array(
621
- 'type' => 'web_url',
622
- 'url' => $productUrl,
623
- 'title' => $mageHelper->__("Visit product's page")
624
- )
625
- );
626
- $element = array(
627
- 'title' => $product->getName(),
628
- 'item_url' => $productUrl,
629
- 'image_url' => $productImage,
630
- 'subtitle' => $chatdata->excerpt($product->getShortDescription(), 60),
631
- 'buttons' => $button
632
- );
633
- array_push($elements, $element);
634
-
635
- if (($i + 1) != $total && $i >= ($showMore + $listingLimit)) // if isn't the 'last but one' and $i is bigger than listing limit + what was shown last time ($show_more)
636
- {
637
- // TODO add option to list more products
638
- $button = array(
639
- array(
640
- 'type' => 'postback',
641
- 'title' => $mageHelper->__("Show more"),
642
- 'payload' => $listMoreCategories . $text . "," . (string)($i + 1)
643
- )
644
- );
645
- $element = array(
646
- 'title' => Mage::app()->getStore()->getName(),
647
- 'item_url' => Mage::getBaseUrl(),
648
- 'image_url' => $placeholder,
649
- 'subtitle' => $chatdata->excerpt(Mage::getStoreConfig('design/head/default_description'), 60),
650
- 'buttons' => $button
651
- );
652
- array_push($elements, $element);
653
- if ($chatdata->getFacebookConvState() != $chatdata->_listProductsState)
654
- if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_listProductsState))
655
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
656
- break;
657
- }
658
- else if (($i + 1) == $total) // if it's the last one, back to _startState
659
- {
660
- $facebook->sendMessage($chatId, $mageHelper->__("And that was the last one."));
661
- if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState))
662
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
663
- }
664
- }
665
- $i++;
666
- }
667
- if ($i == 0)
668
- $noProductFlag = true;
669
- }
670
- else
671
- $errorFlag = true;
672
- }
673
- else
674
- $noProductFlag = true;
675
-
676
- if ($noProductFlag)
677
- $facebook->sendMessage($chatId, $mageHelper->__("Sorry, no products found in this category."));
678
  else
679
- $facebook->sendGenericTemplate($chatId, $elements);
680
  }
681
  else
682
- $errorFlag = true;
683
  }
684
  else
685
  $errorFlag = true;
686
-
687
- if ($errorFlag)
688
- {
689
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
690
- $chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState);
691
- }
692
- return $facebook->respondSuccess();
693
  }
694
- else if ($conversationState == $chatdata->_searchState)
695
- {
696
- if ($showMore == 0) // show only in the first time
697
- $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("please wait while I search for '%s' for you.", $text));
698
- else
699
- $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("listing more."));
700
 
701
- $facebook->sendChatAction($chatId, "typing_on");
702
- $errorFlag = false;
703
- $noProductFlag = false;
704
- $productIDs = $chatdata->getProductIdsBySearch($text);
705
- $elements = array();
706
- if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState))
707
- {
708
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
709
- return $facebook->respondSuccess();
710
- }
711
- else if ($productIDs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
712
  {
713
- $i = 0;
714
- $total = count($productIDs);
715
- if ($showMore < $total)
 
 
 
 
 
 
 
716
  {
717
- if ($showMore == 0)
718
- {
719
- if ($total == 1)
720
- $facebook->sendMessage($chatId, $mageHelper->__("Done. I've found only one product for your criteria."));
721
- else
722
- $facebook->sendMessage($chatId, $mageHelper->__("Done. I've found %s products for your criteria.", $total));
723
- }
724
 
725
- $placeholder = Mage::getSingleton("catalog/product_media_config")->getBaseMediaUrl() . DS . "placeholder" . DS . Mage::getStoreConfig("catalog/placeholder/thumbnail_placeholder");
726
- foreach ($productIDs as $productID)
727
  {
728
- $message = $chatdata->prepareFacebookProdMessages($productID);
729
- //Mage::helper('core')->__("Add to cart") . ": " . $this->_add2CartCmd['command'] . $product->getId();
730
- if ($message) // TODO
 
 
 
 
 
 
 
731
  {
732
  if ($i >= $showMore)
733
  {
@@ -741,7 +705,7 @@
741
  array(
742
  'type' => 'postback',
743
  'title' => $mageHelper->__("Add to cart"),
744
- 'payload' => $chatdata->_add2CartCmd['command'] . $productID
745
  ),
746
  array(
747
  'type' => 'web_url',
@@ -753,7 +717,7 @@
753
  'title' => $product->getName(),
754
  'item_url' => $productUrl,
755
  'image_url' => $productImage,
756
- 'subtitle' => $chatdata->excerpt($product->getShortDescription(), 60),
757
  'buttons' => $button
758
  );
759
  array_push($elements, $element);
@@ -765,75 +729,203 @@
765
  array(
766
  'type' => 'postback',
767
  'title' => $mageHelper->__("Show more"),
768
- 'payload' => $listMoreSearch . $text . "," . (string)($i + 1)
769
  )
770
  );
771
  $element = array(
772
  'title' => Mage::app()->getStore()->getName(),
773
  'item_url' => Mage::getBaseUrl(),
774
  'image_url' => $placeholder,
775
- 'subtitle' => $chatdata->excerpt(Mage::getStoreConfig('design/head/default_description'), 60),
776
  'buttons' => $button
777
  );
778
  array_push($elements, $element);
779
- if ($chatdata->getFacebookConvState() != $chatdata->_listProductsState)
780
- if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_listProductsState))
781
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
782
  break;
783
  }
784
  else if (($i + 1) == $total) // if it's the last one, back to _startState
785
  {
786
- $facebook->sendMessage($chatId, $mageHelper->__("And that was the last one."));
787
- if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState))
788
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
789
  }
790
  }
791
  $i++;
792
  }
 
 
793
  }
794
- if ($i == 0)
795
- $noProductFlag = true;
796
  }
797
  else
798
- $errorFlag = true;
799
- }
800
- else
801
- $noProductFlag = true;
802
-
803
- if ($noProductFlag)
804
- $facebook->sendMessage($chatId, $mageHelper->__("Sorry, no products found for this criteria."));
805
- else if ($errorFlag)
806
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
807
- else if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_listProductsState))
808
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
809
  else
810
  $facebook->sendGenericTemplate($chatId, $elements);
 
 
 
 
 
 
811
 
812
- return $facebook->respondSuccess();
 
 
 
813
  }
814
- else if ($conversationState == $chatdata->_supportState)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
815
  {
816
- $errorFlag = true;
817
- if (!empty($supportGroupId))
 
 
 
 
 
 
818
  {
819
- if ($supportGroupId == $chatdata->_tgBot)
 
 
 
 
 
 
 
 
 
820
  {
821
- if (Mage::getModel('chatbot/api_telegram_handler')->foreignMessageToSupport($chatId, $originalText, $chatdata->_apiKey, $username)) // send chat id, original text and "facebook"
822
- $errorFlag = false;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
823
  }
824
- else // probably have the admin chat id set
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
825
  {
826
  $buttons = array(
827
  array(
828
  'type' => 'postback',
829
  'title' => $mageHelper->__("End support"),
830
- 'payload' => $chatdata->_admEndSupportCmd . $chatId
831
 
832
  ),
833
  array(
834
  'type' => 'postback',
835
  'title' => $mageHelper->__("Enable/Disable support"),
836
- 'payload' => $chatdata->_admBlockSupportCmd . $chatId
837
 
838
  ),
839
  array(
@@ -843,483 +935,839 @@
843
 
844
  )
845
  );
846
-
847
  $message = $mageHelper->__("From") . ": " . $username . "\n" . $mageHelper->__("ID") . ": " . $chatId . "\n" . $text;
848
- $facebook->sendButtonTemplate($supportGroupId, $message, $buttons);
849
- $errorFlag = false;
850
  }
851
- }
 
 
 
 
 
 
 
 
 
 
852
 
853
- if ($errorFlag)
854
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
855
- else
856
- $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("we have sent your message to support."));
857
- return $facebook->respondSuccess();
858
  }
859
- else if ($conversationState == $chatdata->_sendEmailState)
 
 
 
 
 
 
 
 
 
 
860
  {
861
- $facebook->sendMessage($chatId, $mageHelper->__("Trying to send the email..."));
862
- if ($chatdata->sendEmail($text, $username))
863
- {
864
- $facebook->sendMessage($chatId, $mageHelper->__("Done."));
865
- }
866
- else
867
- $facebook->sendMessage($chatId, $mageHelper->__("Sorry, I wasn't able to send an email this time. Please try again later."));
868
- if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState))
869
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
870
- return $facebook->respondSuccess();
871
  }
872
- else if ($conversationState == $chatdata->_trackOrderState)
 
 
 
 
 
 
 
 
 
873
  {
874
- $errorFlag = false;
875
- if ($chatdata->getIsLogged() == "1")
 
 
876
  {
877
- $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("please wait while I check the status for order %s.", $text));
878
- $facebook->sendChatAction($chatId, "typing_on");
879
- $order = Mage::getModel('sales/order')->loadByIncrementId($text);
880
- if ($order->getId())
881
  {
882
- if ($order->getCustomerId() == $chatdata->getCustomerId()) // not a problem if customer dosen't exist
883
- {
884
- $facebook->sendMessage($chatId, $mageHelper->__("Your order status is") . " " . $order->getStatus());
885
- }
886
- else
887
- $errorFlag = true;
888
  }
889
  else
890
  $errorFlag = true;
891
  }
892
  else
893
- $facebook->sendMessage($chatId, $chatdata->_loginFirstMessage);
894
- if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState))
895
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
896
- else if ($errorFlag)
897
- $facebook->sendMessage($chatId, $mageHelper->__("Sorry, we couldn't find any order with this information."));
898
- return $facebook->respondSuccess();
899
  }
 
 
 
 
 
 
 
 
900
 
901
- //general commands
902
- if ($chatdata->checkCommand($text, $chatdata->_listCategoriesCmd))
903
- {
904
- $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("please wait while I gather all categories for you."));
905
- $facebook->sendChatAction($chatId, "typing_on");
906
 
907
- $categoryHelper = Mage::helper('catalog/category');
908
- $categories = $categoryHelper->getStoreCategories(); // TODO test with a store without categories
909
- $i = 0;
910
- if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_listCategoriesState))
911
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
912
- else if ($categories)
 
 
 
913
  {
914
- $replies = array();
915
- foreach ($categories as $_category) // TODO fix buttons max size
916
  {
917
- //array_push($option, $_category->getName());
918
- if ($enableEmptyCategoriesListing != "1") // unallow empty categories listing
919
- {
920
- $category = Mage::getModel('catalog/category')->load($_category->getId()); // reload category because EAV Entity
921
- $productIDs = $category->getProductCollection()
922
- ->addAttributeToSelect('*')
923
- ->addAttributeToFilter('visibility', 4)
924
- ->addAttributeToFilter('type_id', 'simple')
925
- ->getAllIds()
926
- ;
927
- }
928
- else
929
- $productIDs = true;
930
- if (!empty($productIDs)) // category with no products
931
- {
932
- $cat_name = $_category->getName();
933
- if (!empty($cat_name))
934
- {
935
- $reply = array(
936
- 'content_type' => 'text',
937
- 'title' => $cat_name,
938
- 'payload' => 'list_category_' . $_category->getId() // TODO
939
- );
940
- array_push($replies, $reply);
941
- $i++;
942
- }
943
- }
944
  }
945
- if (!empty($replies))
 
 
946
  {
947
- $message = $mageHelper->__("Select a category") . ". " . $chatdata->_cancelMessage;
948
- $facebook->sendQuickReply($chatId, $message, $replies);
 
 
 
 
 
 
 
 
 
949
  }
950
  }
951
- else if ($i == 0)
952
  {
953
- $facebook->sendMessage($chatId, $mageHelper->__("No categories available at the moment, please try again later."));
954
- if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState))
955
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
956
  }
957
- else
958
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
959
-
960
- return $facebook->respondSuccess();
961
  }
962
- else if ($chatdata->checkCommand($text, $chatdata->_checkoutCmd))
963
  {
964
- $sessionId = null;
965
- $quoteId = null;
966
- $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("please wait while I prepare the checkout for you."));
967
- $facebook->sendChatAction($chatId, "typing_on");
968
- if ($chatdata->getIsLogged() == "1")
969
- {
970
- if (Mage::getModel('customer/customer')->load((int)$chatdata->getCustomerId())->getId())
971
- {
972
- // if user is set as logged, then login using magento singleton
973
- $customerSession = Mage::getSingleton('customer/session');
974
- $customerSession->loginById((int)$chatdata->getCustomerId());
975
- // then set current quote as customer quote
976
- $customer = Mage::getModel('customer/customer')->load((int)$chatdata->getCustomerId());
977
- $quote = Mage::getModel('sales/quote')->loadByCustomer($customer);
978
- // set quote and session ids from logged user
979
- $quoteId = $quote->getId();
980
- $sessionId = $customerSession->getEncryptedSessionId();
981
- }
982
- }
983
- if (!($sessionId && $quoteId))
984
- {
985
- // set quote and session ids from chatbot class
986
- $sessionId = $chatdata->getSessionId();
987
- $quoteId = $chatdata->getQuoteId();
988
- }
989
- $emptyCart = true;
990
- if ($sessionId && $quoteId)
991
- {
992
- $cartUrl = Mage::helper('checkout/cart')->getCartUrl();
993
- if (!isset(parse_url($cartUrl)['SID']))
994
- $cartUrl .= "?SID=" . $sessionId; // add session id to url
995
-
996
- $cart = Mage::getModel('checkout/cart')->setQuote(Mage::getModel('sales/quote')->loadByIdWithoutStore((int)$quoteId));
997
- $ordersubtotal = $cart->getQuote()->getSubtotal();
998
- if ($ordersubtotal > 0)
999
- {
1000
- $buttons = array(
1001
- array(
1002
- 'type' => 'web_url',
1003
- 'url' => $cartUrl,
1004
- 'title' => $mageHelper->__("Checkout")
1005
- )
1006
- );
1007
- $emptyCart = false;
1008
- $message = $mageHelper->__("Products on cart") . ":\n";
1009
- foreach ($cart->getQuote()->getItemsCollection() as $item) // TODO
1010
- {
1011
- $message .= $item->getQty() . "x " . $item->getProduct()->getName() . "\n" .
1012
- $mageHelper->__("Price") . ": " . Mage::helper('core')->currency($item->getProduct()->getPrice(), true, false) . "\n\n";
1013
- }
1014
- $message .= $mageHelper->__("Total") . ": " . Mage::helper('core')->currency($ordersubtotal, true, false);
1015
-
1016
- if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_checkoutState))
1017
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1018
- else
1019
- $facebook->sendButtonTemplate($chatId, $message, $buttons);
1020
- }
1021
- else if (!$chatdata->clearCart()) // try to clear cart
1022
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1023
- }
1024
- if ($emptyCart)
1025
- $facebook->sendMessage($chatId, $mageHelper->__("Your cart is empty."));
1026
- return $facebook->respondSuccess();
1027
  }
1028
- else if ($chatdata->checkCommand($text, $chatdata->_clearCartCmd))
 
 
 
 
 
 
 
 
 
 
 
1029
  {
1030
- $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("please wait while I clear your cart."));
1031
- $facebook->sendChatAction($chatId, "typing_on");
1032
- $errorFlag = false;
1033
- if ($chatdata->clearCart())
1034
  {
1035
- if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_clearCartState))
1036
- $errorFlag = true;
1037
- else
1038
- $facebook->sendMessage($chatId, $mageHelper->__("Cart cleared."));
 
 
 
 
 
1039
  }
1040
- else
1041
- $errorFlag = true;
1042
- if ($errorFlag)
1043
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1044
- return $facebook->respondSuccess();
1045
  }
1046
- else if ($chatdata->checkCommand($text, $chatdata->_searchCmd))
1047
  {
1048
- if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_searchState))
1049
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1050
- else
1051
- $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("what do you want to search for?") . " " . $chatdata->_cancelMessage);
1052
- return $facebook->respondSuccess();
1053
  }
1054
- else if ($chatdata->checkCommand($text, $chatdata->_loginCmd))
 
1055
  {
1056
- if ($chatdata->getIsLogged() != "1") // customer not logged
 
 
 
 
 
 
1057
  {
1058
- $hashUrl = Mage::getUrl('chatbot/settings/index/'); // get base module URL
1059
- $hashUrl = strtok($hashUrl, '?') . "hash" . DS . $chatdata->getHashKey(); // remove magento parameters
1060
  $buttons = array(
1061
  array(
1062
  'type' => 'web_url',
1063
- 'url' => $hashUrl,
1064
- 'title' => $mageHelper->__("Login")
1065
  )
1066
  );
1067
- if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_loginState))
1068
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1069
- else
1070
  {
1071
- $facebook->sendButtonTemplate(
1072
- $chatId, $mageHelper->__("To login to your account, access the link below") . ". " .
1073
- $mageHelper->__("If you want to logout from your account, just send") . " " . $chatdata->_logoutCmd, $buttons
1074
- );
1075
  }
 
 
 
 
 
 
1076
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1077
  else
1078
- $facebook->sendMessage($chatId, $mageHelper->__("You're already logged."));
1079
- return $facebook->respondSuccess();
1080
  }
1081
- else if ($chatdata->checkCommand($text, $chatdata->_logoutCmd)) // TODO
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1082
  {
1083
- if ($chatdata->getIsLogged() == "1")
 
 
 
 
 
 
 
 
 
 
 
1084
  {
1085
- $facebook->sendMessage($chatId, $mageHelper->__("Ok, logging out."));
1086
- $errorFlag = false;
1087
- try
1088
- {
1089
- $chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState);
1090
- $chatdata->updateChatdata('is_logged', "0");
1091
- $chatdata->updateChatdata('customer_id', ""); // TODO null?
1092
- $chatdata->clearCart();
1093
- }
1094
- catch (Exception $e)
1095
- {
1096
- $errorFlag = true;
1097
- }
1098
-
1099
- if ($errorFlag)
1100
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1101
- else
1102
- $facebook->sendMessage($chatId, $mageHelper->__("Done."));
1103
  }
1104
- else
1105
- $facebook->sendMessage($chatId, $mageHelper->__("You're not logged."));
1106
-
1107
- return $facebook->respondSuccess();
1108
  }
1109
- else if ($chatdata->checkCommand($text, $chatdata->_registerCmd)) // TODO
 
 
 
 
 
 
1110
  {
1111
- $registerUrl = strtok(Mage::getUrl('customer/account/create'), '?');
1112
- if (!empty($registerUrl))
1113
- $facebook->sendMessage($chatId, $mageHelper->__("Access %s to register a new account on our shop.", $registerUrl));
 
 
 
 
 
 
 
 
 
 
 
 
 
1114
  else
1115
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1116
- return $facebook->respondSuccess();
1117
  }
1118
- else if ($chatdata->checkCommand($text, $chatdata->_listOrdersCmd) || $moreOrders)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1119
  {
1120
- if ($chatdata->getIsLogged() == "1")
1121
- {
1122
- if ($showMore == 0) // show only in the first time
1123
- $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("please wait while I gather your orders for listing."));
1124
- else
1125
- $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("listing more."));
1126
 
1127
- $facebook->sendChatAction($chatId, "typing_on");
1128
- $ordersIDs = $chatdata->getOrdersIdsFromCustomer();
1129
- $i = 0;
1130
- if ($ordersIDs)
 
 
 
 
1131
  {
1132
- $flagBreak = false;
1133
- $total = count($ordersIDs);
1134
- if ($showMore < $total)
1135
  {
1136
- if ($showMore == 0)
1137
- {
1138
- if ($total == 1)
1139
- $facebook->sendMessage($chatId, $mageHelper->__("Done. You've only one order."));
1140
- else
1141
- $facebook->sendMessage($chatId, $mageHelper->__("Done. I've found %s orders.", $total));
1142
- }
1143
 
1144
- foreach($ordersIDs as $orderID)
 
 
 
 
 
1145
  {
1146
- $buttons = array();
1147
- $message = $chatdata->prepareFacebookOrderMessages($orderID);
1148
- if ($message) // TODO
 
 
 
 
 
 
1149
  {
1150
- $button = array(
1151
- 'type' => 'postback',
1152
- 'title' => $mageHelper->__("Reorder"),
1153
- 'payload' => $chatdata->_reorderCmd['command'] . $orderID
1154
- );
1155
- array_push($buttons, $button);
1156
- if ($i >= $showMore)
1157
  {
1158
- if (($i + 1) != $total && $i >= ($showMore + $listingLimit)) // if isn't the 'last but one' and $i is bigger than listing limit + what was shown last time ($show_more)
1159
- {
1160
- // TODO add option to list more orders
1161
- $button = array(
1162
- 'type' => 'postback',
1163
- 'title' => $mageHelper->__("Show more orders"),
1164
- 'payload' => $listMoreOrders . (string)($i + 1)
1165
- );
1166
- array_push($buttons, $button);
1167
- if ($chatdata->getFacebookConvState() != $chatdata->_listOrdersState)
1168
- if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_listOrdersState))
1169
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1170
- $flagBreak = true;
1171
- }
1172
- else if (($i + 1) == $total) // if it's the last one, back to _startState
 
 
 
 
 
 
 
1173
  {
1174
- $facebook->sendMessage($chatId, $mageHelper->__("And that was the last one."));
1175
- if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState))
1176
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1177
  }
1178
-
1179
- $facebook->sendButtonTemplate($chatId, $message, $buttons);
1180
- if ($flagBreak)
1181
- break;
1182
  }
1183
- $i++;
1184
  }
 
1185
  }
1186
- if ($i == 0)
1187
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1188
- // else if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_listOrdersState))
1189
- // $facebook->sendMessage($chat_id, $chatdata->_errorMessage);
1190
  }
1191
- }
1192
- else
1193
- {
1194
- $facebook->sendMessage($chatId, $mageHelper->__("This account has no orders."));
1195
- return $facebook->respondSuccess();
1196
  }
1197
  }
1198
  else
1199
- $facebook->sendMessage($chatId, $chatdata->_loginFirstMessage);
1200
- return $facebook->respondSuccess();
 
 
1201
  }
1202
- else if ($chatdata->startsWith($text, $chatdata->_reorderCmd['command'])) // ignore alias // old checkCommandWithValue
 
 
 
 
 
 
1203
  {
1204
- if ($chatdata->getIsLogged() == "1")
 
 
 
 
1205
  {
1206
- $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("please wait while I add the products from this order to your cart."));
1207
- $facebook->sendChatAction($chatId, "typing_on");
1208
- $errorFlag = false;
1209
- $cmdvalue = $chatdata->getCommandValue($text, $chatdata->_reorderCmd['command']);
1210
- if ($cmdvalue)
1211
  {
1212
- if ($chatdata->clearCart())
 
1213
  {
1214
- $order = Mage::getModel('sales/order')->load($cmdvalue);
1215
- if ($order->getId())
1216
- {
1217
- foreach($order->getAllVisibleItems() as $item) {
1218
- if (!$chatdata->addProd2Cart($item->getProductId()))
1219
- $errorFlag = true;
1220
- }
1221
  }
1222
- else
1223
- $errorFlag = true;
1224
  }
1225
  else
1226
  $errorFlag = true;
1227
  }
1228
  else
1229
  $errorFlag = true;
1230
-
1231
- if ($errorFlag)
1232
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1233
- else if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_reorderState))
1234
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1235
- else // success!!
1236
- $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("to checkout send") . ' "' . $chatdata->_checkoutCmd['command'] . '"');
1237
  }
1238
  else
1239
- $facebook->sendMessage($chatId, $chatdata->_loginFirstMessage);
1240
- return $facebook->respondSuccess();
 
 
 
 
 
 
1241
  }
1242
- else if ($chatdata->checkCommand($text, $chatdata->_trackOrderCmd))
 
 
 
 
 
 
1243
  {
1244
- if ($chatdata->getIsLogged() == "1")
 
1245
  {
1246
- $ordersIDs = $chatdata->getOrdersIdsFromCustomer();
1247
- if ($ordersIDs)
1248
- {
1249
- if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_trackOrderState))
1250
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1251
- else
1252
- $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("send the order number."));
1253
- }
1254
  else
1255
- $facebook->sendMessage($chatId, $mageHelper->__("Your account dosen't have any orders."));
1256
  }
1257
  else
1258
- $facebook->sendMessage($chatId, $chatdata->_loginFirstMessage);
1259
- return $facebook->respondSuccess();
1260
  }
1261
- else if ($chatdata->checkCommand($text, $chatdata->_supportCmd))
 
 
 
 
 
 
 
 
1262
  {
1263
- $supportEnabled = $chatdata->getEnableSupport();
1264
- $errorFlag = false;
1265
- if ($supportEnabled == "1")
1266
  {
1267
- if ($chatdata->getTelegramConvState() != $chatdata->_supportState) // TODO
1268
- {
1269
- if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_supportState))
1270
- $errorFlag = true;
1271
- else
1272
- $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("what do you need support for?") . " " . $chatdata->_cancelMessage);
1273
- }
1274
  else
1275
- $facebook->sendMessage($chatId, $mageHelper->__("You're already on support in other chat application, please close it before opening a new one."));
1276
  }
1277
  else
1278
- $facebook->sendMessage($chatId, $mageHelper->__("I'm sorry, you can't ask for support now. Please try again later."));
 
 
 
1279
 
1280
- if ($errorFlag)
1281
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1282
- return $facebook->respondSuccess();
 
 
 
 
 
 
 
 
 
1283
  }
1284
- else if ($chatdata->checkCommand($text, $chatdata->_sendEmailCmd))
 
 
 
 
 
1285
  {
1286
- if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_sendEmailState))
1287
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1288
- else
1289
  {
1290
- $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("write the email content."));
1291
- $facebook->sendMessage($chatId, $mageHelper->__("By doing this you agree that we may contact you directly via chat message.") . " " . $chatdata->_cancelMessage);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1292
  }
1293
- return $facebook->respondSuccess();
1294
  }
1295
- else
 
 
1296
  {
1297
- if ($enableFinalMessage2Support == "1")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1298
  {
1299
- $errorFlag = true;
1300
- if ($supportGroupId == $chatdata->_tgBot)
1301
- if (Mage::getModel('chatbot/api_telegram_handler')->foreignMessageToSupport($chatId, $originalText, $chatdata->_apiKey, $username)) // send chat id, original text and "facebook"
 
 
 
 
 
 
 
 
 
 
 
 
1302
  {
1303
- // if ($chatdata->getTelegramConvState() != $chatdata->_supportState) // TODO
1304
- // $chatdata->updateChatdata('facebook_conv_state', $chatdata->_supportState);
1305
- $errorFlag = false;
1306
  }
 
1307
 
1308
- if ($errorFlag)
1309
- $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1310
- else
1311
- $facebook->sendMessage($chatId,
1312
- $mageHelper->__("Sorry, I didn't understand that.") . " " .
1313
- $mageHelper->__("Please wait while our support check your message so you can talk to a real person.") . " " .
1314
- $chatdata->_cancelMessage
1315
- ); // TODO
1316
- return $facebook->respondSuccess();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1317
  }
1318
- else // process cases where the customer message wasn't understandable
1319
  {
1320
- //if ($enable_witai == "1"){}
 
1321
 
1322
- $facebook->sendMessage($chatId, $mageHelper->__("Sorry, I didn't understand that.")); // TODO
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1323
 
1324
  $cmdListingOnError = Mage::getStoreConfig('chatbot_enable/facebook_config/enable_error_command_list');
1325
  if ($cmdListingOnError == "1")
@@ -1331,8 +1779,7 @@
1331
  }
1332
  }
1333
  }
1334
-
1335
- return $facebook->respondSuccess();
1336
  }
1337
  }
1338
 
1
  <?php
2
+ // class that handles all Facebook requests.
3
+ require_once("Messenger.php");
4
  //$api_path = Mage::getModuleDir('', 'Werules_Chatbot') . DS . "Model" . DS . "Api" . DS . "witAI" . DS;
5
+ //require_once($api_path . "witAI.php");
6
+
7
+ class MessengerBot extends Messenger
8
+ {
9
+ public $_originalText;
10
+ public $_referral;
11
+ public $_recipientId;
12
+ public $_chatId;
13
+ public $_messageId;
14
+ public $_audioPath;
15
+ public $_isPayload = false;
16
+
17
+ public function postMessage($chatId, $message)
18
+ {
19
+ return $this->sendMessage($chatId, $message);
20
+ }
21
+ }
22
 
23
  class Werules_Chatbot_Model_Api_Facebook_Handler extends Werules_Chatbot_Model_Chatdata
24
  {
25
+ public $_facebook;
26
+
27
  public function _construct()
28
  {
29
  //parent::_construct();
30
  //$this->_init('chatbot/api_facebook_handler'); // this is location of the resource file.
31
+ $apikey = Mage::getStoreConfig('chatbot_enable/facebook_config/facebook_api_key');
32
+ $this->_facebook = new MessengerBot($apikey);
33
+ $this->_chatbotHelper = Mage::helper('werules_chatbot');
34
  }
35
 
36
+ public function foreignMessageFromSupport($chatId, $text)
37
  {
38
+ // helpers
39
+ //$mageHelper = Mage::helper('core');
40
+ $chatbotHelper = $this->_chatbotHelper;
41
  // Instances the model class
42
  $chatdata = Mage::getModel('chatbot/chatdata');
43
+ $chatdata->load($chatId, 'facebook_chat_id');
44
+ $chatdata->_apiType = $chatbotHelper->_fbBot;
45
 
46
  if (is_null($chatdata->getFacebookChatId()))
47
  { // should't happen
48
  return false;
49
  }
50
 
51
+ //$chatdata->_apiType = $chatbotHelper->_fbBot;
52
+ $facebook = $this->_facebook;
53
+ if (isset($facebook))
 
 
54
  {
55
+ //$message = $mageHelper->__("Message from support") . ":\n" . $text;
56
+ $facebook->postMessage($chatId, $text);
 
57
  return true;
58
  }
59
 
60
  return false;
61
  }
62
 
63
+ public function facebookHandler()
64
  {
 
 
 
65
  // Instances the Facebook class
66
+ $facebook = $this->_facebook;
67
 
68
+ if (!isset($facebook)) // if no apiKey available, break process
69
+ return json_encode(array("status" => "error"));
 
70
 
71
  // hub challenge
72
  $hubToken = Mage::getStoreConfig('chatbot_enable/general_config/your_custom_key');
75
  return $verify;
76
 
77
  // Take text and chat_id from the message
78
+ $facebook->_originalText = $facebook->Text();
79
+ $facebook->_chatId = $facebook->ChatID();
80
+ $facebook->_messageId = $facebook->MessageID();
81
  $isEcho = $facebook->getEcho();
82
 
83
+ // helper
84
+ $mageHelper = Mage::helper('core');
85
+
86
+ $enableLog = Mage::getStoreConfig('chatbot_enable/general_config/enable_post_log');
87
+ if ($enableLog == "1") // log all posts
88
+ Mage::log("Post Data:\n" . var_export($facebook->RawData(), true) . "\n\n", null, 'chatbot_facebook.log');
89
+
90
+ $appId = $facebook->getAppId();
91
+ $canDisableBot = Mage::getStoreConfig('chatbot_enable/facebook_config/option_disable_bot');
92
+ if (($isEcho == "true") && ($canDisableBot == "1"))
93
+ {
94
+ if (empty($appId)) // dosen't have an app id, so it's a human reply using the page
95
+ {
96
+ $facebook->_recipientId = $facebook->RecipientID();
97
+ $facebook->_originalText = $mageHelper->__("Bot respond is disabled for now because the customer is being replied by a human.");
98
+ }
99
+ }
100
+
101
+ $referral = $facebook->getReferralRef();
102
+ if (!empty($referral)) // opened m.me with referral
103
+ {
104
+ $facebook->_referral = $referral;
105
+ $facebook->_originalText = $mageHelper->__("Hi");
106
+ }
107
+
108
+ // checking for payload
109
+ $payloadContent = $facebook->getPayload();
110
+ if (!empty($payloadContent) && empty($facebook->_originalText))
111
+ {
112
+ $facebook->_isPayload = true;
113
+ $facebook->_originalText = $payloadContent;
114
+ $facebook->_messageId = $facebook->getMessageTimestamp();
115
+ }
116
+
117
+ // quickreply payload
118
+ if (empty($payloadContent))
119
+ {
120
+ $payloadContent = $facebook->getQuickReplyPayload();
121
+ if (!empty($payloadContent))
122
+ {
123
+ //$facebook->_isPayload = true; // just replace original text as payload and it will work
124
+ $facebook->_originalText = $payloadContent;
125
+ $facebook->_messageId = $facebook->getMessageTimestamp();
126
+ }
127
+ }
128
+
129
+ if (!empty($facebook->_originalText) && !empty($facebook->_chatId) && ($isEcho != "true" || isset($facebook->_recipientId) || isset($facebook->_referral)))
130
+ {
131
+ return $this->processText();
132
+ }
133
+
134
+ return $facebook->respondSuccess();
135
+ }
136
+
137
+ public function processText()
138
+ {
139
  // configs
140
+ //$enableWitai = Mage::getStoreConfig('chatbot_enable/witai_config/enable_witai');
141
  $enabledBot = Mage::getStoreConfig('chatbot_enable/facebook_config/enable_bot');
142
  $enableReplies = Mage::getStoreConfig('chatbot_enable/facebook_config/enable_default_replies');
143
  $enablePredict = Mage::getStoreConfig('chatbot_enable/facebook_config/enable_predict_commands');
 
144
  $enableEmptyCategoriesListing = Mage::getStoreConfig('chatbot_enable/general_config/list_empty_categories');
145
  $enableFinalMessage2Support = Mage::getStoreConfig('chatbot_enable/general_config/enable_support_final_message');
146
  $supportGroupId = Mage::getStoreConfig('chatbot_enable/facebook_config/facebook_support_group');
147
  $showMore = 0;
148
  $moreOrders = false;
149
+ $defaultConfidence = 75;
150
  $listingLimit = 5;
151
  $listMoreCategories = "show_more_list_cat_";
152
  $listMoreSearch = "show_more_search_prod_";
153
  $listMoreOrders = "show_more_order_";
154
  $replyToCustomerMessage = "reply_to_message";
155
+ $message = "";
156
+ $messageLimit = 640; // Messenger API limit
157
+ $minutes = 1 * 60;// * 1000; // 1 minute
158
 
159
+ // instance Facebook API
160
+ $facebook = $this->_facebook;
 
 
 
 
 
 
 
 
 
 
161
 
162
+ // Take text and chat_id from the message
163
+ $originalText = $facebook->_originalText;
164
+ $chatId = $facebook->_chatId;
165
+ $messageId = $facebook->_messageId;
166
+ $isPayload = $facebook->_isPayload;
167
+ $text = strtolower($originalText);
168
+ $recipientId = $facebook->_recipientId;
169
+
170
+ if (isset($recipientId)) // it's only set when a human respond on the facebook page
171
+ $chatId = $recipientId;
172
+
173
+ // Instances facebook user details
174
+ $userData = $facebook->UserData($chatId);
175
+ $username = null;
176
+ if (!empty($userData))
177
+ $username = $userData['first_name'];
178
+
179
+ // helpers
180
+ $mageHelper = Mage::helper('core');
181
+ $chatbotHelper = $this->_chatbotHelper;
182
 
183
+ // Instances the model class
184
+ $chatdata = Mage::getModel('chatbot/chatdata')->load($chatId, 'facebook_chat_id');
185
+ $chatdata->_apiType = $chatbotHelper->_fbBot;
186
+
187
+ //$chatdata->updateChatdata("facebook_processing_request", "0"); // DEBUG
188
+ // if ($chatdata->getFacebookProcessingRequest() == "1") // avoid responding to multiple messages in a row
189
+ // {
190
+ // $updatedAt = strtotime($chatdata->getUpdatedAt());
191
+ // $timeNow = time();
192
+ // if (($timeNow - $updatedAt) < $minutes)
193
+ // return $facebook->respondSuccess();
194
+ // else
195
+ // $chatdata->updateChatdata("facebook_processing_request", "0");
196
+ // }
197
+ //
198
+ // if ($chatdata->getFacebookChatId()) // flag that is processing a request
199
+ // $chatdata->updateChatdata("facebook_processing_request", "1");
200
 
 
 
 
201
 
202
+ // Instances the witAI class
203
+ $enableWitai = Mage::getStoreConfig('chatbot_enable/witai_config/enable_witai');
204
+ if ($enableWitai == "1")
205
+ {
206
+ if (!isset($this->_witAi))
207
+ {
208
+ $witApi = Mage::getStoreConfig('chatbot_enable/witai_config/witai_api_key');
209
+ $this->_witAi = new witAI($witApi);
210
+ }
211
 
212
+ if (!is_null($facebook->_audioPath))
 
213
  {
214
+ $witResponse = $this->_witAi->getAudioResponse($facebook->_audioPath);
215
+ if (isset($witResponse->_text))
216
+ $facebook->_originalText = $witResponse->_text;
217
+ else
218
+ return $chatdata->respondSuccess();
219
  }
220
+ }
221
 
222
+ if ($chatdata->getEnableFacebookAdmin() == "0") // disabled by admin
223
+ return $chatdata->respondSuccess();
224
+
225
+ if (isset($recipientId)) // it's only set when a human respond on the facebook page
226
+ {
227
+ $chatdata->updateChatdata('enable_facebook_admin', "0");
228
+ //$text = $mageHelper->__("Bot respond is disabled for now because the customer is being replied by a human.");
229
+ $chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_supportState); // force update state to support mode
230
+ //return $chatdata->respondSuccess();
231
+ }
232
+
233
+ if ($messageId == $chatdata->getFacebookMessageId() && !($this->_isWitAi)) // prevents to reply the same request twice
234
+ return $chatdata->respondSuccess();
235
+ else if ($chatdata->getFacebookChatId())
236
+ $chatdata->updateChatdata('facebook_message_id', $messageId); // if this fails, it may send the same message twice
237
 
238
+ // bot enabled/disabled
239
+ if ($enabledBot != "1")
240
+ {
241
+ $disabledMessage = Mage::getStoreConfig('chatbot_enable/facebook_config/disabled_message');
242
+ if (!empty($disabledMessage))
243
+ $facebook->postMessage($chatId, $disabledMessage);
244
+ return $chatdata->respondSuccess();
245
+ }
246
+
247
+ // send feedback to user
248
+ $facebook->sendChatAction($chatId, "typing_on");
249
+
250
+ // payload handler, may change the conversation state
251
+ if ($chatdata->getFacebookConvState() == $chatbotHelper->_listProductsState || $chatdata->getFacebookConvState() == $chatbotHelper->_listOrdersState) // listing products
252
+ {
253
+ if ($chatbotHelper->startsWith($text, $listMoreCategories)) // old checkCommandWithValue
254
  {
255
+ if ($chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_listCategoriesState))
256
  {
257
+ $value = $chatbotHelper->getCommandValue($text, $listMoreCategories);
258
+ $arr = explode(",", $value);
259
+ $text = $arr[0];
260
+ $showMore = (int)$arr[1];
 
 
 
261
  }
262
+ }
263
+ else if ($chatbotHelper->startsWith($text, $listMoreSearch)) // old checkCommandWithValue
264
+ {
265
+ if ($chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_searchState))
266
  {
267
+ $value = $chatbotHelper->getCommandValue($text, $listMoreSearch);
268
+ $arr = explode(",", $value);
269
+ $text = $arr[0];
270
+ $showMore = (int)$arr[1];
 
 
 
271
  }
272
+ }
273
+ else if ($chatbotHelper->startsWith($text, $listMoreOrders)) // old checkCommandWithValue
274
+ {
275
+ if ($chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_listOrdersState))
276
  {
277
+ $value = $chatbotHelper->getCommandValue($text, $listMoreOrders);
278
+ $showMore = (int)$value; // get where listing stopped
279
+ $moreOrders = true;
 
 
 
280
  }
 
 
281
  }
282
+ // else
283
+ // $chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_startState);
284
+ }
285
 
286
+ // instances conversation state
287
+ $conversationState = $chatdata->getFacebookConvState();
288
 
289
+ // init error message
290
+ $chatbotHelper->_errorMessage = $mageHelper->__("Something went wrong, please try again.");
291
 
292
+ // handle admin stuff
293
+ //$isAdmin = $chatdata->getIsAdmin();
294
+ // if it's the admin chat id
295
+ if ($chatId == $supportGroupId)// || $isAdmin == "1")
296
+ {
297
  // if ($isAdmin == "0") // set user as admin
298
  // $chatdata->updateChatdata('is_admin', "1");
299
 
300
+ if ($conversationState == $chatbotHelper->_replyToSupportMessageState) // check if admin is replying to a customer
301
+ {
302
+ $customerChatId = $chatdata->getFacebookSupportReplyChatId(); // get customer chat id
303
+ if (!empty($customerChatId))
304
  {
305
+ $chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_startState); // set admin to _startState
306
+ $customerData = Mage::getModel('chatbot/chatdata')->load($customerChatId, 'facebook_chat_id'); // load chatdata model
 
 
 
307
 
308
+ if ($customerData->getFacebookConvState() != $chatbotHelper->_supportState) // if user isn't on support, switch to support
309
+ {
310
+ // TODO IMPORTANT remember to switch off all other supports
311
+ $customerData->updateChatdata('facebook_conv_state', $chatbotHelper->_supportState);
312
+ $facebook->postMessage($customerChatId, $mageHelper->__("You're now on support mode."));
 
 
 
313
  }
314
+ $facebook->postMessage($customerChatId, $mageHelper->__("Message from support") . ":\n" . $text); // send message to customer TODO
315
+ $facebook->postMessage($chatId, $mageHelper->__("Message sent."));
316
  }
317
+ return $chatdata->respondSuccess();
318
+ }
319
+ else if ($chatbotHelper->startsWith($text, $chatbotHelper->_admSendMessage2AllCmd)) // old checkCommandWithValue
320
+ {
321
+ $message = trim($chatbotHelper->getCommandValue($text, $chatbotHelper->_admSendMessage2AllCmd));
322
+ if (!empty($message))
323
  {
324
+ $chatbotCollection = Mage::getModel('chatbot/chatdata')->getCollection();
325
+ foreach($chatbotCollection as $chatbot)
326
  {
327
+ $fbChatId = $chatbot->getFacebookChatId();
328
+ if ($fbChatId)
329
+ $facebook->postMessage($fbChatId, $message); // $magehelper->__("Message from support") . ":\n" .
 
 
 
 
 
330
  }
331
+ $facebook->postMessage($chatId, $mageHelper->__("Message sent."));
 
332
  }
333
+ else
334
+ $facebook->postMessage($chatId, $mageHelper->__("Please use") . ' "' . $chatbotHelper->_admSendMessage2AllCmd . " " . $mageHelper->__("your message here.") . '"');
335
+ }
336
+ else if ($isPayload)
337
+ {
338
+ if ($chatbotHelper->startsWith($text, $chatbotHelper->_admEndSupportCmd)) // finish customer support // old checkCommandWithValue
339
  {
340
+ $customerChatId = trim($chatbotHelper->getCommandValue($text, $chatbotHelper->_admEndSupportCmd)); // get customer chatId from payload
341
+ $customerData = Mage::getModel('chatbot/chatdata')->load($customerChatId, 'facebook_chat_id'); // load chatdata model
 
 
 
342
 
343
+ if ($customerData->getFacebookConvState() == $chatbotHelper->_supportState)
344
+ {
345
+ $customerData->updateChatdata('facebook_conv_state', $chatbotHelper->_startState); // update conversation state
346
+ $facebook->postMessage($chatId, $mageHelper->__("Done. The customer is no longer on support."));
347
+ $facebook->postMessage($customerChatId, $mageHelper->__("Support ended."));
348
  }
349
+ else
350
+ $facebook->postMessage($customerChatId, $mageHelper->__("Customer isn't on support."));
351
+ }
352
+ else if ($chatbotHelper->startsWith($text, $chatbotHelper->_admBlockSupportCmd)) // block user from using support // old checkCommandWithValue
353
+ {
354
+ $customerChatId = trim($chatbotHelper->getCommandValue($text, $chatbotHelper->_admBlockSupportCmd)); // get customer chatId from payload
355
+ $customerData = Mage::getModel('chatbot/chatdata')->load($customerChatId, 'facebook_chat_id'); // load chatdata model
356
+ if (!is_null($customerData->getFacebookChatId()))
357
  {
 
 
358
  if ($customerData->getEnableSupport() == "1")
359
  {
360
  $customerData->updateChatdata('enable_support', "0"); // disable support
361
+ $facebook->postMessage($chatId, $mageHelper->__("Done. The customer is no longer able to enter support."));
362
  }
363
  else //if ($customerData->getEnableSupport() == "0")
364
  {
365
  $customerData->updateChatdata('enable_support', "1"); // enable support
366
+ $facebook->postMessage($chatId, $mageHelper->__("Done. The customer is now able to enter support."));
367
  }
 
368
  }
369
+ else
370
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
 
 
 
371
 
372
+ }
373
+ else if ($chatbotHelper->startsWith($text, $replyToCustomerMessage)) // old checkCommandWithValue
374
+ {
375
+ $customerChatId = trim($chatbotHelper->getCommandValue($text, $replyToCustomerMessage)); // get customer chatId from payload
376
+ $chatdata->updateChatdata('facebook_support_reply_chat_id', $customerChatId);
377
+ $chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_replyToSupportMessageState);
378
+
379
+ $facebook->postMessage($chatId, $mageHelper->__("Ok, send me the message and I'll forward it to the customer."));
380
+ }
381
+ else if ($chatbotHelper->startsWith($text, $chatbotHelper->_admEnableBotCmd)) // old checkCommandWithValue
382
+ {
383
+ $customerChatId = trim($chatbotHelper->getCommandValue($text, $chatbotHelper->_admEnableBotCmd)); // get customer chatId from payload
384
+ $customerData = Mage::getModel('chatbot/chatdata')->load($customerChatId, 'facebook_chat_id'); // load chatdata model
385
 
386
+ if (!is_null($customerData->getFacebookChatId()))
387
+ {
388
+ if ($customerData->getEnableFacebookAdmin() == "1")
389
+ {
390
+ $customerData->updateChatdata('enable_facebook_admin', "0"); // disable bot response
391
+ $facebook->postMessage($chatId, $mageHelper->__("Done. The bot will no longer send messages to this customer."));
392
+ }
393
+ else //if ($customerData->getEnableFacebookAdmin() == "0")
394
+ {
395
+ $customerData->updateChatdata('enable_facebook_admin', "1"); // enable bot response
396
+ $facebook->postMessage($chatId, $mageHelper->__("Done. The bot will now start sending messages to this customer."));
397
+ }
398
  }
399
+ else
400
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
401
+ }
402
+ else if ($chatbotHelper->checkCommand($text, $chatbotHelper->_admSendMessage2AllCmd)) // TODO
403
+ {
404
 
 
405
  }
406
+
407
+ return $chatdata->respondSuccess();
408
  }
409
+ }
410
 
411
+ // ALL CUSTOMER HANDLERS GOES AFTER HERE
412
 
413
+ if ($chatdata->getIsLogged() == "1") // check if customer is logged
414
+ {
415
+ if (Mage::getModel('customer/customer')->load((int)$chatdata->getCustomerId())->getId()) // if is a valid customer id
416
  {
417
+ if ($chatdata->getEnableFacebook() != "1")
418
  {
419
+ $facebook->postMessage($chatId, $mageHelper->__("To talk with me, please enable Facebook Messenger on your account chatbot settings."));
420
+ $facebook->sendChatAction($chatId, "typing_off");
421
+ return $chatdata->respondSuccess();
 
 
 
422
  }
423
  }
424
+ }
425
 
426
+ $blockerStates = (
427
+ $conversationState == $chatbotHelper->_listCategoriesState ||
428
+ $conversationState == $chatbotHelper->_searchState ||
429
+ $conversationState == $chatbotHelper->_supportState ||
430
+ $conversationState == $chatbotHelper->_sendEmailState ||
431
+ $conversationState == $chatbotHelper->_trackOrderState
432
+ );
433
 
434
+ // user isnt registred HERE
435
+ if (is_null($chatdata->getFacebookChatId())) // if user isn't registred
436
+ {
437
+ $message = Mage::getStoreConfig('chatbot_enable/facebook_config/facebook_welcome_msg'); // TODO
438
+ if (!empty($message)) // TODO
439
  {
440
+ if ($username)
441
+ $message = str_replace("{customername}", $username, $message);
442
+ $facebook->postMessage($chatId, $message);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
443
  }
444
+ try
 
 
445
  {
446
+ $hash = substr(md5(uniqid($chatId, true)), 0, 150); // TODO
447
+ $chatdata // using magento model to insert data into database the proper way
448
+ ->setFacebookChatId($chatId)
449
+ ->setHashKey($hash) // TODO
450
+ ->setCreatedAt(date('Y-m-d H:i:s'))
451
+ ->save();
452
+ //$chatdata->updateChatdata('facebook_chat_id', $chatId);
453
+ //$chatdata->updateChatdata('hash_key', $hash);
 
 
 
 
 
 
 
 
 
 
 
 
454
  }
455
+ catch (Exception $e)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
456
  {
457
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage); // TODO
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
458
  }
459
+ //$facebook->sendChatAction($chatId, "typing_off");
460
+ //return $chatdata->respondSuccess(); // commented to keep processing the message
461
+ }
462
 
463
+ // referral handler
464
+ if (isset($facebook->_referral))
465
+ {
466
+ $refMessage = Mage::getStoreConfig('chatbot_enable/facebook_config/facebook_referral_message');
467
+ if (!empty($refMessage) && empty($message)) // only if haven't sent the welcome message
468
  {
469
+ if ($username)
470
+ $refMessage = str_replace("{customername}", $username, $refMessage);
471
+ $facebook->postMessage($chatId, $refMessage);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
472
  }
473
+ $chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_startState); // back to start state
474
+ return $chatdata->respondSuccess();
475
+ }
476
 
477
+ // init commands
478
+ //$chatbotHelper->_startCmd['command'] = "Start";
479
+ $chatbotHelper->_listCategoriesCmd = $chatdata->getCommandString(1);
480
+ $chatbotHelper->_searchCmd = $chatdata->getCommandString(2);
481
+ $chatbotHelper->_loginCmd = $chatdata->getCommandString(3);
482
+ $chatbotHelper->_listOrdersCmd = $chatdata->getCommandString(4);
483
+ $chatbotHelper->_reorderCmd = $chatdata->getCommandString(5);
484
+ $chatbotHelper->_add2CartCmd = $chatdata->getCommandString(6);
485
+ $chatbotHelper->_checkoutCmd = $chatdata->getCommandString(7);
486
+ $chatbotHelper->_clearCartCmd = $chatdata->getCommandString(8);
487
+ $chatbotHelper->_trackOrderCmd = $chatdata->getCommandString(9);
488
+ $chatbotHelper->_supportCmd = $chatdata->getCommandString(10);
489
+ $chatbotHelper->_sendEmailCmd = $chatdata->getCommandString(11);
490
+ $chatbotHelper->_cancelCmd = $chatdata->getCommandString(12);
491
+ $chatbotHelper->_helpCmd = $chatdata->getCommandString(13);
492
+ $chatbotHelper->_aboutCmd = $chatdata->getCommandString(14);
493
+ $chatbotHelper->_logoutCmd = $chatdata->getCommandString(15);
494
+ $chatbotHelper->_registerCmd = $chatdata->getCommandString(16);
495
+ if (!$chatbotHelper->_cancelCmd['command']) $chatbotHelper->_cancelCmd['command'] = "cancel"; // it must always have a cancel command
496
+
497
+ // init messages
498
+ $chatbotHelper->_cancelMessage = $mageHelper->__("To cancel, send") . ' "' . $chatbotHelper->_cancelCmd['command'] . '"';
499
+ $chatbotHelper->_canceledMessage = $mageHelper->__("Ok, canceled.");
500
+ $chatbotHelper->_loginFirstMessage = $mageHelper->__("Please login first.");
501
+ array_push($chatbotHelper->_positiveMessages, $mageHelper->__("Ok"), $mageHelper->__("Okay"), $mageHelper->__("Cool"), $mageHelper->__("Awesome"));
502
+ // $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)]
503
+
504
+ if ($enablePredict == "1" && !$isPayload) // prediction is enabled and itsn't payload
505
+ {
506
+ if ($conversationState == $chatbotHelper->_startState)
507
  {
508
+ $cmdarray = array(
509
+ $chatbotHelper->_startCmd['command'],
510
+ $chatbotHelper->_listCategoriesCmd['command'],
511
+ $chatbotHelper->_searchCmd['command'],
512
+ $chatbotHelper->_loginCmd['command'],
513
+ $chatbotHelper->_listOrdersCmd['command'],
514
+ $chatbotHelper->_reorderCmd['command'],
515
+ $chatbotHelper->_add2CartCmd['command'],
516
+ $chatbotHelper->_checkoutCmd['command'],
517
+ $chatbotHelper->_clearCartCmd['command'],
518
+ $chatbotHelper->_trackOrderCmd['command'],
519
+ $chatbotHelper->_supportCmd['command'],
520
+ $chatbotHelper->_sendEmailCmd['command'],
521
+ $chatbotHelper->_cancelCmd['command'],
522
+ $chatbotHelper->_helpCmd['command'],
523
+ $chatbotHelper->_aboutCmd['command'],
524
+ $chatbotHelper->_logoutCmd['command'],
525
+ $chatbotHelper->_registerCmd['command']
526
+ );
527
+
528
+ foreach ($cmdarray as $cmd)
529
  {
530
+ if (strpos($text, $cmd) !== false)
 
531
  {
532
+ $text = $cmd;
533
+ break;
 
 
 
 
 
 
 
 
 
 
 
 
 
534
  }
 
 
535
  }
 
 
 
 
 
 
 
 
 
536
  }
537
+ }
538
+
539
+ // help command
540
+ if ($chatbotHelper->checkCommand($text, $chatbotHelper->_helpCmd))
541
+ {
542
+ $message = Mage::getStoreConfig('chatbot_enable/facebook_config/facebook_help_msg'); // TODO
543
+ if (!empty($message)) // TODO
544
  {
545
+ $facebook->postMessage($chatId, $message);
546
+ $cmdListing = Mage::getStoreConfig('chatbot_enable/facebook_config/enable_help_command_list');
547
+ if ($cmdListing == "1")
548
  {
549
+ $content = $chatdata->listFacebookCommandsMessage();
550
+ $facebook->sendQuickReply($chatId, $content[0], $content[1]);
 
 
 
 
 
551
  }
 
 
 
552
  }
553
 
554
+ $facebook->sendChatAction($chatId, "typing_off");
555
+ return $chatdata->respondSuccess();
556
+ }
 
 
 
557
 
558
+ // about command
559
+ if ($chatbotHelper->checkCommand($text, $chatbotHelper->_aboutCmd))
560
+ {
561
+ $message = Mage::getStoreConfig('chatbot_enable/facebook_config/facebook_about_msg'); // TODO
562
+ if (!empty($message))
563
+ $facebook->postMessage($chatId, $message);
564
 
565
+ $facebook->sendChatAction($chatId, "typing_off");
566
+ return $chatdata->respondSuccess();
567
+ }
568
+
569
+ // cancel command
570
+ if ($chatbotHelper->checkCommand($text, $chatbotHelper->_cancelCmd))
571
+ {
572
+ if ($conversationState == $chatbotHelper->_listCategoriesState)
573
  {
574
+ $message = $chatbotHelper->_canceledMessage;
575
+ }
576
+ else if ($conversationState == $chatbotHelper->_supportState)
577
+ {
578
+ $message = $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("exiting support mode.");
579
+ }
580
+ else if ($conversationState == $chatbotHelper->_searchState)
581
+ {
582
+ $message = $chatbotHelper->_canceledMessage;
583
+ }
584
+ else if ($conversationState == $chatbotHelper->_sendEmailState)
585
+ {
586
+ $message = $chatbotHelper->_canceledMessage;
587
+ }
588
+ else if ($conversationState == $chatbotHelper->_listProductsState)
589
+ {
590
+ $message = $chatbotHelper->_canceledMessage;
591
+ }
592
+ else if ($conversationState == $chatbotHelper->_listOrdersState)
593
+ {
594
+ $message = $chatbotHelper->_canceledMessage;
595
+ }
596
+ else
597
+ $message = $chatbotHelper->_errorMessage;
598
 
599
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_startState))
600
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
601
+ else
602
+ $facebook->postMessage($chatId, $message);
603
+ $facebook->sendChatAction($chatId, "typing_off");
604
+ return $chatdata->respondSuccess();
605
+ }
606
+
607
+ // add2cart commands
608
+ if ($chatbotHelper->startsWith($text, $chatbotHelper->_add2CartCmd['command'])) // ignore alias // old checkCommandWithValue
609
+ {
610
+ $errorFlag = false;
611
+ $notInStock = false;
612
+ $cmdvalue = $chatbotHelper->getCommandValue($text, $chatbotHelper->_add2CartCmd['command']);
613
+ if ($cmdvalue) // TODO
614
+ {
615
+ $product = Mage::getModel('catalog/product')->load($cmdvalue);
616
+ if ($product->getId())
617
  {
618
+ $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getIsInStock();
619
+ if ($stock > 0)
620
  {
621
+ $productName = $product->getName();
622
+ if (empty($productName))
623
+ $productName = $mageHelper->__("this product");
624
+ $facebook->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("adding %s to your cart.", $productName));
625
+ $facebook->sendChatAction($chatId, "typing_on");
626
+ if ($chatdata->addProd2Cart($cmdvalue))
627
+ $facebook->postMessage($chatId, $mageHelper->__("Added. To checkout send") . ' "' . $chatbotHelper->_checkoutCmd['command'] . '"');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
628
  else
629
+ $errorFlag = true;
630
  }
631
  else
632
+ $notInStock = true;
633
  }
634
  else
635
  $errorFlag = true;
 
 
 
 
 
 
 
636
  }
637
+ else
638
+ $errorFlag = true;
 
 
 
 
639
 
640
+ if ($errorFlag)
641
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
642
+ else if ($notInStock)
643
+ $facebook->postMessage($chatId, $mageHelper->__("This product is not in stock."));
644
+
645
+ return $chatdata->respondSuccess();
646
+ }
647
+
648
+ // states
649
+ if ($conversationState == $chatbotHelper->_listCategoriesState) // TODO show only in stock products
650
+ {
651
+ $_category = Mage::getModel('catalog/category')->loadByAttribute('name', $text);
652
+
653
+ if ($_category)
654
+ $categoryName = $_category->getName();
655
+ else
656
+ $categoryName = $mageHelper->__("this caytegory");
657
+
658
+ if ($showMore == 0) // show only in the first time
659
+ $facebook->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("please wait while I gather all products from %s for you.", $categoryName));
660
+ else
661
+ $facebook->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("listing more."));
662
+
663
+ $facebook->sendChatAction($chatId, "typing_on");
664
+ $errorFlag = false;
665
+ if ($_category) // check if variable isn't false/empty
666
+ {
667
+ if ($_category->getId()) // check if is a valid category
668
  {
669
+ $noProductFlag = false;
670
+ $productCollection = $_category->getProductCollection()
671
+ ->addAttributeToSelect('*')
672
+ ->addAttributeToFilter('visibility', 4)
673
+ ->addAttributeToFilter('type_id', 'simple');
674
+ Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($productCollection);
675
+ $productIDs = $productCollection->getAllIds();
676
+
677
+ $elements = array();
678
+ if ($productIDs)
679
  {
680
+ $i = 0;
681
+ $total = count($productIDs);
 
 
 
 
 
682
 
683
+ if ($showMore < $total)
 
684
  {
685
+ if ($showMore == 0)
686
+ {
687
+ if ($total == 1)
688
+ $facebook->postMessage($chatId, $mageHelper->__("Done. This category has only one product."));
689
+ else
690
+ $facebook->postMessage($chatId, $mageHelper->__("Done. This category has %s products.", $total));
691
+ }
692
+
693
+ $placeholder = Mage::getSingleton("catalog/product_media_config")->getBaseMediaUrl() . DS . "placeholder" . DS . Mage::getStoreConfig("catalog/placeholder/thumbnail_placeholder");
694
+ foreach ($productIDs as $productID)
695
  {
696
  if ($i >= $showMore)
697
  {
705
  array(
706
  'type' => 'postback',
707
  'title' => $mageHelper->__("Add to cart"),
708
+ 'payload' => $chatbotHelper->_add2CartCmd['command'] . $productID
709
  ),
710
  array(
711
  'type' => 'web_url',
717
  'title' => $product->getName(),
718
  'item_url' => $productUrl,
719
  'image_url' => $productImage,
720
+ 'subtitle' => $chatbotHelper->excerpt($product->getShortDescription(), 60),
721
  'buttons' => $button
722
  );
723
  array_push($elements, $element);
729
  array(
730
  'type' => 'postback',
731
  'title' => $mageHelper->__("Show more"),
732
+ 'payload' => $listMoreCategories . $text . "," . (string)($i + 1)
733
  )
734
  );
735
  $element = array(
736
  'title' => Mage::app()->getStore()->getName(),
737
  'item_url' => Mage::getBaseUrl(),
738
  'image_url' => $placeholder,
739
+ 'subtitle' => $chatbotHelper->excerpt(Mage::getStoreConfig('design/head/default_description'), 60),
740
  'buttons' => $button
741
  );
742
  array_push($elements, $element);
743
+ if ($chatdata->getFacebookConvState() != $chatbotHelper->_listProductsState)
744
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_listProductsState))
745
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
746
  break;
747
  }
748
  else if (($i + 1) == $total) // if it's the last one, back to _startState
749
  {
750
+ //$facebook->postMessage($chatId, $mageHelper->__("And that was the last one.")); // uneeded message for facebook
751
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_startState))
752
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
753
  }
754
  }
755
  $i++;
756
  }
757
+ if ($i == 0)
758
+ $noProductFlag = true;
759
  }
760
+ else
761
+ $errorFlag = true;
762
  }
763
  else
764
+ $noProductFlag = true;
765
+
766
+ if ($noProductFlag)
767
+ $facebook->postMessage($chatId, $mageHelper->__("Sorry, no products found in this category."));
 
 
 
 
 
 
 
768
  else
769
  $facebook->sendGenericTemplate($chatId, $elements);
770
+ }
771
+ else
772
+ $errorFlag = true;
773
+ }
774
+ else
775
+ $errorFlag = true;
776
 
777
+ if ($errorFlag)
778
+ {
779
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
780
+ $chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_startState);
781
  }
782
+ return $chatdata->respondSuccess();
783
+ }
784
+ else if ($conversationState == $chatbotHelper->_searchState)
785
+ {
786
+ if ($showMore == 0) // show only in the first time
787
+ $facebook->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("please wait while I search for '%s' for you.", $text));
788
+ else
789
+ $facebook->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("listing more."));
790
+
791
+ $facebook->sendChatAction($chatId, "typing_on");
792
+ $errorFlag = false;
793
+ $noProductFlag = false;
794
+ $productIDs = $chatbotHelper->getProductIdsBySearch($text);
795
+ $elements = array();
796
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_startState))
797
  {
798
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
799
+ return $chatdata->respondSuccess();
800
+ }
801
+ else if ($productIDs)
802
+ {
803
+ $i = 0;
804
+ $total = count($productIDs);
805
+ if ($showMore < $total)
806
  {
807
+ if ($showMore == 0)
808
+ {
809
+ if ($total == 1)
810
+ $facebook->postMessage($chatId, $mageHelper->__("Done. I've found only one product for your criteria."));
811
+ else
812
+ $facebook->postMessage($chatId, $mageHelper->__("Done. I've found %s products for your criteria.", $total));
813
+ }
814
+
815
+ $placeholder = Mage::getSingleton("catalog/product_media_config")->getBaseMediaUrl() . DS . "placeholder" . DS . Mage::getStoreConfig("catalog/placeholder/thumbnail_placeholder");
816
+ foreach ($productIDs as $productID)
817
  {
818
+ $message = $chatbotHelper->prepareFacebookProdMessages($productID);
819
+ //Mage::helper('core')->__("Add to cart") . ": " . $this->_add2CartCmd['command'] . $product->getId();
820
+ if (!empty($message)) // TODO
821
+ {
822
+ if ($i >= $showMore)
823
+ {
824
+ $product = Mage::getModel('catalog/product')->load($productID);
825
+ $productUrl = $product->getProductUrl();
826
+ $productImage = $product->getImageUrl();
827
+ if (empty($productImage))
828
+ $productImage = $placeholder;
829
+
830
+ $button = array(
831
+ array(
832
+ 'type' => 'postback',
833
+ 'title' => $mageHelper->__("Add to cart"),
834
+ 'payload' => $chatbotHelper->_add2CartCmd['command'] . $productID
835
+ ),
836
+ array(
837
+ 'type' => 'web_url',
838
+ 'url' => $productUrl,
839
+ 'title' => $mageHelper->__("Visit product's page")
840
+ )
841
+ );
842
+ $element = array(
843
+ 'title' => $product->getName(),
844
+ 'item_url' => $productUrl,
845
+ 'image_url' => $productImage,
846
+ 'subtitle' => $chatbotHelper->excerpt($product->getShortDescription(), 60),
847
+ 'buttons' => $button
848
+ );
849
+ array_push($elements, $element);
850
+
851
+ if (($i + 1) != $total && $i >= ($showMore + $listingLimit)) // if isn't the 'last but one' and $i is bigger than listing limit + what was shown last time ($show_more)
852
+ {
853
+ // TODO add option to list more products
854
+ $button = array(
855
+ array(
856
+ 'type' => 'postback',
857
+ 'title' => $mageHelper->__("Show more"),
858
+ 'payload' => $listMoreSearch . $text . "," . (string)($i + 1)
859
+ )
860
+ );
861
+ $element = array(
862
+ 'title' => Mage::app()->getStore()->getName(),
863
+ 'item_url' => Mage::getBaseUrl(),
864
+ 'image_url' => $placeholder,
865
+ 'subtitle' => $chatbotHelper->excerpt(Mage::getStoreConfig('design/head/default_description'), 60),
866
+ 'buttons' => $button
867
+ );
868
+ array_push($elements, $element);
869
+ if ($chatdata->getFacebookConvState() != $chatbotHelper->_listProductsState)
870
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_listProductsState))
871
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
872
+ break;
873
+ }
874
+ else if (($i + 1) == $total) // if it's the last one, back to _startState
875
+ {
876
+ //$facebook->postMessage($chatId, $mageHelper->__("And that was the last one.")); // uneeded message for facebook
877
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_startState))
878
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
879
+ }
880
+ }
881
+ $i++;
882
+ }
883
  }
884
+ if ($i == 0)
885
+ $noProductFlag = true;
886
+ }
887
+ else
888
+ $errorFlag = true;
889
+ }
890
+ else
891
+ $noProductFlag = true;
892
+
893
+ if ($noProductFlag)
894
+ $facebook->postMessage($chatId, $mageHelper->__("Sorry, no products found for this criteria."));
895
+ else if ($errorFlag)
896
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
897
+ else if (!$chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_listProductsState))
898
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
899
+ else
900
+ $facebook->sendGenericTemplate($chatId, $elements);
901
+
902
+ return $chatdata->respondSuccess();
903
+ }
904
+ else if ($conversationState == $chatbotHelper->_supportState)
905
+ {
906
+ $errorFlag = true;
907
+ if (!empty($supportGroupId))
908
+ {
909
+ if ($supportGroupId == $chatbotHelper->_tgBot)
910
+ {
911
+ if ($chatdata->foreignMessageToTelegramSupport($chatId, $originalText, $chatdata->_apiType, $username)) // send chat id, original text, "facebook" and username
912
+ $errorFlag = false;
913
+ }
914
+ else // probably have the admin chat id set
915
+ {
916
+ if (!isset($recipientId)) // it's only set when a human respond on the facebook page
917
  {
918
  $buttons = array(
919
  array(
920
  'type' => 'postback',
921
  'title' => $mageHelper->__("End support"),
922
+ 'payload' => $chatbotHelper->_admEndSupportCmd . $chatId
923
 
924
  ),
925
  array(
926
  'type' => 'postback',
927
  'title' => $mageHelper->__("Enable/Disable support"),
928
+ 'payload' => $chatbotHelper->_admBlockSupportCmd . $chatId
929
 
930
  ),
931
  array(
935
 
936
  )
937
  );
 
938
  $message = $mageHelper->__("From") . ": " . $username . "\n" . $mageHelper->__("ID") . ": " . $chatId . "\n" . $text;
 
 
939
  }
940
+ else // if a human is responding
941
+ {
942
+ $buttons = array(
943
+ array(
944
+ 'type' => 'postback',
945
+ 'title' => $mageHelper->__("Enable/Disable Bot Replies"),
946
+ 'payload' => $chatbotHelper->_admEnableBotCmd . $chatId
947
+ )
948
+ );
949
+ $message = $text;
950
+ }
951
 
952
+ $facebook->sendButtonTemplate($supportGroupId, $message, $buttons);
953
+ $errorFlag = false;
954
+ }
 
 
955
  }
956
+
957
+ if ($errorFlag)
958
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
959
+ else if (!isset($recipientId)) // it's only set when a human respond on the facebook page
960
+ $facebook->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("we have sent your message to support."));
961
+ return $chatdata->respondSuccess();
962
+ }
963
+ else if ($conversationState == $chatbotHelper->_sendEmailState)
964
+ {
965
+ $facebook->postMessage($chatId, $mageHelper->__("Trying to send the email..."));
966
+ if ($chatdata->sendEmail($text, $username))
967
  {
968
+ $facebook->postMessage($chatId, $mageHelper->__("Done."));
 
 
 
 
 
 
 
 
 
969
  }
970
+ else
971
+ $facebook->postMessage($chatId, $mageHelper->__("Sorry, I wasn't able to send an email this time. Please try again later."));
972
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_startState))
973
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
974
+ return $chatdata->respondSuccess();
975
+ }
976
+ else if ($conversationState == $chatbotHelper->_trackOrderState)
977
+ {
978
+ $errorFlag = false;
979
+ if ($chatdata->getIsLogged() == "1")
980
  {
981
+ $facebook->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("please wait while I check the status for order %s.", $text));
982
+ $facebook->sendChatAction($chatId, "typing_on");
983
+ $order = Mage::getModel('sales/order')->loadByIncrementId($text);
984
+ if ($order->getId())
985
  {
986
+ if ($order->getCustomerId() == $chatdata->getCustomerId()) // not a problem if customer dosen't exist
 
 
 
987
  {
988
+ $facebook->postMessage($chatId, $mageHelper->__("Your order status is") . " " . $mageHelper->__($order->getStatus()));
 
 
 
 
 
989
  }
990
  else
991
  $errorFlag = true;
992
  }
993
  else
994
+ $errorFlag = true;
 
 
 
 
 
995
  }
996
+ else
997
+ $facebook->postMessage($chatId, $chatbotHelper->_loginFirstMessage);
998
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_startState))
999
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
1000
+ else if ($errorFlag)
1001
+ $facebook->postMessage($chatId, $mageHelper->__("Sorry, we couldn't find any order with this information."));
1002
+ return $chatdata->respondSuccess();
1003
+ }
1004
 
1005
+ //general commands
1006
+ if ($chatbotHelper->checkCommand($text, $chatbotHelper->_listCategoriesCmd))
1007
+ {
1008
+ $facebook->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("please wait while I gather all categories for you."));
1009
+ $facebook->sendChatAction($chatId, "typing_on");
1010
 
1011
+ $categoryHelper = Mage::helper('catalog/category');
1012
+ $categories = $categoryHelper->getStoreCategories(); // TODO test with a store without categories
1013
+ $i = 0;
1014
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_listCategoriesState))
1015
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
1016
+ else if ($categories)
1017
+ {
1018
+ $replies = array();
1019
+ foreach ($categories as $_category) // TODO fix buttons max size
1020
  {
1021
+ //array_push($option, $_category->getName());
1022
+ if ($enableEmptyCategoriesListing != "1") // unallow empty categories listing
1023
  {
1024
+ $category = Mage::getModel('catalog/category')->load($_category->getId()); // reload category because EAV Entity
1025
+ $productIDs = $category->getProductCollection()
1026
+ ->addAttributeToSelect('*')
1027
+ ->addAttributeToFilter('visibility', 4)
1028
+ ->addAttributeToFilter('type_id', 'simple')
1029
+ ->getAllIds()
1030
+ ;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1031
  }
1032
+ else
1033
+ $productIDs = true;
1034
+ if (!empty($productIDs)) // category with no products
1035
  {
1036
+ $catName = $_category->getName();
1037
+ if (!empty($catName))
1038
+ {
1039
+ $reply = array(
1040
+ 'content_type' => 'text',
1041
+ 'title' => $catName,
1042
+ 'payload' => $catName// 'list_category_' . $_category->getId() // TODO
1043
+ );
1044
+ array_push($replies, $reply);
1045
+ $i++;
1046
+ }
1047
  }
1048
  }
1049
+ if (!empty($replies))
1050
  {
1051
+ $message = $mageHelper->__("Select a category") . ". " . $chatbotHelper->_cancelMessage;
1052
+ $facebook->sendQuickReply($chatId, $message, $replies);
 
1053
  }
 
 
 
 
1054
  }
1055
+ else if ($i == 0)
1056
  {
1057
+ $facebook->postMessage($chatId, $mageHelper->__("No categories available at the moment, please try again later."));
1058
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_startState))
1059
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1060
  }
1061
+ else
1062
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
1063
+
1064
+ return $chatdata->respondSuccess();
1065
+ }
1066
+ else if ($chatbotHelper->checkCommand($text, $chatbotHelper->_checkoutCmd))
1067
+ {
1068
+ $sessionId = null;
1069
+ $quoteId = null;
1070
+ $facebook->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("please wait while I prepare the checkout for you."));
1071
+ $facebook->sendChatAction($chatId, "typing_on");
1072
+ if ($chatdata->getIsLogged() == "1")
1073
  {
1074
+ if (Mage::getModel('customer/customer')->load((int)$chatdata->getCustomerId())->getId())
 
 
 
1075
  {
1076
+ // if user is set as logged, then login using magento singleton
1077
+ $customerSession = Mage::getSingleton('customer/session');
1078
+ $customerSession->loginById((int)$chatdata->getCustomerId());
1079
+ // then set current quote as customer quote
1080
+ $customer = Mage::getModel('customer/customer')->load((int)$chatdata->getCustomerId());
1081
+ $quote = Mage::getModel('sales/quote')->loadByCustomer($customer);
1082
+ // set quote and session ids from logged user
1083
+ $quoteId = $quote->getId();
1084
+ $sessionId = $customerSession->getEncryptedSessionId();
1085
  }
 
 
 
 
 
1086
  }
1087
+ if (!($sessionId && $quoteId))
1088
  {
1089
+ // set quote and session ids from chatbot class
1090
+ $sessionId = $chatdata->getSessionId();
1091
+ $quoteId = $chatdata->getQuoteId();
 
 
1092
  }
1093
+ $emptyCart = true;
1094
+ if ($sessionId && $quoteId)
1095
  {
1096
+ $cartUrl = Mage::helper('checkout/cart')->getCartUrl();
1097
+ if (!isset(parse_url($cartUrl)['SID']))
1098
+ $cartUrl .= "?SID=" . $sessionId; // add session id to url
1099
+
1100
+ $cart = Mage::getModel('checkout/cart')->setQuote(Mage::getModel('sales/quote')->loadByIdWithoutStore((int)$quoteId));
1101
+ $ordersubtotal = $cart->getQuote()->getSubtotal();
1102
+ if ($ordersubtotal > 0)
1103
  {
 
 
1104
  $buttons = array(
1105
  array(
1106
  'type' => 'web_url',
1107
+ 'url' => $cartUrl,
1108
+ 'title' => $mageHelper->__("Checkout")
1109
  )
1110
  );
1111
+ $emptyCart = false;
1112
+ $message = $mageHelper->__("Products on cart") . ":\n";
1113
+ foreach ($cart->getQuote()->getItemsCollection() as $item) // TODO
1114
  {
1115
+ $message .= $item->getQty() . "x " . $item->getProduct()->getName() . "\n" .
1116
+ $mageHelper->__("Price") . ": " . Mage::helper('core')->currency($item->getProduct()->getPrice(), true, false) . "\n\n";
 
 
1117
  }
1118
+ $message .= $mageHelper->__("Total") . ": " . Mage::helper('core')->currency($ordersubtotal, true, false);
1119
+
1120
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_checkoutState))
1121
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
1122
+ else
1123
+ $facebook->sendButtonTemplate($chatId, $message, $buttons);
1124
  }
1125
+ else if (!$chatdata->clearCart()) // try to clear cart
1126
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
1127
+ }
1128
+ if ($emptyCart)
1129
+ $facebook->postMessage($chatId, $mageHelper->__("Your cart is empty."));
1130
+ return $chatdata->respondSuccess();
1131
+ }
1132
+ else if ($chatbotHelper->checkCommand($text, $chatbotHelper->_clearCartCmd))
1133
+ {
1134
+ $facebook->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("please wait while I clear your cart."));
1135
+ $facebook->sendChatAction($chatId, "typing_on");
1136
+ $errorFlag = false;
1137
+ if ($chatdata->clearCart())
1138
+ {
1139
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_clearCartState))
1140
+ $errorFlag = true;
1141
  else
1142
+ $facebook->postMessage($chatId, $mageHelper->__("Cart cleared."));
 
1143
  }
1144
+ else
1145
+ $errorFlag = true;
1146
+ if ($errorFlag)
1147
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
1148
+ return $chatdata->respondSuccess();
1149
+ }
1150
+ else if ($chatbotHelper->checkCommand($text, $chatbotHelper->_searchCmd))
1151
+ {
1152
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_searchState))
1153
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
1154
+ else
1155
+ $facebook->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("what do you want to search for?") . " " . $chatbotHelper->_cancelMessage);
1156
+ return $chatdata->respondSuccess();
1157
+ }
1158
+ else if ($chatbotHelper->checkCommand($text, $chatbotHelper->_loginCmd))
1159
+ {
1160
+ if ($chatdata->getIsLogged() != "1") // customer not logged
1161
  {
1162
+ $hashUrl = Mage::getUrl('chatbot/settings/index/'); // get base module URL
1163
+ $hashUrl = strtok($hashUrl, '?') . "hash" . DS . $chatdata->getHashKey(); // remove magento parameters
1164
+ $buttons = array(
1165
+ array(
1166
+ 'type' => 'web_url',
1167
+ 'url' => $hashUrl,
1168
+ 'title' => $mageHelper->__("Login")
1169
+ )
1170
+ );
1171
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_loginState))
1172
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
1173
+ else
1174
  {
1175
+ $facebook->sendButtonTemplate(
1176
+ $chatId, $mageHelper->__("To login to your account, access the link below") . ". " .
1177
+ $mageHelper->__("If you want to logout from your account, just send") . ' "' . $chatbotHelper->_logoutCmd['command'] . '"', $buttons
1178
+ );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1179
  }
 
 
 
 
1180
  }
1181
+ else
1182
+ $facebook->postMessage($chatId, $mageHelper->__("You're already logged."));
1183
+ return $chatdata->respondSuccess();
1184
+ }
1185
+ else if ($chatbotHelper->checkCommand($text, $chatbotHelper->_logoutCmd)) // TODO
1186
+ {
1187
+ if ($chatdata->getIsLogged() == "1")
1188
  {
1189
+ $facebook->postMessage($chatId, $mageHelper->__("Ok, logging out."));
1190
+ $errorFlag = false;
1191
+ try
1192
+ {
1193
+ $chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_startState);
1194
+ $chatdata->updateChatdata('is_logged', "0");
1195
+ $chatdata->updateChatdata('customer_id', ""); // TODO null?
1196
+ $chatdata->clearCart();
1197
+ }
1198
+ catch (Exception $e)
1199
+ {
1200
+ $errorFlag = true;
1201
+ }
1202
+
1203
+ if ($errorFlag)
1204
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
1205
  else
1206
+ $facebook->postMessage($chatId, $mageHelper->__("Done."));
 
1207
  }
1208
+ else
1209
+ $facebook->postMessage($chatId, $mageHelper->__("You're not logged."));
1210
+
1211
+ return $chatdata->respondSuccess();
1212
+ }
1213
+ else if ($chatbotHelper->checkCommand($text, $chatbotHelper->_registerCmd)) // TODO
1214
+ {
1215
+ $registerUrl = strtok(Mage::getUrl('customer/account/create'), '?');
1216
+ if (!empty($registerUrl))
1217
+ $facebook->postMessage($chatId, $mageHelper->__("Access %s to register a new account on our shop.", $registerUrl));
1218
+ else
1219
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
1220
+ return $chatdata->respondSuccess();
1221
+ }
1222
+ else if ($chatbotHelper->checkCommand($text, $chatbotHelper->_listOrdersCmd) || $moreOrders)
1223
+ {
1224
+ if ($chatdata->getIsLogged() == "1")
1225
  {
1226
+ if ($showMore == 0) // show only in the first time
1227
+ $facebook->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("please wait while I gather your orders for listing."));
1228
+ else
1229
+ $facebook->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("listing more."));
 
 
1230
 
1231
+ $facebook->sendChatAction($chatId, "typing_on");
1232
+ $ordersIDs = $chatbotHelper->getOrdersIdsFromCustomer($chatdata->getCustomerId());
1233
+ $i = 0;
1234
+ if ($ordersIDs)
1235
+ {
1236
+ $flagBreak = false;
1237
+ $total = count($ordersIDs);
1238
+ if ($showMore < $total)
1239
  {
1240
+ if ($showMore == 0)
 
 
1241
  {
1242
+ if ($total == 1)
1243
+ $facebook->postMessage($chatId, $mageHelper->__("Done. You've only one order."));
1244
+ else
1245
+ $facebook->postMessage($chatId, $mageHelper->__("Done. I've found %s orders.", $total));
1246
+ }
 
 
1247
 
1248
+ $replies = array();
1249
+ foreach($ordersIDs as $orderID)
1250
+ {
1251
+ //$message = $chatbotHelper->prepareFacebookOrderMessages($orderID);
1252
+ $payload = $chatbotHelper->prepareFacebookOrderPayload($orderID);
1253
+ if (!empty($payload)) // TODO
1254
  {
1255
+ $order = Mage::getModel('sales/order')->load($orderID);
1256
+ $orderNumber = $order->getIncrementId();
1257
+ $reply = array(
1258
+ 'content_type' => 'text',
1259
+ 'title' => $orderNumber,
1260
+ 'payload' => $chatbotHelper->_reorderCmd['command'] . $orderID
1261
+ );
1262
+ array_push($replies, $reply);
1263
+ if ($i >= $showMore)
1264
  {
1265
+ if (($i + 1) != $total && $i >= ($showMore + $listingLimit)) // if isn't the 'last but one' and $i is bigger than listing limit + what was shown last time ($show_more)
 
 
 
 
 
 
1266
  {
1267
+ $reply = array(
1268
+ 'content_type' => 'text',
1269
+ 'title' => $mageHelper->__("Show more orders"),
1270
+ 'payload' => $listMoreOrders . (string)($i + 1)
1271
+ );
1272
+ array_push($replies, $reply);
1273
+ if ($chatdata->getFacebookConvState() != $chatbotHelper->_listOrdersState)
1274
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_listOrdersState))
1275
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
1276
+ $flagBreak = true;
1277
+ }
1278
+ else if (($i + 1) == $total) // if it's the last one, back to _startState
1279
+ {
1280
+ $facebook->postMessage($chatId, $mageHelper->__("And that was the last one."));
1281
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_startState))
1282
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
1283
+ }
1284
+
1285
+ $facebook->sendReceiptTemplate($chatId, $payload);
1286
+ if ($flagBreak)
1287
+ {
1288
+ if (!empty($replies))
1289
  {
1290
+ $message = $mageHelper->__("If you want to reorder one of these orders, choose it below, or choose '%s' to list more orders.", $mageHelper->__("Show more orders"));
1291
+ $facebook->sendQuickReply($chatId, $message, $replies);
 
1292
  }
1293
+ break;
 
 
 
1294
  }
 
1295
  }
1296
+ $i++;
1297
  }
 
 
 
 
1298
  }
1299
+ if ($i == 0)
1300
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
1301
+ // else if (!$chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_listOrdersState))
1302
+ // $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
 
1303
  }
1304
  }
1305
  else
1306
+ {
1307
+ $facebook->postMessage($chatId, $mageHelper->__("This account has no orders."));
1308
+ return $chatdata->respondSuccess();
1309
+ }
1310
  }
1311
+ else
1312
+ $facebook->postMessage($chatId, $chatbotHelper->_loginFirstMessage);
1313
+ return $chatdata->respondSuccess();
1314
+ }
1315
+ else if ($chatbotHelper->startsWith($text, $chatbotHelper->_reorderCmd['command'])) // ignore alias // old checkCommandWithValue
1316
+ {
1317
+ if ($chatdata->getIsLogged() == "1")
1318
  {
1319
+ $facebook->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("please wait while I add the products from this order to your cart."));
1320
+ $facebook->sendChatAction($chatId, "typing_on");
1321
+ $errorFlag = false;
1322
+ $cmdvalue = $chatbotHelper->getCommandValue($text, $chatbotHelper->_reorderCmd['command']);
1323
+ if ($cmdvalue)
1324
  {
1325
+ if ($chatdata->clearCart())
 
 
 
 
1326
  {
1327
+ $order = Mage::getModel('sales/order')->load($cmdvalue);
1328
+ if ($order->getId())
1329
  {
1330
+ foreach($order->getAllVisibleItems() as $item) {
1331
+ if (!$chatdata->addProd2Cart($item->getProductId()))
1332
+ $errorFlag = true;
 
 
 
 
1333
  }
 
 
1334
  }
1335
  else
1336
  $errorFlag = true;
1337
  }
1338
  else
1339
  $errorFlag = true;
 
 
 
 
 
 
 
1340
  }
1341
  else
1342
+ $errorFlag = true;
1343
+
1344
+ if ($errorFlag)
1345
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
1346
+ else if (!$chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_reorderState))
1347
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
1348
+ else // success!!
1349
+ $facebook->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("to checkout send") . ' "' . $chatbotHelper->_checkoutCmd['command'] . '"');
1350
  }
1351
+ else
1352
+ $facebook->postMessage($chatId, $chatbotHelper->_loginFirstMessage);
1353
+ return $chatdata->respondSuccess();
1354
+ }
1355
+ else if ($chatbotHelper->checkCommand($text, $chatbotHelper->_trackOrderCmd))
1356
+ {
1357
+ if ($chatdata->getIsLogged() == "1")
1358
  {
1359
+ $ordersIDs = $chatbotHelper->getOrdersIdsFromCustomer($chatdata->getCustomerId());
1360
+ if ($ordersIDs)
1361
  {
1362
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_trackOrderState))
1363
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
 
 
 
 
 
 
1364
  else
1365
+ $facebook->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("send the order number."));
1366
  }
1367
  else
1368
+ $facebook->postMessage($chatId, $mageHelper->__("Your account dosen't have any orders."));
 
1369
  }
1370
+ else
1371
+ $facebook->postMessage($chatId, $chatbotHelper->_loginFirstMessage);
1372
+ return $chatdata->respondSuccess();
1373
+ }
1374
+ else if ($chatbotHelper->checkCommand($text, $chatbotHelper->_supportCmd))
1375
+ {
1376
+ $supportEnabled = $chatdata->getEnableSupport();
1377
+ $errorFlag = false;
1378
+ if ($supportEnabled == "1")
1379
  {
1380
+ if ($chatdata->getTelegramConvState() != $chatbotHelper->_supportState) // TODO
 
 
1381
  {
1382
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_supportState))
1383
+ $errorFlag = true;
 
 
 
 
 
1384
  else
1385
+ $facebook->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("what do you need support for?") . " " . $chatbotHelper->_cancelMessage);
1386
  }
1387
  else
1388
+ $facebook->postMessage($chatId, $mageHelper->__("You're already on support in other chat application, please close it before opening a new one."));
1389
+ }
1390
+ else
1391
+ $facebook->postMessage($chatId, $mageHelper->__("I'm sorry, you can't ask for support now. Please try again later."));
1392
 
1393
+ if ($errorFlag)
1394
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
1395
+ return $chatdata->respondSuccess();
1396
+ }
1397
+ else if ($chatbotHelper->checkCommand($text, $chatbotHelper->_sendEmailCmd))
1398
+ {
1399
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_sendEmailState))
1400
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
1401
+ else
1402
+ {
1403
+ $facebook->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("write the email content."));
1404
+ $facebook->postMessage($chatId, $mageHelper->__("By doing this you agree that we may contact you directly via chat message.") . " " . $chatbotHelper->_cancelMessage);
1405
  }
1406
+ return $chatdata->respondSuccess();
1407
+ }
1408
+ else // fallback
1409
+ {
1410
+ // handle default replies
1411
+ if ($enableReplies == "1" && !$blockerStates)
1412
  {
1413
+ $defaultReplies = Mage::getStoreConfig('chatbot_enable/facebook_config/default_replies');
1414
+ if ($defaultReplies)
 
1415
  {
1416
+ $replies = unserialize($defaultReplies);
1417
+ if (is_array($replies))
1418
+ {
1419
+ $hasWitaiReplies = false;
1420
+ foreach($replies as $reply)
1421
+ {
1422
+ // MODES
1423
+ // 0 =>'Similarity'
1424
+ // 1 =>'Starts With'
1425
+ // 2 =>'Ends With'
1426
+ // 3 =>'Contains'
1427
+ // 4 =>'Match Regular Expression'
1428
+ // 5 =>'Equals to'
1429
+ // 6 =>'wit.ai'
1430
+
1431
+ $matched = false;
1432
+ $match = $reply["match_sintax"];
1433
+ $matchMode = $reply["match_mode"];
1434
+
1435
+ if ($reply["match_case"] == "0")
1436
+ {
1437
+ $match = strtolower($match);
1438
+ $textToMatch = strtolower($text);
1439
+ }
1440
+ else
1441
+ $textToMatch = $text;
1442
+
1443
+ if ($matchMode == "0") // Similarity
1444
+ {
1445
+ $similarity = $reply["similarity"];
1446
+ if (is_numeric($similarity))
1447
+ {
1448
+ if (!($similarity >= 1 && $similarity <= 100))
1449
+ $similarity = 100;
1450
+ }
1451
+ else
1452
+ $similarity = 100;
1453
+
1454
+ similar_text($textToMatch, $match, $percent);
1455
+ if ($percent >= $similarity)
1456
+ $matched = true;
1457
+ }
1458
+ else if ($matchMode == "1") // Starts With
1459
+ {
1460
+ if ($chatbotHelper->startsWith($textToMatch, $match))
1461
+ $matched = true;
1462
+ }
1463
+ else if ($matchMode == "2") // Ends With
1464
+ {
1465
+ if ($chatbotHelper->endsWith($textToMatch, $match))
1466
+ $matched = true;
1467
+ }
1468
+ else if ($matchMode == "3") // Contains
1469
+ {
1470
+ if (strpos($textToMatch, $match) !== false)
1471
+ $matched = true;
1472
+ }
1473
+ else if ($matchMode == "4") // Match Regular Expression
1474
+ {
1475
+ if (preg_match($match, $textToMatch))
1476
+ $matched = true;
1477
+ }
1478
+ else if ($matchMode == "5") // Equals to
1479
+ {
1480
+ if ($textToMatch == $match)
1481
+ $matched = true;
1482
+ }
1483
+ else if (($matchMode == "6") && (isset($this->_witAi))) // wit.ai and witAi is set
1484
+ {
1485
+ $witAiConfidence = Mage::getStoreConfig('chatbot_enable/witai_config/witai_confidence');
1486
+ if (!is_numeric($witAiConfidence) || (int)$witAiConfidence > 100)
1487
+ $witAiConfidence = $defaultConfidence; // default acceptable confidence percentage
1488
+
1489
+ if (!$hasWitaiReplies) // avoid multiple posts to witai with the same $text
1490
+ {
1491
+ $witResponse = $this->_witAi->getTextResponse($text);
1492
+ $hasWitaiReplies = true;
1493
+ }
1494
+
1495
+ if (!empty($witResponse))
1496
+ {
1497
+ if (property_exists($witResponse->entities, $match))
1498
+ {
1499
+ foreach ($witResponse->entities->{$match} as $m)
1500
+ {
1501
+ if (((float)$m->confidence * 100) < (float)$witAiConfidence)
1502
+ continue;
1503
+
1504
+ $matched = true;
1505
+ break;
1506
+ }
1507
+ }
1508
+ }
1509
+ }
1510
+
1511
+ if ($matched)
1512
+ {
1513
+ $message = $reply["reply_phrase"];
1514
+ if ($username)
1515
+ $message = str_replace("{customername}", $username, $message);
1516
+ if ($reply['reply_mode'] == "1") // Text and Command
1517
+ {
1518
+ $cmdId = $reply['command_id'];
1519
+ if (!empty($cmdId))
1520
+ $text = $chatdata->getCommandString($cmdId)['command']; // 'transform' original text into a known command
1521
+ if (!empty($message))
1522
+ {
1523
+ $count = strlen($message);
1524
+ if ($count > $messageLimit)
1525
+ {
1526
+ $total = ceil($count / $messageLimit);
1527
+ $start = 0;
1528
+ for ($i = 1; $i <= $total; $i++) // loop to send big messages
1529
+ {
1530
+ $cut = ($count / $total) * $i;
1531
+ if ($cut >= $count) // if cut is equal or bigger to message itself
1532
+ $end = $count;
1533
+ else
1534
+ $end = strpos($message, ' ', $cut);
1535
+ $tempMessage = substr($message, $start, $end);
1536
+ $facebook->postMessage($chatId, $tempMessage);
1537
+ $start = $end;
1538
+ }
1539
+ }
1540
+ else
1541
+ $facebook->postMessage($chatId, $message);
1542
+ }
1543
+ }
1544
+ else if ($reply['reply_mode'] == "0") // Text Only
1545
+ {
1546
+ if (!empty($message))
1547
+ {
1548
+ $count = strlen($message);
1549
+ if ($count > $messageLimit)
1550
+ {
1551
+ $total = ceil($count / $messageLimit);
1552
+ $start = 0;
1553
+ for ($i = 1; $i <= $total; $i++) // loop to send big messages
1554
+ {
1555
+ $cut = ($count / $total) * $i;
1556
+ if ($cut >= $count) // if cut is equal or bigger to message itself
1557
+ $end = $count;
1558
+ else
1559
+ $end = strpos($message, ' ', $cut);
1560
+ $tempMessage = substr($message, $start, $end);
1561
+ $facebook->postMessage($chatId, $tempMessage);
1562
+ $start = $end;
1563
+ }
1564
+ }
1565
+ else
1566
+ $facebook->postMessage($chatId, $message);
1567
+
1568
+ if ($reply["stop_processing"] == "1")
1569
+ return $chatdata->respondSuccess();
1570
+ }
1571
+ }
1572
+ else //if ($reply['reply_mode'] == "2") // No Reply
1573
+ {
1574
+ return $chatdata->respondSuccess();
1575
+ //break;
1576
+ }
1577
+ break;
1578
+ }
1579
+ }
1580
+ }
1581
  }
 
1582
  }
1583
+
1584
+ $chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_startState); // back to start state
1585
+ if ($enableFinalMessage2Support == "1")
1586
  {
1587
+ $errorFlag = true;
1588
+ if ($supportGroupId == $chatbotHelper->_tgBot)
1589
+ if ($chatdata->foreignMessageToTelegramSupport($chatId, $originalText, $chatdata->_apiType, $username)) // send chat id, original text, "facebook" and username
1590
+ {
1591
+ // if ($chatdata->getTelegramConvState() != $chatbotHelper->_supportState) // TODO
1592
+ // $chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_supportState);
1593
+ $errorFlag = false;
1594
+ }
1595
+
1596
+ if ($errorFlag)
1597
+ $facebook->postMessage($chatId, $chatbotHelper->_errorMessage);
1598
+ else
1599
+ $facebook->postMessage($chatId,
1600
+ $mageHelper->__("Sorry, I didn't understand that.") . " " .
1601
+ $mageHelper->__("Please wait while our support check your message so you can talk to a real person.") . " " .
1602
+ $chatbotHelper->_cancelMessage
1603
+ ); // TODO
1604
+ return $chatdata->respondSuccess();
1605
+ }
1606
+ else // process cases where the customer message wasn't understandable
1607
+ {
1608
+ if (isset($this->_witAi) && !($this->_isWitAi))
1609
  {
1610
+ $witAiConfidence = Mage::getStoreConfig('chatbot_enable/witai_config/witai_confidence');
1611
+ if (!is_numeric($witAiConfidence) || (int)$witAiConfidence > 100)
1612
+ $witAiConfidence = $defaultConfidence; // default acceptable confidence percentage
1613
+
1614
+ $witResponse = $this->_witAi->getTextResponse($text);
1615
+ $hasIntent = false;
1616
+
1617
+ if (!empty($witResponse))
1618
+ {
1619
+ if (property_exists($witResponse->entities, "facebook_intent"))
1620
+ {
1621
+ $intents = $witResponse->entities->facebook_intent;
1622
+ $hasIntent = true;
1623
+ }
1624
+ else if (property_exists($witResponse->entities, "intent"))
1625
  {
1626
+ $intents = $witResponse->entities->intent;
1627
+ $hasIntent = true;
 
1628
  }
1629
+ }
1630
 
1631
+ if ($hasIntent)
1632
+ {
1633
+ $enableConfirmMessage = Mage::getStoreConfig('chatbot_enable/witai_config/confirmation_message');
1634
+ $messages = array(
1635
+ "Okay, so you want me to list the categories for you.", //_listCategoriesCmd
1636
+ "Okay, so you want to search for a product.", //_searchCmd
1637
+ "Okay, so you want to login.", //_loginCmd
1638
+ "Okay, so you want to list orders.", //_listOrdersCmd
1639
+ "Okay, so you want to reorder.", //_reorderCmd shouldn't be used
1640
+ "Okay, so you want to add a product to the cart.", //_add2CartCmd shouldn't be used
1641
+ "Okay, so you want to checkout.", //_checkoutCmd
1642
+ "Okay, so you want to clear your cart.", //_clearCartCmd
1643
+ "Okay, so you want to track your order.", //_trackOrderCmd
1644
+ "Okay, so you want support.", //_supportCmd
1645
+ "Okay, so you want to send us an email.", //_sendEmailCmd
1646
+ "Okay, so you want to cancel.", //_cancelCmd shouldn't be used
1647
+ "Okay, so you want to help.", //_helpCmd
1648
+ "Okay, so you want to know more about us.", //_aboutCmd
1649
+ "Okay, so you want to logout.", //_logoutCmd
1650
+ "Okay, so you want to register to our store." //registerCmd
1651
+ );
1652
+
1653
+ $i = 1;
1654
+ $hasKeyword = false;
1655
+ $break = false;
1656
+
1657
+ foreach ($messages as $message)
1658
+ {
1659
+ $key = $chatdata->getCommandString($i)['command'];
1660
+ foreach ($intents as $intent)
1661
+ {
1662
+ if ($intent->value == $key && (((float)$intent->confidence * 100) >= (float)$witAiConfidence))
1663
+ {
1664
+ if (property_exists($witResponse->entities, "keyword"))
1665
+ {
1666
+ if (isset($witResponse->entities->keyword))
1667
+ {
1668
+ foreach ($witResponse->entities->keyword as $keyword)
1669
+ {
1670
+ if (((float)$keyword->confidence * 100) < (float)$witAiConfidence)
1671
+ continue;
1672
+ if ($intent->value == $chatbotHelper->_searchCmd['command'])
1673
+ {
1674
+ $chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_searchState);
1675
+ //$facebook->_originalText = $listMoreSearch . $witResponse->entities->keyword . ",1";
1676
+ $facebook->_originalText = $keyword->value;
1677
+ $hasKeyword = true;
1678
+ break;
1679
+ }
1680
+ else if ($intent->value == $chatbotHelper->_listCategoriesCmd['command'])
1681
+ {
1682
+ $_category = Mage::getModel('catalog/category')->loadByAttribute('name', $keyword->value);
1683
+ if ($_category) // check if variable isn't false/empty
1684
+ {
1685
+ if ($_category->getId()) // check if is a valid category
1686
+ {
1687
+ $chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_listCategoriesState);
1688
+ //$facebook->_originalText = $listMoreCategories . $witResponse->entities->keyword . ",1";
1689
+ $facebook->_originalText = $keyword->value;
1690
+ $hasKeyword = true;
1691
+ }
1692
+ }
1693
+ break;
1694
+ }
1695
+ else if ($intent->value == $chatbotHelper->_trackOrderCmd['command'])
1696
+ {
1697
+ if ($chatdata->getIsLogged() == "1")
1698
+ {
1699
+ $chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_trackOrderState);
1700
+ $facebook->_originalText = $keyword->value;
1701
+ $hasKeyword = true;
1702
+ }
1703
+ else
1704
+ {
1705
+ $facebook->postMessage(array('chat_id' => $chatId, 'text' => $chatbotHelper->_loginFirstMessage));
1706
+ $break = true;
1707
+ return $chatdata->respondSuccess();
1708
+ }
1709
+ break;
1710
+ }
1711
+ else if ($intent->value == $chatbotHelper->_supportCmd['command'])
1712
+ {
1713
+ $chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_supportState);
1714
+ $facebook->_originalText = $keyword->value;
1715
+ $hasKeyword = true;
1716
+ break;
1717
+ }
1718
+ else if ($intent->value == $chatbotHelper->_sendEmailCmd['command'])
1719
+ {
1720
+ $chatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_sendEmailState);
1721
+ $facebook->_originalText = $keyword->value;
1722
+ $hasKeyword = true;
1723
+ break;
1724
+ }
1725
+ }
1726
+ if ($break)
1727
+ break;
1728
+ }
1729
+ }
1730
+ if (!$hasKeyword)
1731
+ {
1732
+ $facebook->_originalText = $key; // replace text with command
1733
+ if ($enableConfirmMessage == "1")
1734
+ $facebook->postMessage($chatId, $mageHelper->__($message));
1735
+ }
1736
+
1737
+ $this->_isWitAi = true;
1738
+ return $this->processText();
1739
+ break;
1740
+ }
1741
+ }
1742
+ $i++;
1743
+ }
1744
+ }
1745
  }
1746
+ if (!$this->_isWitAi)
1747
  {
1748
+ $message = $mageHelper->__("Sorry, I didn't understand that.");
1749
+ $fallbackQty = 0;
1750
 
1751
+ $fallbackLimit = Mage::getStoreConfig('chatbot_enable/facebook_config/fallback_message_quantity');
1752
+ if (!empty($fallbackLimit))
1753
+ {
1754
+ $fallbackQty = (int)$chatdata->getFacebookFallbackQty();
1755
+ $fallbackQty++;
1756
+ if (!is_numeric($fallbackLimit))
1757
+ $fallbackLimit = 3;
1758
+ if ($fallbackQty >= (int)$fallbackLimit)
1759
+ {
1760
+ $fallbackMessage = Mage::getStoreConfig('chatbot_enable/facebook_config/fallback_message');
1761
+ if (!empty($fallbackMessage))
1762
+ {
1763
+ $fallbackQty = 0;
1764
+ $message = $fallbackMessage;
1765
+ }
1766
+ }
1767
+ }
1768
+
1769
+ $chatdata->updateChatdata("facebook_fallback_qty", (string)$fallbackQty);
1770
+ $facebook->postMessage($chatId, $message); // TODO
1771
 
1772
  $cmdListingOnError = Mage::getStoreConfig('chatbot_enable/facebook_config/enable_error_command_list');
1773
  if ($cmdListingOnError == "1")
1779
  }
1780
  }
1781
  }
1782
+ $chatdata->respondSuccess();
 
1783
  }
1784
  }
1785
 
app/code/community/Werules/Chatbot/Model/Api/Facebook/Messenger.php CHANGED
@@ -13,7 +13,7 @@
13
  class Messenger {
14
 
15
  private $bot_id = "";
16
- private $api_version = "v2.8";
17
  private $data = array();
18
  private $updates = array();
19
 
@@ -181,6 +181,33 @@
181
  );
182
  }
183
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  /// Get the text of the current message
185
  public function Text() {
186
  return $this->data["entry"][0]["messaging"][0]["message"]["text"];
@@ -196,16 +223,36 @@
196
  return $this->data['entry'][0]['messaging'][0]['sender']['id'];
197
  }
198
 
 
 
 
 
 
199
  /// Get raw data
200
  public function RawData() {
201
  return $this->data;
202
  }
203
 
 
 
 
 
 
 
 
 
 
 
204
  /// Get payload
205
  public function getPayload() {
206
  return $this->data["entry"][0]["messaging"][0]["postback"]["payload"];
207
  }
208
 
 
 
 
 
 
209
  /// Get message timestamp
210
  public function getMessageTimestamp() {
211
  return $this->data["entry"][0]["time"];
@@ -216,11 +263,16 @@
216
  return $this->data["entry"][0]["messaging"][0]["message"]["mid"];
217
  }
218
 
219
- /// Get the message_id of the current message
220
  public function getEcho() {
221
  return $this->data["entry"][0]["messaging"][0]["message"]["is_echo"];
222
  }
223
 
 
 
 
 
 
224
  private function sendAPIRequest($url, array $content, $post = true, $response = true) {
225
  $ch = curl_init($url);
226
  if ($post) {
13
  class Messenger {
14
 
15
  private $bot_id = "";
16
+ private $api_version = "v2.9";
17
  private $data = array();
18
  private $updates = array();
19
 
181
  );
182
  }
183
 
184
+ // send elements
185
+ // $elements = array(
186
+ // array(
187
+ // 'title' => 'TITLE_TEXT_HERE',
188
+ // 'item_url' => 'ITEM_URL_HERE',
189
+ // 'image_url' => 'IMAGE_URL_HERE',
190
+ // 'subtitle' => 'SUBTITLE_HERE',
191
+ // 'buttons' => $buttons
192
+ // )
193
+ // );
194
+ // https://developers.facebook.com/docs/messenger-platform/send-api-reference/receipt-template
195
+ public function sendReceiptTemplate($chat_id, array $payload) {
196
+ return $this->endpoint("me/messages",
197
+ array(
198
+ 'recipient' => array(
199
+ 'id' => $chat_id
200
+ ),
201
+ 'message' => array(
202
+ 'attachment' => array(
203
+ 'type' => 'template',
204
+ 'payload' => $payload
205
+ )
206
+ )
207
+ )
208
+ );
209
+ }
210
+
211
  /// Get the text of the current message
212
  public function Text() {
213
  return $this->data["entry"][0]["messaging"][0]["message"]["text"];
223
  return $this->data['entry'][0]['messaging'][0]['sender']['id'];
224
  }
225
 
226
+ /// Get the recipient_id of the current message
227
+ public function RecipientID() {
228
+ return $this->data['entry'][0]['messaging'][0]['recipient']['id'];
229
+ }
230
+
231
  /// Get raw data
232
  public function RawData() {
233
  return $this->data;
234
  }
235
 
236
+ /// Get m.me ref type
237
+ public function getReferralType() {
238
+ return $this->data["entry"][0]["messaging"][0]["referral"]["type"];
239
+ }
240
+
241
+ /// Get m.me ref data
242
+ public function getReferralRef() {
243
+ return $this->data["entry"][0]["messaging"][0]["referral"]["ref"];
244
+ }
245
+
246
  /// Get payload
247
  public function getPayload() {
248
  return $this->data["entry"][0]["messaging"][0]["postback"]["payload"];
249
  }
250
 
251
+ /// Get quickreply payload
252
+ public function getQuickReplyPayload() {
253
+ return $this->data["entry"][0]["messaging"][0]["message"]["quick_reply"]["payload"];
254
+ }
255
+
256
  /// Get message timestamp
257
  public function getMessageTimestamp() {
258
  return $this->data["entry"][0]["time"];
263
  return $this->data["entry"][0]["messaging"][0]["message"]["mid"];
264
  }
265
 
266
+ /// Get the is_echo of the current message
267
  public function getEcho() {
268
  return $this->data["entry"][0]["messaging"][0]["message"]["is_echo"];
269
  }
270
 
271
+ /// Get the app_id of the current message
272
+ public function getAppId() {
273
+ return $this->data["entry"][0]["messaging"][0]["message"]["app_id"];
274
+ }
275
+
276
  private function sendAPIRequest($url, array $content, $post = true, $response = true) {
277
  $ch = curl_init($url);
278
  if ($post) {
app/code/community/Werules/Chatbot/Model/Api/Telegram/Handler.php CHANGED
@@ -1,1314 +1,1764 @@
1
  <?php
2
- include("Telegram.php");
 
3
  //$api_path = Mage::getModuleDir('', 'Werules_Chatbot') . DS . "Model" . DS . "Api" . DS . "witAI" . DS;
4
- //include($api_path . "witAI.php");
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
  class Werules_Chatbot_Model_Api_Telegram_Handler extends Werules_Chatbot_Model_Chatdata
7
  {
 
 
8
  public function _construct()
9
  {
10
  //parent::_construct();
11
  //$this->_init('chatbot/api_telegram_handler'); // this is location of the resource file.
 
 
 
 
12
  }
13
 
14
- public function foreignMessageToSupport($chat_id, $text, $api_name, $customerName)
15
  {
16
- $chatdata = Mage::getModel('chatbot/chatdata');
17
- if ($api_name == $chatdata->_fbBot && $chat_id)
18
- {
19
- $chatdata->load($chat_id, 'facebook_chat_id');
20
- if (is_null($chatdata->getFacebookChatId()))
21
- { // should't happen
22
- $chatdata->updateChatdata("facebook_chat_id", $chat_id);
23
- }
24
- }
25
-
26
- $chatdata->_apiType = $chatdata->_tgBot;
27
- $apiKey = $chatdata->getApikey($chatdata->_apiType); // get telegram bot api
28
- if ($apiKey)
29
- {
30
- $telegram = new Telegram($apiKey);
31
-
32
- $mageHelper = Mage::helper('core');
33
- $supportgroup = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_support_group');
34
- if (!empty($supportgroup))
35
- {
36
- try{
37
- if ($supportgroup[0] == "g") // remove the 'g' from groupd id, and add '-'
38
- $supportgroup = "-" . ltrim($supportgroup, "g");
39
-
40
- if (!$customerName)
41
- $customerName = $mageHelper->__("Not informed");
42
-
43
- $message = $mageHelper->__("Message via") . " " . $api_name . ":\n" . $mageHelper->__("From") . ": " . $customerName . "\n" . $text;
44
- $result = $telegram->sendMessage(array('chat_id' => $supportgroup, 'text' => $message));
45
- $mid = $result['result']['message_id'];
46
- if (!empty($mid))
47
- {
48
- $chatdata->updateChatdata("last_support_message_id", $mid);
49
- $chatdata->updateChatdata("last_support_chat", $api_name);
50
- }
51
- }
52
- catch (Exception $e){
53
- return false;
54
- }
55
-
56
- return true;
57
- }
58
- }
59
-
60
- return false;
61
  }
62
 
63
- public function telegramHandler($apiKey)
64
  {
65
- if (empty($apiKey)) // if no apiKey available, break proccess
66
- return "";
67
-
68
  // Instances the Telegram class
69
- $telegram = new Telegram($apiKey);
 
 
 
 
70
 
71
  // Take text and chat_id from the message
72
- $text = $telegram->Text();
73
- $chatId = $telegram->ChatID();
74
- $messageId = $telegram->MessageID();
75
  $inlineQuery = $telegram->Inline_Query();
 
76
 
77
  $enableLog = Mage::getStoreConfig('chatbot_enable/general_config/enable_post_log');
78
  if ($enableLog == "1") // log all posts
79
  Mage::log("Post Data:\n" . var_export($telegram->getData(), true) . "\n\n", null, 'chatbot_telegram.log');
80
 
 
 
81
  if (!empty($inlineQuery))
82
  {
83
- $query = $inlineQuery['query'];
84
- $queryId = $inlineQuery['id'];
85
- $results = array();
86
- $chatdataInline = Mage::getModel('chatbot/chatdata');
87
- if (!empty($query))
88
  {
89
- $productIDs = $chatdataInline->getProductIdsBySearch($query);
90
- $mageHelperInline = Mage::helper('core');
91
- if (!empty($productIDs))
 
 
92
  {
93
- //$total = count($productIDs);
94
- $i = 0;
95
- foreach($productIDs as $productID)
96
  {
97
- $product = Mage::getModel('catalog/product')->load($productID);
98
- if ($product->getId())
 
99
  {
100
- if ($product->getStockItem()->getIsInStock() > 0)
 
101
  {
102
- if ($i >= 5)
103
- break;
104
- $productUrl = $product->getProductUrl();
105
- $productImage = $product->getImageUrl();
106
- $productName = $product->getName();
107
- $productDescription = $chatdataInline->excerpt($product->getShortDescription(), 60);
108
- $placeholder = Mage::getSingleton("catalog/product_media_config")->getBaseMediaUrl() . DS . "placeholder" . DS . Mage::getStoreConfig("catalog/placeholder/thumbnail_placeholder");
109
- if (empty($productImage))
110
- $productImage = $placeholder;
111
-
112
- $message = $productName . "\n" .
113
- $mageHelperInline->__("Price") . ": " . Mage::helper('core')->currency($product->getPrice(), true, false) . "\n" .
114
- $productDescription . "\n" .
115
- $productUrl
116
- ;
117
-
118
- $result = array(
119
- 'type' => 'article',
120
- 'id' => $queryId . "/" . (string)$i,
121
- 'title' => $productName,
122
- 'description' => $productDescription,
123
- 'thumb_url' => $productImage,
124
- 'input_message_content' => array(
125
- 'message_text' => $message,
126
- 'parse_mode' => 'HTML'
127
- )
128
- );
129
-
130
- array_push($results, $result);
131
- $i++;
 
 
 
132
  }
133
  }
134
- }
135
 
136
- $telegram->answerInlineQuery(array('inline_query_id' => $queryId, 'results' => json_encode($results)));
137
- }
138
- else
139
- {
140
- $results = array(
141
- array(
142
- 'type' => 'article',
143
- 'id' => $queryId . "/0",
144
- 'title' => $mageHelperInline->__("Sorry, no products found for this criteria."),
145
- 'input_message_content' => array(
146
- 'message_text' => $mageHelperInline->__("Sorry, no products found for this criteria.")
 
147
  )
148
- )
149
- );
150
- $telegram->answerInlineQuery(array('inline_query_id' => $queryId, 'results' => json_encode($results)));
151
  }
152
  }
153
-
154
  $telegram->respondSuccess();
155
  }
156
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  // configs
158
- //$enable_witai = Mage::getStoreConfig('chatbot_enable/witai_config/enable_witai');
159
  $enabledBot = Mage::getStoreConfig('chatbot_enable/telegram_config/enable_bot');
160
  $enableReplies = Mage::getStoreConfig('chatbot_enable/telegram_config/enable_default_replies');
161
  $enableEmptyCategoriesListing = Mage::getStoreConfig('chatbot_enable/general_config/list_empty_categories');
162
  $enableFinalMessage2Support = Mage::getStoreConfig('chatbot_enable/general_config/enable_support_final_message');
163
  $supportGroupId = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_support_group');
164
  $showMore = 0;
165
- $cat_id = null;
166
  $moreOrders = false;
 
167
  $listingLimit = 5;
168
  $categoryLimit = 18;
169
  $listMoreCategories = "/lmc_";
170
  $listMoreSearch = "/lms_";
171
  $listMoreOrders = "/lmo_";
 
 
 
 
172
 
173
- if (!is_null($text) && !is_null($chatId))
174
- {
175
- // Instances facebook user details
176
- $username = $telegram->Username();
177
-
178
- // Instances the model class
179
- $chatdata = Mage::getModel('chatbot/chatdata')->load($chatId, 'telegram_chat_id');
180
- $chatdata->_apiType = $chatdata->_tgBot;
181
 
182
- if ($messageId == $chatdata->getTelegramMessageId()) // prevents to reply the same request twice
183
- return $telegram->respondSuccess();
184
- else if ($chatdata->getTelegramChatId())
185
- $chatdata->updateChatdata('telegram_message_id', $messageId); // if this fails, it may send the same message twice
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
 
187
- // bot enabled/disabled
188
- if ($enabledBot != "1")
189
  {
190
- $disabledMessage = Mage::getStoreConfig('chatbot_enable/telegram_config/disabled_message');
191
- if (!empty($disabledMessage))
192
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $disabledMessage));
193
- return $telegram->respondSuccess();
 
194
  }
 
195
 
196
- // send feedback to user
197
- $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
 
 
 
 
 
 
 
 
 
 
 
198
 
199
- // show more handler, may change the conversation state
200
- if ($chatdata->getTelegramConvState() == $chatdata->_listProductsState || $chatdata->getTelegramConvState() == $chatdata->_listOrdersState) // listing products
 
 
 
 
 
201
  {
202
- if ($chatdata->startsWith($text, $listMoreCategories)) // old checkCommandWithValue
203
  {
204
- if ($chatdata->updateChatdata('telegram_conv_state', $chatdata->_listCategoriesState))
205
- {
206
- $value = $this->getCommandValue($text, $listMoreCategories);
207
- $arr = explode("_", $value);
208
- $cat_id = (int)$arr[0]; // get category id
209
- $showMore = (int)$arr[1]; // get where listing stopped
210
- }
211
  }
212
- else if ($chatdata->startsWith($text, $listMoreSearch)) // old checkCommandWithValue
 
 
 
213
  {
214
- if ($chatdata->updateChatdata('telegram_conv_state', $chatdata->_searchState))
215
- {
216
- $value = $this->getCommandValue($text, $listMoreSearch);
217
- $arr = explode("_", $value);
218
- $showMore = (int)end($arr); // get where listing stopped
219
- $value = str_replace("_" . (string)$showMore, "", $value);
220
- $text = str_replace("_", " ", $value); // get search criteria
221
- }
222
  }
223
- else if ($chatdata->startsWith($text, $listMoreOrders)) // old checkCommandWithValue
 
 
 
224
  {
225
- if ($chatdata->updateChatdata('telegram_conv_state', $chatdata->_listOrdersState))
226
- {
227
- $value = $this->getCommandValue($text, $listMoreOrders);
228
- $showMore = (int)$value; // get where listing stopped
229
- $moreOrders = true;
230
- }
231
  }
232
- // else
233
- // $chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState);
234
  }
 
 
 
235
 
236
- // instances conversation state
237
- $conversationState = $chatdata->getTelegramConvState();
238
 
239
- // mage helper
240
- $mageHelper = Mage::helper('core');
241
 
242
- if ($supportGroupId[0] == "g") // remove the 'g' from groupd id, and add '-'
243
- $supportGroupId = "-" . ltrim($supportGroupId, "g");
244
 
245
- // handle admin stuff
246
- //$isAdmin = $chatdata->getIsAdmin();
247
- // if it's a group message
248
- if ($telegram->messageFromGroup())
 
 
249
  {
250
- if ($chatId == $supportGroupId) // if the group sending the message is the support group
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
  {
252
- $replyMessageId = $telegram->ReplyToMessageID();
253
- if (!empty($replyMessageId)) // if the message is replying another message
 
 
 
254
  {
255
- $foreignchatdata = Mage::getModel('chatbot/chatdata')->load($replyMessageId, 'last_support_message_id');
256
- if (!empty($foreignchatdata->getLastSupportMessageId())) // check if current reply message id is saved on databse
257
- {
258
- $api_name = $foreignchatdata->getLastSupportChat();
259
- if ($api_name == $foreignchatdata->_fbBot)
260
- Mage::getModel('chatbot/api_facebook_handler')->foreignMessageFromSupport($foreignchatdata->getFacebookChatId(), $text); // send chat id and the original text
261
- }
262
- else
 
 
 
 
 
 
 
 
 
 
 
 
263
  {
264
- $replyFromUserId = $telegram->ReplyToMessageFromUserID();
265
- if (!is_null($replyFromUserId))
266
  {
267
- $admEndSupport = "/" . $chatdata->_admEndSupportCmd;
268
- $admBlockSupport = "/" . $chatdata->_admBlockSupportCmd;
269
- $admEnableSupport = "/" . $chatdata->_admEnableSupportCmd;
270
-
271
- $customerData = Mage::getModel('chatbot/chatdata')->load($replyFromUserId, 'telegram_chat_id');
272
- if ($text == $admEndSupport) // finish customer support
273
  {
274
- // TODO IMPORTANT remember to switch off all other supports
275
- $customerData->updateChatdata('telegram_conv_state', $chatdata->_startState);
276
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Done. The customer is no longer on support.")));
277
- $telegram->sendMessage(array('chat_id' => $replyFromUserId, 'text' => $mageHelper->__("Support ended."))); // TODO
 
 
 
278
  }
279
- else if ($text == $admBlockSupport) // block user from using support
280
  {
281
- $customerData->updateChatdata('enable_support', "0"); // disable support
282
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Done. The customer is no longer able to enter support."))); // TODO
 
 
 
 
 
283
  }
284
- else if ($text == $admEnableSupport) // block user from using support
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
285
  {
286
- $customerData->updateChatdata('enable_support', "1"); // enable support
287
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Done. The customer is now able to enter support."))); // TODO
 
 
 
 
 
288
  }
289
- else // if no command, then it's replying the user
290
  {
291
- if ($customerData->getTelegramConvState() != $chatdata->_supportState) // if user isn't on support, switch to support
292
  {
293
- $customerData->updateChatdata('telegram_conv_state', $chatdata->_supportState);
294
- $telegram->sendMessage(array('chat_id' => $replyFromUserId, 'text' => $mageHelper->__("You're now on support mode.")));
295
  }
296
- $telegram->sendMessage(array('chat_id' => $replyFromUserId, 'text' => $mageHelper->__("Message from support") . ":\n" . $text)); // send message to customer TODO
297
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Message sent."))); // send message to admin group TODO
 
298
  }
 
 
299
  }
300
  }
 
 
301
  }
302
- else // proccess other admin commands (that aren't replying messages)
 
 
 
303
  {
304
- $admSend2All = "/" . $chatdata->_admSendMessage2AllCmd;
 
 
 
 
 
 
 
305
 
306
- if ($chatdata->startsWith($text, $admSend2All)) // old checkCommandWithValue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
307
  {
308
- $message = trim($chatdata->getCommandValue($text, $admSend2All));
309
- if (!empty($message))
 
310
  {
311
- $chatbotcollection = Mage::getModel('chatbot/chatdata')->getCollection();
312
- foreach($chatbotcollection as $chatbot)
 
 
 
313
  {
314
- $tgChatId = $chatbot->getTelegramChatId();
315
- if ($tgChatId)
316
- $telegram->sendMessage(array('chat_id' => $tgChatId, 'text' => $message)); // $magehelper->__("Message from support") . ":\n" .
317
  }
318
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Message sent.")));
 
 
 
 
 
 
319
  }
320
  else
321
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Please use") . ' "' . $admSend2All . " " . $mageHelper->__("your message here.") . '"'));
322
  }
 
 
323
  }
324
- return $telegram->respondSuccess();
325
  }
326
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("I don't work with groups."))); // TODO
327
- return $telegram->respondSuccess(); // ignore all group messages
328
  }
 
 
 
329
 
330
- // ALL CUSTOMER HANDLERS GOES AFTER HERE
331
-
332
- if ($chatdata->getIsLogged() == "1") // check if customer is logged
 
333
  {
334
- if (Mage::getModel('customer/customer')->load((int)$chatdata->getCustomerId())->getId()) // if is a valid customer id
335
  {
336
- if ($chatdata->getEnableTelegram() != "1")
337
- {
338
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("To talk with me, please enable Telegram on your account chatbot settings.")));
339
- return $telegram->respondSuccess();
340
- }
341
  }
342
  }
 
343
 
344
- $blockerStates = (
345
- $conversationState == $chatdata->_listCategoriesState ||
346
- $conversationState == $chatdata->_searchState ||
347
- $conversationState == $chatdata->_supportState ||
348
- $conversationState == $chatdata->_sendEmailState ||
349
- $conversationState == $chatdata->_trackOrderState
350
- );
351
 
352
- // handle default replies
353
- if ($enableReplies == "1" && !$blockerStates)
 
 
 
 
 
 
354
  {
355
- $defaultReplies = Mage::getStoreConfig('chatbot_enable/telegram_config/default_replies');
356
- if ($defaultReplies)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
357
  {
358
- $replies = unserialize($defaultReplies);
359
- if (is_array($replies))
360
  {
361
- foreach($replies as $reply)
362
- {
363
- // MODES
364
- // 0 =>'Similarity'
365
- // 1 =>'Starts With'
366
- // 2 =>'Ends With'
367
- // 3 =>'Contains'
368
- // 4 =>'Match Regular Expression'
369
- // 5 =>'Equals to'
370
-
371
- $matched = false;
372
- $match = $reply["match_sintax"];
373
- $mode = $reply["reply_mode"];
374
-
375
- if ($reply["match_case"] == "0")
376
- {
377
- $match = strtolower($match);
378
- $textToMatch = strtolower($text);
379
- }
380
- else
381
- $textToMatch = $text;
382
-
383
- if ($mode == "0") // Similarity
384
- {
385
- $similarity = $reply["similarity"];
386
- if (is_numeric($similarity))
387
- {
388
- if (!($similarity >= 1 && $similarity <= 100))
389
- $similarity = 100;
390
- }
391
- else
392
- $similarity = 100;
393
-
394
- similar_text($textToMatch, $match, $percent);
395
- if ($percent >= $similarity)
396
- $matched = true;
397
- }
398
- else if ($mode == "1") // Starts With
399
- {
400
- if ($chatdata->startsWith($textToMatch, $match))
401
- $matched = true;
402
- }
403
- else if ($mode == "2") // Ends With
404
- {
405
- if ($chatdata->endsWith($textToMatch, $match))
406
- $matched = true;
407
- }
408
- else if ($mode == "3") // Contains
409
- {
410
- if (strpos($textToMatch, $match) !== false)
411
- $matched = true;
412
- }
413
- else if ($mode == "4") // Match Regular Expression
414
- {
415
- // if ($match[0] != "/")
416
- // $match = "/" . $match;
417
- // if ((substr($match, -1) != "/") && ($match[strlen($match) - 2] != "/"))
418
- // $match .= "/";
419
- if (preg_match($match, $textToMatch))
420
- $matched = true;
421
- }
422
- else if ($mode == "5") // Equals to
423
- {
424
- if ($textToMatch == $match)
425
- $matched = true;
426
- }
427
 
428
- if ($matched)
429
- {
430
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $reply["reply_phrase"]));
431
- if ($reply["stop_processing"] == "1")
432
- return $telegram->respondSuccess();
433
- break;
434
- }
435
- }
436
  }
437
  }
438
  }
439
-
440
- // init start command
441
- $chatdata->_startCmd['command'] = "/start";
442
-
443
- if (is_null($chatdata->getTelegramChatId()) && !$chatdata->startsWith($text, $chatdata->_startCmd['command'])) // if user isn't registred, and not using the start command // old checkCommandWithValue
 
 
 
 
 
 
 
 
444
  {
445
  $message = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_welcome_msg'); // TODO
446
- if ($message) // TODO
447
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $message));
448
  try
449
  {
450
  $hash = substr(md5(uniqid($chatId, true)), 0, 150); // TODO
451
- $chatdata // using magento model to insert data into database the proper way
452
  ->setTelegramChatId($chatId)
453
  ->setHashKey($hash) // TODO
 
454
  ->save();
455
  }
456
  catch (Exception $e)
457
  {
458
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage)); // TODO
459
  }
460
- return $telegram->respondSuccess();
461
  }
 
 
462
 
463
- // init other commands (for now, no alias for telegram)
464
- $chatdata->_listCategoriesCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(1)['command']);
465
- $chatdata->_searchCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(2)['command']);
466
- $chatdata->_loginCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(3)['command']);
467
- $chatdata->_listOrdersCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(4)['command']);
468
- $chatdata->_reorderCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(5)['command']);
469
- $chatdata->_add2CartCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(6)['command']);
470
- $chatdata->_checkoutCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(7)['command']);
471
- $chatdata->_clearCartCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(8)['command']);
472
- $chatdata->_trackOrderCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(9)['command']);
473
- $chatdata->_supportCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(10)['command']);
474
- $chatdata->_sendEmailCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(11)['command']);
475
- $chatdata->_cancelCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(12)['command']);
476
- $chatdata->_helpCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(13)['command']);
477
- $chatdata->_aboutCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(14)['command']);
478
- $chatdata->_logoutCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(15)['command']);
479
- $chatdata->_registerCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(16)['command']);
480
- if (!$chatdata->_cancelCmd['command']) $chatdata->_cancelCmd['command'] = "/cancel"; // it must always have a cancel command
481
-
482
- // init messages
483
- $chatdata->_errorMessage = $mageHelper->__("Something went wrong, please try again.");
484
- $chatdata->_cancelMessage = $mageHelper->__("To cancel, send") . " " . $chatdata->_cancelCmd['command'];
485
- $chatdata->_canceledMessage = $mageHelper->__("Ok, canceled.");
486
- $chatdata->_loginFirstMessage = $mageHelper->__("Please login first.");
487
- array_push($chatdata->_positiveMessages, $mageHelper->__("Ok"), $mageHelper->__("Okay"), $mageHelper->__("Cool"), $mageHelper->__("Awesome"));
488
- // $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)]
489
-
490
- // TODO DEBUG COMMANDS
491
- // $temp_var = $chatdata->_startCmd['command'] . " - " .
492
- // $chatdata->_listCategoriesCmd['command'] . " - " .
493
- // $chatdata->_searchCmd['command'] . " - " .
494
- // $chatdata->_loginCmd['command'] . " - " .
495
- // $chatdata->_listOrdersCmd['command'] . " - " .
496
- // $chatdata->_reorderCmd['command'] . " - " .
497
- // $chatdata->_add2CartCmd['command'] . " - " .
498
- // $chatdata->_checkoutCmd['command'] . " - " .
499
- // $chatdata->_clearCartCmd['command'] . " - " .
500
- // $chatdata->_trackOrderCmd['command'] . " - " .
501
- // $chatdata->_supportCmd['command'] . " - " .
502
- // $chatdata->_sendEmailCmd['command'];
503
- // $telegram->sendMessage(array('chat_id' => $chat_id, 'text' => $temp_var));
504
- // $telegram->sendMessage(array('chat_id' => $chat_id, 'text' => $conversationState));
505
-
506
- // start command
507
- if ($chatdata->startsWith($text, $chatdata->_startCmd['command'])) // ignore alias // old checkCommandWithValue
508
- //if ($text == $chatdata->_startCmd['command'])
509
  {
510
- $startdata = explode(" ", $text);
511
- if (is_array($startdata) && count($startdata) > 1) // has hash parameter
512
- {
513
- $chat_hash = $chatdata->load(trim($startdata[1]), 'hash_key');
514
- if ($chat_hash->getHashKey())
515
- {
516
- try
517
- {
518
- $chat_hash->addData(array("telegram_chat_id" => $chatId));
519
- $chat_hash->save();
520
- }catch (Exception $e){}
521
- $message = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_welcome_msg'); // TODO
522
- if ($message) // TODO
523
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $message));
524
- }
525
- }
526
- else if ($chatdata->getTelegramChatId()) // TODO
527
- {
528
- $message = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_about_msg'); // TODO
529
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $message));
530
-
531
- // $data = array(
532
- // //'customer_id' => $customerId,
533
- // 'telegram_chat_id' => $chat_id
534
- // ); // data to be insert on database
535
- // $model = Mage::getModel('chatbot/chatdata')->load($chatdata->getId())->addData($data); // insert data on database
536
- // $model->setId($chatdata->getId())->save(); // save (duh)
537
- }
538
- else // if customer id isnt on our database, means that we need to insert his data
539
- {
540
- $message = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_welcome_msg'); // TODO
541
- if ($message) // TODO
542
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $message));
543
- try
544
- {
545
- $hash = substr(md5(uniqid($chatId, true)), 0, 150); // TODO
546
- Mage::getModel('chatbot/chatdata') // using magento model to insert data into database the proper way
547
- ->setTelegramChatId($chatId)
548
- ->setHashKey($hash) // TODO
549
- ->setCreatedAt(date('Y-m-d H:i:s'))
550
- ->save();
551
- }
552
- catch (Exception $e)
553
- {
554
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage)); // TODO
555
- }
556
- }
557
- return $telegram->respondSuccess();
558
  }
559
 
560
- // help command
561
- if ($chatdata->checkCommand($text, $chatdata->_helpCmd))
562
- {
563
- $message = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_help_msg'); // TODO
564
- if (!empty($message)) // TODO
565
- {
566
- $cmdListing = Mage::getStoreConfig('chatbot_enable/telegram_config/enable_help_command_list');
567
- if ($cmdListing == "1")
568
- $message .= $chatdata->listTelegramCommandsMessage();
569
 
570
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $message));
571
- }
 
 
 
 
572
 
573
- return $telegram->respondSuccess();
574
- }
575
 
576
- // about command
577
- if ($chatdata->checkCommand($text, $chatdata->_aboutCmd))
 
 
578
  {
579
- $message = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_about_msg'); // TODO
580
- if (!empty($message))
581
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $message));
582
-
583
- return $telegram->respondSuccess();
584
  }
585
-
586
- // cancel command
587
- if ($chatdata->checkCommand($text, $chatdata->_cancelCmd)) // TODO
588
  {
589
- if ($conversationState == $chatdata->_listCategoriesState)
590
- {
591
- $keyb = $telegram->buildKeyBoardHide(true); // hide keyboard built on listing categories
592
- $content = array('chat_id' => $chatId, 'reply_markup' => $keyb, 'text' => $chatdata->_canceledMessage);
593
- }
594
- else if ($conversationState == $chatdata->_supportState)
595
- {
596
- $content = array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("exiting support mode."));
597
- //$telegram->sendMessage(array('chat_id' => $chat_id, 'text' => $magehelper->__("Done.")));
598
- }
599
- else if ($conversationState == $chatdata->_searchState)
600
- {
601
- $content = array('chat_id' => $chatId, 'text' => $chatdata->_canceledMessage);
602
- }
603
- else if ($conversationState == $chatdata->_sendEmailState)
604
- {
605
- $content = array('chat_id' => $chatId, 'text' => $chatdata->_canceledMessage);
606
- }
607
- else if ($conversationState == $chatdata->_listProductsState)
608
- {
609
- $content = array('chat_id' => $chatId, 'text' => $chatdata->_canceledMessage);
610
- }
611
- else if ($conversationState == $chatdata->_listOrdersState)
612
- {
613
- $content = array('chat_id' => $chatId, 'text' => $chatdata->_canceledMessage);
614
- }
615
- else
616
- $content = array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage);
617
-
618
- if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState))
619
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
620
- else
621
- $telegram->sendMessage($content);
622
- return $telegram->respondSuccess();
623
  }
 
 
624
 
625
- // add2cart commands
626
- if ($chatdata->startsWith($text, $chatdata->_add2CartCmd['command'])) // ignore alias // old checkCommandWithValue
 
 
 
 
 
 
 
 
 
 
 
 
627
  {
628
- $errorFlag = false;
629
- $notInStock = false;
630
- $cmdvalue = $chatdata->getCommandValue($text, $chatdata->_add2CartCmd['command']);
631
- if ($cmdvalue) // TODO
632
  {
633
- $product = Mage::getModel('catalog/product')->load($cmdvalue);
634
- if ($product->getId())
635
  {
636
- $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getIsInStock();
637
- if ($stock > 0)
638
- {
639
- $productName = $product->getName();
640
- if (empty($productName))
641
- $productName = $mageHelper->__("this product");
642
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("adding %s to your cart.", $productName)));
643
- $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
644
- if ($chatdata->addProd2Cart($cmdvalue))
645
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Added. To checkout send") . " " . $chatdata->_checkoutCmd['command']));
646
- else
647
- $errorFlag = true;
648
- }
649
  else
650
- $notInStock = true;
651
  }
652
  else
653
- $errorFlag = true;
654
  }
655
  else
656
  $errorFlag = true;
 
 
 
657
 
658
- if ($errorFlag)
659
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
660
- else if ($notInStock)
661
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("This product is not in stock.")));
662
 
663
- return $telegram->respondSuccess();
664
- }
665
 
666
- // states
667
- if ($conversationState == $chatdata->_listCategoriesState) // TODO show only in stock products
668
- {
669
- if ($cat_id)
670
- $_category = Mage::getModel('catalog/category')->load($cat_id);
671
- else
672
- $_category = Mage::getModel('catalog/category')->loadByAttribute('name', $text);
673
 
674
- $keyb = $telegram->buildKeyBoardHide(true); // hide keyboard built on listing categories
675
- if ($showMore == 0) // show only in the first time
676
- $telegram->sendMessage(array('chat_id' => $chatId, 'reply_markup' => $keyb, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("please wait while I gather all products from %s for you.", $_category->getName())));
677
- else
678
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("listing more.")));
679
 
680
- $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
681
- $errorFlag = false;
682
- if ($_category) // check if variable isn't false/empty
 
 
 
 
 
 
 
 
683
  {
684
- if ($_category->getId()) // check if is a valid category
 
 
 
 
 
 
 
 
685
  {
686
- $noProductFlag = false;
687
- $productCollection = $_category->getProductCollection()
688
- ->addAttributeToSelect('*')
689
- ->addAttributeToFilter('visibility', 4)
690
- ->addAttributeToFilter('type_id', 'simple');
691
- Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($productCollection);
692
- $productIDs = $productCollection->getAllIds();
693
 
694
- if ($productIDs)
695
  {
696
- $i = 0;
697
- $total = count($productIDs);
698
-
699
- if ($showMore < $total)
700
  {
701
- if ($showMore == 0)
702
- {
703
- if ($total == 1)
704
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Done. This category has only one product.")));
705
- else
706
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Done. This category has %s products.", $total)));
707
- }
708
 
709
- foreach ($productIDs as $productID)
 
 
 
710
  {
711
- $message = $chatdata->prepareTelegramProdMessages($productID);
712
- if ($message) // TODO
713
  {
714
- if ($i >= $showMore)
715
- {
716
- $image = $chatdata->loadImageContent($productID);
717
- if ($image)
718
- $telegram->sendPhoto(array('chat_id' => $chatId, 'photo' => $image, 'caption' => $message));
719
- else
720
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $message));
721
 
722
- if (($i + 1) != $total && $i >= ($showMore + $listingLimit)) // if isn't the 'last but one' and $i is bigger than listing limit + what was shown last time ($show_more)
723
- {
724
- // TODO add option to list more products
725
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("To show more, send") . " " . $listMoreCategories . $_category->getId() . "_" . (string)($i + 1)));
726
- if ($chatdata->getTelegramConvState() != $chatdata->_listProductsState)
727
- if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_listProductsState))
728
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
729
- break;
730
- }
731
- else if (($i + 1) == $total) // if it's the last one, back to _startState
732
- {
733
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("And that was the last one.")));
734
- if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState))
735
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
736
- }
737
  }
738
- $i++;
739
  }
 
740
  }
741
- if ($i == 0)
742
- $noProductFlag = true;
743
  }
744
- else
745
- $errorFlag = true;
746
-
747
  }
748
  else
749
- $noProductFlag = true;
750
 
751
- if ($noProductFlag)
752
- $telegram->sendMessage(array('chat_id' => $chatId, 'reply_markup' => $keyb, 'text' => $mageHelper->__("Sorry, no products found in this category.")));
753
  }
754
  else
755
- $errorFlag = true;
 
 
 
756
  }
757
  else
758
  $errorFlag = true;
 
 
 
759
 
760
- if ($errorFlag)
761
- {
762
- $telegram->sendMessage(array('chat_id' => $chatId, 'reply_markup' => $keyb, 'text' => $chatdata->_errorMessage));
763
- $chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState);
764
- }
765
- return $telegram->respondSuccess();
766
  }
767
- else if ($conversationState == $chatdata->_searchState) // TODO
 
 
 
 
 
 
 
 
 
 
 
 
 
768
  {
769
- if ($showMore == 0) // show only in the first time
770
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("please wait while I search for '%s' for you.", $text)));
771
- else
772
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("listing more.")));
 
 
 
773
 
774
- $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
775
- $errorFlag = false;
776
- $noProductFlag = false;
777
- $productIDs = $chatdata->getProductIdsBySearch($text);
778
- if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState))
779
- {
780
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
781
- return $telegram->respondSuccess();
782
- }
783
- else if ($productIDs)
784
  {
785
- $i = 0;
786
- $total = count($productIDs);
787
-
788
- if ($showMore < $total)
789
  {
790
- if ($showMore == 0)
791
- {
792
- if ($total == 1)
793
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Done. I've found only one product for your criteria.")));
794
- else
795
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Done. I've found %s products for your criteria.", $total)));
796
- }
797
 
798
- foreach ($productIDs as $productID)
 
 
 
799
  {
800
- $message = $chatdata->prepareTelegramProdMessages($productID);
801
- if ($message) // TODO
802
  {
803
- if ($i >= $showMore)
804
- {
805
- $image = $chatdata->loadImageContent($productID);
806
- if ($image)
807
- $telegram->sendPhoto(array('chat_id' => $chatId, 'photo' => $image, 'caption' => $message));
808
- else
809
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $message));
810
 
811
- if (($i + 1) != $total && $i >= ($showMore + $listingLimit)) // if isn't the 'last but one' and $i is bigger than listing limit + what was shown last time ($show_more)
812
- {
813
- // TODO add option to list more products
814
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("To show more, send") . " " . $listMoreSearch . str_replace(" ", "_", $text) . "_" . (string)($i + 1)));
815
- if ($chatdata->getTelegramConvState() != $chatdata->_listProductsState)
816
- if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_listProductsState))
817
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
818
- break;
819
- }
820
- else if (($i + 1) == $total) // if it's the last one, back to _startState
821
- {
822
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("And that was the last one.")));
823
- if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState))
824
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
825
- }
826
  }
827
- $i++;
828
  }
 
829
  }
830
- if ($i == 0)
831
- $noProductFlag = true;
832
  }
833
- else
834
- $errorFlag = true;
835
  }
836
  else
837
- $noProductFlag = true;
838
-
839
- if ($noProductFlag)
840
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Sorry, no products found for this criteria.")));
841
 
842
- if ($errorFlag)
843
- {
844
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
845
- $chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState);
846
- }
847
 
848
- return $telegram->respondSuccess();
 
 
 
849
  }
850
- else if ($conversationState == $chatdata->_supportState)
 
 
 
 
 
851
  {
852
- if (!empty($supportGroupId))
853
- {
854
- $telegram->forwardMessage(array('chat_id' => $supportGroupId, 'from_chat_id' => $chatId, 'message_id' => $telegram->MessageID())); // Reply to this message to reply to the customer
855
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("we have sent your message to support.")));
856
- }
857
- else
858
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
859
- return $telegram->respondSuccess();
860
  }
861
- else if ($conversationState == $chatdata->_sendEmailState)
 
 
 
 
 
 
 
862
  {
863
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Trying to send the email...")));
864
- if ($chatdata->sendEmail($text, $username))
865
- {
866
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Done.")));
867
- }
868
- else
869
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Sorry, I wasn't able to send an email this time. Please try again later.")));
870
- if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState))
871
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
872
- return $telegram->respondSuccess();
873
  }
874
- else if ($conversationState == $chatdata->_trackOrderState)
 
 
 
 
 
 
 
 
 
875
  {
876
- $errorFlag = false;
877
- if ($chatdata->getIsLogged() == "1")
 
 
878
  {
879
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("please wait while I check the status for order %s.", $text)));
880
- $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
881
- $order = Mage::getModel('sales/order')->loadByIncrementId($text);
882
- if ($order->getId())
883
  {
884
- if ($order->getCustomerId() == $chatdata->getCustomerId()) // not a problem if customer dosen't exist
885
- {
886
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Your order status is") . " " . $order->getStatus()));
887
- }
888
- else
889
- $errorFlag = true;
890
  }
891
  else
892
  $errorFlag = true;
893
  }
894
  else
895
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_loginFirstMessage));
896
- if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState))
897
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
898
- else if ($errorFlag)
899
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Sorry, we couldn't find any order with this information.")));
900
- return $telegram->respondSuccess();
901
  }
 
 
 
 
 
 
 
 
902
 
903
- // general commands
904
- if ($chatdata->checkCommand($text, $chatdata->_listCategoriesCmd))
905
- {
906
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("please wait while I gather all categories for you.")));
907
- $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
908
 
909
- $categoryHelper = Mage::helper('catalog/category');
910
- $categories = $categoryHelper->getStoreCategories(); // TODO test with a store without categories
911
- $i = 0;
912
- if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_listCategoriesState))
913
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
914
- else if ($categories)
 
 
 
 
 
915
  {
916
- $option = array();
917
- $arr = array();
918
- $charCount = 0;
919
- foreach ($categories as $category) // TODO fix buttons max size
920
  {
921
- if ($enableEmptyCategoriesListing != "1") // unallow empty categories listing
922
- {
923
- $category = Mage::getModel('catalog/category')->load($category->getId()); // reload category because EAV Entity
924
- $productIDs = $category->getProductCollection()
925
- ->addAttributeToSelect('*')
926
- ->addAttributeToFilter('visibility', 4)
927
- ->addAttributeToFilter('type_id', 'simple')
928
- ->getAllIds();
929
- }
930
- else
931
- $productIDs = true;
932
- if (!empty($productIDs)) // category with no products
 
 
 
 
933
  {
934
- //$option = array( array("A", "B"), array("C", "D") );
935
- $catName = $category->getName();
936
- $charCount = $charCount + strlen($catName);
937
- array_push($arr, $catName); // push category name into array arr
938
- if ($charCount > $categoryLimit) // size limit for Telegram buttons
939
- {
940
- array_push($option, $arr); // when hits the limit, add array to options
941
- $arr = array(); // clear array
942
- $charCount = 0;
943
- }
944
-
945
- $i++;
946
  }
 
 
947
  }
 
948
 
949
- if (!empty($arr)) // if the loop ended, and there's still categories on arr
950
- array_push($option, $arr);
951
 
952
- $keyb = $telegram->buildKeyBoard($option);
953
- $telegram->sendMessage(array('chat_id' => $chatId, 'reply_markup' => $keyb, 'resize_keyboard' => true, 'text' => $mageHelper->__("Select a category") . ". " . $chatdata->_cancelMessage));
954
- }
955
- else if ($i == 0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
956
  {
957
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("No categories available at the moment, please try again later.")));
958
- if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState))
959
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
 
 
 
 
 
 
960
  }
961
- else
962
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
963
-
964
- return $telegram->respondSuccess();
965
  }
966
- else if ($chatdata->checkCommand($text, $chatdata->_checkoutCmd)) // TODO
967
  {
968
- $sessionId = null;
969
- $quoteId = null;
970
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("please wait while I prepare the checkout for you.")));
971
- $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
972
- if ($chatdata->getIsLogged() == "1")
 
 
 
 
 
 
 
 
 
973
  {
974
- if (Mage::getModel('customer/customer')->load((int)$chatdata->getCustomerId())->getId())
 
 
975
  {
976
- // if user is set as logged, then login using magento singleton
977
- $customerSession = Mage::getSingleton('customer/session');
978
- $customerSession->loginById((int)$chatdata->getCustomerId());
979
- // then set current quote as customer quote
980
- $customer = Mage::getModel('customer/customer')->load((int)$chatdata->getCustomerId());
981
- $quote = Mage::getModel('sales/quote')->loadByCustomer($customer);
982
- // set quote and session ids from logged user
983
- $quoteId = $quote->getId();
984
- $sessionId = $customerSession->getEncryptedSessionId();
985
  }
 
 
 
 
 
 
 
 
986
  }
987
- if (!($sessionId && $quoteId))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
988
  {
989
- // set quote and session ids from chatbot class
990
- $sessionId = $chatdata->getSessionId();
991
- $quoteId = $chatdata->getQuoteId();
 
 
 
992
  }
993
- $emptyCart = true;
994
- if ($sessionId && $quoteId)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
995
  {
996
- $cartUrl = Mage::helper('checkout/cart')->getCartUrl();
997
- if (!isset(parse_url($cartUrl)['SID']))
998
- $cartUrl .= "?SID=" . $sessionId; // add session id to url
 
 
 
 
 
 
 
999
 
1000
- $cart = Mage::getModel('checkout/cart')->setQuote(Mage::getModel('sales/quote')->loadByIdWithoutStore((int)$quoteId));
1001
- $ordersubtotal = $cart->getQuote()->getSubtotal();
1002
- if ($ordersubtotal > 0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1003
  {
1004
- $emptyCart = false;
1005
- $message = $mageHelper->__("Products on cart") . ":\n";
1006
- foreach ($cart->getQuote()->getItemsCollection() as $item) // TODO
1007
  {
1008
- $message .= $item->getQty() . "x " . $item->getProduct()->getName() . "\n" .
1009
- $mageHelper->__("Price") . ": " . Mage::helper('core')->currency($item->getProduct()->getPrice(), true, false) . "\n\n";
 
 
1010
  }
1011
- $message .= $mageHelper->__("Total") . ": " .
1012
- Mage::helper('core')->currency($ordersubtotal, true, false) . "\n\n" .
1013
- "[" . $mageHelper->__("Checkout Here") . "](" . $cartUrl . ")";
1014
 
1015
- if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_checkoutState))
1016
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
1017
- else
1018
- $telegram->sendMessage(array('chat_id' => $chatId, 'parse_mode' => 'Markdown', 'text' => $message));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1019
  }
1020
- else if (!$chatdata->clearCart()) // try to clear cart
1021
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
1022
  }
1023
- if ($emptyCart)
1024
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Your cart is empty.")));
1025
- return $telegram->respondSuccess();
 
 
1026
  }
1027
- else if ($chatdata->checkCommand($text, $chatdata->_clearCartCmd))
 
 
 
 
 
 
1028
  {
1029
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("please wait while I clear your cart.")));
1030
  $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
1031
  $errorFlag = false;
1032
- if ($chatdata->clearCart())
 
1033
  {
1034
- if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_clearCartState))
1035
- $errorFlag = true;
 
 
 
 
 
 
 
 
 
 
 
1036
  else
1037
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Cart cleared.")));
1038
  }
1039
  else
1040
  $errorFlag = true;
 
1041
  if ($errorFlag)
1042
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
1043
- return $telegram->respondSuccess();
1044
- }
1045
- else if ($chatdata->checkCommand($text, $chatdata->_searchCmd))
1046
- {
1047
- if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_searchState))
1048
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
1049
- else
1050
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("what do you want to search for?") . " " . $chatdata->_cancelMessage));
1051
- return $telegram->respondSuccess();
1052
  }
1053
- else if ($chatdata->checkCommand($text, $chatdata->_loginCmd)) // TODO
 
 
 
 
 
 
1054
  {
1055
- if ($chatdata->getIsLogged() != "1") // customer not logged
 
1056
  {
1057
- $hashUrl = Mage::getUrl('chatbot/settings/index/'); // get base module URL
1058
- $hashUrl = strtok($hashUrl, '?') . "hash" . DS . $chatdata->getHashKey(); // remove magento parameters
1059
- if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_loginState))
1060
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
1061
  else
1062
- {
1063
- $telegram->sendMessage(array(
1064
- 'chat_id' => $chatId, 'text' => $mageHelper->__("To login to your account, click this link") . ": " .
1065
- $hashUrl . " . " .
1066
- $mageHelper->__("If you want to logout from your account, just send") . " " .
1067
- $chatdata->_logoutCmd
1068
- ));
1069
- }
1070
  }
1071
  else
1072
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("You're already logged.")));
1073
- return $telegram->respondSuccess();
1074
  }
1075
- else if ($chatdata->checkCommand($text, $chatdata->_logoutCmd)) // TODO
 
 
 
 
 
 
 
 
1076
  {
1077
- if ($chatdata->getIsLogged() == "1")
1078
  {
1079
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Ok, logging out.")));
1080
- $errorFlag = false;
1081
- try
1082
- {
1083
- $chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState);
1084
- $chatdata->updateChatdata('is_logged', "0");
1085
- $chatdata->updateChatdata('customer_id', ""); // TODO null?
1086
- $chatdata->clearCart();
1087
- }
1088
- catch (Exception $e)
1089
- {
1090
  $errorFlag = true;
1091
- }
1092
-
1093
- if ($errorFlag)
1094
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
1095
  else
1096
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Done.")));
1097
  }
1098
  else
1099
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("You're not logged.")));
1100
-
1101
- return $telegram->respondSuccess();
1102
  }
1103
- else if ($chatdata->checkCommand($text, $chatdata->_registerCmd)) // TODO
 
 
 
 
 
 
 
 
 
 
 
1104
  {
1105
- $registerUrl = strtok(Mage::getUrl('customer/account/create'), '?');
1106
- if (!empty($registerUrl))
1107
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Access %s to register a new account on our shop.", $registerUrl)));
1108
- else
1109
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
1110
- return $telegram->respondSuccess();
1111
  }
1112
- else if ($chatdata->checkCommand($text, $chatdata->_listOrdersCmd) || $moreOrders) // TODO
 
 
 
 
 
1113
  {
1114
- if ($chatdata->getIsLogged() == "1")
 
1115
  {
1116
- if ($showMore == 0) // show only in the first time
1117
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("please wait while I gather your orders for listing.")));
1118
- else
1119
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("listing more.")));
1120
-
1121
- $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
1122
- $ordersIDs = $chatdata->getOrdersIdsFromCustomer();
1123
- if ($ordersIDs)
1124
  {
1125
- $i = 0;
1126
- $total = count($ordersIDs);
1127
- if ($showMore < $total)
1128
  {
1129
- if ($showMore == 0)
 
 
 
 
 
 
 
 
 
 
 
 
 
1130
  {
1131
- if ($total == 1)
1132
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Done. You've only one order.")));
1133
- else
1134
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Done. I've found %s orders.", $total)));
1135
  }
 
 
1136
 
1137
- foreach($ordersIDs as $orderID)
1138
  {
1139
- $message = $chatdata->prepareTelegramOrderMessages($orderID);
1140
- if ($message) // TODO
1141
  {
1142
- if ($i >= $showMore)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1143
  {
1144
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $message));
1145
- if (($i + 1) != $total && $i >= ($showMore + $listingLimit)) // if isn't the 'last but one' and $i is bigger than listing limit + what was shown last time ($show_more)
1146
  {
1147
- // TODO add option to list more orders
1148
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("To show more, send") . " " . $listMoreOrders . (string)($i + 1)));
1149
- if ($chatdata->getTelegramConvState() != $chatdata->_listOrdersState)
1150
- if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_listOrdersState))
1151
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
1152
  break;
1153
  }
1154
- else if (($i + 1) == $total) // if it's the last one, back to _startState
1155
- {
1156
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("And that was the last one.")));
1157
- if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState))
1158
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
1159
- }
1160
  }
1161
- $i++;
1162
  }
1163
  }
1164
- if ($i == 0)
1165
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
1166
- // else if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_listOrdersState))
1167
- // $telegram->sendMessage(array('chat_id' => $chat_id, 'text' => $chatdata->_errorMessage));
1168
- }
1169
- }
1170
- else
1171
- {
1172
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("This account has no orders.")));
1173
- return $telegram->respondSuccess();
1174
- }
1175
- }
1176
- else
1177
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_loginFirstMessage));
1178
- return $telegram->respondSuccess();
1179
- }
1180
- else if ($chatdata->startsWith($text, $chatdata->_reorderCmd['command'])) // ignore alias TODO // old checkCommandWithValue
1181
- {
1182
- if ($chatdata->getIsLogged() == "1")
1183
- {
1184
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("please wait while I add the products from this order to your cart.")));
1185
- $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
1186
- $errorFlag = false;
1187
- $cmdvalue = $chatdata->getCommandValue($text, $chatdata->_reorderCmd['command']);
1188
- if ($cmdvalue)
1189
- {
1190
- if ($chatdata->clearCart())
1191
- {
1192
- $order = Mage::getModel('sales/order')->load($cmdvalue);
1193
- if ($order->getId())
1194
  {
1195
- foreach($order->getAllVisibleItems() as $item) {
1196
- if (!$chatdata->addProd2Cart($item->getProductId()))
1197
- $errorFlag = true;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1198
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1199
  }
1200
- else
1201
- $errorFlag = true;
1202
  }
1203
- else
1204
- $errorFlag = true;
1205
  }
1206
- else
1207
- $errorFlag = true;
1208
-
1209
- if ($errorFlag)
1210
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
1211
- else if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_reorderState))
1212
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
1213
- else // success!!
1214
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("to checkout send") . " " . $chatdata->_checkoutCmd['command']));
1215
  }
1216
- else
1217
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_loginFirstMessage));
1218
- return $telegram->respondSuccess();
1219
  }
1220
- else if ($chatdata->checkCommand($text, $chatdata->_trackOrderCmd)) // TODO
 
 
1221
  {
1222
- if ($chatdata->getIsLogged() == "1")
1223
  {
1224
- $ordersIDs = $chatdata->getOrdersIdsFromCustomer();
1225
- if ($ordersIDs)
1226
- {
1227
- if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_trackOrderState))
1228
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
1229
- else
1230
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("send the order number.")));
1231
- }
1232
- else
1233
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Your account dosen't have any orders.")));
1234
  }
1235
  else
1236
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_loginFirstMessage));
1237
- return $telegram->respondSuccess();
1238
  }
1239
- else if ($chatdata->checkCommand($text, $chatdata->_supportCmd)) // TODO
1240
  {
1241
- $supportEnabled = $chatdata->getEnableSupport();
1242
- $errorFlag = false;
1243
- if ($supportEnabled == "1")
1244
  {
1245
- if ($chatdata->getFacebookConvState() != $chatdata->_supportState)
 
 
 
 
 
 
 
1246
  {
1247
- if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_supportState))
1248
- $errorFlag = true;
1249
- else
1250
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("what do you need support for?") . " " . $chatdata->_cancelMessage));
 
 
 
 
 
 
1251
  }
1252
- else
1253
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("You're already on support in other chat application, please close it before opening a new one.")));
1254
- }
1255
- else
1256
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("I'm sorry, you can't ask for support now. Please try again later.")));
1257
 
1258
- if ($errorFlag)
1259
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
1260
- return $telegram->respondSuccess();
1261
- }
1262
- else if ($chatdata->checkCommand($text, $chatdata->_sendEmailCmd)) // TODO
1263
- {
1264
- if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_sendEmailState))
1265
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
1266
- else
1267
- {
1268
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $mageHelper->__("write the email content.")));
1269
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("By doing this you agree that we may contact you directly via chat message.") . " " . $chatdata->_cancelMessage));
1270
- }
1271
- return $telegram->respondSuccess();
1272
- }
1273
- else
1274
- {
1275
- if ($enableFinalMessage2Support == "1")
1276
- {
1277
- if (!empty($supportGroupId))
1278
  {
1279
- // if ($chatdata->getFacebookConvState() != $chatdata->_supportState) // TODO
1280
- // $chatdata->updateChatdata('telegram_conv_state', $chatdata->_supportState);
1281
- $telegram->forwardMessage(array('chat_id' => $supportGroupId, 'from_chat_id' => $chatId, 'message_id' => $telegram->MessageID()));
1282
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' =>
1283
- $mageHelper->__("Sorry, I didn't understand that.") . " " .
1284
- $mageHelper->__("Please wait while our support check your message so you can talk to a real person.")// . " " .
1285
- //$chatdata->_cancelMessage
1286
- )); // TODO
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1287
  }
1288
- else
1289
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
1290
- return $telegram->respondSuccess();
1291
  }
1292
- else // process cases where the customer message wasn't understandable
1293
  {
1294
- //else if ($enable_witai == "1"){}
1295
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $mageHelper->__("Sorry, I didn't understand that."))); // TODO
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1296
 
1297
  $cmdListingOnError = Mage::getStoreConfig('chatbot_enable/telegram_config/enable_error_command_list');
1298
  if ($cmdListingOnError == "1")
1299
  {
1300
  $message = $mageHelper->__("Please try one of the following commands.");
1301
  $message .= $chatdata->listTelegramCommandsMessage();
1302
- $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $message)); // TODO
1303
  }
1304
-
1305
  }
1306
  }
1307
  }
1308
-
1309
- return $telegram->respondSuccess();
1310
  }
1311
  }
1312
 
1313
-
1314
  ?>
1
  <?php
2
+ // class that handles all Telegram requests.
3
+ require_once("Telegram.php");
4
  //$api_path = Mage::getModuleDir('', 'Werules_Chatbot') . DS . "Model" . DS . "Api" . DS . "witAI" . DS;
5
+ //require_once($api_path . "witAI.php");
6
+
7
+ class TelegramBot extends Telegram
8
+ {
9
+ public $_text;
10
+ public $_chatId;
11
+ public $_messageId;
12
+ public $_audioPath;
13
+
14
+ public function postMessage($chatId, $message)
15
+ {
16
+ return $this->sendMessage(array('chat_id' => $chatId, 'text' => $message));
17
+ }
18
+ }
19
 
20
  class Werules_Chatbot_Model_Api_Telegram_Handler extends Werules_Chatbot_Model_Chatdata
21
  {
22
+ public $_telegram;
23
+
24
  public function _construct()
25
  {
26
  //parent::_construct();
27
  //$this->_init('chatbot/api_telegram_handler'); // this is location of the resource file.
28
+ $apikey = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_api_key');
29
+ $this->_telegram = new TelegramBot($apikey);
30
+ $this->_chatbotHelper = Mage::helper('werules_chatbot');
31
+ $this->_apiKey = $apikey;
32
  }
33
 
34
+ public function setWebhook($webhookUrl)
35
  {
36
+ $telegram = $this->_telegram;
37
+ return $telegram->setWebhook($webhookUrl);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  }
39
 
40
+ public function telegramHandler()
41
  {
 
 
 
42
  // Instances the Telegram class
43
+ $telegram = $this->_telegram;
44
+ //$telegram = new TelegramBot("");
45
+
46
+ if (!isset($telegram)) // if no apiKey available, break process
47
+ return json_encode(array("status" => "error"));
48
 
49
  // Take text and chat_id from the message
50
+ $telegram->_text = $telegram->Text();
51
+ $telegram->_chatId = $telegram->ChatID();
52
+ $telegram->_messageId = $telegram->MessageID();
53
  $inlineQuery = $telegram->Inline_Query();
54
+ $audio = $telegram->getData();
55
 
56
  $enableLog = Mage::getStoreConfig('chatbot_enable/general_config/enable_post_log');
57
  if ($enableLog == "1") // log all posts
58
  Mage::log("Post Data:\n" . var_export($telegram->getData(), true) . "\n\n", null, 'chatbot_telegram.log');
59
 
60
+ $enableInlineBot = Mage::getStoreConfig('chatbot_enable/telegram_config/enable_inline_search');
61
+ // handle inline search
62
  if (!empty($inlineQuery))
63
  {
64
+ $chatbotHelper = $this->_chatbotHelper;
65
+ if ($enableInlineBot == "1")
 
 
 
66
  {
67
+ $query = $inlineQuery['query'];
68
+ $queryId = $inlineQuery['id'];
69
+ $results = array();
70
+ //$chatdataInline = Mage::getModel('chatbot/chatdata');
71
+ if (!empty($query))
72
  {
73
+ $productIDs = $chatbotHelper->getProductIdsBySearch($query);
74
+ $mageHelperInline = Mage::helper('core');
75
+ if (!empty($productIDs))
76
  {
77
+ //$total = count($productIDs);
78
+ $i = 0;
79
+ foreach($productIDs as $productID)
80
  {
81
+ $product = Mage::getModel('catalog/product')->load($productID);
82
+ if ($product->getId())
83
  {
84
+ if ($product->getStockItem()->getIsInStock() > 0)
85
+ {
86
+ if ($i >= 5)
87
+ break;
88
+ $productUrl = $product->getProductUrl();
89
+ $productImage = $product->getImageUrl();
90
+ $productName = $product->getName();
91
+ $productDescription = $chatbotHelper->excerpt($product->getShortDescription(), 60);
92
+ $placeholder = Mage::getSingleton("catalog/product_media_config")->getBaseMediaUrl() . DS . "placeholder" . DS . Mage::getStoreConfig("catalog/placeholder/thumbnail_placeholder");
93
+ if (empty($productImage))
94
+ $productImage = $placeholder;
95
+
96
+ $message = $productName . "\n" .
97
+ $mageHelperInline->__("Price") . ": " . Mage::helper('core')->currency($product->getPrice(), true, false) . "\n" .
98
+ $productDescription . "\n" .
99
+ $productUrl
100
+ ;
101
+
102
+ $result = array(
103
+ 'type' => 'article',
104
+ 'id' => $queryId . "/" . (string)$i,
105
+ 'title' => $productName,
106
+ 'description' => $productDescription,
107
+ 'thumb_url' => $productImage,
108
+ 'input_message_content' => array(
109
+ 'message_text' => $message,
110
+ 'parse_mode' => 'HTML'
111
+ )
112
+ );
113
+
114
+ array_push($results, $result);
115
+ $i++;
116
+ }
117
  }
118
  }
 
119
 
120
+ $telegram->answerInlineQuery(array('inline_query_id' => $queryId, 'results' => json_encode($results)));
121
+ }
122
+ else
123
+ {
124
+ $results = array(
125
+ array(
126
+ 'type' => 'article',
127
+ 'id' => $queryId . "/0",
128
+ 'title' => $mageHelperInline->__("Sorry, no products found for this criteria."),
129
+ 'input_message_content' => array(
130
+ 'message_text' => $mageHelperInline->__("Sorry, no products found for this criteria.")
131
+ )
132
  )
133
+ );
134
+ $telegram->answerInlineQuery(array('inline_query_id' => $queryId, 'results' => json_encode($results)));
135
+ }
136
  }
137
  }
 
138
  $telegram->respondSuccess();
139
  }
140
 
141
+ // handle received audio
142
+ $enableWitai = Mage::getStoreConfig('chatbot_enable/witai_config/enable_witai');
143
+ $enableSpeech = Mage::getStoreConfig('chatbot_enable/telegram_config/enable_speech_recognition');
144
+ if ((isset($audio["message"]["voice"])) && ($enableWitai == "1") && ($enableSpeech == "1"))
145
+ {
146
+ $fileUrl = $telegram->getFile($audio["message"]["voice"]["file_id"]);
147
+ $apiFilePath = $fileUrl["result"]["file_path"];
148
+ $telegramFileUrl = "https://api.telegram.org/file/bot" . $this->_apiKey . "/" . $apiFilePath; // DS
149
+ $fileContent = $this->_chatbotHelper->getContent($telegramFileUrl);
150
+
151
+ $folderPath = Mage::getBaseDir('tmp') . DS . "werules/";
152
+ $fileName = "audio." . explode('.', $apiFilePath)[1];
153
+ $filePath = $folderPath . $fileName;
154
+
155
+ if (!file_exists($folderPath))
156
+ mkdir($folderPath, 0777, true);
157
+ if (!file_exists($filePath))
158
+ unlink($filePath);
159
+
160
+ file_put_contents($filePath, $fileContent);
161
+ $convertedFilePath = $this->_chatbotHelper->convertOggToMp3($folderPath, $fileName);
162
+
163
+ if ($convertedFilePath)
164
+ $telegram->_audioPath = $convertedFilePath;
165
+ }
166
+
167
+ if ((!is_null($telegram->_chatId)) && (!is_null($telegram->_text) || !is_null($telegram->_audioPath)))
168
+ {
169
+ return $this->processText();
170
+ }
171
+
172
+ return $telegram->respondSuccess();
173
+ }
174
+
175
+ public function processText()
176
+ {
177
  // configs
 
178
  $enabledBot = Mage::getStoreConfig('chatbot_enable/telegram_config/enable_bot');
179
  $enableReplies = Mage::getStoreConfig('chatbot_enable/telegram_config/enable_default_replies');
180
  $enableEmptyCategoriesListing = Mage::getStoreConfig('chatbot_enable/general_config/list_empty_categories');
181
  $enableFinalMessage2Support = Mage::getStoreConfig('chatbot_enable/general_config/enable_support_final_message');
182
  $supportGroupId = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_support_group');
183
  $showMore = 0;
184
+ $catId = null;
185
  $moreOrders = false;
186
+ $defaultConfidence = 75;
187
  $listingLimit = 5;
188
  $categoryLimit = 18;
189
  $listMoreCategories = "/lmc_";
190
  $listMoreSearch = "/lms_";
191
  $listMoreOrders = "/lmo_";
192
+ $commandPrefix = "/";
193
+ $message = "";
194
+ $messageLimit = 4096; // Telegram API limit
195
+ $minutes = 1 * 60;// * 1000; // 1 minute
196
 
197
+ // instance Telegram API
198
+ $telegram = $this->_telegram;
 
 
 
 
 
 
199
 
200
+ // Take text and chat_id from the message
201
+ $text = $telegram->_text;
202
+ $chatId = $telegram->_chatId;
203
+ $messageId = $telegram->_messageId;
204
+
205
+ // Instances Telegram user details
206
+ $username = $telegram->Username();
207
+
208
+ // helpers
209
+ $mageHelper = Mage::helper('core');
210
+ $chatbotHelper = $this->_chatbotHelper;
211
+
212
+ // Instances the model class
213
+ $chatdata = Mage::getModel('chatbot/chatdata')->load($chatId, 'telegram_chat_id');
214
+ $chatdata->_apiType = $chatbotHelper->_tgBot;
215
+
216
+ // if ($chatdata->getTelegramProcessingRequest() == "1") // avoid responding to multiple messages in a row
217
+ // {
218
+ // $updatedAt = strtotime($chatdata->getUpdatedAt());
219
+ // $timeNow = time();
220
+ // if (($timeNow - $updatedAt) < $minutes)
221
+ // return $telegram->respondSuccess();
222
+ // else
223
+ // $chatdata->updateChatdata("telegram_processing_request", "0");
224
+ // }
225
+ //
226
+ // if ($chatdata->getTelegramChatId()) // flag that is processing a request
227
+ // $chatdata->updateChatdata("telegram_processing_request", "1");
228
+
229
+ // Instances the witAI class
230
+ $enableWitai = Mage::getStoreConfig('chatbot_enable/witai_config/enable_witai');
231
+ if ($enableWitai == "1")
232
+ {
233
+ if (!isset($this->_witAi))
234
+ {
235
+ $witApi = Mage::getStoreConfig('chatbot_enable/witai_config/witai_api_key');
236
+ $this->_witAi = new witAI($witApi);
237
+ }
238
 
239
+ if (!is_null($telegram->_audioPath))
 
240
  {
241
+ $witResponse = $this->_witAi->getAudioResponse($telegram->_audioPath);
242
+ if (isset($witResponse->_text))
243
+ $telegram->_text = $witResponse->_text;
244
+ else
245
+ return $chatdata->respondSuccess();
246
  }
247
+ }
248
 
249
+ if ($messageId == $chatdata->getTelegramMessageId() && !($this->_isWitAi)) // prevents to reply the same request twice
250
+ return $chatdata->respondSuccess();
251
+ else if ($chatdata->getTelegramChatId())
252
+ $chatdata->updateChatdata('telegram_message_id', $messageId); // if this fails, it may send the same message twice
253
+
254
+ // bot enabled/disabled
255
+ if ($enabledBot != "1")
256
+ {
257
+ $disabledMessage = Mage::getStoreConfig('chatbot_enable/telegram_config/disabled_message');
258
+ if (!empty($disabledMessage))
259
+ $telegram->postMessage($chatId, $disabledMessage);
260
+ return $chatdata->respondSuccess();
261
+ }
262
 
263
+ // send feedback to user
264
+ $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
265
+
266
+ // show more handler, may change the conversation state
267
+ if ($chatdata->getTelegramConvState() == $chatbotHelper->_listProductsState || $chatdata->getTelegramConvState() == $chatbotHelper->_listOrdersState) // listing products
268
+ {
269
+ if ($chatbotHelper->startsWith($text, $listMoreCategories)) // old checkCommandWithValue
270
  {
271
+ if ($chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_listCategoriesState))
272
  {
273
+ $value = $chatbotHelper->getCommandValue($text, $listMoreCategories);
274
+ $arr = explode("_", $value);
275
+ $catId = (int)$arr[0]; // get category id
276
+ $showMore = (int)$arr[1]; // get where listing stopped
 
 
 
277
  }
278
+ }
279
+ else if ($chatbotHelper->startsWith($text, $listMoreSearch)) // old checkCommandWithValue
280
+ {
281
+ if ($chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_searchState))
282
  {
283
+ $value = $chatbotHelper->getCommandValue($text, $listMoreSearch);
284
+ $arr = explode("_", $value);
285
+ $showMore = (int)end($arr); // get where listing stopped
286
+ $value = str_replace("_" . (string)$showMore, "", $value);
287
+ $text = str_replace("_", " ", $value); // get search criteria
 
 
 
288
  }
289
+ }
290
+ else if ($chatbotHelper->startsWith($text, $listMoreOrders)) // old checkCommandWithValue
291
+ {
292
+ if ($chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_listOrdersState))
293
  {
294
+ $value = $chatbotHelper->getCommandValue($text, $listMoreOrders);
295
+ $showMore = (int)$value; // get where listing stopped
296
+ $moreOrders = true;
 
 
 
297
  }
 
 
298
  }
299
+ // else
300
+ // $chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_startState);
301
+ }
302
 
303
+ // instances conversation state
304
+ $conversationState = $chatdata->getTelegramConvState();
305
 
306
+ // init error message
307
+ $chatbotHelper->_errorMessage = $mageHelper->__("Something went wrong, please try again.");
308
 
309
+ if ($supportGroupId[0] == "g") // remove the 'g' from groupd id, and add '-'
310
+ $supportGroupId = "-" . ltrim($supportGroupId, "g");
311
 
312
+ // handle admin stuff
313
+ //$isAdmin = $chatdata->getIsAdmin();
314
+ // if it's a group message
315
+ if ($telegram->messageFromGroup())
316
+ {
317
+ if ($chatId == $supportGroupId) // if the group sending the message is the support group
318
  {
319
+ // admin commands
320
+ $admEndSupport = $commandPrefix . $chatbotHelper->_admEndSupportCmd;
321
+ $admBlockSupport = $commandPrefix . $chatbotHelper->_admBlockSupportCmd;
322
+ $admEnableSupport = $commandPrefix . $chatbotHelper->_admEnableSupportCmd;
323
+ $admDisableBotCmd = $commandPrefix . $chatbotHelper->_admDisableBotCmd;
324
+ $admEnableBotCmd = $commandPrefix . $chatbotHelper->_admEnableBotCmd;
325
+
326
+ // check if the command is /command@MyBot
327
+ $botUsername = "@" . $chatbotHelper->getTelegramBotUsername();
328
+ if (strpos($text, $botUsername) !== false)
329
+ $text = explode($botUsername, $text)[0];
330
+
331
+ $replyMessageId = $telegram->ReplyToMessageID();
332
+
333
+ if (!empty($replyMessageId)) // if the message is replying another message
334
  {
335
+ $errorFlag = false;
336
+ //$isForeign = false;
337
+
338
+ preg_match('/(#\w+)/', $telegram->ReplyToMessageText(), $matches); // match hashtag which contains the chatid
339
+ if (!empty($matches[0])) // if matched, load using chatid
340
  {
341
+ $matchedChatId = ltrim($matches[0], "#");
342
+ $foreignChatdata = Mage::getModel('chatbot/chatdata')->load($matchedChatId, 'facebook_chat_id');
343
+ $isForeign = !empty($foreignChatdata->getFacebookChatId()); // check if current reply message id is saved on database
344
+ }
345
+ else // if not, try to load using last message id for support
346
+ {
347
+ $foreignChatdata = Mage::getModel('chatbot/chatdata')->load($replyMessageId, 'last_support_message_id');
348
+ $isForeign = !empty($foreignChatdata->getLastSupportMessageId()); // check if current reply message id is saved on database
349
+ }
350
+
351
+ $replyFromUserId = $telegram->ReplyToMessageFromUserID();
352
+ $isLocal = !is_null($replyFromUserId);
353
+ if ($isLocal != $isForeign) // XOR
354
+ {
355
+ if ($isLocal)
356
+ $customerChatdata = Mage::getModel('chatbot/chatdata')->load($replyFromUserId, 'telegram_chat_id');
357
+ else //if ($isForeign)
358
+ $customerChatdata = $foreignChatdata;
359
+
360
+ if ((!is_null($customerChatdata->getTelegramChatId())) || (!is_null($customerChatdata->getFacebookChatId()))) // TODO make this generic
361
  {
362
+ $handler = Mage::getModel('chatbot/api_facebook_handler'); // instances new Facebook model
363
+ if ($text == $admEndSupport) // finish customer support
364
  {
365
+ // TODO IMPORTANT remember to switch off all other supports
366
+ if ($isLocal)
 
 
 
 
367
  {
368
+ if ($customerChatdata->getTelegramConvState() == $chatbotHelper->_supportState)
369
+ {
370
+ $customerChatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_startState);
371
+ $telegram->postMessage($replyFromUserId, $mageHelper->__("Support ended.")); // TODO
372
+ }
373
+ else
374
+ $telegram->postMessage($replyFromUserId, $mageHelper->__("Customer isn't on support.")); // TODO
375
  }
376
+ else// if ($isForeign) // TODO make this generic
377
  {
378
+ if ($customerChatdata->getFacebookConvState() == $chatbotHelper->_supportState)
379
+ {
380
+ $customerChatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_startState);
381
+ $handler->foreignMessageFromSupport($foreignChatdata->getFacebookChatId(), $mageHelper->__("Support ended."));
382
+ }
383
+ else
384
+ $handler->foreignMessageFromSupport($foreignChatdata->getFacebookChatId(), $mageHelper->__("Customer isn't on support."));
385
  }
386
+
387
+ $telegram->postMessage($chatId, $mageHelper->__("Done. The customer is no longer on support."));
388
+ }
389
+ else if ($text == $admBlockSupport) // block user from using support
390
+ {
391
+ $customerChatdata->updateChatdata('enable_support', "0"); // disable support
392
+ $telegram->postMessage($chatId, $mageHelper->__("Done. The customer is no longer able to enter support.")); // TODO
393
+ }
394
+ else if ($text == $admEnableSupport) // unblock user from using support
395
+ {
396
+ $customerChatdata->updateChatdata('enable_support', "1"); // enable support
397
+ $telegram->postMessage($chatId, $mageHelper->__("Done. The customer is now able to enter support.")); // TODO
398
+ }
399
+ else if ($text == $admDisableBotCmd) // disable bot response
400
+ {
401
+ if ($isLocal)
402
+ $customerChatdata->updateChatdata('enable_telegram_admin', "0"); // disable support
403
+ else// if ($isForeign) // TODO make this generic
404
+ $customerChatdata->updateChatdata('enable_facebook_admin', "0"); // disable support
405
+
406
+ $telegram->postMessage($chatId, $mageHelper->__("Done. The bot will no longer send messages to this customer.")); // TODO
407
+ }
408
+ else if ($text == $admEnableBotCmd) // enable bot response
409
+ {
410
+ if ($isLocal)
411
+ $customerChatdata->updateChatdata('enable_telegram_admin', "1"); // enable support
412
+ else// if ($isForeign) // TODO make this generic
413
+ $customerChatdata->updateChatdata('enable_facebook_admin', "1"); // enable support
414
+
415
+ $telegram->postMessage($chatId, $mageHelper->__("Done. The bot will now start sending messages to this customer.")); // TODO
416
+ }
417
+ else // if no command, then it's replying the user
418
+ {
419
+ if ($isLocal)
420
  {
421
+ if ($customerChatdata->getTelegramConvState() != $chatbotHelper->_supportState) // if user isn't on support, switch to support
422
+ {
423
+ $customerChatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_supportState);
424
+ $telegram->postMessage($replyFromUserId, $mageHelper->__("You're now on support mode."));
425
+ }
426
+
427
+ $telegram->postMessage($replyFromUserId, $mageHelper->__("Message from support") . ":\n" . $text); // send message to customer TODO
428
  }
429
+ else //if ($isForeign) // TODO make this generic
430
  {
431
+ if ($customerChatdata->getFacebookConvState() != $chatbotHelper->_supportState) // if user isn't on support, switch to support
432
  {
433
+ $customerChatdata->updateChatdata('facebook_conv_state', $chatbotHelper->_supportState);
434
+ $handler->foreignMessageFromSupport($foreignChatdata->getFacebookChatId(), $mageHelper->__("You're now on support mode."));
435
  }
436
+
437
+ $message = $mageHelper->__("Message from support") . ":\n" . $text;
438
+ $handler->foreignMessageFromSupport($foreignChatdata->getFacebookChatId(), $message);
439
  }
440
+
441
+ $telegram->postMessage($chatId, $mageHelper->__("Message sent.")); // send message to admin group TODO
442
  }
443
  }
444
+ else
445
+ $errorFlag = true;
446
  }
447
+ else
448
+ $errorFlag = true;
449
+
450
+ if ($errorFlag)
451
  {
452
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
453
+ return $chatdata->respondSuccess();
454
+ }
455
+ }
456
+ else // proccess other admin commands (that aren't replying messages)
457
+ {
458
+ $admSend2All = $commandPrefix . $chatbotHelper->_admSendMessage2AllCmd;
459
+ $admListCmds = $commandPrefix . $chatbotHelper->_admListCmds;
460
 
461
+ if ($text == $admListCmds)
462
+ {
463
+ $message = $mageHelper->__("List of all admin commands") . ":\n" .
464
+ $admListCmds . " - " . $mageHelper->__("List all admin commands") . "\n" .
465
+ $admSend2All . " - " . $mageHelper->__("Send message to all customers") . "\n" .
466
+ $admEndSupport . " - " . $mageHelper->__("End support for customer") . "\n" .
467
+ $admBlockSupport . " - " . $mageHelper->__("Block customer for entering support mode") . "\n" .
468
+ $admEnableSupport . " - " . $mageHelper->__("Enable customer for entering support mode") . "\n" .
469
+ $admDisableBotCmd . " - " . $mageHelper->__("Disable bot responses") . "\n" .
470
+ $admEnableBotCmd . " - " . $mageHelper->__("Enable bot responses")
471
+ ;
472
+ $telegram->postMessage($chatId, $message);
473
+ }
474
+ else if ($chatbotHelper->startsWith($text, $admSend2All)) // old checkCommandWithValue
475
+ {
476
+ $message = trim($chatbotHelper->getCommandValue($text, $admSend2All));
477
+ if (!empty($message))
478
  {
479
+ $chatbotCollection = Mage::getModel('chatbot/chatdata')->getCollection();
480
+ $i = 0;
481
+ foreach($chatbotCollection as $chatbot)
482
  {
483
+ $tgChatId = $chatbot->getTelegramChatId();
484
+ $enabled = // if backend promotional messages are disabled or if the customer wants to receive promotional messages
485
+ (Mage::getStoreConfig('chatbot_enable/general_config/disable_promotional_messages') != "1") ||
486
+ ($chatbot->getEnablePromotionalMessages() == "1");
487
+ if (!empty($tgChatId) && ($enabled))
488
  {
489
+ $i++;
490
+ $telegram->postMessage($tgChatId, $message); // $magehelper->__("Message from support") . ":\n" .
 
491
  }
492
+ }
493
+ if ($i > 0)
494
+ {
495
+ if ($i == 1)
496
+ $telegram->postMessage($chatId, $mageHelper->__("One message sent."));
497
+ else
498
+ $telegram->postMessage($chatId, $mageHelper->__("%s messages sent.", $i));
499
  }
500
  else
501
+ $telegram->postMessage($chatId, $mageHelper->__("No customer available to receive this message."));
502
  }
503
+ else
504
+ $telegram->postMessage($chatId, $mageHelper->__("Please use") . ' "' . $admSend2All . " " . $mageHelper->__("your message here.") . '"');
505
  }
 
506
  }
507
+ return $chatdata->respondSuccess();
 
508
  }
509
+ $telegram->postMessage($chatId, $mageHelper->__("I don't work with groups.")); // TODO
510
+ return $chatdata->respondSuccess(); // ignore all group messages
511
+ }
512
 
513
+ // ALL CUSTOMER HANDLERS GOES AFTER HERE
514
+ if ($chatdata->getIsLogged() == "1") // check if customer is logged
515
+ {
516
+ if (Mage::getModel('customer/customer')->load((int)$chatdata->getCustomerId())->getId()) // if is a valid customer id
517
  {
518
+ if ($chatdata->getEnableTelegram() != "1")
519
  {
520
+ $telegram->postMessage($chatId, $mageHelper->__("To talk with me, please enable Telegram on your account chatbot settings."));
521
+ return $chatdata->respondSuccess();
 
 
 
522
  }
523
  }
524
+ }
525
 
526
+ $blockerStates = (
527
+ $conversationState == $chatbotHelper->_listCategoriesState ||
528
+ $conversationState == $chatbotHelper->_searchState ||
529
+ $conversationState == $chatbotHelper->_supportState ||
530
+ $conversationState == $chatbotHelper->_sendEmailState ||
531
+ $conversationState == $chatbotHelper->_trackOrderState
532
+ );
533
 
534
+ // init start command
535
+ $chatbotHelper->_startCmd['command'] = "/start"; // $commandPrefix
536
+
537
+ // user isnt registred HERE
538
+ if (is_null($chatdata->getTelegramChatId()) && !$chatbotHelper->startsWith($text, $chatbotHelper->_startCmd['command'])) // if user isn't registred, and not using the start command // old checkCommandWithValue
539
+ {
540
+ $message = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_welcome_msg'); // TODO
541
+ if (!empty($message)) // TODO
542
  {
543
+ if ($username)
544
+ $message = str_replace("{customername}", $username, $message);
545
+ $telegram->postMessage($chatId, $message);
546
+ }
547
+ try
548
+ {
549
+ $hash = substr(md5(uniqid($chatId, true)), 0, 150); // TODO
550
+ $chatdata // using magento model to insert data into database the proper way
551
+ ->setTelegramChatId($chatId)
552
+ ->setHashKey($hash) // TODO
553
+ ->save();
554
+ }
555
+ catch (Exception $e)
556
+ {
557
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage); // TODO
558
+ }
559
+ //return $chatdata->respondSuccess(); // commented to keep processing the message
560
+ }
561
+
562
+ // init other commands (for now, no alias for telegram)
563
+ $chatbotHelper->_listCategoriesCmd['command'] = $chatbotHelper->validateTelegramCmd($commandPrefix . $chatdata->getCommandString(1)['command']);
564
+ $chatbotHelper->_searchCmd['command'] = $chatbotHelper->validateTelegramCmd($commandPrefix . $chatdata->getCommandString(2)['command']);
565
+ $chatbotHelper->_loginCmd['command'] = $chatbotHelper->validateTelegramCmd($commandPrefix . $chatdata->getCommandString(3)['command']);
566
+ $chatbotHelper->_listOrdersCmd['command'] = $chatbotHelper->validateTelegramCmd($commandPrefix . $chatdata->getCommandString(4)['command']);
567
+ $chatbotHelper->_reorderCmd['command'] = $chatbotHelper->validateTelegramCmd($commandPrefix . $chatdata->getCommandString(5)['command']);
568
+ $chatbotHelper->_add2CartCmd['command'] = $chatbotHelper->validateTelegramCmd($commandPrefix . $chatdata->getCommandString(6)['command']);
569
+ $chatbotHelper->_checkoutCmd['command'] = $chatbotHelper->validateTelegramCmd($commandPrefix . $chatdata->getCommandString(7)['command']);
570
+ $chatbotHelper->_clearCartCmd['command'] = $chatbotHelper->validateTelegramCmd($commandPrefix . $chatdata->getCommandString(8)['command']);
571
+ $chatbotHelper->_trackOrderCmd['command'] = $chatbotHelper->validateTelegramCmd($commandPrefix . $chatdata->getCommandString(9)['command']);
572
+ $chatbotHelper->_supportCmd['command'] = $chatbotHelper->validateTelegramCmd($commandPrefix . $chatdata->getCommandString(10)['command']);
573
+ $chatbotHelper->_sendEmailCmd['command'] = $chatbotHelper->validateTelegramCmd($commandPrefix . $chatdata->getCommandString(11)['command']);
574
+ $chatbotHelper->_cancelCmd['command'] = $chatbotHelper->validateTelegramCmd($commandPrefix . $chatdata->getCommandString(12)['command']);
575
+ $chatbotHelper->_helpCmd['command'] = $chatbotHelper->validateTelegramCmd($commandPrefix . $chatdata->getCommandString(13)['command']);
576
+ $chatbotHelper->_aboutCmd['command'] = $chatbotHelper->validateTelegramCmd($commandPrefix . $chatdata->getCommandString(14)['command']);
577
+ $chatbotHelper->_logoutCmd['command'] = $chatbotHelper->validateTelegramCmd($commandPrefix . $chatdata->getCommandString(15)['command']);
578
+ $chatbotHelper->_registerCmd['command'] = $chatbotHelper->validateTelegramCmd($commandPrefix . $chatdata->getCommandString(16)['command']);
579
+ if (!$chatbotHelper->_cancelCmd['command']) $chatbotHelper->_cancelCmd['command'] = "/cancel"; // it must always have a cancel command // $commandPrefix
580
+
581
+ // init messages
582
+ $chatbotHelper->_cancelMessage = $mageHelper->__("To cancel, send") . " " . $chatbotHelper->_cancelCmd['command'];
583
+ $chatbotHelper->_canceledMessage = $mageHelper->__("Ok, canceled.");
584
+ $chatbotHelper->_loginFirstMessage = $mageHelper->__("Please login first.");
585
+ array_push($chatbotHelper->_positiveMessages, $mageHelper->__("Ok"), $mageHelper->__("Okay"), $mageHelper->__("Cool"), $mageHelper->__("Awesome"));
586
+ // $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)]
587
+
588
+ // TODO DEBUG COMMANDS
589
+ // $temp_var = $chatbotHelper->_startCmd['command'] . " - " .
590
+ // $chatbotHelper->_listCategoriesCmd['command'] . " - " .
591
+ // $chatbotHelper->_searchCmd['command'] . " - " .
592
+ // $chatbotHelper->_loginCmd['command'] . " - " .
593
+ // $chatbotHelper->_listOrdersCmd['command'] . " - " .
594
+ // $chatbotHelper->_reorderCmd['command'] . " - " .
595
+ // $chatbotHelper->_add2CartCmd['command'] . " - " .
596
+ // $chatbotHelper->_checkoutCmd['command'] . " - " .
597
+ // $chatbotHelper->_clearCartCmd['command'] . " - " .
598
+ // $chatbotHelper->_trackOrderCmd['command'] . " - " .
599
+ // $chatbotHelper->_supportCmd['command'] . " - " .
600
+ // $chatbotHelper->_sendEmailCmd['command'];
601
+ // $telegram->postMessage($chatId, $temp_var);
602
+ // $telegram->postMessage($chatId, $conversationState);
603
+
604
+ // start command
605
+ //if ($text == $chatbotHelper->_startCmd['command'])
606
+ if ($chatbotHelper->startsWith($text, $chatbotHelper->_startCmd['command'])) // ignore alias // old checkCommandWithValue
607
+ {
608
+ $startdata = explode(" ", $text);
609
+ if (is_array($startdata) && count($startdata) > 1) // has hash parameter
610
+ {
611
+ $chatHash = $chatdata->load(trim($startdata[1]), 'hash_key');
612
+ if ($chatHash->getHashKey())
613
  {
614
+ try
 
615
  {
616
+ $chatHash->addData(array("telegram_chat_id" => $chatId));
617
+ $chatHash->save();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
618
 
619
+ $message = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_welcome_msg'); // TODO
620
+ if (!empty($message)) // TODO
621
+ $telegram->postMessage($chatId, $message);
622
+ }
623
+ catch (Exception $e)
624
+ {
625
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage); // TODO
 
626
  }
627
  }
628
  }
629
+ else if ($chatdata->getTelegramChatId()) // TODO
630
+ {
631
+ $message = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_about_msg'); // TODO
632
+ $telegram->postMessage($chatId, $message);
633
+
634
+ // $data = array(
635
+ // //'customer_id' => $customerId,
636
+ // 'telegram_chat_id' => $chatId
637
+ // ); // data to be insert on database
638
+ // $model = Mage::getModel('chatbot/chatdata')->load($chatdata->getId())->addData($data); // insert data on database
639
+ // $model->setId($chatdata->getId())->save(); // save (duh)
640
+ }
641
+ else // if customer id isnt on our database, means that we need to insert his data
642
  {
643
  $message = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_welcome_msg'); // TODO
644
+ if (!empty($message)) // TODO
645
+ $telegram->postMessage($chatId, $message);
646
  try
647
  {
648
  $hash = substr(md5(uniqid($chatId, true)), 0, 150); // TODO
649
+ Mage::getModel('chatbot/chatdata') // using magento model to insert data into database the proper way
650
  ->setTelegramChatId($chatId)
651
  ->setHashKey($hash) // TODO
652
+ ->setCreatedAt(date('Y-m-d H:i:s'))
653
  ->save();
654
  }
655
  catch (Exception $e)
656
  {
657
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage); // TODO
658
  }
 
659
  }
660
+ return $chatdata->respondSuccess();
661
+ }
662
 
663
+ // help command
664
+ if ($chatbotHelper->checkCommand($text, $chatbotHelper->_helpCmd))
665
+ {
666
+ $message = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_help_msg'); // TODO
667
+ if (!empty($message)) // TODO
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
668
  {
669
+ $cmdListing = Mage::getStoreConfig('chatbot_enable/telegram_config/enable_help_command_list');
670
+ if ($cmdListing == "1")
671
+ $message .= $chatdata->listTelegramCommandsMessage();
672
+
673
+ $telegram->postMessage($chatId, $message);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
674
  }
675
 
676
+ return $chatdata->respondSuccess();
677
+ }
 
 
 
 
 
 
 
678
 
679
+ // about command
680
+ if ($chatbotHelper->checkCommand($text, $chatbotHelper->_aboutCmd))
681
+ {
682
+ $message = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_about_msg'); // TODO
683
+ if (!empty($message))
684
+ $telegram->postMessage($chatId, $message);
685
 
686
+ return $chatdata->respondSuccess();
687
+ }
688
 
689
+ // cancel command
690
+ if ($chatbotHelper->checkCommand($text, $chatbotHelper->_cancelCmd)) // TODO
691
+ {
692
+ if ($conversationState == $chatbotHelper->_listCategoriesState)
693
  {
694
+ $keyb = $telegram->buildKeyBoardHide(true); // hide keyboard built on listing categories
695
+ $content = array('chat_id' => $chatId, 'reply_markup' => $keyb, 'text' => $chatbotHelper->_canceledMessage);
 
 
 
696
  }
697
+ else if ($conversationState == $chatbotHelper->_supportState)
 
 
698
  {
699
+ $content = array('chat_id' => $chatId, 'text' => $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("exiting support mode."));
700
+ //$telegram->postMessage($chatId, $magehelper->__("Done."));
701
+ }
702
+ else if ($conversationState == $chatbotHelper->_searchState)
703
+ {
704
+ $content = array('chat_id' => $chatId, 'text' => $chatbotHelper->_canceledMessage);
705
+ }
706
+ else if ($conversationState == $chatbotHelper->_sendEmailState)
707
+ {
708
+ $content = array('chat_id' => $chatId, 'text' => $chatbotHelper->_canceledMessage);
709
+ }
710
+ else if ($conversationState == $chatbotHelper->_listProductsState)
711
+ {
712
+ $content = array('chat_id' => $chatId, 'text' => $chatbotHelper->_canceledMessage);
713
+ }
714
+ else if ($conversationState == $chatbotHelper->_listOrdersState)
715
+ {
716
+ $content = array('chat_id' => $chatId, 'text' => $chatbotHelper->_canceledMessage);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
717
  }
718
+ else
719
+ $content = array('chat_id' => $chatId, 'text' => $chatbotHelper->_errorMessage);
720
 
721
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_startState))
722
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
723
+ else
724
+ $telegram->sendMessage($content);
725
+ return $chatdata->respondSuccess();
726
+ }
727
+
728
+ // add2cart commands
729
+ if ($chatbotHelper->startsWith($text, $chatbotHelper->_add2CartCmd['command'])) // ignore alias // old checkCommandWithValue
730
+ {
731
+ $errorFlag = false;
732
+ $notInStock = false;
733
+ $cmdvalue = $chatbotHelper->getCommandValue($text, $chatbotHelper->_add2CartCmd['command']);
734
+ if ($cmdvalue) // TODO
735
  {
736
+ $product = Mage::getModel('catalog/product')->load($cmdvalue);
737
+ if ($product->getId())
 
 
738
  {
739
+ $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getIsInStock();
740
+ if ($stock > 0)
741
  {
742
+ $productName = $product->getName();
743
+ if (empty($productName))
744
+ $productName = $mageHelper->__("this product");
745
+ $telegram->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("adding %s to your cart.", $productName));
746
+ $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
747
+ if ($chatdata->addProd2Cart($cmdvalue))
748
+ $telegram->postMessage($chatId, $mageHelper->__("Added. To checkout send") . " " . $chatbotHelper->_checkoutCmd['command']);
 
 
 
 
 
 
749
  else
750
+ $errorFlag = true;
751
  }
752
  else
753
+ $notInStock = true;
754
  }
755
  else
756
  $errorFlag = true;
757
+ }
758
+ else
759
+ $errorFlag = true;
760
 
761
+ if ($errorFlag)
762
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
763
+ else if ($notInStock)
764
+ $telegram->postMessage($chatId, $mageHelper->__("This product is not in stock."));
765
 
766
+ return $chatdata->respondSuccess();
767
+ }
768
 
769
+ // states
770
+ if ($conversationState == $chatbotHelper->_listCategoriesState) // TODO show only in stock products
771
+ {
772
+ if ($catId)
773
+ $_category = Mage::getModel('catalog/category')->load($catId);
774
+ else
775
+ $_category = Mage::getModel('catalog/category')->loadByAttribute('name', $text);
776
 
777
+ if ($_category)
778
+ $categoryName = $_category->getName();
779
+ else
780
+ $categoryName = $mageHelper->__("this caytegory");
 
781
 
782
+ $keyb = $telegram->buildKeyBoardHide(true); // hide keyboard built on listing categories
783
+ if ($showMore == 0) // show only in the first time
784
+ $telegram->sendMessage(array('chat_id' => $chatId, 'reply_markup' => $keyb, 'text' => $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("please wait while I gather all products from %s for you.", $categoryName)));
785
+ else
786
+ $telegram->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("listing more."));
787
+
788
+ $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
789
+ $errorFlag = false;
790
+ if ($_category) // check if variable isn't false/empty
791
+ {
792
+ if ($_category->getId()) // check if is a valid category
793
  {
794
+ $noProductFlag = false;
795
+ $productCollection = $_category->getProductCollection()
796
+ ->addAttributeToSelect('*')
797
+ ->addAttributeToFilter('visibility', 4)
798
+ ->addAttributeToFilter('type_id', 'simple');
799
+ Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($productCollection);
800
+ $productIDs = $productCollection->getAllIds();
801
+
802
+ if ($productIDs)
803
  {
804
+ $i = 0;
805
+ $total = count($productIDs);
 
 
 
 
 
806
 
807
+ if ($showMore < $total)
808
  {
809
+ if ($showMore == 0)
 
 
 
810
  {
811
+ if ($total == 1)
812
+ $telegram->postMessage($chatId, $mageHelper->__("Done. This category has only one product."));
813
+ else
814
+ $telegram->postMessage($chatId, $mageHelper->__("Done. This category has %s products.", $total));
815
+ }
 
 
816
 
817
+ foreach ($productIDs as $productID)
818
+ {
819
+ $message = $chatbotHelper->prepareTelegramProdMessages($productID);
820
+ if (!empty($message)) // TODO
821
  {
822
+ $message .= "\n" . $mageHelper->__("Add to cart") . ": " . $chatbotHelper->_add2CartCmd['command'] . $productID;
823
+ if ($i >= $showMore)
824
  {
825
+ $productImage = $chatbotHelper->loadImageContent($productID);
826
+ if (!empty($productImage))
827
+ $telegram->sendPhoto(array('chat_id' => $chatId, 'photo' => $productImage, 'caption' => $message));
828
+ else
829
+ $telegram->postMessage($chatId, $message);
 
 
830
 
831
+ if (($i + 1) != $total && $i >= ($showMore + $listingLimit)) // if isn't the 'last but one' and $i is bigger than listing limit + what was shown last time ($show_more)
832
+ {
833
+ // TODO add option to list more products
834
+ $telegram->postMessage($chatId, $mageHelper->__("To show more, send") . " " . $listMoreCategories . $_category->getId() . "_" . (string)($i + 1));
835
+ if ($chatdata->getTelegramConvState() != $chatbotHelper->_listProductsState)
836
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_listProductsState))
837
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
838
+ break;
839
+ }
840
+ else if (($i + 1) == $total) // if it's the last one, back to _startState
841
+ {
842
+ $telegram->postMessage($chatId, $mageHelper->__("And that was the last one."));
843
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_startState))
844
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
 
845
  }
 
846
  }
847
+ $i++;
848
  }
 
 
849
  }
850
+ if ($i == 0)
851
+ $noProductFlag = true;
 
852
  }
853
  else
854
+ $errorFlag = true;
855
 
 
 
856
  }
857
  else
858
+ $noProductFlag = true;
859
+
860
+ if ($noProductFlag)
861
+ $telegram->sendMessage(array('chat_id' => $chatId, 'reply_markup' => $keyb, 'text' => $mageHelper->__("Sorry, no products found in this category.")));
862
  }
863
  else
864
  $errorFlag = true;
865
+ }
866
+ else
867
+ $errorFlag = true;
868
 
869
+ if ($errorFlag)
870
+ {
871
+ $telegram->sendMessage(array('chat_id' => $chatId, 'reply_markup' => $keyb, 'text' => $chatbotHelper->_errorMessage));
872
+ $chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_startState);
 
 
873
  }
874
+ return $chatdata->respondSuccess();
875
+ }
876
+ else if ($conversationState == $chatbotHelper->_searchState) // TODO
877
+ {
878
+ if ($showMore == 0) // show only in the first time
879
+ $telegram->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("please wait while I search for '%s' for you.", $text));
880
+ else
881
+ $telegram->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("listing more."));
882
+
883
+ $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
884
+ $errorFlag = false;
885
+ $noProductFlag = false;
886
+ $productIDs = $chatbotHelper->getProductIdsBySearch($text);
887
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_startState))
888
  {
889
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
890
+ return $chatdata->respondSuccess();
891
+ }
892
+ else if ($productIDs)
893
+ {
894
+ $i = 0;
895
+ $total = count($productIDs);
896
 
897
+ if ($showMore < $total)
 
 
 
 
 
 
 
 
 
898
  {
899
+ if ($showMore == 0)
 
 
 
900
  {
901
+ if ($total == 1)
902
+ $telegram->postMessage($chatId, $mageHelper->__("Done. I've found only one product for your criteria."));
903
+ else
904
+ $telegram->postMessage($chatId, $mageHelper->__("Done. I've found %s products for your criteria.", $total));
905
+ }
 
 
906
 
907
+ foreach ($productIDs as $productID)
908
+ {
909
+ $message = $chatbotHelper->prepareTelegramProdMessages($productID);
910
+ if (!empty($message)) // TODO
911
  {
912
+ $message .= "\n" . $mageHelper->__("Add to cart") . ": " . $chatbotHelper->_add2CartCmd['command'] . $productID;
913
+ if ($i >= $showMore)
914
  {
915
+ $productImage = $chatbotHelper->loadImageContent($productID);
916
+ if (!empty($productImage))
917
+ $telegram->sendPhoto(array('chat_id' => $chatId, 'photo' => $productImage, 'caption' => $message));
918
+ else
919
+ $telegram->postMessage($chatId, $message);
 
 
920
 
921
+ if (($i + 1) != $total && $i >= ($showMore + $listingLimit)) // if isn't the 'last but one' and $i is bigger than listing limit + what was shown last time ($show_more)
922
+ {
923
+ // TODO add option to list more products
924
+ $telegram->postMessage($chatId, $mageHelper->__("To show more, send") . " " . $listMoreSearch . str_replace(" ", "_", $text) . "_" . (string)($i + 1));
925
+ if ($chatdata->getTelegramConvState() != $chatbotHelper->_listProductsState)
926
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_listProductsState))
927
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
928
+ break;
929
+ }
930
+ else if (($i + 1) == $total) // if it's the last one, back to _startState
931
+ {
932
+ $telegram->postMessage($chatId, $mageHelper->__("And that was the last one."));
933
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_startState))
934
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
 
935
  }
 
936
  }
937
+ $i++;
938
  }
 
 
939
  }
940
+ if ($i == 0)
941
+ $noProductFlag = true;
942
  }
943
  else
944
+ $errorFlag = true;
945
+ }
946
+ else
947
+ $noProductFlag = true;
948
 
949
+ if ($noProductFlag)
950
+ $telegram->postMessage($chatId, $mageHelper->__("Sorry, no products found for this criteria."));
 
 
 
951
 
952
+ if ($errorFlag)
953
+ {
954
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
955
+ $chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_startState);
956
  }
957
+
958
+ return $chatdata->respondSuccess();
959
+ }
960
+ else if ($conversationState == $chatbotHelper->_supportState)
961
+ {
962
+ if (!empty($supportGroupId))
963
  {
964
+ $telegram->forwardMessage(array('chat_id' => $supportGroupId, 'from_chat_id' => $chatId, 'message_id' => $telegram->MessageID())); // Reply to this message to reply to the customer
965
+ $telegram->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("we have sent your message to support."));
 
 
 
 
 
 
966
  }
967
+ else
968
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
969
+ return $chatdata->respondSuccess();
970
+ }
971
+ else if ($conversationState == $chatbotHelper->_sendEmailState)
972
+ {
973
+ $telegram->postMessage($chatId, $mageHelper->__("Trying to send the email..."));
974
+ if ($chatdata->sendEmail($text, $username))
975
  {
976
+ $telegram->postMessage($chatId, $mageHelper->__("Done."));
 
 
 
 
 
 
 
 
 
977
  }
978
+ else
979
+ $telegram->postMessage($chatId, $mageHelper->__("Sorry, I wasn't able to send an email this time. Please try again later."));
980
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_startState))
981
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
982
+ return $chatdata->respondSuccess();
983
+ }
984
+ else if ($conversationState == $chatbotHelper->_trackOrderState)
985
+ {
986
+ $errorFlag = false;
987
+ if ($chatdata->getIsLogged() == "1")
988
  {
989
+ $telegram->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("please wait while I check the status for order %s.", $text));
990
+ $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
991
+ $order = Mage::getModel('sales/order')->loadByIncrementId($text);
992
+ if ($order->getId())
993
  {
994
+ if ($order->getCustomerId() == $chatdata->getCustomerId()) // not a problem if customer dosen't exist
 
 
 
995
  {
996
+ $telegram->postMessage($chatId, $mageHelper->__("Your order status is") . " " . $mageHelper->__($order->getStatus()));
 
 
 
 
 
997
  }
998
  else
999
  $errorFlag = true;
1000
  }
1001
  else
1002
+ $errorFlag = true;
 
 
 
 
 
1003
  }
1004
+ else
1005
+ $telegram->postMessage($chatId, $chatbotHelper->_loginFirstMessage);
1006
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_startState))
1007
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
1008
+ else if ($errorFlag)
1009
+ $telegram->postMessage($chatId, $mageHelper->__("Sorry, we couldn't find any order with this information."));
1010
+ return $chatdata->respondSuccess();
1011
+ }
1012
 
1013
+ // general commands
1014
+ if ($chatbotHelper->checkCommand($text, $chatbotHelper->_listCategoriesCmd))
1015
+ {
1016
+ $telegram->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("please wait while I gather all categories for you."));
1017
+ $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
1018
 
1019
+ $categoryHelper = Mage::helper('catalog/category');
1020
+ $categories = $categoryHelper->getStoreCategories(); // TODO test with a store without categories
1021
+ $i = 0;
1022
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_listCategoriesState))
1023
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
1024
+ else if ($categories)
1025
+ {
1026
+ $option = array();
1027
+ $arr = array();
1028
+ $charCount = 0;
1029
+ foreach ($categories as $category) // TODO fix buttons max size
1030
  {
1031
+ if ($enableEmptyCategoriesListing != "1") // unallow empty categories listing
 
 
 
1032
  {
1033
+ $category = Mage::getModel('catalog/category')->load($category->getId()); // reload category because EAV Entity
1034
+ $productIDs = $category->getProductCollection()
1035
+ ->addAttributeToSelect('*')
1036
+ ->addAttributeToFilter('visibility', 4)
1037
+ ->addAttributeToFilter('type_id', 'simple')
1038
+ ->getAllIds();
1039
+ }
1040
+ else
1041
+ $productIDs = true;
1042
+ if (!empty($productIDs)) // category with no products
1043
+ {
1044
+ //$option = array( array("A", "B"), array("C", "D") );
1045
+ $catName = $category->getName();
1046
+ $charCount = $charCount + strlen($catName);
1047
+ array_push($arr, $catName); // push category name into array arr
1048
+ if ($charCount > $categoryLimit) // size limit for Telegram buttons
1049
  {
1050
+ array_push($option, $arr); // when hits the limit, add array to options
1051
+ $arr = array(); // clear array
1052
+ $charCount = 0;
 
 
 
 
 
 
 
 
 
1053
  }
1054
+
1055
+ $i++;
1056
  }
1057
+ }
1058
 
1059
+ if (!empty($arr)) // if the loop ended, and there's still categories on arr
1060
+ array_push($option, $arr);
1061
 
1062
+ $keyb = $telegram->buildKeyBoard($option);
1063
+ $telegram->sendMessage(array('chat_id' => $chatId, 'reply_markup' => $keyb, 'resize_keyboard' => true, 'text' => $mageHelper->__("Select a category") . ". " . $chatbotHelper->_cancelMessage));
1064
+ }
1065
+ else if ($i == 0)
1066
+ {
1067
+ $telegram->postMessage($chatId, $mageHelper->__("No categories available at the moment, please try again later."));
1068
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_startState))
1069
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
1070
+ }
1071
+ else
1072
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
1073
+
1074
+ return $chatdata->respondSuccess();
1075
+ }
1076
+ else if ($chatbotHelper->checkCommand($text, $chatbotHelper->_checkoutCmd)) // TODO
1077
+ {
1078
+ $sessionId = null;
1079
+ $quoteId = null;
1080
+ $telegram->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("please wait while I prepare the checkout for you."));
1081
+ $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
1082
+ if ($chatdata->getIsLogged() == "1")
1083
+ {
1084
+ if (Mage::getModel('customer/customer')->load((int)$chatdata->getCustomerId())->getId())
1085
  {
1086
+ // if user is set as logged, then login using magento singleton
1087
+ $customerSession = Mage::getSingleton('customer/session');
1088
+ $customerSession->loginById((int)$chatdata->getCustomerId());
1089
+ // then set current quote as customer quote
1090
+ $customer = Mage::getModel('customer/customer')->load((int)$chatdata->getCustomerId());
1091
+ $quote = Mage::getModel('sales/quote')->loadByCustomer($customer);
1092
+ // set quote and session ids from logged user
1093
+ $quoteId = $quote->getId();
1094
+ $sessionId = $customerSession->getEncryptedSessionId();
1095
  }
 
 
 
 
1096
  }
1097
+ if (!($sessionId && $quoteId))
1098
  {
1099
+ // set quote and session ids from chatbot class
1100
+ $sessionId = $chatdata->getSessionId();
1101
+ $quoteId = $chatdata->getQuoteId();
1102
+ }
1103
+ $emptyCart = true;
1104
+ if ($sessionId && $quoteId)
1105
+ {
1106
+ $cartUrl = Mage::helper('checkout/cart')->getCartUrl();
1107
+ if (!isset(parse_url($cartUrl)['SID']))
1108
+ $cartUrl .= "?SID=" . $sessionId; // add session id to url
1109
+
1110
+ $cart = Mage::getModel('checkout/cart')->setQuote(Mage::getModel('sales/quote')->loadByIdWithoutStore((int)$quoteId));
1111
+ $ordersubtotal = $cart->getQuote()->getSubtotal();
1112
+ if ($ordersubtotal > 0)
1113
  {
1114
+ $emptyCart = false;
1115
+ $message = $mageHelper->__("Products on cart") . ":\n";
1116
+ foreach ($cart->getQuote()->getItemsCollection() as $item) // TODO
1117
  {
1118
+ $message .= $item->getQty() . "x " . $item->getProduct()->getName() . "\n" .
1119
+ $mageHelper->__("Price") . ": " . Mage::helper('core')->currency($item->getProduct()->getPrice(), true, false) . "\n\n";
 
 
 
 
 
 
 
1120
  }
1121
+ $message .= $mageHelper->__("Total") . ": " .
1122
+ Mage::helper('core')->currency($ordersubtotal, true, false) . "\n\n" .
1123
+ "[" . $mageHelper->__("Checkout Here") . "](" . $cartUrl . ")";
1124
+
1125
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_checkoutState))
1126
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
1127
+ else
1128
+ $telegram->sendMessage(array('chat_id' => $chatId, 'parse_mode' => 'Markdown', 'text' => $message));
1129
  }
1130
+ else if (!$chatdata->clearCart()) // try to clear cart
1131
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
1132
+ }
1133
+ if ($emptyCart)
1134
+ $telegram->postMessage($chatId, $mageHelper->__("Your cart is empty."));
1135
+ return $chatdata->respondSuccess();
1136
+ }
1137
+ else if ($chatbotHelper->checkCommand($text, $chatbotHelper->_clearCartCmd))
1138
+ {
1139
+ $telegram->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("please wait while I clear your cart."));
1140
+ $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
1141
+ $errorFlag = false;
1142
+ if ($chatdata->clearCart())
1143
+ {
1144
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_clearCartState))
1145
+ $errorFlag = true;
1146
+ else
1147
+ $telegram->postMessage($chatId, $mageHelper->__("Cart cleared."));
1148
+ }
1149
+ else
1150
+ $errorFlag = true;
1151
+ if ($errorFlag)
1152
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
1153
+ return $chatdata->respondSuccess();
1154
+ }
1155
+ else if ($chatbotHelper->checkCommand($text, $chatbotHelper->_searchCmd))
1156
+ {
1157
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_searchState))
1158
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
1159
+ else
1160
+ $telegram->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("what do you want to search for?") . " " . $chatbotHelper->_cancelMessage);
1161
+ return $chatdata->respondSuccess();
1162
+ }
1163
+ else if ($chatbotHelper->checkCommand($text, $chatbotHelper->_loginCmd)) // TODO
1164
+ {
1165
+ if ($chatdata->getIsLogged() != "1") // customer not logged
1166
+ {
1167
+ $hashUrl = Mage::getUrl('chatbot/settings/index/'); // get base module URL
1168
+ $hashUrl = strtok($hashUrl, '?') . "hash" . DS . $chatdata->getHashKey(); // remove magento parameters
1169
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_loginState))
1170
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
1171
+ else
1172
  {
1173
+ $telegram->postMessage($chatId,
1174
+ $mageHelper->__("To login to your account, click this link") . ": " .
1175
+ $hashUrl . " . " .
1176
+ $mageHelper->__("If you want to logout from your account, just send") . " " .
1177
+ $chatbotHelper->_logoutCmd['command']
1178
+ );
1179
  }
1180
+ }
1181
+ else
1182
+ $telegram->postMessage($chatId, $mageHelper->__("You're already logged."));
1183
+ return $chatdata->respondSuccess();
1184
+ }
1185
+ else if ($chatbotHelper->checkCommand($text, $chatbotHelper->_logoutCmd)) // TODO
1186
+ {
1187
+ if ($chatdata->getIsLogged() == "1")
1188
+ {
1189
+ $telegram->postMessage($chatId, $mageHelper->__("Ok, logging out."));
1190
+ $errorFlag = false;
1191
+ try
1192
+ {
1193
+ $chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_startState);
1194
+ $chatdata->updateChatdata('is_logged', "0");
1195
+ $chatdata->updateChatdata('customer_id', ""); // TODO null?
1196
+ $chatdata->clearCart();
1197
+ }
1198
+ catch (Exception $e)
1199
  {
1200
+ $errorFlag = true;
1201
+ }
1202
+
1203
+ if ($errorFlag)
1204
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
1205
+ else
1206
+ $telegram->postMessage($chatId, $mageHelper->__("Done."));
1207
+ }
1208
+ else
1209
+ $telegram->postMessage($chatId, $mageHelper->__("You're not logged."));
1210
 
1211
+ return $chatdata->respondSuccess();
1212
+ }
1213
+ else if ($chatbotHelper->checkCommand($text, $chatbotHelper->_registerCmd)) // TODO
1214
+ {
1215
+ $registerUrl = strtok(Mage::getUrl('customer/account/create'), '?');
1216
+ if (!empty($registerUrl))
1217
+ $telegram->postMessage($chatId, $mageHelper->__("Access %s to register a new account on our shop.", $registerUrl));
1218
+ else
1219
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
1220
+ return $chatdata->respondSuccess();
1221
+ }
1222
+ else if ($chatbotHelper->checkCommand($text, $chatbotHelper->_listOrdersCmd) || $moreOrders) // TODO
1223
+ {
1224
+ if ($chatdata->getIsLogged() == "1")
1225
+ {
1226
+ if ($showMore == 0) // show only in the first time
1227
+ $telegram->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("please wait while I gather your orders for listing."));
1228
+ else
1229
+ $telegram->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("listing more."));
1230
+
1231
+ $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
1232
+ $ordersIDs = $chatbotHelper->getOrdersIdsFromCustomer($chatdata->getCustomerId());
1233
+ if ($ordersIDs)
1234
+ {
1235
+ $i = 0;
1236
+ $total = count($ordersIDs);
1237
+ if ($showMore < $total)
1238
  {
1239
+ if ($showMore == 0)
 
 
1240
  {
1241
+ if ($total == 1)
1242
+ $telegram->postMessage($chatId, $mageHelper->__("Done. You've only one order."));
1243
+ else
1244
+ $telegram->postMessage($chatId, $mageHelper->__("Done. I've found %s orders.", $total));
1245
  }
 
 
 
1246
 
1247
+ foreach($ordersIDs as $orderID)
1248
+ {
1249
+ $message = $chatbotHelper->prepareTelegramOrderMessages($orderID);
1250
+ if (!empty($message)) // TODO
1251
+ {
1252
+ if ($chatbotHelper->_reorderCmd['command'])
1253
+ $message .= "\n\n" . $mageHelper->__("Reorder") . ": " . $chatbotHelper->_reorderCmd['command'] . $orderID;
1254
+ if ($i >= $showMore)
1255
+ {
1256
+ $telegram->postMessage($chatId, $message);
1257
+ if (($i + 1) != $total && $i >= ($showMore + $listingLimit)) // if isn't the 'last but one' and $i is bigger than listing limit + what was shown last time ($show_more)
1258
+ {
1259
+ // TODO add option to list more orders
1260
+ $telegram->postMessage($chatId, $mageHelper->__("To show more, send") . " " . $listMoreOrders . (string)($i + 1));
1261
+ if ($chatdata->getTelegramConvState() != $chatbotHelper->_listOrdersState)
1262
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_listOrdersState))
1263
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
1264
+ break;
1265
+ }
1266
+ else if (($i + 1) == $total) // if it's the last one, back to _startState
1267
+ {
1268
+ $telegram->postMessage($chatId, $mageHelper->__("And that was the last one."));
1269
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_startState))
1270
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
1271
+ }
1272
+ }
1273
+ $i++;
1274
+ }
1275
+ }
1276
+ if ($i == 0)
1277
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
1278
+ // else if (!$chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_listOrdersState))
1279
+ // $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
1280
  }
 
 
1281
  }
1282
+ else
1283
+ {
1284
+ $telegram->postMessage($chatId, $mageHelper->__("This account has no orders."));
1285
+ return $chatdata->respondSuccess();
1286
+ }
1287
  }
1288
+ else
1289
+ $telegram->postMessage($chatId, $chatbotHelper->_loginFirstMessage);
1290
+ return $chatdata->respondSuccess();
1291
+ }
1292
+ else if ($chatbotHelper->startsWith($text, $chatbotHelper->_reorderCmd['command'])) // ignore alias TODO // old checkCommandWithValue
1293
+ {
1294
+ if ($chatdata->getIsLogged() == "1")
1295
  {
1296
+ $telegram->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("please wait while I add the products from this order to your cart."));
1297
  $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
1298
  $errorFlag = false;
1299
+ $cmdvalue = $chatbotHelper->getCommandValue($text, $chatbotHelper->_reorderCmd['command']);
1300
+ if ($cmdvalue)
1301
  {
1302
+ if ($chatdata->clearCart())
1303
+ {
1304
+ $order = Mage::getModel('sales/order')->load($cmdvalue);
1305
+ if ($order->getId())
1306
+ {
1307
+ foreach($order->getAllVisibleItems() as $item) {
1308
+ if (!$chatdata->addProd2Cart($item->getProductId()))
1309
+ $errorFlag = true;
1310
+ }
1311
+ }
1312
+ else
1313
+ $errorFlag = true;
1314
+ }
1315
  else
1316
+ $errorFlag = true;
1317
  }
1318
  else
1319
  $errorFlag = true;
1320
+
1321
  if ($errorFlag)
1322
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
1323
+ else if (!$chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_reorderState))
1324
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
1325
+ else // success!!
1326
+ $telegram->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("to checkout send") . " " . $chatbotHelper->_checkoutCmd['command']);
 
 
 
 
 
1327
  }
1328
+ else
1329
+ $telegram->postMessage($chatId, $chatbotHelper->_loginFirstMessage);
1330
+ return $chatdata->respondSuccess();
1331
+ }
1332
+ else if ($chatbotHelper->checkCommand($text, $chatbotHelper->_trackOrderCmd)) // TODO
1333
+ {
1334
+ if ($chatdata->getIsLogged() == "1")
1335
  {
1336
+ $ordersIDs = $chatbotHelper->getOrdersIdsFromCustomer($chatdata->getCustomerId());
1337
+ if ($ordersIDs)
1338
  {
1339
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_trackOrderState))
1340
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
 
 
1341
  else
1342
+ $telegram->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("send the order number."));
 
 
 
 
 
 
 
1343
  }
1344
  else
1345
+ $telegram->postMessage($chatId, $mageHelper->__("Your account dosen't have any orders."));
 
1346
  }
1347
+ else
1348
+ $telegram->postMessage($chatId, $chatbotHelper->_loginFirstMessage);
1349
+ return $chatdata->respondSuccess();
1350
+ }
1351
+ else if ($chatbotHelper->checkCommand($text, $chatbotHelper->_supportCmd)) // TODO
1352
+ {
1353
+ $supportEnabled = $chatdata->getEnableSupport();
1354
+ $errorFlag = false;
1355
+ if ($supportEnabled == "1")
1356
  {
1357
+ if ($chatdata->getFacebookConvState() != $chatbotHelper->_supportState)
1358
  {
1359
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_supportState))
 
 
 
 
 
 
 
 
 
 
1360
  $errorFlag = true;
 
 
 
 
1361
  else
1362
+ $telegram->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("what do you need support for?") . " " . $chatbotHelper->_cancelMessage);
1363
  }
1364
  else
1365
+ $telegram->postMessage($chatId, $mageHelper->__("You're already on support in other chat application, please close it before opening a new one."));
 
 
1366
  }
1367
+ else
1368
+ $telegram->postMessage($chatId, $mageHelper->__("I'm sorry, you can't ask for support now. Please try again later."));
1369
+
1370
+ if ($errorFlag)
1371
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
1372
+ return $chatdata->respondSuccess();
1373
+ }
1374
+ else if ($chatbotHelper->checkCommand($text, $chatbotHelper->_sendEmailCmd)) // TODO
1375
+ {
1376
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_sendEmailState))
1377
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
1378
+ else
1379
  {
1380
+ $telegram->postMessage($chatId, $chatbotHelper->_positiveMessages[array_rand($chatbotHelper->_positiveMessages)] . ", " . $mageHelper->__("write the email content."));
1381
+ $telegram->postMessage($chatId, $mageHelper->__("By doing this you agree that we may contact you directly via chat message.") . " " . $chatbotHelper->_cancelMessage);
 
 
 
 
1382
  }
1383
+ return $chatdata->respondSuccess();
1384
+ }
1385
+ else // fallback
1386
+ {
1387
+ // handle default replies
1388
+ if ($enableReplies == "1" && !$blockerStates)
1389
  {
1390
+ $defaultReplies = Mage::getStoreConfig('chatbot_enable/telegram_config/default_replies');
1391
+ if ($defaultReplies)
1392
  {
1393
+ $replies = unserialize($defaultReplies);
1394
+ if (is_array($replies))
 
 
 
 
 
 
1395
  {
1396
+ $hasWitaiReplies = false;
1397
+ foreach($replies as $reply)
 
1398
  {
1399
+ // MODES
1400
+ // 0 =>'Similarity'
1401
+ // 1 =>'Starts With'
1402
+ // 2 =>'Ends With'
1403
+ // 3 =>'Contains'
1404
+ // 4 =>'Match Regular Expression'
1405
+ // 5 =>'Equals to'
1406
+ // 6 =>'wit.ai'
1407
+
1408
+ $matched = false;
1409
+ $match = $reply["match_sintax"];
1410
+ $matchMode = $reply["match_mode"];
1411
+
1412
+ if ($reply["match_case"] == "0")
1413
  {
1414
+ $match = strtolower($match);
1415
+ $textToMatch = strtolower($text);
 
 
1416
  }
1417
+ else
1418
+ $textToMatch = $text;
1419
 
1420
+ if ($matchMode == "0") // Similarity
1421
  {
1422
+ $similarity = $reply["similarity"];
1423
+ if (is_numeric($similarity))
1424
  {
1425
+ if (!($similarity >= 1 && $similarity <= 100))
1426
+ $similarity = 100;
1427
+ }
1428
+ else
1429
+ $similarity = 100;
1430
+
1431
+ similar_text($textToMatch, $match, $percent);
1432
+ if ($percent >= $similarity)
1433
+ $matched = true;
1434
+ }
1435
+ else if ($matchMode == "1") // Starts With
1436
+ {
1437
+ if ($chatbotHelper->startsWith($textToMatch, $match))
1438
+ $matched = true;
1439
+ }
1440
+ else if ($matchMode == "2") // Ends With
1441
+ {
1442
+ if ($chatbotHelper->endsWith($textToMatch, $match))
1443
+ $matched = true;
1444
+ }
1445
+ else if ($matchMode == "3") // Contains
1446
+ {
1447
+ if (strpos($textToMatch, $match) !== false)
1448
+ $matched = true;
1449
+ }
1450
+ else if ($matchMode == "4") // Match Regular Expression
1451
+ {
1452
+ // if ($match[0] != $commandPrefix)
1453
+ // $match = $commandPrefix . $match;
1454
+ // if ((substr($match, -1) != $commandPrefix) && ($match[strlen($match) - 2] != $commandPrefix))
1455
+ // $match .= $commandPrefix;
1456
+ if (preg_match($match, $textToMatch))
1457
+ $matched = true;
1458
+ }
1459
+ else if ($matchMode == "5") // Equals to
1460
+ {
1461
+ if ($textToMatch == $match)
1462
+ $matched = true;
1463
+ }
1464
+ else if (($matchMode == "6") && (isset($this->_witAi))) // wit.ai and witAi is set
1465
+ {
1466
+ $witAiConfidence = Mage::getStoreConfig('chatbot_enable/witai_config/witai_confidence');
1467
+ if (!is_numeric($witAiConfidence) || (int)$witAiConfidence > 100)
1468
+ $witAiConfidence = $defaultConfidence; // default acceptable confidence percentage
1469
+
1470
+ if (!$hasWitaiReplies) // avoid multiple posts to witai with the same $text
1471
+ {
1472
+ $witResponse = $this->_witAi->getTextResponse($text);
1473
+ $hasWitaiReplies = true;
1474
+ }
1475
+
1476
+ if (!empty($witResponse))
1477
+ {
1478
+ if (property_exists($witResponse->entities, $match))
1479
  {
1480
+ foreach ($witResponse->entities->{$match} as $m)
 
1481
  {
1482
+ if (((float)$m->confidence * 100) < (float)$witAiConfidence)
1483
+ continue;
1484
+
1485
+ $matched = true;
 
1486
  break;
1487
  }
 
 
 
 
 
 
1488
  }
 
1489
  }
1490
  }
1491
+
1492
+ if ($matched)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1493
  {
1494
+ $message = $reply["reply_phrase"];
1495
+ if ($username)
1496
+ $message = str_replace("{customername}", $username, $message);
1497
+ if ($reply['reply_mode'] == "1") // Text and Command
1498
+ {
1499
+ $cmdId = $reply['command_id'];
1500
+ if (!empty($cmdId))
1501
+ $text = $chatbotHelper->validateTelegramCmd($commandPrefix . $chatdata->getCommandString($cmdId)['command']); // 'transform' original text into a known command
1502
+ if (!empty($message))
1503
+ {
1504
+ $count = strlen($message);
1505
+ if ($count > $messageLimit)
1506
+ {
1507
+ $total = ceil($count / $messageLimit);
1508
+ $start = 0;
1509
+ for ($i = 1; $i <= $total; $i++) // loop to send big messages
1510
+ {
1511
+ $cut = ($count / $total) * $i;
1512
+ if ($cut >= $count) // if cut is equal or bigger to message itself
1513
+ $end = $count;
1514
+ else
1515
+ $end = strpos($message, ' ', $cut);
1516
+ $tempMessage = substr($message, $start, $end);
1517
+ $telegram->postMessage($chatId, $tempMessage);
1518
+ $start = $end;
1519
+ }
1520
+ }
1521
+ else
1522
+ $telegram->postMessage($chatId, $message);
1523
+ }
1524
  }
1525
+ else if ($reply['reply_mode'] == "0") // Text Only
1526
+ {
1527
+ if (!empty($message))
1528
+ {
1529
+ $count = strlen($message);
1530
+ if ($count > $messageLimit)
1531
+ {
1532
+ $total = ceil($count / $messageLimit);
1533
+ $start = 0;
1534
+ for ($i = 1; $i <= $total; $i++) // loop to send big messages
1535
+ {
1536
+ $cut = ($count / $total) * $i;
1537
+ if ($cut >= $count) // if cut is equal or bigger to message itself
1538
+ $end = $count;
1539
+ else
1540
+ $end = strpos($message, ' ', $cut);
1541
+ $tempMessage = substr($message, $start, $end);
1542
+ $telegram->postMessage($chatId, $tempMessage);
1543
+ $start = $end;
1544
+ }
1545
+ }
1546
+ else
1547
+ $telegram->postMessage($chatId, $message);
1548
+
1549
+ if ($reply["stop_processing"] == "1")
1550
+ return $chatdata->respondSuccess();
1551
+ }
1552
+ }
1553
+ else //if ($reply['reply_mode'] == "2") // No Reply
1554
+ {
1555
+ return $chatdata->respondSuccess();
1556
+ //break;
1557
+ }
1558
+ break;
1559
  }
 
 
1560
  }
 
 
1561
  }
 
 
 
 
 
 
 
 
 
1562
  }
 
 
 
1563
  }
1564
+
1565
+ $chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_startState); // back to start state
1566
+ if ($enableFinalMessage2Support == "1")
1567
  {
1568
+ if (!empty($supportGroupId))
1569
  {
1570
+ // if ($chatdata->getFacebookConvState() != $chatbotHelper->_supportState) // TODO
1571
+ // $chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_supportState);
1572
+ $telegram->forwardMessage(array('chat_id' => $supportGroupId, 'from_chat_id' => $chatId, 'message_id' => $telegram->MessageID()));
1573
+ $telegram->postMessage($chatId,
1574
+ $mageHelper->__("Sorry, I didn't understand that.") . " " .
1575
+ $mageHelper->__("Please wait while our support check your message so you can talk to a real person.")// . " " .
1576
+ //$chatbotHelper->_cancelMessage
1577
+ ); // TODO
 
 
1578
  }
1579
  else
1580
+ $telegram->postMessage($chatId, $chatbotHelper->_errorMessage);
1581
+ return $chatdata->respondSuccess();
1582
  }
1583
+ else // process cases where the customer message wasn't understandable
1584
  {
1585
+ //$witAiMatch = false;
1586
+ if (isset($this->_witAi) && !($this->_isWitAi))
 
1587
  {
1588
+ $witAiConfidence = Mage::getStoreConfig('chatbot_enable/witai_config/witai_confidence');
1589
+ if (!is_numeric($witAiConfidence) || (int)$witAiConfidence > 100)
1590
+ $witAiConfidence = $defaultConfidence; // default acceptable confidence percentage
1591
+
1592
+ $witResponse = $this->_witAi->getTextResponse($text);
1593
+ $hasIntent = false;
1594
+
1595
+ if (!empty($witResponse))
1596
  {
1597
+ if (property_exists($witResponse->entities, "telegram_intent"))
1598
+ {
1599
+ $intents = $witResponse->entities->telegram_intent;
1600
+ $hasIntent = true;
1601
+ }
1602
+ else if (property_exists($witResponse->entities, "intent"))
1603
+ {
1604
+ $intents = $witResponse->entities->intent;
1605
+ $hasIntent = true;
1606
+ }
1607
  }
 
 
 
 
 
1608
 
1609
+ if ($hasIntent)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1610
  {
1611
+ $enableConfirmMessage = Mage::getStoreConfig('chatbot_enable/witai_config/confirmation_message');
1612
+ $messages = array(
1613
+ "Okay, so you want me to list the categories for you.", //_listCategoriesCmd
1614
+ "Okay, so you want to search for a product.", //_searchCmd
1615
+ "Okay, so you want to login.", //_loginCmd
1616
+ "Okay, so you want to list orders.", //_listOrdersCmd
1617
+ "Okay, so you want to reorder.", //_reorderCmd shouldn't be used
1618
+ "Okay, so you want to add a product to the cart.", //_add2CartCmd shouldn't be used
1619
+ "Okay, so you want to checkout.", //_checkoutCmd
1620
+ "Okay, so you want to clear your cart.", //_clearCartCmd
1621
+ "Okay, so you want to track your order.", //_trackOrderCmd
1622
+ "Okay, so you want support.", //_supportCmd
1623
+ "Okay, so you want to send us an email.", //_sendEmailCmd
1624
+ "Okay, so you want to cancel.", //_cancelCmd shouldn't be used
1625
+ "Okay, so you want to help.", //_helpCmd
1626
+ "Okay, so you want to know more about us.", //_aboutCmd
1627
+ "Okay, so you want to logout.", //_logoutCmd
1628
+ "Okay, so you want to register to our store." //registerCmd
1629
+ );
1630
+
1631
+ $i = 1;
1632
+ $hasKeyword = false;
1633
+ $break = false;
1634
+
1635
+ foreach ($messages as $message)
1636
+ {
1637
+ $key = $chatdata->getCommandString($i)['command'];
1638
+ foreach ($intents as $intent)
1639
+ {
1640
+ if ($intent->value == $key && (((float)$intent->confidence * 100) >= (float)$witAiConfidence))
1641
+ {
1642
+ if (property_exists($witResponse->entities, "keyword"))
1643
+ {
1644
+ if (isset($witResponse->entities->keyword))
1645
+ {
1646
+ foreach ($witResponse->entities->keyword as $keyword)
1647
+ {
1648
+ if (((float)$keyword->confidence * 100) < (float)$witAiConfidence)
1649
+ continue;
1650
+ if ($commandPrefix . $intent->value == $chatbotHelper->_searchCmd['command'])
1651
+ {
1652
+ $chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_searchState);
1653
+ //$telegram->_text = $listMoreSearch . str_replace(" ", "_", $keyword->value) . "_1";
1654
+ $telegram->_text = $keyword->value;
1655
+ $hasKeyword = true;
1656
+ break;
1657
+ }
1658
+ else if ($commandPrefix . $intent->value == $chatbotHelper->_listCategoriesCmd['command'])
1659
+ {
1660
+ $_category = Mage::getModel('catalog/category')->loadByAttribute('name', $keyword->value);
1661
+ if ($_category) // check if variable isn't false/empty
1662
+ {
1663
+ if ($_category->getId()) // check if is a valid category
1664
+ {
1665
+ $chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_listCategoriesState);
1666
+ //$telegram->_text = $listMoreCategories . $_category->getId() . "_1";
1667
+ $telegram->_text = $keyword->value;
1668
+ $hasKeyword = true;
1669
+ }
1670
+ }
1671
+ break;
1672
+ }
1673
+ else if ($commandPrefix . $intent->value == $chatbotHelper->_trackOrderCmd['command'])
1674
+ {
1675
+ if ($chatdata->getIsLogged() == "1")
1676
+ {
1677
+ $chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_trackOrderState);
1678
+ $telegram->_text = $keyword->value;
1679
+ $hasKeyword = true;
1680
+ }
1681
+ else
1682
+ {
1683
+ $telegram->postMessage($chatId, $chatbotHelper->_loginFirstMessage);
1684
+ $break = true;
1685
+ return $chatdata->respondSuccess();
1686
+ }
1687
+ break;
1688
+ }
1689
+ else if ($commandPrefix . $intent->value == $chatbotHelper->_supportCmd['command'])
1690
+ {
1691
+ $chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_supportState);
1692
+ $telegram->_text = $keyword->value;
1693
+ $hasKeyword = true;
1694
+ break;
1695
+ }
1696
+ else if ($commandPrefix . $intent->value == $chatbotHelper->_sendEmailCmd['command'])
1697
+ {
1698
+ $chatdata->updateChatdata('telegram_conv_state', $chatbotHelper->_sendEmailState);
1699
+ $telegram->_text = $keyword->value;
1700
+ $hasKeyword = true;
1701
+ break;
1702
+ }
1703
+ }
1704
+ if ($break)
1705
+ break;
1706
+ }
1707
+ }
1708
+ if (!$hasKeyword)
1709
+ {
1710
+ $telegram->_text = $commandPrefix . $key; // replace text with command
1711
+ if ($enableConfirmMessage == "1")
1712
+ $telegram->postMessage($chatId, $mageHelper->__($message)); // TODO
1713
+ }
1714
+
1715
+ $this->_isWitAi = true;
1716
+ return $this->processText();
1717
+ break;
1718
+ }
1719
+ }
1720
+ $i++;
1721
+ }
1722
  }
 
 
 
1723
  }
1724
+ if (!$this->_isWitAi)
1725
  {
1726
+ $message = $mageHelper->__("Sorry, I didn't understand that.");
1727
+ $fallbackQty = 0;
1728
+
1729
+ $fallbackLimit = Mage::getStoreConfig('chatbot_enable/telegram_config/fallback_message_quantity');
1730
+ if (!empty($fallbackLimit))
1731
+ {
1732
+ $fallbackQty = (int)$chatdata->getTelegramFallbackQty();
1733
+ $fallbackQty++;
1734
+ if (!is_numeric($fallbackLimit))
1735
+ $fallbackLimit = 3;
1736
+ if ($fallbackQty >= (int)$fallbackLimit)
1737
+ {
1738
+ $fallbackMessage = Mage::getStoreConfig('chatbot_enable/telegram_config/fallback_message');
1739
+ if (!empty($fallbackMessage))
1740
+ {
1741
+ $fallbackQty = 0;
1742
+ $message = $fallbackMessage;
1743
+ }
1744
+ }
1745
+ }
1746
+
1747
+ $chatdata->updateChatdata("telegram_fallback_qty", (string)$fallbackQty);
1748
+ $telegram->postMessage($chatId, $message); // TODO
1749
 
1750
  $cmdListingOnError = Mage::getStoreConfig('chatbot_enable/telegram_config/enable_error_command_list');
1751
  if ($cmdListingOnError == "1")
1752
  {
1753
  $message = $mageHelper->__("Please try one of the following commands.");
1754
  $message .= $chatdata->listTelegramCommandsMessage();
1755
+ $telegram->postMessage($chatId, $message); // TODO
1756
  }
 
1757
  }
1758
  }
1759
  }
1760
+ $chatdata->respondSuccess();
 
1761
  }
1762
  }
1763
 
 
1764
  ?>
app/code/community/Werules/Chatbot/Model/Api/witAI/witAI.php CHANGED
@@ -1,29 +1,51 @@
1
  <?php
2
- class witAI {
3
-
4
- private $_apiKey = "";
 
 
5
 
6
  /// Class constructor
7
- public function __construct($apiKey) {
8
- $this->_apiKey = $apiKey;
9
  }
10
 
11
- // get witAI response
12
- function getWitAIResponse($query)
13
  {
14
  $options = array(
15
  'http' => array(
16
  'method' => 'GET',
17
- 'header' => "Authorization: Bearer " . $this->_apiKey . "\r\n" .
18
- "Accept: appliation/vnd.wit.20141022+json\r\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  )
20
  );
 
 
 
 
 
21
  $context = stream_context_create($options);
22
- $url = 'https://api.wit.ai/message?q=' . urlencode($query);
23
  $result = file_get_contents($url, false, $context);
24
  $result = json_decode($result);
25
 
26
- return $result;
 
 
 
27
  }
28
  }
29
  ?>
1
  <?php
2
+ class witAI
3
+ {
4
+ protected $_token;
5
+ protected $_version = '20170415';
6
+ //protected $_data;
7
 
8
  /// Class constructor
9
+ public function __construct($token) {
10
+ $this->_token = $token;
11
  }
12
 
13
+ function getTextResponse($query)
 
14
  {
15
  $options = array(
16
  'http' => array(
17
  'method' => 'GET',
18
+ 'header' => "Authorization: Bearer " . $this->_token . "\r\n"
19
+ )
20
+ );
21
+ $content = "&q=" . urlencode($query);
22
+ return $this->getWitAIResponse("message", $content, $options);
23
+ }
24
+
25
+ function getAudioResponse($audioFile)
26
+ {
27
+ $options = array(
28
+ 'http' => array(
29
+ 'method' => 'POST',
30
+ 'header' => "Authorization: Bearer " . $this->_token . "\n" .
31
+ "Content-Type: audio/mpeg3" . "\r\n",
32
+ 'content' => file_get_contents($audioFile)
33
  )
34
  );
35
+ return $this->getWitAIResponse("speech", "", $options);
36
+ }
37
+
38
+ function getWitAIResponse($endPoint, $content, $options)
39
+ {
40
  $context = stream_context_create($options);
41
+ $url = 'https://api.wit.ai/' . $endPoint . '?v=' . $this->_version . $content;
42
  $result = file_get_contents($url, false, $context);
43
  $result = json_decode($result);
44
 
45
+ if ($result)
46
+ return $result;
47
+
48
+ return null;
49
  }
50
  }
51
  ?>
app/code/community/Werules/Chatbot/Model/Chatdata.php CHANGED
@@ -1,123 +1,44 @@
1
  <?php
2
- include("Api/Telegram/Handler.php");
3
- include("Api/Facebook/Handler.php");
4
- //include("Api/Whatsapp/Handler.php");
5
- //include("Api/WeChat/Handler.php");
6
- include("Api/witAI/witAI.php");
 
7
 
8
  class Werules_Chatbot_Model_Chatdata extends Mage_Core_Model_Abstract
9
  {
10
- // APIs
11
- protected $_apiType = "";
12
- protected $_tgBot = "telegram";
13
- protected $_fbBot = "facebook";
14
- protected $_wappBot = "whatsapp";
15
- protected $_wechatBot = "wechat";
16
-
17
- // CONVERSATION STATES
18
- protected $_startState = 0;
19
- protected $_listCategoriesState = 1;
20
- protected $_listProductsState = 2;
21
- protected $_searchState = 3;
22
- protected $_loginState = 4;
23
- protected $_listOrdersState = 5;
24
- protected $_reorderState = 6;
25
- protected $_add2CartState = 7;
26
- protected $_checkoutState = 9;
27
- protected $_trackOrderState = 10;
28
- protected $_supportState = 11;
29
- protected $_sendEmailState = 12;
30
- protected $_clearCartState = 13;
31
-
32
- // ADMIN STATES
33
- protected $_replyToSupportMessageState = 14;
34
-
35
- // COMMANDS
36
- protected $_cmdList =
37
- "
38
- start,
39
- list_categories,
40
- search,
41
- login,
42
- list_orders,
43
- reorder,
44
- add2cart,
45
- checkout,
46
- clear_cart,
47
- track_order,
48
- support,
49
- send_email,
50
- cancel,
51
- help,
52
- about,
53
- logout,
54
- register
55
- ";
56
- protected $_startCmd = array();
57
- protected $_listCategoriesCmd = array();
58
- protected $_searchCmd = array();
59
- protected $_loginCmd = array();
60
- protected $_listOrdersCmd = array();
61
- protected $_reorderCmd = array();
62
- protected $_add2CartCmd = array();
63
- protected $_checkoutCmd = array();
64
- protected $_clearCartCmd = array();
65
- protected $_trackOrderCmd = array();
66
- protected $_supportCmd = array();
67
- protected $_sendEmailCmd = array();
68
- protected $_cancelCmd = array();
69
- protected $_helpCmd = array();
70
- protected $_aboutCmd = array();
71
- protected $_logoutCmd = array();
72
- protected $_registerCmd = array();
73
-
74
- // admin cmds
75
- // protected $adminCmdList =
76
- // "
77
- // messagetoall,
78
- // endsupport,
79
- // blocksupport
80
- // ";
81
- protected $_admSendMessage2AllCmd = "messagetoall";
82
- protected $_admEndSupportCmd = "endsupport";
83
- protected $_admBlockSupportCmd = "blocksupport";
84
- protected $_admEnableSupportCmd = "enablesupport";
85
-
86
- // REGEX
87
- protected $_unallowedCharacters = "/[^A-Za-z0-9 _]/";
88
-
89
- // DEFAULT MESSAGES
90
- protected $_errorMessage = "";
91
- protected $_cancelMessage = "";
92
- protected $_canceledMessage = "";
93
- protected $_loginFirstMessage = "";
94
- protected $_positiveMessages = array();
95
-
96
- // URLS
97
- public $_tgUrl = "https://t.me/";
98
- public $_fbUrl = "https://m.me/";
99
- // protected $_wappUrl = "";
100
- // protected $_wechatUrl = "";
101
 
102
  public function _construct()
103
  {
104
  //parent::_construct();
105
  $this->_init('chatbot/chatdata'); // this is location of the resource file.
 
106
  }
107
 
108
  // GENERAL FUNCTIONS
109
  public function requestHandler($action, $webhook) // handle request
110
  {
111
- $apiKey = $this->getApikey($action);
112
  // handle webhook configuration
113
- if ($webhook && $apiKey && $action == $this->_tgBot) // set telegram webhook
 
114
  {
115
  $mageHelper = Mage::helper('core');
116
- $telegram = new Telegram($apiKey);
 
 
117
  $customKey = Mage::getStoreConfig('chatbot_enable/general_config/your_custom_key');
118
  //$webhookUrl = str_replace("http://", "https://", Mage::getUrl('*/*/*', array('_use_rewrite' => true, '_forced_secure' => true)));
119
  // replace http by https, and remove all url parameters with strok
120
- $webhookUrl = str_replace("http://", "https://", strtok(Mage::getUrl('chatbot/chatdata/' . $this->_tgBot, array('_forced_secure' => true)), '?') . "key" . DS . $customKey . DS);
121
  try {
122
  $telegram->setWebhook($webhookUrl);
123
  }
@@ -135,59 +56,59 @@ class Werules_Chatbot_Model_Chatdata extends Mage_Core_Model_Abstract
135
  ;
136
  return $message;
137
  }
138
- else if ($webhook && $apiKey && $action == $this->_fbBot) // set facebook webhook
139
  {
140
  $mageHelper = Mage::helper('core');
141
  $customKey = Mage::getStoreConfig('chatbot_enable/general_config/your_custom_key');
142
  // replace http by https, and remove all url parameters with strok
143
- $webhookUrl = str_replace("http://", "https://", strtok(Mage::getUrl('chatbot/chatdata/' . $this->_fbBot, array('_forced_secure' => true)), '?') . "key" . DS . $customKey . DS);
144
 
145
  $message = $mageHelper->__("To configure Facebook webhook access") .
146
  " https://developers.facebook.com/apps/(FACEBOOK_APP_ID)/webhooks/ " .
 
147
  $mageHelper->__("and set the webhook URL as") . " " . $webhookUrl
148
  ;
149
  return $message;
150
  } // start to handle conversation
151
- else if ($action == $this->_tgBot && $apiKey) // telegram api
152
  {
153
  // all logic goes here
154
- return Mage::getModel('chatbot/api_telegram_handler')->telegramHandler($apiKey);
 
155
  }
156
- else if ($action == $this->_fbBot && $apiKey) // facebook api
157
  {
158
  // all logic goes here
159
- return Mage::getModel('chatbot/api_facebook_handler')->facebookHandler($apiKey);
 
160
  }
161
  else
162
- return "Nothing to see here"; // TODO
163
  }
164
 
165
- protected function getApikey($apiType) // check if bot integration is enabled
166
  {
167
- if ($apiType == $this->_tgBot) // telegram api
168
- {
169
- //$enabled = Mage::getStoreConfig('chatbot_enable/telegram_config/enable_bot');
170
- $apikey = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_api_key');
171
- //if ($enabled == 1 && $apikey) // is enabled and has API
172
- if ($apikey) // has API
173
- return $apikey;
174
- }
175
- else if ($apiType == $this->_fbBot)
176
- {
177
- //$enabled = Mage::getStoreConfig('chatbot_enable/facebook_config/enable_bot');
178
- $apikey = Mage::getStoreConfig('chatbot_enable/facebook_config/facebook_api_key');
179
- //if ($enabled == 1 && $apikey) // is enabled and has API
180
- if ($apikey) // has API
181
- return $apikey;
182
- }
183
- return null;
184
  }
185
-
186
  protected function sendEmail($text, $username)
187
  {
188
  $storeName = Mage::app()->getStore()->getName();
189
  $storeEmail = Mage::getStoreConfig('trans_email/ident_general/email');// TODO
 
190
  $mageHelper = Mage::helper('core');
 
191
 
192
  $url = $mageHelper->__("Not informed");
193
  $customerEmail = $mageHelper->__("Not informed");
@@ -198,9 +119,9 @@ class Werules_Chatbot_Model_Chatdata extends Mage_Core_Model_Abstract
198
 
199
  $mail = new Zend_Mail('UTF-8');
200
 
201
- if ($this->_apiType == $this->_tgBot)
202
  {
203
- $url = $this->_tgUrl . $this->getTelegramChatId();
204
  if ($this->getCustomerId())
205
  {
206
  $customer = Mage::getModel('customer/customer')->load((int)$this->getCustomerId());
@@ -212,7 +133,7 @@ class Werules_Chatbot_Model_Chatdata extends Mage_Core_Model_Abstract
212
  }
213
  }
214
  }
215
- else if ($this->_apiType == $this->_fbBot)
216
  {
217
  // code here etc
218
  }
@@ -308,20 +229,21 @@ class Werules_Chatbot_Model_Chatdata extends Mage_Core_Model_Abstract
308
 
309
  protected function getCommandString($cmdId)
310
  {
 
311
  $rep = "";
312
  $confPath = "";
313
- if ($this->_apiType == $this->_tgBot)
314
  {
315
  $rep = "_";
316
  $confPath = 'chatbot_enable/telegram_config/';
317
  }
318
- else if ($this->_apiType == $this->_fbBot)
319
  {
320
  $rep = " ";
321
  $confPath = 'chatbot_enable/facebook_config/';
322
  }
323
 
324
- $defaultCmds = explode(',', $this->_cmdList);
325
  if (is_array($defaultCmds)) // should never fail
326
  {
327
  $cmdCode = "";
@@ -358,7 +280,7 @@ class Werules_Chatbot_Model_Chatdata extends Mage_Core_Model_Abstract
358
  return array('command' => null, 'alias' => null);
359
 
360
  $cmdCode = preg_replace( // remove all non-alphanumerics
361
- $this->_unallowedCharacters,
362
  '',
363
  str_replace( // replace whitespace for underscore
364
  ' ',
@@ -373,55 +295,6 @@ class Werules_Chatbot_Model_Chatdata extends Mage_Core_Model_Abstract
373
  return array('command' => null, 'alias' => null);
374
  }
375
 
376
- protected function getCommandValue($text, $cmd)
377
- {
378
- if (strlen($text) > strlen($cmd))
379
- return substr($text, strlen($cmd), strlen($text));
380
- return null;
381
- }
382
-
383
- protected function checkCommand($text, $cmd)
384
- {
385
- if ($cmd['command'])
386
- {
387
- $t = strtolower($text);
388
- if ($t == $cmd['command'])
389
- return true;
390
- else if ($cmd['alias'])
391
- {
392
- //$alias = explode(",", $cmd['alias']);
393
- $alias = $cmd['alias'];
394
- if (is_array($alias))
395
- {
396
- foreach ($alias as $al)
397
- {
398
- if (!empty($al))
399
- if (strpos($t, $al) !== false)
400
- return true;
401
- }
402
- }
403
- }
404
- }
405
-
406
- return false;
407
- }
408
-
409
- protected function startsWith($haystack, $needle)
410
- {
411
- if ($needle)
412
- return substr($haystack, 0, strlen($needle)) == $needle;
413
- return false;
414
- }
415
-
416
- protected function endsWith($haystack, $needle)
417
- {
418
- $length = strlen($needle);
419
- if ($length == 0)
420
- return true;
421
-
422
- return (substr($haystack, -$length) === $needle);
423
- }
424
-
425
  protected function clearCart()
426
  {
427
  try
@@ -462,6 +335,9 @@ class Werules_Chatbot_Model_Chatdata extends Mage_Core_Model_Abstract
462
  $dataType => $state,
463
  "updated_at" => date('Y-m-d H:i:s')
464
  ); // data to be insert on database
 
 
 
465
  $this->addData($data);
466
  $this->save();
467
  }
@@ -473,148 +349,92 @@ class Werules_Chatbot_Model_Chatdata extends Mage_Core_Model_Abstract
473
  return true;
474
  }
475
 
476
- protected function excerpt($text, $size)
 
477
  {
478
- if (strlen($text) > $size)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
479
  {
480
- $text = substr($text, 0, $size);
481
- $text = substr($text, 0, strrpos($text, " "));
482
- $etc = " ...";
483
- $text = $text . $etc;
484
- }
485
- return $text;
486
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
487
 
488
- protected function getOrdersIdsFromCustomer()
489
- {
490
- $ids = array();
491
- $orders = Mage::getResourceModel('sales/order_collection')
492
- ->addFieldToSelect('*')
493
- ->addFieldToFilter('customer_id', $this->getCustomerId()) // not a problem if customer dosen't exist
494
- ->setOrder('created_at', 'desc');
495
- foreach ($orders as $_order)
496
- {
497
- array_push($ids, $_order->getId());
498
  }
499
- if ($ids)
500
- return $ids;
501
- return false;
502
- }
503
-
504
- protected function getProductIdsBySearch($searchString)
505
- {
506
- // Code to Search Product by $searchstring and get Product IDs
507
- $productCollection = Mage::getResourceModel('catalog/product_collection')
508
- ->addAttributeToSelect('*')
509
- ->addAttributeToFilter('visibility', 4)
510
- ->addAttributeToFilter('type_id', 'simple')
511
- ->addAttributeToFilter(
512
- array(
513
- array('attribute' => 'sku', 'like' => '%' . $searchString .'%'),
514
- array('attribute' => 'name', 'like' => '%' . $searchString .'%')
515
- )
516
- );
517
- //->getAllIds();
518
- Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($productCollection);
519
- $productIDs = $productCollection->getAllIds();
520
-
521
- if (!empty($productIDs))
522
- return $productIDs;
523
 
524
  return false;
525
  }
526
 
527
- protected function loadImageContent($productID)
528
- {
529
- $imagepath = Mage::getModel('catalog/product')->load($productID)->getSmallImage();
530
- if ($imagepath && $imagepath != "no_selection")
531
- {
532
- $absolutePath =
533
- Mage::getBaseDir('media') .
534
- DS . "catalog" . DS . "product" .
535
- $imagepath;
536
-
537
- return curl_file_create($absolutePath, 'image/jpg');
538
- }
539
- return null;
540
- }
541
-
542
- // TELEGRAM FUNCTIONS
543
- protected function validateTelegramCmd($cmd)
544
- {
545
- if ($cmd == "/")
546
- return null;
547
- return $cmd;
548
- }
549
-
550
  protected function listTelegramCommandsMessage()
551
  {
 
552
  $mageHelper = Mage::helper('core');
553
 
554
  $message = "\n\n" . $mageHelper->__("Command list") . ":\n";
555
- if ($this->_listCategoriesCmd['command']) $message .= $this->_listCategoriesCmd['command'] . " - " . $mageHelper->__("List store categories.") . "\n";
556
- if ($this->_searchCmd['command']) $message .= $this->_searchCmd['command'] . " - " . $mageHelper->__("Search for products.") . "\n";
557
- if ($this->_loginCmd['command']) $message .= $this->_loginCmd['command'] . " - " . $mageHelper->__("Login into your account.") . "\n";
558
- if ($this->_logoutCmd['command']) $message .= $this->_logoutCmd['command'] . " - " . $mageHelper->__("Logout from your account.") . "\n";
559
- if ($this->_registerCmd['command']) $message .= $this->_registerCmd['command'] . " - " . $mageHelper->__("Create a new account.") . "\n";
560
- if ($this->_listOrdersCmd['command']) $message .= $this->_listOrdersCmd['command'] . " - " . $mageHelper->__("List your personal orders.") . "\n";
561
- //$message .= $chatdata->_reorderCmd['command'] . " - " . $magehelper->__("Reorder a order.") . "\n";
562
- //$message .= $chatdata->_add2CartCmd['command'] . " - " . $magehelper->__("Add product to cart.") . "\n";
563
- if ($this->_checkoutCmd['command']) $message .= $this->_checkoutCmd['command'] . " - " . $mageHelper->__("Checkout your order.") . "\n";
564
- if ($this->_clearCartCmd['command']) $message .= $this->_clearCartCmd['command'] . " - " . $mageHelper->__("Clear your cart.") . "\n";
565
- if ($this->_trackOrderCmd['command']) $message .= $this->_trackOrderCmd['command'] . " - " . $mageHelper->__("Track your order status.") . "\n";
566
- if ($this->_supportCmd['command']) $message .= $this->_supportCmd['command'] . " - " . $mageHelper->__("Send message to support.") . "\n";
567
- if ($this->_sendEmailCmd['command']) $message .= $this->_sendEmailCmd['command'] . " - " . $mageHelper->__("Send email.") . "\n";
568
- //$message .= $chatdata->_cancelCmd['command'] . " - " . $magehelper->__("Cancel.");
569
- if ($this->_helpCmd['command']) $message .= $this->_helpCmd['command'] . " - " . $mageHelper->__("Get help.") . "\n";
570
- if ($this->_aboutCmd['command']) $message .= $this->_aboutCmd['command'] . " - " . $mageHelper->__("About.") . "\n";
571
 
572
  return $message;
573
  }
574
 
575
- protected function prepareTelegramOrderMessages($orderID) // TODO add link to product name
576
- {
577
- $order = Mage::getModel('sales/order')->load($orderID);
578
- if ($order->getId())
579
- {
580
- $message = Mage::helper('core')->__("Order") . " # " . $order->getIncrementId() . "\n\n";
581
- $items = $order->getAllVisibleItems();
582
- foreach($items as $item)
583
- {
584
- $message .= (int)$item->getQtyOrdered() . "x " .
585
- $item->getName() . "\n" .
586
- Mage::helper('core')->__("Price") . ": " . Mage::helper('core')->currency($item->getPrice(), true, false) . "\n\n";
587
- }
588
- $message .= Mage::helper('core')->__("Total") . ": " . Mage::helper('core')->currency($order->getGrandTotal(), true, false) . "\n" .
589
- Mage::helper('core')->__("Zipcode") . ": " . $order->getShippingAddress()->getPostcode();
590
- if ($this->_reorderCmd['command'])
591
- $message .= "\n\n" . Mage::helper('core')->__("Reorder") . ": " . $this->_reorderCmd['command'] . $orderID;
592
- return $message;
593
- }
594
- return null;
595
- }
596
-
597
- protected function prepareTelegramProdMessages($productID) // TODO add link to product name
598
- {
599
- $product = Mage::getModel('catalog/product')->load($productID);
600
- if ($product->getId())
601
- {
602
- if ($product->getStockItem()->getIsInStock() > 0)
603
- {
604
- $mageHelper = Mage::helper('core');
605
- $message = $product->getName() . "\n" .
606
- $mageHelper->__("Price") . ": " . Mage::helper('core')->currency($product->getPrice(), true, false) . "\n" .
607
- $this->excerpt($product->getShortDescription(), 60) . "\n" .
608
- $mageHelper->__("Add to cart") . ": " . $this->_add2CartCmd['command'] . $product->getId();
609
- return $message;
610
- }
611
- }
612
- return null;
613
- }
614
-
615
  // FACEBOOK FUNCTIONS
616
  protected function listFacebookCommandsMessage()
617
  {
 
618
  $mageHelper = Mage::helper('core');
619
 
620
  $message = "\n\n" . $mageHelper->__("Command list") . ":\n";
@@ -622,125 +442,77 @@ class Werules_Chatbot_Model_Chatdata extends Mage_Core_Model_Abstract
622
  $content = array();
623
  // some commands are commented because of the 10 limit from Facebook
624
  // just getting the command string, not checking the command
625
- if ($this->_listCategoriesCmd['command']) // 1
626
  {
627
- array_push($replies, array('content_type' => 'text', 'title' => $this->_listCategoriesCmd['command'], 'payload' => str_replace(' ', '_', $this->_listCategoriesCmd['command'])));
628
- $message .= '"' . $this->_listCategoriesCmd['command'] . '"' . " - " . $mageHelper->__("List store categories.") . "\n";
629
  }
630
- if ($this->_searchCmd['command']) // 2
631
  {
632
- array_push($replies, array('content_type' => 'text', 'title' => $this->_searchCmd['command'], 'payload' => str_replace(' ', '_', $this->_searchCmd['command'])));
633
- $message .= '"' . $this->_searchCmd['command'] . '"' . " - " . $mageHelper->__("Search for products.") . "\n";
634
  }
635
- if ($this->_loginCmd['command']) // 3
636
  {
637
- array_push($replies, array('content_type' => 'text', 'title' => $this->_loginCmd['command'], 'payload' => str_replace(' ', '_', $this->_loginCmd['command'])));
638
- $message .= '"' . $this->_loginCmd['command'] . '"' . " - " . $mageHelper->__("Login into your account.") . "\n";
639
  }
640
- if ($this->_logoutCmd['command']) // 4
641
  {
642
- //array_push($replies, array('content_type' => 'text', 'title' => $chatdata->_logoutCmd['command'], 'payload' => str_replace(' ', '_', $chatdata->_loginCmd['command'])));
643
- $message .= '"' . $this->_logoutCmd['command'] . '"' . " - " . $mageHelper->__("Logout from your account.") . "\n";
644
  }
645
- if ($this->_registerCmd['command']) // 5
646
  {
647
- array_push($replies, array('content_type' => 'text', 'title' => $this->_registerCmd['command'], 'payload' => str_replace(' ', '_', $this->_registerCmd['command'])));
648
- $message .= '"' . $this->_registerCmd['command'] . '"' . " - " . $mageHelper->__("Create a new account.") . "\n";
649
  }
650
- if ($this->_listOrdersCmd['command']) // 6
651
  {
652
- array_push($replies, array('content_type' => 'text', 'title' => $this->_listOrdersCmd['command'], 'payload' => str_replace(' ', '_', $this->_listOrdersCmd['command'])));
653
- $message .= '"' . $this->_listOrdersCmd['command'] . '"' . " - " . $mageHelper->__("List your personal orders.") . "\n";
654
  }
655
- //$message .= '"' . $chatdata->_reorderCmd['command'] . '"' . " - " . $magehelper->__("Reorder a order.") . "\n";
656
- //$message .= '"' . $chatdata->_add2CartCmd['command'] . '"' . " - " . $magehelper->__("Add product to cart.") . "\n";
657
- if ($this->_checkoutCmd['command']) // 7
658
  {
659
- //array_push($replies, array('content_type' => 'text', 'title' => $chatdata->_checkoutCmd['command'], 'payload' => str_replace(' ', '_', $chatdata->_checkoutCmd['command'])));
660
- $message .= '"' . $this->_checkoutCmd['command'] . '"' . " - " . $mageHelper->__("Checkout your order.") . "\n";
661
  }
662
- if ($this->_clearCartCmd['command']) // 8
663
  {
664
- array_push($replies, array('content_type' => 'text', 'title' => $this->_clearCartCmd['command'], 'payload' => str_replace(' ', '_', $this->_clearCartCmd['command'])));
665
- $message .= '"' . $this->_clearCartCmd['command'] . '"' . " - " . $mageHelper->__("Clear your cart.") . "\n";
666
  }
667
- if ($this->_trackOrderCmd['command']) // 9
668
  {
669
- array_push($replies, array('content_type' => 'text', 'title' => $this->_trackOrderCmd['command'], 'payload' => str_replace(' ', '_', $this->_trackOrderCmd['command'])));
670
- $message .= '"' . $this->_trackOrderCmd['command'] . '"' . " - " . $mageHelper->__("Track your order status.") . "\n";
671
  }
672
- if ($this->_supportCmd['command']) // 10
673
  {
674
- array_push($replies, array('content_type' => 'text', 'title' => $this->_supportCmd['command'], 'payload' => str_replace(' ', '_', $this->_supportCmd['command'])));
675
- $message .= '"' . $this->_supportCmd['command'] . '"' . " - " . $mageHelper->__("Send message to support.") . "\n";
676
  }
677
- if ($this->_sendEmailCmd['command']) // 11
678
  {
679
- array_push($replies, array('content_type' => 'text', 'title' => $this->_sendEmailCmd['command'], 'payload' => str_replace(' ', '_', $this->_sendEmailCmd['command'])));
680
- $message .= '"' . $this->_sendEmailCmd['command'] . '"' . " - " . $mageHelper->__("Send email.") . "\n";
681
  }
682
- //$message .= '"' . $chatdata->_cancelCmd['command'] . '"' . " - " . $magehelper->__("Cancel.");
683
- if ($this->_aboutCmd['command']) // 12
684
  {
685
- array_push($replies, array('content_type' => 'text', 'title' => $this->_aboutCmd['command'], 'payload' => str_replace(' ', '_', $this->_aboutCmd['command'])));
686
- $message .= '"' . $this->_aboutCmd['command'] . '"' . " - " . $mageHelper->__("About.") . "\n";
687
  }
688
- if ($this->_helpCmd['command']) // 13
689
  {
690
- //array_push($replies, array('content_type' => 'text', 'title' => $this->_helpCmd['command'], 'payload' => str_replace(' ', '_', $this->_helpCmd['command'])));
691
- $message .= '"' . $this->_helpCmd['command'] . '"' . " - " . $mageHelper->__("Get help.") . "\n";
692
  }
693
 
694
  array_push($content, $message); // $content[0] -> $message
695
  array_push($content, $replies); // $content[1] -> $replies
696
  return $content;
697
  }
698
-
699
- protected function prepareFacebookProdMessages($productID) // TODO add link to product name
700
- {
701
- $product = Mage::getModel('catalog/product')->load($productID);
702
- if ($product->getId())
703
- {
704
- if ($product->getStockItem()->getIsInStock() > 0)
705
- {
706
- $message = $product->getName() . "\n" .
707
- $this->excerpt($product->getShortDescription(), 60);
708
- return $message;
709
- }
710
- }
711
- return null;
712
- }
713
-
714
- protected function prepareFacebookOrderMessages($orderID) // TODO add link to product name
715
- {
716
- $order = Mage::getModel('sales/order')->load($orderID);
717
- if ($order->getId())
718
- {
719
- $message = Mage::helper('core')->__("Order") . " # " . $order->getIncrementId() . "\n\n";
720
- $items = $order->getAllVisibleItems();
721
- foreach($items as $item)
722
- {
723
- $message .= (int)$item->getQtyOrdered() . "x " .
724
- $item->getName() . "\n" .
725
- Mage::helper('core')->__("Price") . ": " . Mage::helper('core')->currency($item->getPrice(), true, false) . "\n\n";
726
- }
727
- $message .= Mage::helper('core')->__("Total") . ": " . Mage::helper('core')->currency($order->getGrandTotal(), true, false) . "\n" .
728
- Mage::helper('core')->__("Zipcode") . ": " . $order->getShippingAddress()->getPostcode();
729
-
730
- return $message;
731
- }
732
- return null;
733
- }
734
-
735
- // // WHATSAPP FUNCTIONS
736
- // public function whatsappHandler($apiKey)
737
- // {
738
- //
739
- // }
740
-
741
- // WECHAT FUNCTIONS (maybe)
742
- // public function wechatHandler($apiKey)
743
- // {
744
- //
745
- // }
746
  }
1
  <?php
2
+ // this is the main module, which contains all the data from the customer and make calls to the APIs handlers
3
+ // require_once("Api/Telegram/Handler.php");
4
+ // require_once("Api/Facebook/Handler.php");
5
+ // require_once("Api/Whatsapp/Handler.php");
6
+ // require_once("Api/WeChat/Handler.php");
7
+ require_once("Api/witAI/witAI.php");
8
 
9
  class Werules_Chatbot_Model_Chatdata extends Mage_Core_Model_Abstract
10
  {
11
+ //APIs
12
+ protected $_apiType;
13
+ protected $_apiKey;
14
+ protected $_chatbotHelper;
15
+
16
+ // WITAI
17
+ protected $_isWitAi = false;
18
+ protected $_witAi;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  public function _construct()
21
  {
22
  //parent::_construct();
23
  $this->_init('chatbot/chatdata'); // this is location of the resource file.
24
+ $this->_chatbotHelper = Mage::helper('werules_chatbot');
25
  }
26
 
27
  // GENERAL FUNCTIONS
28
  public function requestHandler($action, $webhook) // handle request
29
  {
 
30
  // handle webhook configuration
31
+ $chatbotHelper = $this->_chatbotHelper;
32
+ if (!empty($webhook) && $action == $chatbotHelper->_tgBot) // set telegram webhook
33
  {
34
  $mageHelper = Mage::helper('core');
35
+ $apiKey = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_api_key');
36
+ //$telegram = new Telegram($apiKey);
37
+ $telegram = Mage::getModel('chatbot/api_telegram_handler')->_telegram;
38
  $customKey = Mage::getStoreConfig('chatbot_enable/general_config/your_custom_key');
39
  //$webhookUrl = str_replace("http://", "https://", Mage::getUrl('*/*/*', array('_use_rewrite' => true, '_forced_secure' => true)));
40
  // replace http by https, and remove all url parameters with strok
41
+ $webhookUrl = str_replace("http://", "https://", strtok(Mage::getUrl('chatbot/chatdata/' . $chatbotHelper->_tgBot, array('_forced_secure' => true)), '?') . "key" . DS . $customKey . DS);
42
  try {
43
  $telegram->setWebhook($webhookUrl);
44
  }
56
  ;
57
  return $message;
58
  }
59
+ else if (!empty($webhook) && $action == $chatbotHelper->_fbBot) // set facebook webhook
60
  {
61
  $mageHelper = Mage::helper('core');
62
  $customKey = Mage::getStoreConfig('chatbot_enable/general_config/your_custom_key');
63
  // replace http by https, and remove all url parameters with strok
64
+ $webhookUrl = str_replace("http://", "https://", strtok(Mage::getUrl('chatbot/chatdata/' . $chatbotHelper->_fbBot, array('_forced_secure' => true)), '?') . "key" . DS . $customKey . DS);
65
 
66
  $message = $mageHelper->__("To configure Facebook webhook access") .
67
  " https://developers.facebook.com/apps/(FACEBOOK_APP_ID)/webhooks/ " .
68
+ $mageHelper->__("use your Custom Key (%s) as your Verify Token", $webhook) . " " .
69
  $mageHelper->__("and set the webhook URL as") . " " . $webhookUrl
70
  ;
71
  return $message;
72
  } // start to handle conversation
73
+ else if ($action == $chatbotHelper->_tgBot) // telegram api
74
  {
75
  // all logic goes here
76
+ $handler = Mage::getModel('chatbot/api_telegram_handler');
77
+ return $handler->telegramHandler();
78
  }
79
+ else if ($action == $chatbotHelper->_fbBot) // facebook api
80
  {
81
  // all logic goes here
82
+ $handler = Mage::getModel('chatbot/api_facebook_handler');
83
+ return $handler->facebookHandler();
84
  }
85
  else
86
+ return json_encode(array("status" => "error")); // TODO
87
  }
88
 
89
+ protected function respondSuccess()
90
  {
91
+ // $chatbotHelper = $this->_chatbotHelper;
92
+ // if ($this->_apiType == $chatbotHelper->_tgBot)
93
+ // {
94
+ // $this->updateChatdata("telegram_processing_request", "0");
95
+ // }
96
+ // else if ($this->_apiType == $chatbotHelper->_fbBot)
97
+ // {
98
+ // $this->updateChatdata("facebook_processing_request", "0");
99
+ // }
100
+ // // TODO add other apis
101
+
102
+ http_response_code(200);
103
+ return json_encode(array("status" => "success"));
 
 
 
 
104
  }
 
105
  protected function sendEmail($text, $username)
106
  {
107
  $storeName = Mage::app()->getStore()->getName();
108
  $storeEmail = Mage::getStoreConfig('trans_email/ident_general/email');// TODO
109
+ // helpers
110
  $mageHelper = Mage::helper('core');
111
+ $chatbotHelper = $this->_chatbotHelper;
112
 
113
  $url = $mageHelper->__("Not informed");
114
  $customerEmail = $mageHelper->__("Not informed");
119
 
120
  $mail = new Zend_Mail('UTF-8');
121
 
122
+ if ($this->_apiType == $chatbotHelper->_tgBot)
123
  {
124
+ $url = $chatbotHelper->_tgUrl . $this->getTelegramChatId();
125
  if ($this->getCustomerId())
126
  {
127
  $customer = Mage::getModel('customer/customer')->load((int)$this->getCustomerId());
133
  }
134
  }
135
  }
136
+ else if ($this->_apiType == $chatbotHelper->_fbBot)
137
  {
138
  // code here etc
139
  }
229
 
230
  protected function getCommandString($cmdId)
231
  {
232
+ $chatbotHelper = $this->_chatbotHelper;
233
  $rep = "";
234
  $confPath = "";
235
+ if ($this->_apiType == $chatbotHelper->_tgBot)
236
  {
237
  $rep = "_";
238
  $confPath = 'chatbot_enable/telegram_config/';
239
  }
240
+ else if ($this->_apiType == $chatbotHelper->_fbBot)
241
  {
242
  $rep = " ";
243
  $confPath = 'chatbot_enable/facebook_config/';
244
  }
245
 
246
+ $defaultCmds = explode(',', $chatbotHelper->_cmdList);
247
  if (is_array($defaultCmds)) // should never fail
248
  {
249
  $cmdCode = "";
280
  return array('command' => null, 'alias' => null);
281
 
282
  $cmdCode = preg_replace( // remove all non-alphanumerics
283
+ $chatbotHelper->_unallowedCharacters,
284
  '',
285
  str_replace( // replace whitespace for underscore
286
  ' ',
295
  return array('command' => null, 'alias' => null);
296
  }
297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
  protected function clearCart()
299
  {
300
  try
335
  $dataType => $state,
336
  "updated_at" => date('Y-m-d H:i:s')
337
  ); // data to be insert on database
338
+
339
+ // Mage::log("data -> " . var_export($data, true), null, 'updateChatdata.log');
340
+ // Mage::log("this -> " . var_export($this, true), null, 'updateChatdata.log');
341
  $this->addData($data);
342
  $this->save();
343
  }
349
  return true;
350
  }
351
 
352
+ // TELEGRAM FUNCTIONS
353
+ public function foreignMessageToTelegramSupport($foreignChatId, $text, $apiName, $customerName)
354
  {
355
+ //$chatdata = Mage::getModel('chatbot/chatdata');
356
+ $chatdata = $this;
357
+ $chatbotHelper = $this->_chatbotHelper;
358
+ // if ($apiName == $chatbotHelper->_fbBot && $chatId)
359
+ // {
360
+ // $chatdata->load($chatId, 'facebook_chat_id');
361
+ // if (is_null($chatdata->getFacebookChatId()))
362
+ // { // should't happen
363
+ // $chatdata->updateChatdata("facebook_chat_id", $chatId);
364
+ // }
365
+ // }
366
+
367
+ //$chatdata->_apiType = $chatbotHelper->_tgBot;
368
+ //$telegram = $this->_telegram;
369
+ $telegram = Mage::getModel('chatbot/api_telegram_handler')->_telegram; // TODO
370
+ if (isset($telegram))
371
  {
372
+ $mageHelper = Mage::helper('core');
373
+ $supportgroup = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_support_group');
374
+ if (!empty($supportgroup))
375
+ {
376
+ try{
377
+ if ($supportgroup[0] == "g") // remove the 'g' from groupd id, and add '-'
378
+ $supportgroup = "-" . ltrim($supportgroup, "g");
379
+
380
+ if (!$customerName)
381
+ $customerName = $mageHelper->__("Not informed");
382
+
383
+ $message =
384
+ "#" . $foreignChatId . "\n" .
385
+ $mageHelper->__("Message via") . " " . $apiName . ":\n" .
386
+ $mageHelper->__("From") . ": " . $customerName . "\n" .
387
+ $text
388
+ ;
389
+ $result = $telegram->postMessage($supportgroup, $message);
390
+ $mid = $result['result']['message_id'];
391
+ if (!empty($mid))
392
+ {
393
+ $chatdata->updateChatdata("last_support_message_id", $mid);
394
+ $chatdata->updateChatdata("last_support_chat", $apiName);
395
+ }
396
+ }
397
+ catch (Exception $e){
398
+ return false;
399
+ }
400
 
401
+ return true;
402
+ }
 
 
 
 
 
 
 
 
403
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
404
 
405
  return false;
406
  }
407
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
408
  protected function listTelegramCommandsMessage()
409
  {
410
+ $chatbotHelper = $this->_chatbotHelper;
411
  $mageHelper = Mage::helper('core');
412
 
413
  $message = "\n\n" . $mageHelper->__("Command list") . ":\n";
414
+ if ($chatbotHelper->_listCategoriesCmd['command']) $message .= $chatbotHelper->_listCategoriesCmd['command'] . " - " . $mageHelper->__("List store categories.") . "\n";
415
+ if ($chatbotHelper->_searchCmd['command']) $message .= $chatbotHelper->_searchCmd['command'] . " - " . $mageHelper->__("Search for products.") . "\n";
416
+ if ($chatbotHelper->_loginCmd['command']) $message .= $chatbotHelper->_loginCmd['command'] . " - " . $mageHelper->__("Login into your account.") . "\n";
417
+ if ($chatbotHelper->_logoutCmd['command']) $message .= $chatbotHelper->_logoutCmd['command'] . " - " . $mageHelper->__("Logout from your account.") . "\n";
418
+ if ($chatbotHelper->_registerCmd['command']) $message .= $chatbotHelper->_registerCmd['command'] . " - " . $mageHelper->__("Create a new account.") . "\n";
419
+ if ($chatbotHelper->_listOrdersCmd['command']) $message .= $chatbotHelper->_listOrdersCmd['command'] . " - " . $mageHelper->__("List your personal orders.") . "\n";
420
+ //$message .= $chatbotHelper->_reorderCmd['command'] . " - " . $magehelper->__("Reorder a order.") . "\n";
421
+ //$message .= $chatbotHelper->_add2CartCmd['command'] . " - " . $magehelper->__("Add product to cart.") . "\n";
422
+ if ($chatbotHelper->_checkoutCmd['command']) $message .= $chatbotHelper->_checkoutCmd['command'] . " - " . $mageHelper->__("Checkout your order.") . "\n";
423
+ if ($chatbotHelper->_clearCartCmd['command']) $message .= $chatbotHelper->_clearCartCmd['command'] . " - " . $mageHelper->__("Clear your cart.") . "\n";
424
+ if ($chatbotHelper->_trackOrderCmd['command']) $message .= $chatbotHelper->_trackOrderCmd['command'] . " - " . $mageHelper->__("Track your order status.") . "\n";
425
+ if ($chatbotHelper->_supportCmd['command']) $message .= $chatbotHelper->_supportCmd['command'] . " - " . $mageHelper->__("Send message to support.") . "\n";
426
+ if ($chatbotHelper->_sendEmailCmd['command']) $message .= $chatbotHelper->_sendEmailCmd['command'] . " - " . $mageHelper->__("Send email.") . "\n";
427
+ //$message .= $chatbotHelper->_cancelCmd['command'] . " - " . $magehelper->__("Cancel.");
428
+ if ($chatbotHelper->_helpCmd['command']) $message .= $chatbotHelper->_helpCmd['command'] . " - " . $mageHelper->__("Get help.") . "\n";
429
+ if ($chatbotHelper->_aboutCmd['command']) $message .= $chatbotHelper->_aboutCmd['command'] . " - " . $mageHelper->__("About.") . "\n";
430
 
431
  return $message;
432
  }
433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
434
  // FACEBOOK FUNCTIONS
435
  protected function listFacebookCommandsMessage()
436
  {
437
+ $chatbotHelper = $this->_chatbotHelper;
438
  $mageHelper = Mage::helper('core');
439
 
440
  $message = "\n\n" . $mageHelper->__("Command list") . ":\n";
442
  $content = array();
443
  // some commands are commented because of the 10 limit from Facebook
444
  // just getting the command string, not checking the command
445
+ if ($chatbotHelper->_listCategoriesCmd['command']) // 1
446
  {
447
+ array_push($replies, array('content_type' => 'text', 'title' => $chatbotHelper->_listCategoriesCmd['command'], 'payload' => str_replace(' ', '_', $chatbotHelper->_listCategoriesCmd['command'])));
448
+ $message .= '"' . $chatbotHelper->_listCategoriesCmd['command'] . '"' . " - " . $mageHelper->__("List store categories.") . "\n";
449
  }
450
+ if ($chatbotHelper->_searchCmd['command']) // 2
451
  {
452
+ array_push($replies, array('content_type' => 'text', 'title' => $chatbotHelper->_searchCmd['command'], 'payload' => str_replace(' ', '_', $chatbotHelper->_searchCmd['command'])));
453
+ $message .= '"' . $chatbotHelper->_searchCmd['command'] . '"' . " - " . $mageHelper->__("Search for products.") . "\n";
454
  }
455
+ if ($chatbotHelper->_loginCmd['command']) // 3
456
  {
457
+ array_push($replies, array('content_type' => 'text', 'title' => $chatbotHelper->_loginCmd['command'], 'payload' => str_replace(' ', '_', $chatbotHelper->_loginCmd['command'])));
458
+ $message .= '"' . $chatbotHelper->_loginCmd['command'] . '"' . " - " . $mageHelper->__("Login into your account.") . "\n";
459
  }
460
+ if ($chatbotHelper->_logoutCmd['command']) // 4
461
  {
462
+ //array_push($replies, array('content_type' => 'text', 'title' => $chatbotHelper->_logoutCmd['command'], 'payload' => str_replace(' ', '_', $chatbotHelper->_loginCmd['command'])));
463
+ $message .= '"' . $chatbotHelper->_logoutCmd['command'] . '"' . " - " . $mageHelper->__("Logout from your account.") . "\n";
464
  }
465
+ if ($chatbotHelper->_registerCmd['command']) // 5
466
  {
467
+ array_push($replies, array('content_type' => 'text', 'title' => $chatbotHelper->_registerCmd['command'], 'payload' => str_replace(' ', '_', $chatbotHelper->_registerCmd['command'])));
468
+ $message .= '"' . $chatbotHelper->_registerCmd['command'] . '"' . " - " . $mageHelper->__("Create a new account.") . "\n";
469
  }
470
+ if ($chatbotHelper->_listOrdersCmd['command']) // 6
471
  {
472
+ array_push($replies, array('content_type' => 'text', 'title' => $chatbotHelper->_listOrdersCmd['command'], 'payload' => str_replace(' ', '_', $chatbotHelper->_listOrdersCmd['command'])));
473
+ $message .= '"' . $chatbotHelper->_listOrdersCmd['command'] . '"' . " - " . $mageHelper->__("List your personal orders.") . "\n";
474
  }
475
+ //$message .= '"' . $chatbotHelper->_reorderCmd['command'] . '"' . " - " . $magehelper->__("Reorder a order.") . "\n";
476
+ //$message .= '"' . $chatbotHelper->_add2CartCmd['command'] . '"' . " - " . $magehelper->__("Add product to cart.") . "\n";
477
+ if ($chatbotHelper->_checkoutCmd['command']) // 7
478
  {
479
+ //array_push($replies, array('content_type' => 'text', 'title' => $chatbotHelper->_checkoutCmd['command'], 'payload' => str_replace(' ', '_', $chatbotHelper->_checkoutCmd['command'])));
480
+ $message .= '"' . $chatbotHelper->_checkoutCmd['command'] . '"' . " - " . $mageHelper->__("Checkout your order.") . "\n";
481
  }
482
+ if ($chatbotHelper->_clearCartCmd['command']) // 8
483
  {
484
+ array_push($replies, array('content_type' => 'text', 'title' => $chatbotHelper->_clearCartCmd['command'], 'payload' => str_replace(' ', '_', $chatbotHelper->_clearCartCmd['command'])));
485
+ $message .= '"' . $chatbotHelper->_clearCartCmd['command'] . '"' . " - " . $mageHelper->__("Clear your cart.") . "\n";
486
  }
487
+ if ($chatbotHelper->_trackOrderCmd['command']) // 9
488
  {
489
+ array_push($replies, array('content_type' => 'text', 'title' => $chatbotHelper->_trackOrderCmd['command'], 'payload' => str_replace(' ', '_', $chatbotHelper->_trackOrderCmd['command'])));
490
+ $message .= '"' . $chatbotHelper->_trackOrderCmd['command'] . '"' . " - " . $mageHelper->__("Track your order status.") . "\n";
491
  }
492
+ if ($chatbotHelper->_supportCmd['command']) // 10
493
  {
494
+ array_push($replies, array('content_type' => 'text', 'title' => $chatbotHelper->_supportCmd['command'], 'payload' => str_replace(' ', '_', $chatbotHelper->_supportCmd['command'])));
495
+ $message .= '"' . $chatbotHelper->_supportCmd['command'] . '"' . " - " . $mageHelper->__("Send message to support.") . "\n";
496
  }
497
+ if ($chatbotHelper->_sendEmailCmd['command']) // 11
498
  {
499
+ array_push($replies, array('content_type' => 'text', 'title' => $chatbotHelper->_sendEmailCmd['command'], 'payload' => str_replace(' ', '_', $chatbotHelper->_sendEmailCmd['command'])));
500
+ $message .= '"' . $chatbotHelper->_sendEmailCmd['command'] . '"' . " - " . $mageHelper->__("Send email.") . "\n";
501
  }
502
+ //$message .= '"' . $chatbotHelper->_cancelCmd['command'] . '"' . " - " . $magehelper->__("Cancel.");
503
+ if ($chatbotHelper->_aboutCmd['command']) // 12
504
  {
505
+ array_push($replies, array('content_type' => 'text', 'title' => $chatbotHelper->_aboutCmd['command'], 'payload' => str_replace(' ', '_', $chatbotHelper->_aboutCmd['command'])));
506
+ $message .= '"' . $chatbotHelper->_aboutCmd['command'] . '"' . " - " . $mageHelper->__("About.") . "\n";
507
  }
508
+ if ($chatbotHelper->_helpCmd['command']) // 13
509
  {
510
+ //array_push($replies, array('content_type' => 'text', 'title' => $this->_helpCmd['command'], 'payload' => str_replace(' ', '_', $chatbotHelper->_helpCmd['command'])));
511
+ $message .= '"' . $chatbotHelper->_helpCmd['command'] . '"' . " - " . $mageHelper->__("Get help.") . "\n";
512
  }
513
 
514
  array_push($content, $message); // $content[0] -> $message
515
  array_push($content, $replies); // $content[1] -> $replies
516
  return $content;
517
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
518
  }
app/code/community/Werules/Chatbot/Model/MatchMode.php ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Werules_Chatbot_Model_MatchMode
3
+ {
4
+ /**
5
+ * Provide available enable as a value/label array
6
+ *
7
+ * @return array
8
+ */
9
+ public function toOptionArray()
10
+ {
11
+ return array(
12
+ array('value'=>0, 'label'=>'Similarity'),
13
+ array('value'=>1, 'label'=>'Starts With'),
14
+ array('value'=>2, 'label'=>'Ends With'),
15
+ array('value'=>3, 'label'=>'Contains'),
16
+ array('value'=>4, 'label'=>'Match RegEx'),
17
+ array('value'=>5, 'label'=>'Equals to'),
18
+ array('value'=>6, 'label'=>'wit.ai')
19
+ );
20
+ }
21
+ }
app/code/community/Werules/Chatbot/Model/Mysql4/Chatdata.php CHANGED
@@ -2,7 +2,7 @@
2
  class Werules_Chatbot_Model_Mysql4_Chatdata extends Mage_Core_Model_Resource_Db_Abstract
3
  {
4
  public function _construct()
5
- {
6
  $this->_init('chatbot/chatdata', 'entity_id'); // here entity_id is the primary of the table of our module. And chatbot/chatdata, is the magento table name as mentioned in the config.xml file.
7
  }
8
  }
2
  class Werules_Chatbot_Model_Mysql4_Chatdata extends Mage_Core_Model_Resource_Db_Abstract
3
  {
4
  public function _construct()
5
+ {
6
  $this->_init('chatbot/chatdata', 'entity_id'); // here entity_id is the primary of the table of our module. And chatbot/chatdata, is the magento table name as mentioned in the config.xml file.
7
  }
8
  }
app/code/community/Werules/Chatbot/Model/Options.php CHANGED
@@ -15,8 +15,8 @@ class Werules_Chatbot_Model_Options
15
  array('value'=>3, 'label'=>'Login'),
16
  array('value'=>4, 'label'=>'List Orders'),
17
  array('value'=>5, 'label'=>'Reorder'),
18
- array('value'=>6, 'label'=>'Add Product To Cart'),
19
- array('value'=>7, 'label'=>'Checkout On Site'),
20
  array('value'=>8, 'label'=>'Clear Cart'),
21
  array('value'=>9, 'label'=>'Track Order Status'),
22
  array('value'=>10, 'label'=>'Talk to Support'),
15
  array('value'=>3, 'label'=>'Login'),
16
  array('value'=>4, 'label'=>'List Orders'),
17
  array('value'=>5, 'label'=>'Reorder'),
18
+ array('value'=>6, 'label'=>'Add Product to Cart'),
19
+ array('value'=>7, 'label'=>'Checkout on Website'),
20
  array('value'=>8, 'label'=>'Clear Cart'),
21
  array('value'=>9, 'label'=>'Track Order Status'),
22
  array('value'=>10, 'label'=>'Talk to Support'),
app/code/community/Werules/Chatbot/Model/ReplyMode.php CHANGED
@@ -9,12 +9,9 @@ class Werules_Chatbot_Model_ReplyMode
9
  public function toOptionArray()
10
  {
11
  return array(
12
- array('value'=>0, 'label'=>'Similarity'),
13
- array('value'=>1, 'label'=>'Starts With'),
14
- array('value'=>2, 'label'=>'Ends With'),
15
- array('value'=>3, 'label'=>'Contains'),
16
- array('value'=>4, 'label'=>'Match Regular Expression'),
17
- array('value'=>5, 'label'=>'Equals to')
18
  );
19
  }
20
  }
9
  public function toOptionArray()
10
  {
11
  return array(
12
+ array('value'=>2, 'label'=>'No Reply'),
13
+ array('value'=>0, 'label'=>'Text Only'),
14
+ array('value'=>1, 'label'=>'Text and Command')
 
 
 
15
  );
16
  }
17
  }
app/code/community/Werules/Chatbot/controllers/SettingsController.php CHANGED
@@ -1,4 +1,6 @@
1
  <?php
 
 
2
  class Werules_Chatbot_SettingsController extends Mage_Core_Controller_Front_Action {
3
  public function preDispatch() // function that makes the settings page only available when the user is logged in
4
  {
@@ -25,17 +27,24 @@ class Werules_Chatbot_SettingsController extends Mage_Core_Controller_Front_Acti
25
  $postData = $this->getRequest()->getPost(); // get all post data
26
  if ($postData)
27
  {
28
- $rand = str_shuffle("11e09rg009UUu89FSwe9yGRE4h");
29
  $clientid = Mage::getSingleton('customer/session')->getCustomer()->getId(); // get customer id
30
  $chatdata = Mage::getModel('chatbot/chatdata')->load($clientid, 'customer_id'); // load profile info from customer id
31
  try
32
  {
33
  $data = array(
34
  "enable_telegram" => ((isset($postData['enable_telegram'])) ? 1 : 0),
 
35
  "enable_facebook" => ((isset($postData['enable_facebook'])) ? 1 : 0)
36
  //"enable_whatsapp" => ((isset($postData['enable_whatsapp'])) ? 1 : 0),
37
  //"enable_wechat" => ((isset($postData['enable_wechat'])) ? 1 : 0)
38
  );
 
 
 
 
 
 
39
  if (!$chatdata->getCustomerId()) // attach class to customer id
40
  {
41
  $data["hash_key"] = substr(md5(uniqid(str_shuffle($rand), true)), 0, 150); // TODO
@@ -57,10 +66,11 @@ class Werules_Chatbot_SettingsController extends Mage_Core_Controller_Front_Acti
57
  private function requestHandler()
58
  {
59
  $hash = Mage::app()->getRequest()->getParam('hash');
60
- if ($hash)
61
  $this->loginFromChatbot($hash);
62
  }
63
 
 
64
  private function loginFromChatbot($hash)
65
  {
66
  $success = false;
@@ -78,6 +88,8 @@ class Werules_Chatbot_SettingsController extends Mage_Core_Controller_Front_Acti
78
  {
79
  try
80
  {
 
 
81
  while ($chatdata->getCustomerId()) // gather all data from all chatdata models
82
  {
83
  if ($chatdata->getTelegramChatId() && $chatdata->getFacebookChatId() && $chatdata->getWhatsappChatId() && $chatdata->getWechatChatId())
@@ -108,6 +120,9 @@ class Werules_Chatbot_SettingsController extends Mage_Core_Controller_Front_Acti
108
  }
109
  if (!isset($data["created_at"]))
110
  $data["created_at"] = $chatdata->getCreatedAt();
 
 
 
111
  $chatdata->delete();
112
  $chatdata = Mage::getModel('chatbot/chatdata')->load($customerid, 'customer_id'); // reload
113
  }
1
  <?php
2
+ // settings controller, used to save all data from customer configurations
3
+ // and also "links" a chatbot to the customer in the function loginFromChatbot
4
  class Werules_Chatbot_SettingsController extends Mage_Core_Controller_Front_Action {
5
  public function preDispatch() // function that makes the settings page only available when the user is logged in
6
  {
27
  $postData = $this->getRequest()->getPost(); // get all post data
28
  if ($postData)
29
  {
30
+ $rand = str_shuffle("11e09rg009UUu89FSwe9yGRE4h"); // TODO
31
  $clientid = Mage::getSingleton('customer/session')->getCustomer()->getId(); // get customer id
32
  $chatdata = Mage::getModel('chatbot/chatdata')->load($clientid, 'customer_id'); // load profile info from customer id
33
  try
34
  {
35
  $data = array(
36
  "enable_telegram" => ((isset($postData['enable_telegram'])) ? 1 : 0),
37
+ "enable_promotional_messages" => ((isset($postData['enable_promotional_messages'])) ? 1 : 0),
38
  "enable_facebook" => ((isset($postData['enable_facebook'])) ? 1 : 0)
39
  //"enable_whatsapp" => ((isset($postData['enable_whatsapp'])) ? 1 : 0),
40
  //"enable_wechat" => ((isset($postData['enable_wechat'])) ? 1 : 0)
41
  );
42
+ // setting data if is the first time
43
+ if (!isset($data["created_at"]))
44
+ {
45
+ $data["created_at"] = date('Y-m-d H:i:s');
46
+ }
47
+
48
  if (!$chatdata->getCustomerId()) // attach class to customer id
49
  {
50
  $data["hash_key"] = substr(md5(uniqid(str_shuffle($rand), true)), 0, 150); // TODO
66
  private function requestHandler()
67
  {
68
  $hash = Mage::app()->getRequest()->getParam('hash');
69
+ if ($hash) // if is receiving a hash as URL parameter, we need to link the customer to a chatbot
70
  $this->loginFromChatbot($hash);
71
  }
72
 
73
+ // function that links/login a customer to a chatbot
74
  private function loginFromChatbot($hash)
75
  {
76
  $success = false;
88
  {
89
  try
90
  {
91
+ // we'll get all chatdata information from the database and check if this customer is already logged in a chatbot
92
+ // then we merge all his data to a single chatdata data on the database
93
  while ($chatdata->getCustomerId()) // gather all data from all chatdata models
94
  {
95
  if ($chatdata->getTelegramChatId() && $chatdata->getFacebookChatId() && $chatdata->getWhatsappChatId() && $chatdata->getWechatChatId())
120
  }
121
  if (!isset($data["created_at"]))
122
  $data["created_at"] = $chatdata->getCreatedAt();
123
+ if (!isset($data["enable_promotional_messages"]))
124
+ $data["enable_promotional_messages"] = $chatdata->getEnablePromotionalMessages();
125
+
126
  $chatdata->delete();
127
  $chatdata = Mage::getModel('chatbot/chatdata')->load($customerid, 'customer_id'); // reload
128
  }
app/code/community/Werules/Chatbot/etc/config.xml CHANGED
@@ -2,7 +2,7 @@
2
  <config>
3
  <modules>
4
  <Werules_Chatbot>
5
- <version>0.0.9</version>
6
  </Werules_Chatbot>
7
  </modules>
8
  <frontend>
@@ -81,6 +81,13 @@
81
  </resources>
82
  </global>
83
  <adminhtml>
 
 
 
 
 
 
 
84
  <acl>
85
  <resources>
86
  <admin>
2
  <config>
3
  <modules>
4
  <Werules_Chatbot>
5
+ <version>0.0.15</version>
6
  </Werules_Chatbot>
7
  </modules>
8
  <frontend>
81
  </resources>
82
  </global>
83
  <adminhtml>
84
+ <layout>
85
+ <updates>
86
+ <chatbot_enable>
87
+ <file>werules_chatbot.xml</file>
88
+ </chatbot_enable>
89
+ </updates>
90
+ </layout>
91
  <acl>
92
  <resources>
93
  <admin>
app/code/community/Werules/Chatbot/etc/system.xml CHANGED
@@ -33,27 +33,28 @@
33
  <show_in_default>1</show_in_default>
34
  <show_in_website>1</show_in_website>
35
  <show_in_store>1</show_in_store>
 
36
  <comment>This is Your Custom Secret Key Used For The Webhook URL, to Activate/Deactivate The API Webhook For Telegram, And to Use as Your Challenge Hub For Facebook. Alphanumeric Only! Access http://(YOUR_STORE_URL)/chatbot/chatdata/(API)/webhook/(YOUR_CUSTOM_KEY) to Set The Webhook, change API to "telegram" or "facebook".</comment>
37
  </your_custom_key>
38
- <master_support_group>
39
- <label>Master Support Group</label>
40
- <frontend_type>select</frontend_type>
41
- <source_model>chatbot/chats</source_model>
42
- <sort_order>1</sort_order>
43
- <show_in_default>1</show_in_default>
44
- <show_in_website>1</show_in_website>
45
- <show_in_store>1</show_in_store>
46
- <comment>Choose to receive all support messages in one single message app. In Development.</comment>
47
- </master_support_group>
48
  <enable_support_final_message>
49
- <label>Forward Unknown Messages to Support</label>
50
  <frontend_type>select</frontend_type>
51
  <source_model>chatbot/enable</source_model>
52
  <sort_order>2</sort_order>
53
  <show_in_default>1</show_in_default>
54
  <show_in_website>1</show_in_website>
55
  <show_in_store>1</show_in_store>
56
- <comment>Automatically Enable Support if Customer Types a Message That The Bot Dosen't Understand</comment>
57
  </enable_support_final_message>
58
  <list_empty_categories>
59
  <label>List Empty Categoies</label>
@@ -65,11 +66,21 @@
65
  <show_in_store>1</show_in_store>
66
  <comment>Enable Listing of Categories With No Products or Unallowed Products (This Module Supports Only Simple Products For Now).</comment>
67
  </list_empty_categories>
 
 
 
 
 
 
 
 
 
 
68
  <enable_post_log>
69
  <label>Enable Log</label>
70
  <frontend_type>select</frontend_type>
71
  <source_model>chatbot/enable</source_model>
72
- <sort_order>4</sort_order>
73
  <show_in_default>1</show_in_default>
74
  <show_in_website>1</show_in_website>
75
  <show_in_store>1</show_in_store>
@@ -84,17 +95,17 @@
84
  <show_in_default>1</show_in_default>
85
  <show_in_website>1</show_in_website>
86
  <show_in_store>1</show_in_store>
87
- <comment>Still in Development</comment>
88
  <fields>
89
  <enable_witai>
90
- <label>Enable WitAI Integration</label>
91
  <frontend_type>select</frontend_type>
92
  <source_model>chatbot/enable</source_model>
93
  <sort_order>0</sort_order>
94
  <show_in_default>1</show_in_default>
95
  <show_in_website>1</show_in_website>
96
  <show_in_store>1</show_in_store>
97
- <comment>Soon</comment>
98
  </enable_witai>
99
  <witai_api_key>
100
  <label>witAI API Key</label>
@@ -103,8 +114,28 @@
103
  <show_in_default>1</show_in_default>
104
  <show_in_website>1</show_in_website>
105
  <show_in_store>1</show_in_store>
106
- <comment>Soon</comment>
107
  </witai_api_key>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  </fields>
109
  </witai_config>
110
  <telegram_config translate="label">
@@ -133,6 +164,9 @@
133
  <show_in_default>1</show_in_default>
134
  <show_in_website>1</show_in_website>
135
  <show_in_store>1</show_in_store>
 
 
 
136
  <comment>Message To Send When Bot Is Disabled. Leave It Empty To Send No Message. Please Check The Maximum Size For Messages On Telegram API, Otherwise Your Message Might Not Be Sent.</comment>
137
  </disabled_message>
138
  <telegram_api_key>
@@ -144,10 +178,45 @@
144
  <show_in_store>1</show_in_store>
145
  <comment>Your Telegram Bot API Key.</comment>
146
  </telegram_api_key>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  <telegram_support_group>
148
  <label>Telegram Support Group ID</label>
149
  <frontend_type>text</frontend_type>
150
- <sort_order>3</sort_order>
151
  <show_in_default>1</show_in_default>
152
  <show_in_website>1</show_in_website>
153
  <show_in_store>1</show_in_store>
@@ -156,16 +225,16 @@
156
  <telegram_welcome_msg>
157
  <label>Telegram Welcome Message</label>
158
  <frontend_type>text</frontend_type>
159
- <sort_order>4</sort_order>
160
  <show_in_default>1</show_in_default>
161
  <show_in_website>1</show_in_website>
162
  <show_in_store>1</show_in_store>
163
- <comment>First Message The Bot Will Send To Your Client. Please Check The Maximum Size For Messages On Telegram API, Otherwise Your Message Might Not Be Sent.</comment>
164
  </telegram_welcome_msg>
165
  <telegram_help_msg>
166
  <label>Telegram Help Message</label>
167
  <frontend_type>text</frontend_type>
168
- <sort_order>5</sort_order>
169
  <show_in_default>1</show_in_default>
170
  <show_in_website>1</show_in_website>
171
  <show_in_store>1</show_in_store>
@@ -174,7 +243,7 @@
174
  <telegram_about_msg>
175
  <label>Telegram About Message</label>
176
  <frontend_type>text</frontend_type>
177
- <sort_order>6</sort_order>
178
  <show_in_default>1</show_in_default>
179
  <show_in_website>1</show_in_website>
180
  <show_in_store>1</show_in_store>
@@ -184,7 +253,7 @@
184
  <label>Enable Command Listing On Help</label>
185
  <frontend_type>select</frontend_type>
186
  <source_model>chatbot/enable</source_model>
187
- <sort_order>7</sort_order>
188
  <show_in_default>1</show_in_default>
189
  <show_in_website>1</show_in_website>
190
  <show_in_store>1</show_in_store>
@@ -194,7 +263,7 @@
194
  <label>Enable Command Listing On Error</label>
195
  <frontend_type>select</frontend_type>
196
  <source_model>chatbot/enable</source_model>
197
- <sort_order>8</sort_order>
198
  <show_in_default>1</show_in_default>
199
  <show_in_website>1</show_in_website>
200
  <show_in_store>1</show_in_store>
@@ -204,17 +273,17 @@
204
  <label>Commands List</label>
205
  <frontend_model>werules_chatbot/commands</frontend_model>
206
  <backend_model>chatbot/adminhtml_serialized</backend_model> <!-- TODO adminhtml/system_config_backend_serialized_array -->
207
- <sort_order>10</sort_order>
208
  <show_in_default>1</show_in_default>
209
  <show_in_website>1</show_in_website>
210
  <show_in_store>0</show_in_store>
211
- <comment>Code of the commands and it's alias.</comment>
212
  </commands_list>
213
  <enable_default_replies>
214
  <label>Enable Default Replies</label>
215
  <frontend_type>select</frontend_type>
216
  <source_model>chatbot/enable</source_model>
217
- <sort_order>11</sort_order>
218
  <show_in_default>1</show_in_default>
219
  <show_in_website>1</show_in_website>
220
  <show_in_store>1</show_in_store>
@@ -224,12 +293,32 @@
224
  <label>Default Replies</label>
225
  <frontend_model>werules_chatbot/replies</frontend_model>
226
  <backend_model>chatbot/adminhtml_serialized</backend_model> <!-- TODO adminhtml/system_config_backend_serialized_array -->
227
- <sort_order>12</sort_order>
228
  <show_in_default>1</show_in_default>
229
  <show_in_website>1</show_in_website>
230
  <show_in_store>0</show_in_store>
231
  <comment>Replies to be Send to The Customer Whenever Matches One of The Requirements.</comment>
 
232
  </default_replies>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
  </fields>
234
  </telegram_config>
235
  <facebook_config translate="label">
@@ -258,39 +347,125 @@
258
  <show_in_default>1</show_in_default>
259
  <show_in_website>1</show_in_website>
260
  <show_in_store>1</show_in_store>
 
 
 
261
  <comment>Message To Send When Bot Is Disabled. Leave It Empty To Send No Message. Please Check The Maximum Size For Messages On Facebook API, Otherwise Your Message Might Not Be Sent.</comment>
262
  </disabled_message>
263
  <facebook_api_key>
264
- <label>Messenger Bot API Key</label>
265
  <frontend_type>text</frontend_type>
266
  <sort_order>2</sort_order>
267
  <show_in_default>1</show_in_default>
268
  <show_in_website>1</show_in_website>
269
  <show_in_store>1</show_in_store>
270
- <comment>Your Messenger Bot API Key.</comment>
271
  </facebook_api_key>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
272
  <facebook_support_group>
273
  <label>Messenger Support Chat ID</label>
274
  <frontend_type>text</frontend_type>
275
- <sort_order>3</sort_order>
276
  <show_in_default>1</show_in_default>
277
  <show_in_website>1</show_in_website>
278
  <show_in_store>1</show_in_store>
279
  <comment>The Chat ID of The Support Admin. This Feature Isn't Very Useful Since You Can Simply Log Into Your Page And Directly Reply Your Customers From There. You Can Forward All Messages to Telegram, Just Write "telegram" in Here to Enable This Feature.</comment>
280
  </facebook_support_group>
 
 
 
 
 
 
 
 
 
 
281
  <facebook_welcome_msg>
282
  <label>Messenger Welcome Message</label>
283
  <frontend_type>text</frontend_type>
284
- <sort_order>4</sort_order>
285
  <show_in_default>1</show_in_default>
286
  <show_in_website>1</show_in_website>
287
  <show_in_store>1</show_in_store>
288
- <comment>First Message The Bot Will Send To Your Client. Please Check The Maximum Size For Messages On Facebook API, Otherwise Your Message Might Not Be Sent.</comment>
289
  </facebook_welcome_msg>
290
  <facebook_help_msg>
291
  <label>Messenger Help Message</label>
292
  <frontend_type>text</frontend_type>
293
- <sort_order>5</sort_order>
294
  <show_in_default>1</show_in_default>
295
  <show_in_website>1</show_in_website>
296
  <show_in_store>1</show_in_store>
@@ -299,7 +474,7 @@
299
  <facebook_about_msg>
300
  <label>Messenger About Message</label>
301
  <frontend_type>text</frontend_type>
302
- <sort_order>6</sort_order>
303
  <show_in_default>1</show_in_default>
304
  <show_in_website>1</show_in_website>
305
  <show_in_store>1</show_in_store>
@@ -309,7 +484,7 @@
309
  <label>Enable Command Listing On Help</label>
310
  <frontend_type>select</frontend_type>
311
  <source_model>chatbot/enable</source_model>
312
- <sort_order>7</sort_order>
313
  <show_in_default>1</show_in_default>
314
  <show_in_website>1</show_in_website>
315
  <show_in_store>1</show_in_store>
@@ -319,7 +494,7 @@
319
  <label>Enable Command Listing On Error</label>
320
  <frontend_type>select</frontend_type>
321
  <source_model>chatbot/enable</source_model>
322
- <sort_order>8</sort_order>
323
  <show_in_default>1</show_in_default>
324
  <show_in_website>1</show_in_website>
325
  <show_in_store>1</show_in_store>
@@ -329,7 +504,7 @@
329
  <label>Enable Command Prediction</label>
330
  <frontend_type>select</frontend_type>
331
  <source_model>chatbot/enable</source_model>
332
- <sort_order>9</sort_order>
333
  <show_in_default>1</show_in_default>
334
  <show_in_website>1</show_in_website>
335
  <show_in_store>1</show_in_store>
@@ -339,17 +514,17 @@
339
  <label>Commands List</label>
340
  <frontend_model>werules_chatbot/commands</frontend_model>
341
  <backend_model>chatbot/adminhtml_serialized</backend_model> <!-- TODO adminhtml/system_config_backend_serialized_array -->
342
- <sort_order>11</sort_order>
343
  <show_in_default>1</show_in_default>
344
  <show_in_website>1</show_in_website>
345
  <show_in_store>0</show_in_store>
346
- <comment>Code of the commands and it's alias.</comment>
347
  </commands_list>
348
  <enable_default_replies>
349
  <label>Enable Default Replies</label>
350
  <frontend_type>select</frontend_type>
351
  <source_model>chatbot/enable</source_model>
352
- <sort_order>12</sort_order>
353
  <show_in_default>1</show_in_default>
354
  <show_in_website>1</show_in_website>
355
  <show_in_store>1</show_in_store>
@@ -359,12 +534,32 @@
359
  <label>Default Replies</label>
360
  <frontend_model>werules_chatbot/replies</frontend_model>
361
  <backend_model>chatbot/adminhtml_serialized</backend_model> <!-- TODO adminhtml/system_config_backend_serialized_array -->
362
- <sort_order>13</sort_order>
363
  <show_in_default>1</show_in_default>
364
  <show_in_website>1</show_in_website>
365
  <show_in_store>0</show_in_store>
366
  <comment>Replies to be Send to The Customer Whenever Matches One of The Requirements.</comment>
 
367
  </default_replies>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
368
  </fields>
369
  </facebook_config>
370
  </groups>
33
  <show_in_default>1</show_in_default>
34
  <show_in_website>1</show_in_website>
35
  <show_in_store>1</show_in_store>
36
+ <validate>validate-alphanum</validate>
37
  <comment>This is Your Custom Secret Key Used For The Webhook URL, to Activate/Deactivate The API Webhook For Telegram, And to Use as Your Challenge Hub For Facebook. Alphanumeric Only! Access http://(YOUR_STORE_URL)/chatbot/chatdata/(API)/webhook/(YOUR_CUSTOM_KEY) to Set The Webhook, change API to "telegram" or "facebook".</comment>
38
  </your_custom_key>
39
+ <!--<master_support_group>-->
40
+ <!--<label>Master Support Group</label>-->
41
+ <!--<frontend_type>select</frontend_type>-->
42
+ <!--<source_model>chatbot/chats</source_model>-->
43
+ <!--<sort_order>1</sort_order>-->
44
+ <!--<show_in_default>1</show_in_default>-->
45
+ <!--<show_in_website>1</show_in_website>-->
46
+ <!--<show_in_store>1</show_in_store>-->
47
+ <!--<comment>Choose to receive all support messages in one single message app. In Development.</comment>-->
48
+ <!--</master_support_group>-->
49
  <enable_support_final_message>
50
+ <label>Forward Fallback Messages to Support</label>
51
  <frontend_type>select</frontend_type>
52
  <source_model>chatbot/enable</source_model>
53
  <sort_order>2</sort_order>
54
  <show_in_default>1</show_in_default>
55
  <show_in_website>1</show_in_website>
56
  <show_in_store>1</show_in_store>
57
+ <comment>Automatically Enable Support if Customer Types a Message That The Bot Dosen't Understand.</comment>
58
  </enable_support_final_message>
59
  <list_empty_categories>
60
  <label>List Empty Categoies</label>
66
  <show_in_store>1</show_in_store>
67
  <comment>Enable Listing of Categories With No Products or Unallowed Products (This Module Supports Only Simple Products For Now).</comment>
68
  </list_empty_categories>
69
+ <disable_promotional_messages>
70
+ <label>Disable Promotional Messages</label>
71
+ <frontend_type>select</frontend_type>
72
+ <source_model>chatbot/enable</source_model>
73
+ <sort_order>4</sort_order>
74
+ <show_in_default>1</show_in_default>
75
+ <show_in_website>1</show_in_website>
76
+ <show_in_store>1</show_in_store>
77
+ <comment>Enable The Option For The Customer To Choose To Receive Or Not Promotional Messages.</comment>
78
+ </disable_promotional_messages>
79
  <enable_post_log>
80
  <label>Enable Log</label>
81
  <frontend_type>select</frontend_type>
82
  <source_model>chatbot/enable</source_model>
83
+ <sort_order>5</sort_order>
84
  <show_in_default>1</show_in_default>
85
  <show_in_website>1</show_in_website>
86
  <show_in_store>1</show_in_store>
95
  <show_in_default>1</show_in_default>
96
  <show_in_website>1</show_in_website>
97
  <show_in_store>1</show_in_store>
98
+ <comment>***Still in Development***</comment>
99
  <fields>
100
  <enable_witai>
101
+ <label>Enable witAI Integration</label>
102
  <frontend_type>select</frontend_type>
103
  <source_model>chatbot/enable</source_model>
104
  <sort_order>0</sort_order>
105
  <show_in_default>1</show_in_default>
106
  <show_in_website>1</show_in_website>
107
  <show_in_store>1</show_in_store>
108
+ <comment>Enable witAI Integration</comment>
109
  </enable_witai>
110
  <witai_api_key>
111
  <label>witAI API Key</label>
114
  <show_in_default>1</show_in_default>
115
  <show_in_website>1</show_in_website>
116
  <show_in_store>1</show_in_store>
117
+ <comment>witAI API Key</comment>
118
  </witai_api_key>
119
+ <witai_confidence>
120
+ <label>Acceptable witAI Confidence Percentage</label>
121
+ <frontend_type>text</frontend_type>
122
+ <sort_order>2</sort_order>
123
+ <show_in_default>1</show_in_default>
124
+ <show_in_website>1</show_in_website>
125
+ <show_in_store>1</show_in_store>
126
+ <validate>input-number validate-number validate-number-range number-range-1-100</validate>
127
+ <comment>Acceptable witAI Confidence Percentage</comment>
128
+ </witai_confidence>
129
+ <confirmation_message>
130
+ <label>Enable Confirmation Message</label>
131
+ <frontend_type>select</frontend_type>
132
+ <source_model>chatbot/enable</source_model>
133
+ <sort_order>0</sort_order>
134
+ <show_in_default>1</show_in_default>
135
+ <show_in_website>1</show_in_website>
136
+ <show_in_store>1</show_in_store>
137
+ <comment>Enable Confirmation Message When wit.ai Understands a Command, Like "So You Want To Clear Your Cart" For Clearing The Cart.</comment>
138
+ </confirmation_message>
139
  </fields>
140
  </witai_config>
141
  <telegram_config translate="label">
164
  <show_in_default>1</show_in_default>
165
  <show_in_website>1</show_in_website>
166
  <show_in_store>1</show_in_store>
167
+ <depends>
168
+ <enable_bot>0</enable_bot>
169
+ </depends>
170
  <comment>Message To Send When Bot Is Disabled. Leave It Empty To Send No Message. Please Check The Maximum Size For Messages On Telegram API, Otherwise Your Message Might Not Be Sent.</comment>
171
  </disabled_message>
172
  <telegram_api_key>
178
  <show_in_store>1</show_in_store>
179
  <comment>Your Telegram Bot API Key.</comment>
180
  </telegram_api_key>
181
+ <telegram_bot_username>
182
+ <label>Telegram Bot Username</label>
183
+ <frontend_type>text</frontend_type>
184
+ <sort_order>3</sort_order>
185
+ <show_in_default>1</show_in_default>
186
+ <show_in_website>1</show_in_website>
187
+ <show_in_store>1</show_in_store>
188
+ <comment>Your Telegram Bot Username.</comment>
189
+ </telegram_bot_username>
190
+ <enable_inline_search>
191
+ <label>Enable Inline Search</label>
192
+ <frontend_type>select</frontend_type>
193
+ <source_model>chatbot/enable</source_model>
194
+ <sort_order>4</sort_order>
195
+ <show_in_default>1</show_in_default>
196
+ <show_in_website>1</show_in_website>
197
+ <show_in_store>1</show_in_store>
198
+ <comment>Enable Telegram Inline Search</comment>
199
+ </enable_inline_search>
200
+ <enable_speech_recognition>
201
+ <label>Enable Speech Recognition</label>
202
+ <frontend_type>select</frontend_type>
203
+ <source_model>chatbot/enable</source_model>
204
+ <sort_order>5</sort_order>
205
+ <show_in_default>1</show_in_default>
206
+ <show_in_website>1</show_in_website>
207
+ <show_in_store>1</show_in_store>
208
+ <depends>
209
+ <enable_witai>
210
+ <fieldset>witai_config</fieldset>
211
+ <value>1</value>
212
+ </enable_witai>
213
+ </depends>
214
+ <comment>Enable Speech Recognition. Works Only if wit.ai is Enabled.</comment>
215
+ </enable_speech_recognition>
216
  <telegram_support_group>
217
  <label>Telegram Support Group ID</label>
218
  <frontend_type>text</frontend_type>
219
+ <sort_order>6</sort_order>
220
  <show_in_default>1</show_in_default>
221
  <show_in_website>1</show_in_website>
222
  <show_in_store>1</show_in_store>
225
  <telegram_welcome_msg>
226
  <label>Telegram Welcome Message</label>
227
  <frontend_type>text</frontend_type>
228
+ <sort_order>7</sort_order>
229
  <show_in_default>1</show_in_default>
230
  <show_in_website>1</show_in_website>
231
  <show_in_store>1</show_in_store>
232
+ <comment>First Message The Bot Will Send To Your Client. Please Check The Maximum Size For Messages On Telegram API, Otherwise Your Message Might Not Be Sent. You Can Use "{customername}" to Send The Customer Name.</comment>
233
  </telegram_welcome_msg>
234
  <telegram_help_msg>
235
  <label>Telegram Help Message</label>
236
  <frontend_type>text</frontend_type>
237
+ <sort_order>8</sort_order>
238
  <show_in_default>1</show_in_default>
239
  <show_in_website>1</show_in_website>
240
  <show_in_store>1</show_in_store>
243
  <telegram_about_msg>
244
  <label>Telegram About Message</label>
245
  <frontend_type>text</frontend_type>
246
+ <sort_order>9</sort_order>
247
  <show_in_default>1</show_in_default>
248
  <show_in_website>1</show_in_website>
249
  <show_in_store>1</show_in_store>
253
  <label>Enable Command Listing On Help</label>
254
  <frontend_type>select</frontend_type>
255
  <source_model>chatbot/enable</source_model>
256
+ <sort_order>10</sort_order>
257
  <show_in_default>1</show_in_default>
258
  <show_in_website>1</show_in_website>
259
  <show_in_store>1</show_in_store>
263
  <label>Enable Command Listing On Error</label>
264
  <frontend_type>select</frontend_type>
265
  <source_model>chatbot/enable</source_model>
266
+ <sort_order>11</sort_order>
267
  <show_in_default>1</show_in_default>
268
  <show_in_website>1</show_in_website>
269
  <show_in_store>1</show_in_store>
273
  <label>Commands List</label>
274
  <frontend_model>werules_chatbot/commands</frontend_model>
275
  <backend_model>chatbot/adminhtml_serialized</backend_model> <!-- TODO adminhtml/system_config_backend_serialized_array -->
276
+ <sort_order>12</sort_order>
277
  <show_in_default>1</show_in_default>
278
  <show_in_website>1</show_in_website>
279
  <show_in_store>0</show_in_store>
280
+ <comment>Code of the commands and it's alias. Alias must be split by comma. Eg.: "support,chat,talk,sac".</comment>
281
  </commands_list>
282
  <enable_default_replies>
283
  <label>Enable Default Replies</label>
284
  <frontend_type>select</frontend_type>
285
  <source_model>chatbot/enable</source_model>
286
+ <sort_order>13</sort_order>
287
  <show_in_default>1</show_in_default>
288
  <show_in_website>1</show_in_website>
289
  <show_in_store>1</show_in_store>
293
  <label>Default Replies</label>
294
  <frontend_model>werules_chatbot/replies</frontend_model>
295
  <backend_model>chatbot/adminhtml_serialized</backend_model> <!-- TODO adminhtml/system_config_backend_serialized_array -->
296
+ <sort_order>14</sort_order>
297
  <show_in_default>1</show_in_default>
298
  <show_in_website>1</show_in_website>
299
  <show_in_store>0</show_in_store>
300
  <comment>Replies to be Send to The Customer Whenever Matches One of The Requirements.</comment>
301
+ <!--<depends><enable_default_replies>1</enable_default_replies></depends>-->
302
  </default_replies>
303
+ <fallback_message>
304
+ <label>Fallback Message</label>
305
+ <frontend_type>text</frontend_type>
306
+ <sort_order>15</sort_order>
307
+ <show_in_default>1</show_in_default>
308
+ <show_in_website>1</show_in_website>
309
+ <show_in_store>1</show_in_store>
310
+ <comment>Message Will be Sent When The Bot Don't Understand Customer Messages For The Nst Time.</comment>
311
+ </fallback_message>
312
+ <fallback_message_quantity>
313
+ <label>Fallback Times</label>
314
+ <frontend_type>text</frontend_type>
315
+ <sort_order>16</sort_order>
316
+ <show_in_default>1</show_in_default>
317
+ <show_in_website>1</show_in_website>
318
+ <show_in_store>1</show_in_store>
319
+ <validate>input-number validate-number</validate>
320
+ <comment>Number of Fallbacks Before Sending The Fallback Message. To disable, Just Leave it Empty.</comment>
321
+ </fallback_message_quantity>
322
  </fields>
323
  </telegram_config>
324
  <facebook_config translate="label">
347
  <show_in_default>1</show_in_default>
348
  <show_in_website>1</show_in_website>
349
  <show_in_store>1</show_in_store>
350
+ <depends>
351
+ <enable_bot>0</enable_bot>
352
+ </depends>
353
  <comment>Message To Send When Bot Is Disabled. Leave It Empty To Send No Message. Please Check The Maximum Size For Messages On Facebook API, Otherwise Your Message Might Not Be Sent.</comment>
354
  </disabled_message>
355
  <facebook_api_key>
356
+ <label>Page Access Token</label>
357
  <frontend_type>text</frontend_type>
358
  <sort_order>2</sort_order>
359
  <show_in_default>1</show_in_default>
360
  <show_in_website>1</show_in_website>
361
  <show_in_store>1</show_in_store>
362
+ <comment>Your Page Access Token.</comment>
363
  </facebook_api_key>
364
+ <facebook_page_username>
365
+ <label>Facebook Page Username</label>
366
+ <frontend_type>text</frontend_type>
367
+ <sort_order>3</sort_order>
368
+ <show_in_default>1</show_in_default>
369
+ <show_in_website>1</show_in_website>
370
+ <show_in_store>1</show_in_store>
371
+ <comment>Facebook Page Username.</comment>
372
+ </facebook_page_username>
373
+ <!--<enable_speech_recognition>-->
374
+ <!--<label>Enable Speech Recognition</label>-->
375
+ <!--<frontend_type>select</frontend_type>-->
376
+ <!--<source_model>chatbot/enable</source_model>-->
377
+ <!--<sort_order>4</sort_order>-->
378
+ <!--<show_in_default>1</show_in_default>-->
379
+ <!--<show_in_website>1</show_in_website>-->
380
+ <!--<show_in_store>1</show_in_store>-->
381
+ <!--<depends>-->
382
+ <!--<enable_witai>-->
383
+ <!--<fieldset>witai_config</fieldset>-->
384
+ <!--<value>1</value>-->
385
+ <!--</enable_witai>-->
386
+ <!--</depends>-->
387
+ <!--<comment>Enable Speech Recognition. Works Only if wit.ai is Enabled.</comment>-->
388
+ <!--</enable_speech_recognition>-->
389
+ <facebook_messenger_box>
390
+ <label>Enable Facebook Messenger Box</label>
391
+ <frontend_type>select</frontend_type>
392
+ <source_model>chatbot/enable</source_model>
393
+ <sort_order>5</sort_order>
394
+ <show_in_default>1</show_in_default>
395
+ <show_in_website>1</show_in_website>
396
+ <show_in_store>1</show_in_store>
397
+ <comment>Enable Facebook Messenger Box.</comment>
398
+ </facebook_messenger_box>
399
+ <facebook_messenger_box_width>
400
+ <label>Facebook Messenger Box Size</label>
401
+ <frontend_type>text</frontend_type>
402
+ <sort_order>6</sort_order>
403
+ <show_in_default>1</show_in_default>
404
+ <show_in_website>1</show_in_website>
405
+ <show_in_store>1</show_in_store>
406
+ <depends>
407
+ <facebook_messenger_box>1</facebook_messenger_box>
408
+ </depends>
409
+ <validate>input-number validate-number</validate>
410
+ <comment>Facebook Messenger Box Size.</comment>
411
+ </facebook_messenger_box_width>
412
+ <enable_referral>
413
+ <label>Enable Referral</label>
414
+ <frontend_type>select</frontend_type>
415
+ <source_model>chatbot/enable</source_model>
416
+ <sort_order>7</sort_order>
417
+ <show_in_default>1</show_in_default>
418
+ <show_in_website>1</show_in_website>
419
+ <show_in_store>1</show_in_store>
420
+ <depends>
421
+ <facebook_messenger_box>1</facebook_messenger_box>
422
+ </depends>
423
+ <comment>Enable Referral When Customer Opens Messenger Box.</comment>
424
+ </enable_referral>
425
+ <facebook_referral_message>
426
+ <label>Referral Message</label>
427
+ <frontend_type>text</frontend_type>
428
+ <sort_order>8</sort_order>
429
+ <show_in_default>1</show_in_default>
430
+ <show_in_website>1</show_in_website>
431
+ <show_in_store>1</show_in_store>
432
+ <depends>
433
+ <enable_referral>1</enable_referral>
434
+ </depends>
435
+ <comment>Message The Bot Will Send To Your Client When He Opens The Messenger Box. You Can Use "{customername}" to Send The Customer Name.</comment>
436
+ </facebook_referral_message>
437
  <facebook_support_group>
438
  <label>Messenger Support Chat ID</label>
439
  <frontend_type>text</frontend_type>
440
+ <sort_order>9</sort_order>
441
  <show_in_default>1</show_in_default>
442
  <show_in_website>1</show_in_website>
443
  <show_in_store>1</show_in_store>
444
  <comment>The Chat ID of The Support Admin. This Feature Isn't Very Useful Since You Can Simply Log Into Your Page And Directly Reply Your Customers From There. You Can Forward All Messages to Telegram, Just Write "telegram" in Here to Enable This Feature.</comment>
445
  </facebook_support_group>
446
+ <option_disable_bot>
447
+ <label>Enable Option to Disable Bot</label>
448
+ <frontend_type>select</frontend_type>
449
+ <source_model>chatbot/enable</source_model>
450
+ <sort_order>10</sort_order>
451
+ <show_in_default>1</show_in_default>
452
+ <show_in_website>1</show_in_website>
453
+ <show_in_store>1</show_in_store>
454
+ <comment>Enable Option to Disable Bot When Sending a Message Directly to Customer Via Page Message.</comment>
455
+ </option_disable_bot>
456
  <facebook_welcome_msg>
457
  <label>Messenger Welcome Message</label>
458
  <frontend_type>text</frontend_type>
459
+ <sort_order>11</sort_order>
460
  <show_in_default>1</show_in_default>
461
  <show_in_website>1</show_in_website>
462
  <show_in_store>1</show_in_store>
463
+ <comment>First Message The Bot Will Send To Your Client. Please Check The Maximum Size For Messages On Facebook API, Otherwise Your Message Might Not Be Sent. You Can Use "{customername}" to Send The Customer Name.</comment>
464
  </facebook_welcome_msg>
465
  <facebook_help_msg>
466
  <label>Messenger Help Message</label>
467
  <frontend_type>text</frontend_type>
468
+ <sort_order>12</sort_order>
469
  <show_in_default>1</show_in_default>
470
  <show_in_website>1</show_in_website>
471
  <show_in_store>1</show_in_store>
474
  <facebook_about_msg>
475
  <label>Messenger About Message</label>
476
  <frontend_type>text</frontend_type>
477
+ <sort_order>13</sort_order>
478
  <show_in_default>1</show_in_default>
479
  <show_in_website>1</show_in_website>
480
  <show_in_store>1</show_in_store>
484
  <label>Enable Command Listing On Help</label>
485
  <frontend_type>select</frontend_type>
486
  <source_model>chatbot/enable</source_model>
487
+ <sort_order>14</sort_order>
488
  <show_in_default>1</show_in_default>
489
  <show_in_website>1</show_in_website>
490
  <show_in_store>1</show_in_store>
494
  <label>Enable Command Listing On Error</label>
495
  <frontend_type>select</frontend_type>
496
  <source_model>chatbot/enable</source_model>
497
+ <sort_order>15</sort_order>
498
  <show_in_default>1</show_in_default>
499
  <show_in_website>1</show_in_website>
500
  <show_in_store>1</show_in_store>
504
  <label>Enable Command Prediction</label>
505
  <frontend_type>select</frontend_type>
506
  <source_model>chatbot/enable</source_model>
507
+ <sort_order>16</sort_order>
508
  <show_in_default>1</show_in_default>
509
  <show_in_website>1</show_in_website>
510
  <show_in_store>1</show_in_store>
514
  <label>Commands List</label>
515
  <frontend_model>werules_chatbot/commands</frontend_model>
516
  <backend_model>chatbot/adminhtml_serialized</backend_model> <!-- TODO adminhtml/system_config_backend_serialized_array -->
517
+ <sort_order>17</sort_order>
518
  <show_in_default>1</show_in_default>
519
  <show_in_website>1</show_in_website>
520
  <show_in_store>0</show_in_store>
521
+ <comment>Code of the commands and it's alias. Alias must be split by comma. Eg.: "support,chat,talk,sac".</comment>
522
  </commands_list>
523
  <enable_default_replies>
524
  <label>Enable Default Replies</label>
525
  <frontend_type>select</frontend_type>
526
  <source_model>chatbot/enable</source_model>
527
+ <sort_order>18</sort_order>
528
  <show_in_default>1</show_in_default>
529
  <show_in_website>1</show_in_website>
530
  <show_in_store>1</show_in_store>
534
  <label>Default Replies</label>
535
  <frontend_model>werules_chatbot/replies</frontend_model>
536
  <backend_model>chatbot/adminhtml_serialized</backend_model> <!-- TODO adminhtml/system_config_backend_serialized_array -->
537
+ <sort_order>19</sort_order>
538
  <show_in_default>1</show_in_default>
539
  <show_in_website>1</show_in_website>
540
  <show_in_store>0</show_in_store>
541
  <comment>Replies to be Send to The Customer Whenever Matches One of The Requirements.</comment>
542
+ <!--<depends><enable_default_replies>1</enable_default_replies></depends>-->
543
  </default_replies>
544
+ <fallback_message>
545
+ <label>Fallback Message</label>
546
+ <frontend_type>text</frontend_type>
547
+ <sort_order>20</sort_order>
548
+ <show_in_default>1</show_in_default>
549
+ <show_in_website>1</show_in_website>
550
+ <show_in_store>1</show_in_store>
551
+ <comment>Message Will be Sent When The Bot Don't Understand Customer Messages For The Nst Time.</comment>
552
+ </fallback_message>
553
+ <fallback_message_quantity>
554
+ <label>Fallback Times</label>
555
+ <frontend_type>text</frontend_type>
556
+ <sort_order>21</sort_order>
557
+ <show_in_default>1</show_in_default>
558
+ <show_in_website>1</show_in_website>
559
+ <show_in_store>1</show_in_store>
560
+ <validate>input-number validate-number</validate>
561
+ <comment>Number of Fallbacks Before Sending The Fallback Message. To disable, Just Leave it Empty.</comment>
562
+ </fallback_message_quantity>
563
  </fields>
564
  </facebook_config>
565
  </groups>
app/code/community/Werules/Chatbot/sql/chatbot_setup/{mysql4-install-0.0.9.php → mysql4-install-0.0.15.php} RENAMED
@@ -16,29 +16,50 @@ $installer->run("
16
  `hash_key` varchar(150) NULL,
17
  `is_admin` smallint(1) NOT NULL default '0',
18
  `is_logged` smallint(1) NOT NULL default '0',
 
19
  `enable_support` smallint(1) NOT NULL default '1',
20
  `last_support_message_id` varchar(50) NULL,
21
  `last_support_chat` varchar(20) NULL,
 
22
  `enable_telegram` smallint(1) NOT NULL default '1',
 
23
  `telegram_chat_id` varchar(50) NULL,
24
  `telegram_message_id` varchar(50) NULL,
25
  `telegram_conv_state` int(10) NOT NULL default '0',
26
  `telegram_support_reply_chat_id` varchar(50) NULL,
 
 
27
  `enable_facebook` smallint(1) NOT NULL default '1',
 
28
  `facebook_chat_id` varchar(50) NULL,
29
  `facebook_message_id` varchar(50) NULL,
30
  `facebook_conv_state` int(10) NOT NULL default '0',
31
  `facebook_support_reply_chat_id` varchar(50) NULL,
 
 
32
  `enable_whatsapp` smallint(1) NOT NULL default '1',
 
33
  `whatsapp_chat_id` varchar(50) NULL,
34
  `whatsapp_message_id` varchar(50) NULL,
35
  `whatsapp_conv_state` int(10) NOT NULL default '0',
36
  `whatsapp_support_reply_chat_id` varchar(50) NULL,
 
 
37
  `enable_wechat` smallint(1) NOT NULL default '1',
 
38
  `wechat_chat_id` varchar(50) NULL,
39
  `wechat_message_id` varchar(50) NULL,
40
  `wechat_conv_state` int(10) NOT NULL default '0',
41
  `wechat_support_reply_chat_id` varchar(50) NULL,
 
 
 
 
 
 
 
 
 
42
  PRIMARY KEY (entity_id)
43
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
44
  ");
16
  `hash_key` varchar(150) NULL,
17
  `is_admin` smallint(1) NOT NULL default '0',
18
  `is_logged` smallint(1) NOT NULL default '0',
19
+ `enable_promotional_messages` smallint(1) NOT NULL default '1',
20
  `enable_support` smallint(1) NOT NULL default '1',
21
  `last_support_message_id` varchar(50) NULL,
22
  `last_support_chat` varchar(20) NULL,
23
+ `enable_telegram_admin` smallint(1) NOT NULL default '1',
24
  `enable_telegram` smallint(1) NOT NULL default '1',
25
+ `telegram_processing_request` smallint(1) NOT NULL default '0',
26
  `telegram_chat_id` varchar(50) NULL,
27
  `telegram_message_id` varchar(50) NULL,
28
  `telegram_conv_state` int(10) NOT NULL default '0',
29
  `telegram_support_reply_chat_id` varchar(50) NULL,
30
+ `telegram_fallback_qty` int(10) NOT NULL default '0',
31
+ `enable_facebook_admin` smallint(1) NOT NULL default '1',
32
  `enable_facebook` smallint(1) NOT NULL default '1',
33
+ `facebook_processing_request` smallint(1) NOT NULL default '0',
34
  `facebook_chat_id` varchar(50) NULL,
35
  `facebook_message_id` varchar(50) NULL,
36
  `facebook_conv_state` int(10) NOT NULL default '0',
37
  `facebook_support_reply_chat_id` varchar(50) NULL,
38
+ `facebook_fallback_qty` int(10) NOT NULL default '0',
39
+ `enable_whatsapp_admin` smallint(1) NOT NULL default '1',
40
  `enable_whatsapp` smallint(1) NOT NULL default '1',
41
+ `whatsapp_processing_request` smallint(1) NOT NULL default '0',
42
  `whatsapp_chat_id` varchar(50) NULL,
43
  `whatsapp_message_id` varchar(50) NULL,
44
  `whatsapp_conv_state` int(10) NOT NULL default '0',
45
  `whatsapp_support_reply_chat_id` varchar(50) NULL,
46
+ `whatsapp_fallback_qty` int(10) NOT NULL default '0',
47
+ `enable_wechat_admin` smallint(1) NOT NULL default '1',
48
  `enable_wechat` smallint(1) NOT NULL default '1',
49
+ `wechat_processing_request` smallint(1) NOT NULL default '0',
50
  `wechat_chat_id` varchar(50) NULL,
51
  `wechat_message_id` varchar(50) NULL,
52
  `wechat_conv_state` int(10) NOT NULL default '0',
53
  `wechat_support_reply_chat_id` varchar(50) NULL,
54
+ `wechat_fallback_qty` int(10) NOT NULL default '0',
55
+ `enable_skype_admin` smallint(1) NOT NULL default '1',
56
+ `enable_skype` smallint(1) NOT NULL default '1',
57
+ `skype_processing_request` smallint(1) NOT NULL default '0',
58
+ `skype_chat_id` varchar(50) NULL,
59
+ `skype_message_id` varchar(50) NULL,
60
+ `skype_conv_state` int(10) NOT NULL default '0',
61
+ `skype_support_reply_chat_id` varchar(50) NULL,
62
+ `skype_fallback_qty` int(10) NOT NULL default '0',
63
  PRIMARY KEY (entity_id)
64
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
65
  ");
app/code/community/Werules/Chatbot/sql/chatbot_setup/mysql4-upgrade-0.0.9-0.0.15.php ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ $table = 'wr_chatbot';
4
+ $installer = $this;
5
+ $installer->startSetup(); //db update
6
+
7
+ $installer->run("
8
+ ALTER TABLE {$this->getTable($table)}
9
+ ADD COLUMN `enable_promotional_messages` smallint(1) NOT NULL default '1' AFTER `is_logged`,
10
+ ADD COLUMN `enable_telegram_admin` smallint(1) NOT NULL default '1' AFTER `last_support_chat`,
11
+ ADD COLUMN `telegram_processing_request` smallint(1) NOT NULL default '0' AFTER `enable_telegram`,
12
+ ADD COLUMN `telegram_fallback_qty` int(10) NOT NULL default '0' AFTER `telegram_support_reply_chat_id`,
13
+ ADD COLUMN `enable_facebook_admin` smallint(1) NOT NULL default '1' AFTER `telegram_fallback_qty`,
14
+ ADD COLUMN `facebook_processing_request` smallint(1) NOT NULL default '0' AFTER `enable_facebook`,
15
+ ADD COLUMN `facebook_fallback_qty` int(10) NOT NULL default '0' AFTER `facebook_support_reply_chat_id`,
16
+ ADD COLUMN `enable_whatsapp_admin` smallint(1) NOT NULL default '1' AFTER `facebook_fallback_qty`,
17
+ ADD COLUMN `whatsapp_processing_request` smallint(1) NOT NULL default '0' AFTER `enable_whatsapp`,
18
+ ADD COLUMN `whatsapp_fallback_qty` int(10) NOT NULL default '0' AFTER `whatsapp_support_reply_chat_id`,
19
+ ADD COLUMN `enable_wechat_admin` smallint(1) NOT NULL default '1' AFTER `whatsapp_fallback_qty`,
20
+ ADD COLUMN `wechat_processing_request` smallint(1) NOT NULL default '0' AFTER `enable_wechat`,
21
+ ADD COLUMN `wechat_fallback_qty` int(10) NOT NULL default '0' AFTER `wechat_support_reply_chat_id`,
22
+ ADD COLUMN `enable_skype_admin` smallint(1) NOT NULL default '1' AFTER `wechat_fallback_qty`,
23
+ ADD COLUMN `enable_skype` smallint(1) NOT NULL default '1' AFTER `enable_skype_admin`,
24
+ ADD COLUMN `skype_processing_request` smallint(1) NOT NULL default '0' AFTER `enable_skype`,
25
+ ADD COLUMN `skype_chat_id` varchar(50) NULL AFTER `skype_processing_request`,
26
+ ADD COLUMN `skype_message_id` varchar(50) NULL AFTER `skype_chat_id`,
27
+ ADD COLUMN `skype_conv_state` int(10) NOT NULL default '0' AFTER `skype_message_id`,
28
+ ADD COLUMN `skype_support_reply_chat_id` varchar(50) NULL AFTER `skype_conv_state`,
29
+ ADD COLUMN `skype_fallback_qty` int(10) NOT NULL default '0' AFTER `skype_support_reply_chat_id`;
30
+ ");
31
+
32
+ $installer->endSetup();
app/design/adminhtml/default/default/layout/werules_chatbot.xml ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <layout>
3
+ <default> <!-- TODO load this only on the module page -->
4
+ <reference name="head">
5
+ <action method="addJs"><script>werules/chatbot/chatbot.js</script></action>
6
+ <action method="addCss"><script>css/werules_chatbot/chatbot.css</script></action>
7
+ </reference>
8
+ </default>
9
+ </layout>
app/design/frontend/base/default/layout/werules_chatbot.xml CHANGED
@@ -1,3 +1,4 @@
 
1
  <layout>
2
  <customer_account>
3
  <reference name="customer_account_navigation">
@@ -8,13 +9,13 @@
8
  </action>
9
  </reference>
10
  </customer_account>
11
- <chatbot_settings_index>
12
  <update handle="customer_account" />
13
  <reference name="my.account.wrapper">
14
  <block type="core/template" name="chatbot_content" template="werules_chatbot_config.phtml"/>
15
  </reference>
16
  </chatbot_settings_index>
17
- <chatbot_chatdata_index>
18
  <remove name="head" />
19
  <remove name="right" />
20
  <remove name="left" />
@@ -27,7 +28,7 @@
27
  <block type="core/template" name="chatbot_content" template="werules_chatbot_view.phtml"/>
28
  </reference>
29
  </chatbot_chatdata_index>
30
- <chatbot_chatdata_telegram>
31
  <remove name="head" />
32
  <remove name="right" />
33
  <remove name="left" />
@@ -40,7 +41,7 @@
40
  <block type="core/template" name="chatbot_content" template="werules_chatbot_view.phtml"/>
41
  </reference>
42
  </chatbot_chatdata_telegram>
43
- <chatbot_chatdata_facebook>
44
  <remove name="head" />
45
  <remove name="right" />
46
  <remove name="left" />
@@ -53,4 +54,9 @@
53
  <block type="core/template" name="chatbot_content" template="werules_chatbot_view.phtml"/>
54
  </reference>
55
  </chatbot_chatdata_facebook>
56
- </layout>
 
 
 
 
 
1
+ <?xml version="1.0" ?>
2
  <layout>
3
  <customer_account>
4
  <reference name="customer_account_navigation">
9
  </action>
10
  </reference>
11
  </customer_account>
12
+ <chatbot_settings_index> <!-- module/controller/action -->
13
  <update handle="customer_account" />
14
  <reference name="my.account.wrapper">
15
  <block type="core/template" name="chatbot_content" template="werules_chatbot_config.phtml"/>
16
  </reference>
17
  </chatbot_settings_index>
18
+ <chatbot_chatdata_index> <!-- module/controller/action -->
19
  <remove name="head" />
20
  <remove name="right" />
21
  <remove name="left" />
28
  <block type="core/template" name="chatbot_content" template="werules_chatbot_view.phtml"/>
29
  </reference>
30
  </chatbot_chatdata_index>
31
+ <chatbot_chatdata_telegram> <!-- module/controller/action -->
32
  <remove name="head" />
33
  <remove name="right" />
34
  <remove name="left" />
41
  <block type="core/template" name="chatbot_content" template="werules_chatbot_view.phtml"/>
42
  </reference>
43
  </chatbot_chatdata_telegram>
44
+ <chatbot_chatdata_facebook> <!-- module/controller/action -->
45
  <remove name="head" />
46
  <remove name="right" />
47
  <remove name="left" />
54
  <block type="core/template" name="chatbot_content" template="werules_chatbot_view.phtml"/>
55
  </reference>
56
  </chatbot_chatdata_facebook>
57
+ <default> <!-- module/controller/action -->
58
+ <reference name="content">
59
+ <block type="werules_chatbot/messenger" name="messenger" template="werules_chatbot_messenger_box.phtml"/>
60
+ </reference>
61
+ </default>
62
+ </layout>
app/design/frontend/base/default/template/werules_chatbot_config.phtml CHANGED
@@ -1,21 +1,12 @@
1
  <?php
2
- $clientid = Mage::getSingleton('customer/session')->getCustomer()->getId(); // get customer id
3
- $chatdata = Mage::getModel('chatbot/chatdata')->load($clientid, 'customer_id'); // load profile info from customer id
4
 
5
- // TODO please
6
- $tg_apikey = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_api_key');
7
- $getme = "https://api.telegram.org/bot" . $tg_apikey . "/getMe";
8
- $response = json_decode(file_get_contents($getme), true);
9
- $tg_username = null;
10
- if ($response["ok"])
11
- $tg_username = $response["result"]["username"];
12
 
13
- $fb_apikey = Mage::getStoreConfig('chatbot_enable/facebook_config/facebook_api_key');
14
- $getme = "https://graph.facebook.com/v2.8/me?access_token=" . $fb_apikey;
15
- $response = json_decode(file_get_contents($getme), true);
16
- $fb_username = null;
17
- if (!empty($response))
18
- $fb_username = $response["id"];
19
  ?>
20
  <div class="dashboard">
21
  <?php echo $this->getMessagesBlock()->getGroupedHtml() ?>
@@ -26,16 +17,24 @@
26
  <input type="hidden" name="form_key" value="<?php echo Mage::getSingleton('core/session')->getFormKey(); ?>" />
27
  <div class="fieldset">
28
  <ul class="form-list">
 
 
 
 
 
 
 
 
29
  <li>
30
  <div class="input-box">
31
- <input <?php if ($chatdata->getEnableTelegram() == "1") echo "checked"; ?> type="checkbox" title="<?php echo $this->__('Enable Telegram?') ?>" class="checkbox" name="enable_telegram" id="enable_telegram" />
32
  <label for="enable_telegram" class="required"><em>*</em><?php echo $this->__('Enable Telegram?') ?></label>
33
  </div>
34
- <?php if ($tg_username): ?><!-- bot username -->
35
  <p>
36
  <?php
37
  echo $this->__("Start a bot conversation on Telegram") . ": ";
38
- $url = $chatdata->_tgUrl . $tg_username;
39
  if (empty($chatdata->getTelegramChatId()))
40
  $url .= "?start=" . $chatdata->getHashKey();
41
  ?>
@@ -45,14 +44,14 @@
45
  </li>
46
  <li>
47
  <div class="input-box">
48
- <input <?php if ($chatdata->getEnableFacebook() == "1") echo "checked"; ?> type="checkbox" title="<?php echo $this->__('Enable Facebook?') ?>" class="checkbox" name="enable_facebook" id="enable_facebook" />
49
  <label for="enable_facebook" class="required"><em>*</em><?php echo $this->__('Enable Facebook?') ?></label>
50
  </div>
51
- <?php if ($fb_username): ?><!-- bot username -->
52
  <p>
53
  <?php
54
  echo $this->__("Start a bot conversation on Facebook Messenger") . ": ";
55
- $url = $chatdata->_fbUrl . $fb_username;
56
  ?>
57
  <a href="<?php echo $url; ?>" target="_blank"><?php echo $this->__('Here') ?></a>
58
  </p>
1
  <?php
2
+ // this is the customer panel settings, here he can enable/disable a chatbot and receiving promotional messages
 
3
 
4
+ $clientId = Mage::getSingleton('customer/session')->getCustomer()->getId(); // get customer id
5
+ $chatdata = Mage::getModel('chatbot/chatdata')->load($clientId, 'customer_id'); // load profile info from customer id
6
+ $chatbotHelper = Mage::helper('werules_chatbot');
 
 
 
 
7
 
8
+ $tgUsername = $chatbotHelper->getTelegramBotUsername();
9
+ $fbUsername = $chatbotHelper->getFacebookPageChatID();
 
 
 
 
10
  ?>
11
  <div class="dashboard">
12
  <?php echo $this->getMessagesBlock()->getGroupedHtml() ?>
17
  <input type="hidden" name="form_key" value="<?php echo Mage::getSingleton('core/session')->getFormKey(); ?>" />
18
  <div class="fieldset">
19
  <ul class="form-list">
20
+ <?php if (Mage::getStoreConfig('chatbot_enable/general_config/disable_promotional_messages') == "1"): ?>
21
+ <li>
22
+ <div class="input-box">
23
+ <input <?php if ($chatdata->getEnablePromotionalMessages() != "0") echo "checked"; ?> type="checkbox" title="<?php echo $this->__('Receive Promotional Messages?') ?>" class="checkbox" name="enable_promotional_messages" id="enable_promotional_messages" />
24
+ <label for="enable_telegram" class="required"><em>*</em><?php echo $this->__('Receive Promotional Messages?') ?></label>
25
+ </div>
26
+ </li>
27
+ <?php endif; ?>
28
  <li>
29
  <div class="input-box">
30
+ <input <?php if ($chatdata->getEnableTelegram() != "0") echo "checked"; ?> type="checkbox" title="<?php echo $this->__('Enable Telegram?') ?>" class="checkbox" name="enable_telegram" id="enable_telegram" />
31
  <label for="enable_telegram" class="required"><em>*</em><?php echo $this->__('Enable Telegram?') ?></label>
32
  </div>
33
+ <?php if ($tgUsername): ?> <!-- bot username -->
34
  <p>
35
  <?php
36
  echo $this->__("Start a bot conversation on Telegram") . ": ";
37
+ $url = $chatbotHelper->_tgUrl . $tgUsername;
38
  if (empty($chatdata->getTelegramChatId()))
39
  $url .= "?start=" . $chatdata->getHashKey();
40
  ?>
44
  </li>
45
  <li>
46
  <div class="input-box">
47
+ <input <?php if ($chatdata->getEnableFacebook() != "0") echo "checked"; ?> type="checkbox" title="<?php echo $this->__('Enable Facebook?') ?>" class="checkbox" name="enable_facebook" id="enable_facebook" />
48
  <label for="enable_facebook" class="required"><em>*</em><?php echo $this->__('Enable Facebook?') ?></label>
49
  </div>
50
+ <?php if ($fbUsername): ?> <!-- bot username -->
51
  <p>
52
  <?php
53
  echo $this->__("Start a bot conversation on Facebook Messenger") . ": ";
54
+ $url = $chatbotHelper->_fbUrl . $fbUsername;
55
  ?>
56
  <a href="<?php echo $url; ?>" target="_blank"><?php echo $this->__('Here') ?></a>
57
  </p>
app/design/frontend/base/default/template/werules_chatbot_messenger_box.phtml ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ $enableMessengerBox = Mage::getStoreConfig('chatbot_enable/facebook_config/facebook_messenger_box');
3
+ if ($enableMessengerBox == "1"): // { OPEN IF
4
+ ?>
5
+ <?php
6
+ $chatbotHelper = Mage::helper('werules_chatbot');
7
+ $mageHelper = Mage::helper('core');
8
+ $imgWidth = (int)Mage::getStoreConfig('chatbot_enable/facebook_config/facebook_messenger_box_width');
9
+ if (empty($imgWidth))
10
+ $imgWidth = 60;
11
+ ?>
12
+ <style>
13
+ #werules-messenger-box {
14
+ position: fixed;
15
+ display: block;
16
+ z-index: 999;
17
+ bottom: 20px;
18
+ right: 30px;
19
+ cursor: pointer;
20
+ }
21
+
22
+ #werules-messenger-box:hover .werules-messenger-icon img{
23
+ transform:scale(1.1, 1.1);
24
+ -webkit-transform:scale(1.1, 1.1);
25
+ -moz-transform:scale(1.1, 1.1);
26
+ }
27
+
28
+ .werules-messenger-icon img {
29
+ width: <?php echo $imgWidth;?>px;
30
+ filter: drop-shadow(2px 6px 4px rgba(0,0,0,.3));
31
+ -webkit-filter: drop-shadow(2px 6px 4px rgba(0,0,0,.3));
32
+ }
33
+
34
+ .werules-tiptext{
35
+ width: 120px;
36
+ background-color: white;
37
+ color: #2c2c2c; ;
38
+ text-align: center;
39
+ padding: 5px 0;
40
+ border: 1px solid #eeeeee;
41
+ border-radius: 6px;
42
+ position: fixed;
43
+ bottom: 30px;
44
+ right: <?php echo (int)$imgWidth + 40;?>px;
45
+ text-transform: uppercase;
46
+ filter: drop-shadow(2px 6px 4px rgba(0,0,0,.3));
47
+ -webkit-filter: drop-shadow(2px 6px 4px rgba(0,0,0,.3));
48
+ }
49
+
50
+ .werules-tiptext:after{
51
+ content: "";
52
+ position: absolute;
53
+ top: 50%;
54
+ left: 100%;
55
+ margin-top: -5px;
56
+ border-width: 5px;
57
+ border-style: solid;
58
+ border-color: transparent transparent transparent #eeeeee;
59
+ }
60
+
61
+ @media (max-width: 480px)
62
+ {
63
+ .werules-mobilehidden{
64
+ display: none;
65
+ }
66
+ }
67
+ </style>
68
+ <?php
69
+ $fbUsername = $chatbotHelper->getFacebookPageChatID();
70
+ $enableReferral = Mage::getStoreConfig('chatbot_enable/facebook_config/enable_referral');
71
+ $ref = "";
72
+ if ($enableReferral == "1")
73
+ {
74
+ $refData = array(
75
+ "page" => Mage::helper('core/url')->getCurrentUrl() // TODO
76
+ );
77
+ $ref = "?ref=" . serialize($refData);
78
+ }
79
+ $fbChatUrl = null;
80
+ if (!empty($fbUsername))
81
+ $fbChatUrl = $chatbotHelper->_fbUrl . $fbUsername . $ref;
82
+ ?>
83
+
84
+ <div id="werules-messenger-box">
85
+ <!-- code from https://gist.github.com/tomcritchlow/493774b09b02e31d1184d7cda926c659 -->
86
+ <a href="<?php echo $fbChatUrl; ?>" target="_blank" onclick="OpenChatInNewTab();">
87
+ <div class="werules-messenger-icon">
88
+ <img src="<?php echo $this->getSkinUrl('images/werules_chatbot/messenger-icon.png'); ?>"/>
89
+ <span class="werules-tiptext werules-mobilehidden"><?php echo $mageHelper->__("Message us"); ?></span>
90
+ </div>
91
+ </a>
92
+ </div>
93
+ <script>
94
+ function OpenChatInNewTab() {
95
+ var screenwidth = screen.width;
96
+ var screenheight = window.innerHeight;
97
+ window.open('<?php echo $fbChatUrl; ?>', '_blank', "directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=500,height=" + screenheight + ",left=" + (screenwidth - 500));
98
+ }
99
+ </script>
100
+ <?php
101
+ //} // CLOSE IF
102
+ endif;
103
+ ?>
app/design/frontend/base/default/template/werules_chatbot_view.phtml CHANGED
@@ -1,15 +1,16 @@
1
  <?php
 
2
  $action = $this->getRequest()->getActionName();
3
 
4
- if (!empty($action))
5
  {
6
  $webhook = Mage::app()->getRequest()->getParam('webhook');
7
  $key = Mage::app()->getRequest()->getParam('key');
8
  $customKey = Mage::getStoreConfig('chatbot_enable/general_config/your_custom_key');
9
 
10
- if ($webhook == $customKey) // set webhook
11
  echo Mage::getModel('chatbot/chatdata')->requestHandler($action, $webhook);
12
- else if ($key == $customKey) // process request
13
  echo Mage::getModel('chatbot/chatdata')->requestHandler($action, null);
14
  else // error
15
  {
1
  <?php
2
+ // this is the post view, where the module receives the posts from the chat APIs
3
  $action = $this->getRequest()->getActionName();
4
 
5
+ if (!empty($action)) // the view must have a action
6
  {
7
  $webhook = Mage::app()->getRequest()->getParam('webhook');
8
  $key = Mage::app()->getRequest()->getParam('key');
9
  $customKey = Mage::getStoreConfig('chatbot_enable/general_config/your_custom_key');
10
 
11
+ if ($webhook == $customKey) // set webhook eg.: https://store.com/chatbot/chatdata/telegram/webhook/custom_key_here/ -> set webhook
12
  echo Mage::getModel('chatbot/chatdata')->requestHandler($action, $webhook);
13
+ else if ($key == $customKey) // process request eg.: https://store.com/chatbot/chatdata/telegram/key/custom_key_here/ -> process post requests
14
  echo Mage::getModel('chatbot/chatdata')->requestHandler($action, null);
15
  else // error
16
  {
app/locale/en_US/Werules_Chatbot.csv CHANGED
@@ -145,3 +145,124 @@
145
  "This product is not in stock.","This product is not in stock."
146
  "If you want to logout from your account, just send","If you want to logout from your account, just send"
147
  "Please try one of the following commands.","Please try one of the following commands."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  "This product is not in stock.","This product is not in stock."
146
  "If you want to logout from your account, just send","If you want to logout from your account, just send"
147
  "Please try one of the following commands.","Please try one of the following commands."
148
+ "Okay, so you want me to list the categories for you.","Okay, so you want me to list the categories for you."
149
+ "Okay, so you want to search for a product.","Okay, so you want to search for a product."
150
+ "Okay, so you want to login.","Okay, so you want to login."
151
+ "Okay, so you want to list orders.","Okay, so you want to list orders."
152
+ "Okay, so you want to reorder.","Okay, so you want to reorder."
153
+ "Okay, so you want to add a product to the cart.","Okay, so you want to add a product to the cart."
154
+ "Okay, so you want to checkout.","Okay, so you want to checkout."
155
+ "Okay, so you want to clear your cart.","Okay, so you want to clear your cart."
156
+ "Okay, so you want to track your order.","Okay, so you want to track your order."
157
+ "Okay, so you want support.","Okay, so you want support."
158
+ "Okay, so you want to send us an email.","Okay, so you want to send us an email."
159
+ "Okay, so you want to cancel.","Okay, so you want to cancel."
160
+ "Okay, so you want to help.","Okay, so you want to help."
161
+ "Okay, so you want to know more about us.","Okay, so you want to know more about us."
162
+ "Okay, so you want to logout.","Okay, so you want to logout."
163
+ "Okay, so you want to register to our store.","Okay, so you want to register to our store."
164
+ "use your Custom Key (%s) as your Verify Token","use your Custom Key (%s) as your Verify Token"
165
+ "Receive Promotional Messages?","Receive Promotional Messages?"
166
+ "One message sent.","One message sent."
167
+ "%s messages sent.","%s messages sent."
168
+ "No customer available to receive this message.","No customer available to receive this message."
169
+ "Chatbot Settings","Chatbot Settings"
170
+ "Your Secret Key","Your Secret Key"
171
+ "Master Support Group","Master Support Group"
172
+ "Forward Fallback Messages to Support","Forward Fallback Messages to Support"
173
+ "List Empty Categoies","List Empty Categoies"
174
+ "Disable Promotional Messages","Disable Promotional Messages"
175
+ "Enable Log","Enable Log"
176
+ "General Configuration","General Configuration"
177
+ "***Still in Development***","***Still in Development***"
178
+ "Enable witAI Integration","Enable witAI Integration"
179
+ "Enable Confirmation Message","Enable Confirmation Message"
180
+ "witAI API Key","witAI API Key"
181
+ "Acceptable witAI Confidence Percentage","Acceptable witAI Confidence Percentage"
182
+ "Telegram Configurations","Telegram Configurations"
183
+ "Enable Telegram Bot","Enable Telegram Bot"
184
+ "Unavailability Message","Unavailability Message"
185
+ "Telegram Bot API Key","Telegram Bot API Key"
186
+ "Enable Inline Search","Enable Inline Search"
187
+ "Enable Speech Recognition","Enable Speech Recognition"
188
+ "Telegram Support Group ID","Telegram Support Group ID"
189
+ "Telegram Welcome Message","Telegram Welcome Message"
190
+ "Telegram Help Message","Telegram Help Message"
191
+ "Telegram About Message","Telegram About Message"
192
+ "Enable Command Listing On Help","Enable Command Listing On Help"
193
+ "Enable Command Listing On Error","Enable Command Listing On Error"
194
+ "Commands List","Commands List"
195
+ "Enable Default Replies","Enable Default Replies"
196
+ "Default Replies","Default Replies"
197
+ "Fallback Message","Fallback Message"
198
+ "Fallback Times","Fallback Times"
199
+ "Facebook Messenger Configurations","Facebook Messenger Configurations"
200
+ "Enable Messenger Bot","Enable Messenger Bot"
201
+ "Page Access Token","Page Access Token"
202
+ "Messenger Support Chat ID","Messenger Support Chat ID"
203
+ "Messenger Welcome Message","Messenger Welcome Message"
204
+ "Messenger Help Message","Messenger Help Message"
205
+ "Messenger About Message","Messenger About Message"
206
+ "Enable Command Prediction","Enable Command Prediction"
207
+ "Command","Command"
208
+ "Enable Command","Enable Command"
209
+ "Command Code","Command Code"
210
+ "Command Alias (Separated by Comma)","Command Alias (Separated by Comma)"
211
+ "Match Mode","Match Mode"
212
+ "Match Text, Regex or wit.ai entity","Match Text, Regex or wit.ai entity"
213
+ "Match Case","Match Case"
214
+ "Stop Processing","Stop Processing"
215
+ "Similarity (%)","Similarity (%)"
216
+ "Reply Mode","Reply Mode"
217
+ "Reply Text","Reply Text"
218
+ "Command","Command"
219
+ "List Categories","List Categories"
220
+ "Search For Product","Search For Product"
221
+ "Login","Login"
222
+ "List Orders","List Orders"
223
+ "Reorder","Reorder"
224
+ "Add Product to Cart","Add Product to Cart"
225
+ "Checkout on Website","Checkout on Website"
226
+ "Clear Cart","Clear Cart"
227
+ "Track Order Status","Track Order Status"
228
+ "Talk to Support","Talk to Support"
229
+ "Send Email","Send Email"
230
+ "Cancel","Cancel"
231
+ "Help","Help"
232
+ "About","About"
233
+ "Logout","Logout"
234
+ "Register","Register"
235
+ "Similarity","Similarity"
236
+ "Starts With","Starts With"
237
+ "Ends With","Ends With"
238
+ "Contains","Contains"
239
+ "Match RegEx","Match RegEx"
240
+ "Equals to","Equals to"
241
+ "wit.ai","wit.ai"
242
+ "Disable","Disable"
243
+ "Enable","Enable"
244
+ "Telegram Group","Telegram Group"
245
+ "Messenger Group","Messenger Group"
246
+ "Message us","Message us"
247
+ "Enable Facebook Messenger Box","Enable Facebook Messenger Box"
248
+ "Facebook Messenger Box Size","Facebook Messenger Box Size"
249
+ "Telegram Bot Username","Telegram Bot Username"
250
+ "Facebook Page Username","Facebook Page Username"
251
+ "Your order status is","Your order status is"
252
+ "Done. The bot will no longer send messages to this customer.","Done. The bot will no longer send messages to this customer."
253
+ "Done. The bot will now start sending messages to this customer.","Done. The bot will now start sending messages to this customer."
254
+ "Bot respond is disabled for now because the customer is being replied by a human.","Bot respond is disabled for now because the customer is being replied by a human."
255
+ "Enable/Disable Bot Replies","Enable/Disable Bot Replies"
256
+ "List of all admin commands","List of all admin commands"
257
+ "List all admin commands","List all admin commands"
258
+ "Send message to all customers","Send message to all customers"
259
+ "End support for customer","End support for customer"
260
+ "Block customer for entering support mode","Block customer for entering support mode"
261
+ "Enable customer for entering support mode","Enable customer for entering support mode"
262
+ "Disable bot responses","Disable bot responses"
263
+ "Enable bot responses","Enable bot responses"
264
+ "Enable Option to Disable Bot","Enable Option to Disable Bot"
265
+ "Hi","Hi"
266
+ "Enable Referral","Enable Referral"
267
+ "If you want to reorder one of these orders, choose it below, or choose '%s' to list more orders.","If you want to reorder one of these orders, choose it below, or choose '%s' to list more orders."
268
+ "Customer isn't on support.","Customer isn't on support."
app/locale/pt_BR/Werules_Chatbot.csv CHANGED
@@ -145,3 +145,124 @@
145
  "This product is not in stock.","Não temos estoque para esse produto."
146
  "If you want to logout from your account, just send","Se você quiser sair da sua conta, envie"
147
  "Please try one of the following commands.","Por gentileza tente um dos comandos abaixo."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  "This product is not in stock.","Não temos estoque para esse produto."
146
  "If you want to logout from your account, just send","Se você quiser sair da sua conta, envie"
147
  "Please try one of the following commands.","Por gentileza tente um dos comandos abaixo."
148
+ "Okay, so you want me to list the categories for you.","Ok, então você quer ver as categorias da loja."
149
+ "Okay, so you want to search for a product.","Ok, então você quer buscar por produtos."
150
+ "Okay, so you want to login.","Ok, então você quer entrar na sua conta."
151
+ "Okay, so you want to list orders.","Ok, então você quer listar seus pedidos."
152
+ "Okay, so you want to reorder.","Ok, então você quer refazer um pedido."
153
+ "Okay, so you want to add a product to the cart.","Ok, então você quer adicionar um produto no carrinho."
154
+ "Okay, so you want to checkout.","Ok, então você quer finalizar seu pedido."
155
+ "Okay, so you want to clear your cart.","Ok, então você quer limpar seu carrinho."
156
+ "Okay, so you want to track your order.","Ok, então você quer rastrear seu pedido."
157
+ "Okay, so you want support.","Ok, então você quer suporte."
158
+ "Okay, so you want to send us an email.","Ok, então você quer enviar um e-mail."
159
+ "Okay, so you want to cancel.","Ok, então você quer cancelar"
160
+ "Okay, so you want to help.","Ok, então você quer ajuda."
161
+ "Okay, so you want to know more about us.","Ok, então você quer saber mais sobre a nossa empresa."
162
+ "Okay, so you want to logout.","Ok, então você quer sair da sua conta."
163
+ "Okay, so you want to register to our store.","Ok, então você quer se registrar em nossa loja."
164
+ "use your Custom Key (%s) as your Verify Token","use sua Custom Key (%s) como o seu Verify Token"
165
+ "Receive Promotional Messages?","Receber Mensagens Promocionais?"
166
+ "One message sent.","Uma mensagem enviada."
167
+ "%s messages sent.","%s mensagens enviadas."
168
+ "No customer available to receive this message.","Nenhum cliente disponível para receber essa mensagem."
169
+ "Chatbot Settings","Configurações do Chatbot"
170
+ "Your Secret Key","Sua Chave Secreta"
171
+ "Master Support Group","Grupo de Suporte Mestre"
172
+ "Forward Fallback Messages to Support","Encaminhar Mensagens Desconhecidas Para o Suporte"
173
+ "List Empty Categoies","List Empty Categoies"
174
+ "Disable Promotional Messages","Desativar Mensagens Promocionais"
175
+ "Enable Log","Ativar Log"
176
+ "General Configuration","Configurações Gerais"
177
+ "***Still in Development***","***Em Desenvolvimento***"
178
+ "Enable witAI Integration","Ativar Integração Com witAI"
179
+ "Enable Confirmation Message","Ativar Mensagem de Confirmação"
180
+ "witAI API Key","Chave de API do witAI"
181
+ "Acceptable witAI Confidence Percentage","Porcentagem de Confidência Aceitavel Para o witAI"
182
+ "Telegram Configurations","Configurações do Telegram"
183
+ "Enable Telegram Bot","Ativar Telegram Bot"
184
+ "Unavailability Message","Mensagem de Indisponibilidade"
185
+ "Telegram Bot API Key","Chave de API do Telegram Bot"
186
+ "Enable Inline Search","Ativar Buscar Inline"
187
+ "Enable Speech Recognition","Ativar Reconhecimento de Voz"
188
+ "Telegram Support Group ID","ID do Grupo de Suporte do Telegram"
189
+ "Telegram Welcome Message","Mensagem de Bem-Vindo do Telegram"
190
+ "Telegram Help Message","Mensagem de Ajuda do Telegram"
191
+ "Telegram About Message","Mensagem de Sobre do Telegram"
192
+ "Enable Command Listing On Help","Ativar Lista de Comandos na Ajuda"
193
+ "Enable Command Listing On Error","Ativar Lista de Comandos no Erro"
194
+ "Commands List","Lista de Comandos"
195
+ "Enable Default Replies","Ativar Respostas Padrão"
196
+ "Default Replies","Respostas Padrão"
197
+ "Fallback Message","Mensagen Desconhecida"
198
+ "Fallback Times","Quantidade de Erros Para Mandar a Mensagem Desconhecida"
199
+ "Facebook Messenger Configurations","Configurações do Facebook Messenger"
200
+ "Enable Messenger Bot","Ativar Messenger Bot"
201
+ "Page Access Token","Token de Acesso da Página"
202
+ "Messenger Support Chat ID","ID do Chat de Suporte do Messenger"
203
+ "Messenger Welcome Message","Mensagem de Bem-Vindo do Messenger"
204
+ "Messenger Help Message","Mensagem de Ajuda do Messenger"
205
+ "Messenger About Message","Mensagem de Sobre do Messenger"
206
+ "Enable Command Prediction","Ativar Previsão de Comandos"
207
+ "Command","Comando"
208
+ "Enable Command","Ativar Comando"
209
+ "Command Code","Código do Comando"
210
+ "Command Alias (Separated by Comma)","Pseudônimos do Comando (Separados Por Vírgula)"
211
+ "Match Mode","Modo de Combinação"
212
+ "Match Text, Regex or wit.ai entity","Texto, Regex ou Entity do wit.ai"
213
+ "Match Case","Diferenciar Mai/Min"
214
+ "Stop Processing","Parar Processamento"
215
+ "Similarity (%)","Similaridade (%)"
216
+ "Reply Mode","Modo de Resposta"
217
+ "Reply Text","Texto de Resposta"
218
+ "Command","Comando"
219
+ "List Categories","Listar Categorias"
220
+ "Search For Product","Buscar Por Produto"
221
+ "Login","Entrar"
222
+ "List Orders","Listar Pedidos"
223
+ "Reorder","Refazer Pedido"
224
+ "Add Product to Cart","Adicionar Produto ao Carrinho"
225
+ "Checkout on Website","Finalizar Pedido"
226
+ "Clear Cart","Limpar Carrinho"
227
+ "Track Order Status","Rastrear Pedido"
228
+ "Talk to Support","Conversar Com Suporte"
229
+ "Send Email","Enviar E-mail"
230
+ "Cancel","Cancelar"
231
+ "Help","Ajuda"
232
+ "About","Sobre"
233
+ "Logout","Sair"
234
+ "Register","Registrar"
235
+ "Similarity","Similaridade"
236
+ "Starts With","Começar Com"
237
+ "Ends With","Termina Com"
238
+ "Contains","Contém"
239
+ "Match RegEx","RegEx"
240
+ "Equals to","Igual à"
241
+ "wit.ai","wit.ai"
242
+ "Disable","Desativar"
243
+ "Enable","Ativar"
244
+ "Telegram Group","Grupo do Telegram"
245
+ "Messenger Group","Grupo do Messenger"
246
+ "Message us","Enviar Mensagem"
247
+ "Enable Facebook Messenger Box","Ativar Caixa de Chat do Messenger"
248
+ "Facebook Messenger Box Size","Tamanho da Caixa de Chat do Messenger"
249
+ "Telegram Bot Username","Username do Bot do Telegram"
250
+ "Facebook Page Username","Username da Página do Facebook"
251
+ "Your order status is","O status do seu pedido é"
252
+ "Done. The bot will no longer send messages to this customer.","Pronto. O bot não enviará mais mensagens para esse usuário."
253
+ "Done. The bot will now start sending messages to this customer.","Pronto. O bot está ativado para enviar mensagens para esse usuário."
254
+ "Bot respond is disabled for now because the customer is being replied by a human.","Bot respond is disabled for now because the customer is being replied by a human."
255
+ "Enable/Disable Bot Replies","Habilita/desabilita Respostas do Bot"
256
+ "List of all admin commands","Lista de todos os comandos de admin"
257
+ "List all admin commands","Lista todos os comandos de admin"
258
+ "Send message to all customers","Envia mensagem para todos os clientes"
259
+ "End support for customer","Finaliza suporte para o cliente"
260
+ "Block customer for entering support mode","Bloqueia cliente de pedir por suporte"
261
+ "Enable customer for entering support mode","Habilita cliente de pedir por suporte"
262
+ "Disable bot responses","Desabilita respostas do bot"
263
+ "Enable bot responses","Habilita respostas do bot"
264
+ "Enable Option to Disable Bot","Habilita Opção de Desabilitar o Bot"
265
+ "Hi","Olá"
266
+ "Enable Referral","Ativar Referencial"
267
+ "If you want to reorder one of these orders, choose it below, or choose '%s' to list more orders.","Se você quiser refazer um dos pedidos acima, selecione-o abaixo, ou para listar mais selecione '%s'."
268
+ "Customer isn't on support.","O cliente não está em modo de suporte."
js/werules/chatbot/chatbot.js ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function werulesTogleMatchMode(element)
2
+ {
3
+ //debugger;
4
+ var val = element.value;
5
+ var name = element.name;
6
+ if (val == 0)
7
+ {
8
+ name = name.substr(0, name.lastIndexOf("[")) + "[similarity]";
9
+ var target = document.getElementsByName(name);
10
+ target[0].disabled = false;
11
+ }
12
+ else
13
+ {
14
+ name = name.substr(0, name.lastIndexOf("[")) + "[similarity]";
15
+ var target = document.getElementsByName(name);
16
+ target[0].disabled = true;
17
+ }
18
+ }
19
+
20
+ function werulesTogleReplyMode(element)
21
+ {
22
+ //debugger;
23
+ var val = element.value;
24
+ var name = element.name;
25
+ if (val == 0)
26
+ {
27
+ name = name.substr(0, name.lastIndexOf("[")) + "[command_id]";
28
+ var target = document.getElementsByName(name);
29
+ target[0].disabled = true;
30
+ }
31
+ else
32
+ {
33
+ name = name.substr(0, name.lastIndexOf("[")) + "[command_id]";
34
+ var target = document.getElementsByName(name);
35
+ //target[0].classList.remove("werules-disabled");
36
+ //target[0].style = "";
37
+ target[0].disabled = false;
38
+ }
39
+ }
package.xml CHANGED
@@ -1,8 +1,14 @@
1
  <?xml version="1.0"?>
2
- <package><name>Chatbot_Integration</name><version>0.0.9</version><stability>stable</stability><license>OSL</license><channel>community</channel><extends></extends><summary>Chatbot Integration for Telegram and Facebook Messenger.</summary><description>Chatbot (Telegram and Facebook Messenger), with this module you can fully integrate your Magento store with the most popular chat apps in the market. This means that by simply installing this module and a few clicks you can have a new way to show and sell your products to your clients. Very easy to use! Try now, it's FREE.&lt;br&gt;&#xD;
3
  Customers will be able to simply enter into a chat conversation with your bot, and ask him to do things like add products to cart, check order status, send emails to your store, and much much more. Check the features below.&lt;br&gt;&#xD;
4
  &lt;img src="http://i.imgur.com/W3pudq0.gif"/&gt;&lt;br&gt;&#xD;
 
 
 
 
 
5
  &lt;h1&gt;Features&lt;/h1&gt;&lt;br&gt;&#xD;
 
6
  - List store categories&lt;br&gt;&#xD;
7
  - List products from category&lt;br&gt;&#xD;
8
  - Search for products&lt;br&gt;&#xD;
@@ -20,6 +26,7 @@ Customers will be able to simply enter into a chat conversation with your bot, a
20
  - Block a customer for using support mode&lt;br&gt;&#xD;
21
  - Use Telegram to receive and reply messages from Facebook&lt;br&gt;&#xD;
22
  - Set custom reply messages for predetermined text or regex&lt;br&gt;&#xD;
 
23
  &lt;br&gt;&#xD;
24
  &lt;b&gt;Currently not working with Configurable Products and products with custom options&lt;/b&gt;&lt;br&gt;&#xD;
25
  &lt;br&gt;&#xD;
@@ -27,4 +34,4 @@ Customers will be able to simply enter into a chat conversation with your bot, a
27
  1. Unpack the extension ZIP file in your Magento root directory&lt;br&gt;&#xD;
28
  2. Clear the Magento cache: **System &gt; Cache Management**&lt;br&gt;&#xD;
29
  3. Log out the Magento admin and log back in to clear the ACL list&lt;br&gt;&#xD;
30
- 4. Recompile if you are using the Magento Compiler&lt;br&gt;</description><notes>Add option to send custom replies to predetermined messages.</notes><authors><author><name>Pablo</name><user>pablomontenegro</user><email>blopa@werules.com</email></author></authors><date>2017-03-17</date><time>21:33:50</time><compatible></compatible><dependencies><required><php><min>5.2.0</min><max>6.0.0</max></php></required></dependencies><contents><target name="mage"><dir name="app"><dir name="code"><dir name="community"><dir name="Werules"><dir name="Chatbot"><dir name="Block"><file name="Commands.php" hash="ff76acbe888fe51f655b543dcedfefd9"/><file name="CommandsSelect.php" hash="21d792402bb6758700e08885fc0708b5"/><file name="Enable.php" hash="91137cacb5a60f061deefed4ca8e4f91"/><file name="Replies.php" hash="4d0d42024f3db1d404011c24fb1c8e8e"/><file name="ReplyMode.php" hash="627a852f4a4686ec7304528e512f3d4e"/></dir><dir name="controllers"><file name="ChatdataController.php" hash="e646f390c1e5d1b7c69c667913587085"/><file name="IndexController.php" hash="eae277df370ef69ebd75f72691523154"/><file name="SettingsController.php" hash="5c924a7091e535dff538becb6d4dc6fd"/></dir><dir name="etc"><file name="config.xml" hash="7bef96632623db6ec40c914a9f35032d"/><file name="system.xml" hash="5631b31eeff99dca781a4562bd23ee9c"/></dir><dir name="Helper"><file name="Data.php" hash="288462ee4ca74138d88e758a602a6311"/></dir><dir name="Model"><file name="Chatdata.php" hash="dbd39655a9c7bb383e38c1656a51d1c9"/><file name="Chats.php" hash="174b05d4ceb3e98936a9e87f82b23621"/><file name="Enable.php" hash="c8c53bf3b4237632bb74d7721a1159a4"/><file name="Options.php" hash="1a4b5c16044d342106d6f570782f06b0"/><file name="ReplyMode.php" hash="b183ff17102bdc0c2c8b63806487fe7d"/><dir name="Adminhtml"><file name="Serialized.php" hash="270219dca43a25113933afb8c819e8da"/></dir><dir name="Api"><dir name="Facebook"><file name="Handler.php" hash="bcd7fdf2c47dd5c206fe4c448a84f36b"/><file name="Messenger.php" hash="35c4bbe5df4b43f432b56b54b968bdc7"/></dir><dir name="Telegram"><file name="Handler.php" hash="bd3f0854806edaeb3535f9a7ca3f4357"/><file name="Telegram.php" hash="e45a3a7c734cbdfe620d1458a34a604f"/></dir><dir name="witAI"><file name="witAI.php" hash="f751d285f9d93aa8558f6c50c6535327"/></dir></dir><dir name="Mysql4"><file name="Chatdata.php" hash="5b1926048637e2bf7833a8a35643c812"/><dir name="Chatdata"><file name="Collection.php" hash="89bf742cfd5eeaf3704259fd3aedbdce"/></dir></dir></dir><dir name="sql"><dir name="chatbot_setup"><file name="mysql4-install-0.0.9.php" hash="60f58885b022c7165dbd12be3aadee9f"/></dir></dir></dir></dir></dir></dir><dir name="design"><dir name="frontend"><dir name="base"><dir name="default"><dir name="layout"><file name="werules_chatbot.xml" hash="0e79cf08dfd69fe93226c26d2c0b3836"/></dir><dir name="template"><file name="werules_chatbot_config.phtml" hash="6a855bcae6c7bb2b914573b3f3081329"/><file name="werules_chatbot_view.phtml" hash="29a3e82118b1a9df5fc00f72c2a59882"/></dir></dir></dir></dir></dir><dir name="etc"><dir name="modules"><file name="Werules_Chatbot.xml" hash="2d37b23d0f8894ec6627cd4877286019"/></dir></dir><dir name="locale"><dir name="en_US"><file name="Werules_Chatbot.csv" hash="393a4ce32f2eda1e4c1c5c579be5641b"/></dir><dir name="pt_BR"><file name="Werules_Chatbot.csv" hash="90eef98c8e72ee1982abe5a6ee05979d"/></dir><dir name="zh_CN"><file name="Werules_Chatbot.csv" hash="d2f6f680907942c0f55ed7e6b1eabd6d"/></dir><dir name="zh_HK"><file name="Werules_Chatbot.csv" hash="731541b30881e92df2f0c27772e1509c"/></dir><dir name="zh_TW"><file name="Werules_Chatbot.csv" hash="484eff00afdb9caf7928078948233005"/></dir></dir></dir></target></contents></package>
1
  <?xml version="1.0"?>
2
+ <package><name>Chatbot_Integration</name><version>0.0.15</version><stability>stable</stability><license>OSL</license><channel>community</channel><extends></extends><summary>Chatbot Integration for Telegram and Facebook Messenger.</summary><description>Chatbot (Telegram and Facebook Messenger), with this module you can fully integrate your Magento store with the most popular chat apps in the market. This means that by simply installing this module and a few clicks you can have a new way to show and sell your products to your clients. Very easy to use! Try now, it's FREE.&lt;br&gt;&#xD;
3
  Customers will be able to simply enter into a chat conversation with your bot, and ask him to do things like add products to cart, check order status, send emails to your store, and much much more. Check the features below.&lt;br&gt;&#xD;
4
  &lt;img src="http://i.imgur.com/W3pudq0.gif"/&gt;&lt;br&gt;&#xD;
5
+ &lt;br&gt;&#xD;
6
+ Acess our GitHub page to get the latest version, and don't forget to give us a star :D - https://github.com/blopa/Magento-Chatbot&#xD;
7
+ &lt;br&gt;&#xD;
8
+ For a complete documentation on how to use (specially for advanced wit.ai configuration) access &lt;a src="https://blopa.github.io/docs/magento_chatbot/"&gt;Magento Chatbot Documentation&lt;/a&gt;.&#xD;
9
+ &lt;br&gt;&#xD;
10
  &lt;h1&gt;Features&lt;/h1&gt;&lt;br&gt;&#xD;
11
+ - wit.ai integration for NLP&lt;br&gt;&#xD;
12
  - List store categories&lt;br&gt;&#xD;
13
  - List products from category&lt;br&gt;&#xD;
14
  - Search for products&lt;br&gt;&#xD;
26
  - Block a customer for using support mode&lt;br&gt;&#xD;
27
  - Use Telegram to receive and reply messages from Facebook&lt;br&gt;&#xD;
28
  - Set custom reply messages for predetermined text or regex&lt;br&gt;&#xD;
29
+ - Custom fallback messages&lt;br&gt;&#xD;
30
  &lt;br&gt;&#xD;
31
  &lt;b&gt;Currently not working with Configurable Products and products with custom options&lt;/b&gt;&lt;br&gt;&#xD;
32
  &lt;br&gt;&#xD;
34
  1. Unpack the extension ZIP file in your Magento root directory&lt;br&gt;&#xD;
35
  2. Clear the Magento cache: **System &gt; Cache Management**&lt;br&gt;&#xD;
36
  3. Log out the Magento admin and log back in to clear the ACL list&lt;br&gt;&#xD;
37
+ 4. Recompile if you are using the Magento Compiler&lt;br&gt;</description><notes>First stable version.</notes><authors><author><name>Pablo</name><user>pablomontenegro</user><email>blopa@werules.com</email></author></authors><date>2017-05-13</date><time>12:27:36</time><compatible></compatible><dependencies><required><php><min>5.2.0</min><max>6.0.0</max></php></required></dependencies><contents><target name="mage"><dir name="app"><dir name="code"><dir name="community"><dir name="Werules"><dir name="Chatbot"><dir name="Block"><file name="Commands.php" hash="5eee0cec904a3a3a3a278d2c9ded0c39"/><file name="CommandsSelect.php" hash="21d792402bb6758700e08885fc0708b5"/><file name="Enable.php" hash="91137cacb5a60f061deefed4ca8e4f91"/><file name="MatchMode.php" hash="263c74d8b7263267d44f55c49f73650d"/><file name="Messenger.php" hash="0ae4c0435d479b5fd3391850f4768998"/><file name="Replies.php" hash="fd6f1d661613dafb5f651ce482ed57c7"/><file name="ReplyMode.php" hash="627a852f4a4686ec7304528e512f3d4e"/></dir><dir name="controllers"><file name="ChatdataController.php" hash="e646f390c1e5d1b7c69c667913587085"/><file name="IndexController.php" hash="eae277df370ef69ebd75f72691523154"/><file name="SettingsController.php" hash="0c2dc91d91cacb422d73a3bfa287201a"/></dir><dir name="etc"><file name="config.xml" hash="7b2b61721a1c469e2719f9ffd072842e"/><file name="system.xml" hash="d52591e0efef9f663eac46a947a600ba"/></dir><dir name="Helper"><file name="Data.php" hash="0b832ddab5e6b3bcabe7f06e798fca24"/></dir><dir name="Model"><file name="Chatdata.php" hash="c9face4e2f38e57ee1f90293695bc3b7"/><file name="Chats.php" hash="174b05d4ceb3e98936a9e87f82b23621"/><file name="Enable.php" hash="c8c53bf3b4237632bb74d7721a1159a4"/><file name="MatchMode.php" hash="feafa9d7193007784f94728d8f26c54a"/><file name="Options.php" hash="c722dedd2c50878bd1b51adfba86ec07"/><file name="ReplyMode.php" hash="33bd10ebe655e81d5279f6fdb4d03113"/><dir name="Adminhtml"><file name="Serialized.php" hash="270219dca43a25113933afb8c819e8da"/></dir><dir name="Api"><dir name="Facebook"><file name="Handler.php" hash="3924a40b83b00c6998c84a45ff1e703c"/><file name="Messenger.php" hash="8f7cf10f18eb82a47472e178f09d69d8"/></dir><dir name="Telegram"><file name="Handler.php" hash="78d591b40d521113e44556c91aa29188"/><file name="Telegram.php" hash="e45a3a7c734cbdfe620d1458a34a604f"/></dir><dir name="witAI"><file name="witAI.php" hash="1552c5e56ed1744f38a3e84ef51ec054"/></dir></dir><dir name="Mysql4"><file name="Chatdata.php" hash="3a7ca7e5f663c9f81ff2b73826f29d0e"/><dir name="Chatdata"><file name="Collection.php" hash="89bf742cfd5eeaf3704259fd3aedbdce"/></dir></dir></dir><dir name="sql"><dir name="chatbot_setup"><file name="mysql4-install-0.0.15.php" hash="3decf9438852a6894e4efc7988a18f62"/><file name="mysql4-upgrade-0.0.9-0.0.15.php" hash="9485039af19d2c9ede3e2a4ca3bc1a99"/></dir></dir></dir></dir></dir></dir><dir name="design"><dir name="adminhtml"><dir name="default"><dir name="default"><dir name="layout"><file name="werules_chatbot.xml" hash="1751bd620ac7e86475e9142515371c79"/></dir></dir></dir></dir><dir name="frontend"><dir name="base"><dir name="default"><dir name="layout"><file name="werules_chatbot.xml" hash="986682a2301edbac06fd0f579205779a"/></dir><dir name="template"><file name="werules_chatbot_config.phtml" hash="63dd550fbba009663e77b041cc7c9474"/><file name="werules_chatbot_messenger_box.phtml" hash="358a9c1653ea1342e4f60fbb5a053b7d"/><file name="werules_chatbot_view.phtml" hash="7c307fa35a78db3032a1abc1746bc812"/></dir></dir></dir></dir></dir><dir name="etc"><dir name="modules"><file name="Werules_Chatbot.xml" hash="2d37b23d0f8894ec6627cd4877286019"/></dir></dir><dir name="locale"><dir name="en_US"><file name="Werules_Chatbot.csv" hash="2d546519be0686ca652b6b1fd69256bb"/></dir><dir name="pt_BR"><file name="Werules_Chatbot.csv" hash="4218f4d85a16246d00e8dff7ca000906"/></dir><dir name="zh_CN"><file name="Werules_Chatbot.csv" hash="d2f6f680907942c0f55ed7e6b1eabd6d"/></dir><dir name="zh_HK"><file name="Werules_Chatbot.csv" hash="731541b30881e92df2f0c27772e1509c"/></dir><dir name="zh_TW"><file name="Werules_Chatbot.csv" hash="484eff00afdb9caf7928078948233005"/></dir></dir></dir><dir name="js"><dir name="werules"><dir name="chatbot"><file name="chatbot.js" hash="533eee37f30ebb348aa59d4a8bdeafaf"/></dir></dir></dir><dir name="skin"><dir name="adminhtml"><dir name="base"><dir name="default"><dir name="css"><dir name="werules_chatbot"><file name="chatbot.css" hash="5af6b8285ee43e603b309dea05c8118e"/></dir></dir></dir></dir></dir><dir name="frontend"><dir name="base"><dir name="default"><dir name="images"><dir name="werules_chatbot"><file name="messenger-icon.png" hash="54e076fdd7d3be35ba011b548ce7671c"/></dir></dir></dir></dir></dir></dir></target></contents></package>
skin/adminhtml/base/default/css/werules_chatbot/chatbot.css ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ .werules-disabled-input{
2
+ pointer-events: none;
3
+ background-color: #ebebe4;
4
+ color: #545454;
5
+ }
6
+
7
+ .werules-disabled-select{
8
+ pointer-events: none;
9
+ background-color: #FFFFFF;
10
+ color: #808080;
11
+ }
skin/frontend/base/default/images/werules_chatbot/messenger-icon.png ADDED
Binary file