Chatbot_Integration - Version 0.0.5

Version Notes

Add option to send custom replies to predetermined messages.

Download this release

Release Info

Developer Pablo
Extension Chatbot_Integration
Version 0.0.5
Comparing to
See all releases


Version 0.0.5

Files changed (29) hide show
  1. app/code/community/Werules/Chatbot/Block/Commands.php +45 -0
  2. app/code/community/Werules/Chatbot/Block/CommandsSelect.php +22 -0
  3. app/code/community/Werules/Chatbot/Block/Enable.php +22 -0
  4. app/code/community/Werules/Chatbot/Block/Replies.php +52 -0
  5. app/code/community/Werules/Chatbot/Helper/Data.php +5 -0
  6. app/code/community/Werules/Chatbot/Model/Adminhtml/Serialized.php +35 -0
  7. app/code/community/Werules/Chatbot/Model/Api/Facebook/Handler.php +1292 -0
  8. app/code/community/Werules/Chatbot/Model/Api/Facebook/Messenger.php +259 -0
  9. app/code/community/Werules/Chatbot/Model/Api/Telegram/Handler.php +1122 -0
  10. app/code/community/Werules/Chatbot/Model/Api/Telegram/Telegram.php +1570 -0
  11. app/code/community/Werules/Chatbot/Model/Api/witAI/witAI.php +29 -0
  12. app/code/community/Werules/Chatbot/Model/Chatdata.php +598 -0
  13. app/code/community/Werules/Chatbot/Model/Chats.php +19 -0
  14. app/code/community/Werules/Chatbot/Model/Enable.php +16 -0
  15. app/code/community/Werules/Chatbot/Model/Mysql4/Chatdata.php +8 -0
  16. app/code/community/Werules/Chatbot/Model/Mysql4/Chatdata/Collection.php +7 -0
  17. app/code/community/Werules/Chatbot/Model/Options.php +30 -0
  18. app/code/community/Werules/Chatbot/controllers/ChatdataController.php +23 -0
  19. app/code/community/Werules/Chatbot/controllers/IndexController.php +8 -0
  20. app/code/community/Werules/Chatbot/controllers/SettingsController.php +166 -0
  21. app/code/community/Werules/Chatbot/etc/config.xml +104 -0
  22. app/code/community/Werules/Chatbot/etc/system.xml +373 -0
  23. app/code/community/Werules/Chatbot/sql/chatbot_setup/mysql4-install-0.0.5.php +46 -0
  24. app/design/frontend/base/default/layout/werules_chatbot.xml +47 -0
  25. app/design/frontend/base/default/template/werules_chatbot_config.phtml +96 -0
  26. app/design/frontend/base/default/template/werules_chatbot_view.phtml +9 -0
  27. app/etc/modules/Werules_Chatbot.xml +9 -0
  28. app/locale/pt_BR/Werules_Chatbot.csv +135 -0
  29. package.xml +28 -0
app/code/community/Werules/Chatbot/Block/Commands.php ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Werules_Chatbot_Block_Commands extends Mage_Adminhtml_Block_System_Config_Form_Field_Array_Abstract
3
+ {
4
+ protected $_itemRenderer;
5
+
6
+ public function _prepareToRender()
7
+ {
8
+ $this->addColumn('command_id', array(
9
+ 'label' => Mage::helper('core')->__('Command'),
10
+ 'renderer' => $this->_getRenderer()
11
+ ));
12
+ $this->addColumn('command_code', array(
13
+ 'label' => Mage::helper('core')->__('Command Code'),
14
+ 'style' => 'width: 150px'
15
+ ));
16
+ $this->addColumn('command_alias_list', array(
17
+ 'label' => Mage::helper('core')->__('Alias'),
18
+ 'style' => 'width: 250px'
19
+ ));
20
+
21
+ $this->_addAfter = false;
22
+ $this->_addButtonLabel = Mage::helper('core')->__('Add');
23
+ }
24
+
25
+ protected function _getRenderer()
26
+ {
27
+ if (!$this->_itemRenderer)
28
+ {
29
+ $this->_itemRenderer = $this->getLayout()->createBlock(
30
+ 'werules_chatbot/commandsSelect',
31
+ '',
32
+ array('is_render_to_js_template' => true)
33
+ )->setExtraParams("style='width: auto;'");
34
+ }
35
+ return $this->_itemRenderer;
36
+ }
37
+
38
+ protected function _prepareArrayRow(Varien_Object $row)
39
+ {
40
+ $row->setData(
41
+ 'option_extra_attr_' . $this->_getRenderer()->calcOptionHash($row->getData('command_id')),
42
+ 'selected="selected"'
43
+ );
44
+ }
45
+ }
app/code/community/Werules/Chatbot/Block/CommandsSelect.php ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Werules_Chatbot_Block_CommandsSelect extends Mage_Core_Block_Html_Select
3
+ {
4
+ public function _toHtml()
5
+ {
6
+ $options = Mage::getSingleton('chatbot/options')->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/Enable.php ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Werules_Chatbot_Block_Enable extends Mage_Core_Block_Html_Select
3
+ {
4
+ public function _toHtml()
5
+ {
6
+ $options = Mage::getSingleton('chatbot/enable')->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/Replies.php ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Werules_Chatbot_Block_Replies extends Mage_Adminhtml_Block_System_Config_Form_Field_Array_Abstract
3
+ {
4
+ protected $_itemRenderer;
5
+
6
+ public function _prepareToRender()
7
+ {
8
+ $this->addColumn('catch_phrase', array(
9
+ 'label' => Mage::helper('core')->__('Phrase'),
10
+ 'style' => 'width: 250px'
11
+ ));
12
+ $this->addColumn('reply_phrase', array(
13
+ 'label' => Mage::helper('core')->__('Reply'),
14
+ 'style' => 'width: 250px'
15
+ ));
16
+ $this->addColumn('similarity', array(
17
+ 'label' => Mage::helper('core')->__('Similarity (%)'),
18
+ 'style' => 'width: 50px',
19
+ //'type' => 'number',
20
+ //'maxlength' => '3',
21
+ 'class' => 'input-number validate-number validate-number-range number-range-1-100'
22
+ ));
23
+ $this->addColumn('match_case', array(
24
+ 'label' => Mage::helper('core')->__('Match Case'),
25
+ 'renderer' => $this->_getRenderer()
26
+ ));
27
+
28
+ $this->_addAfter = false;
29
+ $this->_addButtonLabel = Mage::helper('core')->__('Add');
30
+ }
31
+
32
+ protected function _getRenderer()
33
+ {
34
+ if (!$this->_itemRenderer)
35
+ {
36
+ $this->_itemRenderer = $this->getLayout()->createBlock(
37
+ 'werules_chatbot/enable',
38
+ '',
39
+ array('is_render_to_js_template' => true)
40
+ )->setExtraParams("style='width: auto;'");
41
+ }
42
+ return $this->_itemRenderer;
43
+ }
44
+
45
+ protected function _prepareArrayRow(Varien_Object $row)
46
+ {
47
+ $row->setData(
48
+ 'option_extra_attr_' . $this->_getRenderer()->calcOptionHash($row->getData('match_case')),
49
+ 'selected="selected"'
50
+ );
51
+ }
52
+ }
app/code/community/Werules/Chatbot/Helper/Data.php ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
1
+ <?php
2
+ class Werules_Chatbot_Helper_Data extends Mage_Core_Helper_Abstract
3
+ {
4
+
5
+ }
app/code/community/Werules/Chatbot/Model/Adminhtml/Serialized.php ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Werules_Chatbot_Model_Adminhtml_Serialized extends Mage_Adminhtml_Model_System_Config_Backend_Serialized
4
+ {
5
+ protected function _afterLoad()
6
+ {
7
+ if (!is_array($this->getValue())) {
8
+ $serializedValue = $this->getValue();
9
+ $unserializedValue = false;
10
+ if (!empty($serializedValue)) {
11
+ try {
12
+ $unserializedValue = Mage::helper('core/unserializeArray')
13
+ ->unserialize((string)$serializedValue); // fix magento unserializing bug
14
+ } catch (Exception $e) {
15
+ Mage::logException($e);
16
+ }
17
+ }
18
+ $this->setValue($unserializedValue);
19
+ }
20
+ }
21
+
22
+ protected function _beforeSave()
23
+ {
24
+ $value = $this->getValue();
25
+ if (is_array($value)) {
26
+ unset($value['__empty']);
27
+ }
28
+ $this->setValue($value);
29
+
30
+ if (is_array($this->getValue()))
31
+ {
32
+ $this->setValue(serialize($this->getValue()));
33
+ }
34
+ }
35
+ }
app/code/community/Werules/Chatbot/Model/Api/Facebook/Handler.php ADDED
@@ -0,0 +1,1292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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');
55
+ $verify = $facebook->verifyWebhook($hubToken);
56
+ if ($verify)
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
+ $user_data = $facebook->UserData($chatId);
99
+ $username = null;
100
+ if (!empty($user_data))
101
+ $username = $user_data['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
+ // handle default replies
127
+ if ($enableReplies == "1")
128
+ {
129
+ $defaultReplies = Mage::getStoreConfig('chatbot_enable/facebook_config/default_replies');
130
+ if ($defaultReplies)
131
+ {
132
+ $replies = unserialize($defaultReplies);
133
+ if (is_array($replies))
134
+ {
135
+ foreach($replies as $reply)
136
+ {
137
+ $match = $reply["catch_phrase"];
138
+ $similarity = $reply["similarity"];
139
+ if (is_numeric($similarity))
140
+ {
141
+ if (!($similarity >= 1 && $similarity <= 100))
142
+ $similarity = 100;
143
+ }
144
+ else
145
+ $similarity = 100;
146
+
147
+ if ($reply["match_case"] == "0")
148
+ {
149
+ $match = strtolower($match);
150
+ $text = strtolower($text);
151
+ }
152
+
153
+ similar_text($text, $match, $percent);
154
+ if ($percent >= $similarity)
155
+ {
156
+ $facebook->sendMessage($chatId, $reply["reply_phrase"]);
157
+ return $facebook->respondSuccess();
158
+ break; // probably useless
159
+ }
160
+ }
161
+ }
162
+ }
163
+ }
164
+
165
+ // payload handler, may change the conversation state
166
+ if ($chatdata->getFacebookConvState() == $chatdata->_listProductsState || $chatdata->getFacebookConvState() == $chatdata->_listOrdersState) // listing products
167
+ {
168
+ if ($chatdata->checkCommandWithValue($text, $listMoreCategories))
169
+ {
170
+ if ($chatdata->updateChatdata('facebook_conv_state', $chatdata->_listCategoriesState))
171
+ {
172
+ $value = $this->getCommandValue($text, $listMoreCategories);
173
+ $arr = explode(",", $value);
174
+ $text = $arr[0];
175
+ $showMore = (int)$arr[1];
176
+ }
177
+ }
178
+ else if ($chatdata->checkCommandWithValue($text, $listMoreSearch))
179
+ {
180
+ if ($chatdata->updateChatdata('facebook_conv_state', $chatdata->_searchState))
181
+ {
182
+ $value = $this->getCommandValue($text, $listMoreSearch);
183
+ $arr = explode(",", $value);
184
+ $text = $arr[0];
185
+ $showMore = (int)$arr[1];
186
+ }
187
+ }
188
+ else if ($chatdata->checkCommandWithValue($text, $listMoreOrders))
189
+ {
190
+ if ($chatdata->updateChatdata('facebook_conv_state', $chatdata->_listOrdersState))
191
+ {
192
+ $value = $this->getCommandValue($text, $listMoreOrders);
193
+ $showMore = (int)$value; // get where listing stopped
194
+ $moreOrders = true;
195
+ }
196
+ }
197
+ // else
198
+ // $chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState);
199
+ }
200
+
201
+ // instances conversation state
202
+ $conversationState = $chatdata->getFacebookConvState();
203
+
204
+ // mage helper
205
+ $magehelper = Mage::helper('core');
206
+
207
+ // handle admin stuff
208
+ //$isAdmin = $chatdata->getIsAdmin();
209
+ // if it's the admin chat id
210
+ if ($chatId == $supportGroupId)// || $isAdmin == "1")
211
+ {
212
+ // if ($isAdmin == "0") // set user as admin
213
+ // $chatdata->updateChatdata('is_admin', "1");
214
+
215
+ if ($conversationState == $chatdata->_replyToSupportMessageState) // check if admin is replying to a customer
216
+ {
217
+ $customerChatId = $chatdata->getFacebookSupportReplyChatId(); // get customer chat id
218
+ if (!empty($customerChatId))
219
+ {
220
+ $chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState); // set admin to _startState
221
+ $customerData = Mage::getModel('chatbot/chatdata')->load($customerChatId, 'facebook_chat_id'); // load chatdata model
222
+
223
+ if ($customerData->getFacebookConvState() != $chatdata->_supportState) // if user isn't on support, switch to support
224
+ {
225
+ // TODO IMPORTANT remember to switch off all other supports
226
+ $customerData->updateChatdata('facebook_conv_state', $chatdata->_supportState);
227
+ $facebook->sendMessage($customerChatId, $magehelper->__("You're now on support mode."));
228
+ }
229
+ $facebook->sendMessage($customerChatId, $magehelper->__("Message from support") . ":\n" . $text); // send message to customer TODO
230
+ $facebook->sendMessage($chatId, $magehelper->__("Message sent."));
231
+ }
232
+ return $facebook->respondSuccess();
233
+ }
234
+ else if ($chatdata->checkCommandWithValue($text, $chatdata->_admSendMessage2AllCmd))
235
+ {
236
+ $message = trim($chatdata->getCommandValue($text, $chatdata->_admSendMessage2AllCmd));
237
+ if (!empty($message))
238
+ {
239
+ $chatbotcollection = Mage::getModel('chatbot/chatdata')->getCollection();
240
+ foreach($chatbotcollection as $chatbot)
241
+ {
242
+ $fbChatId = $chatbot->getFacebookChatId();
243
+ if ($fbChatId)
244
+ $facebook->sendMessage($fbChatId, $message); // $magehelper->__("Message from support") . ":\n" .
245
+ }
246
+ $facebook->sendMessage($chatId, $magehelper->__("Message sent."));
247
+ }
248
+ else
249
+ $facebook->sendMessage($chatId, $magehelper->__("Please use") . ' "' . $chatdata->_admSendMessage2AllCmd . " " . $magehelper->__("your message here.") . '"');
250
+ }
251
+ else if ($isPayload)
252
+ {
253
+ if ($chatdata->checkCommandWithValue($text, $chatdata->_admEndSupportCmd)) // finish customer support
254
+ {
255
+ $customerChatId = trim($chatdata->getCommandValue($text, $chatdata->_admEndSupportCmd)); // get customer chatId from payload
256
+ $customerData = Mage::getModel('chatbot/chatdata')->load($customerChatId, 'facebook_chat_id'); // load chatdata model
257
+ $customerData->updateChatdata('facebook_conv_state', $chatdata->_startState); // update conversation state
258
+
259
+ $facebook->sendMessage($chatId, $magehelper->__("Done. The customer is no longer on support."));
260
+ $facebook->sendMessage($customerChatId, $magehelper->__("Support ended."));
261
+ }
262
+ else if ($chatdata->checkCommandWithValue($text, $chatdata->_admBlockSupportCmd)) // block user from using support
263
+ {
264
+ $customerChatId = trim($chatdata->getCommandValue($text, $chatdata->_admBlockSupportCmd)); // get customer chatId from payload
265
+ $customerData = Mage::getModel('chatbot/chatdata')->load($customerChatId, 'facebook_chat_id'); // load chatdata model
266
+ if ($customerData->getEnableSupport() == "1")
267
+ {
268
+ $customerData->updateChatdata('enable_support', "0"); // disable support
269
+ $facebook->sendMessage($chatId, $magehelper->__("Done. The customer is no longer able to enter support."));
270
+ }
271
+ else //if ($customerData->getEnableSupport() == "0")
272
+ {
273
+ $customerData->updateChatdata('enable_support', "1"); // enable support
274
+ $facebook->sendMessage($chatId, $magehelper->__("Done. The customer is now able to enter support."));
275
+ }
276
+
277
+ }
278
+ else if ($chatdata->checkCommandWithValue($text, $replyToCustomerMessage))
279
+ {
280
+ $customerChatId = trim($chatdata->getCommandValue($text, $replyToCustomerMessage)); // get customer chatId from payload
281
+ $chatdata->updateChatdata('facebook_support_reply_chat_id', $customerChatId);
282
+ $chatdata->updateChatdata('facebook_conv_state', $chatdata->_replyToSupportMessageState);
283
+
284
+ $facebook->sendMessage($chatId, $magehelper->__("Ok, send me the message and I'll forward it to the customer."));
285
+ }
286
+ else if ($chatdata->checkCommand($text, $chatdata->_admSendMessage2AllCmd)) // TODO
287
+ {
288
+
289
+ }
290
+
291
+ return $facebook->respondSuccess();
292
+ }
293
+ }
294
+
295
+ if ($chatdata->getIsLogged() == "1") // check if customer is logged
296
+ {
297
+ if (Mage::getModel('customer/customer')->load((int)$chatdata->getCustomerId())->getId()) // if is a valid customer id
298
+ {
299
+ if ($chatdata->getEnableFacebook() != "1")
300
+ {
301
+ $facebook->sendMessage($chatId, $magehelper->__("To talk with me, please enable Facebook Messenger on your account chatbot settings."));
302
+ $facebook->sendChatAction($chatId, "typing_off");
303
+ return $facebook->respondSuccess();
304
+ }
305
+ }
306
+ }
307
+
308
+ // user isnt registred HERE
309
+ if (is_null($chatdata->getFacebookChatId())) // if user isn't registred
310
+ {
311
+ $message = Mage::getStoreConfig('chatbot_enable/facebook_config/facebook_welcome_msg'); // TODO
312
+ if ($message) // TODO
313
+ $facebook->sendMessage($chatId, $message);
314
+ try
315
+ {
316
+ $hash = substr(md5(uniqid($chatId, true)), 0, 150); // TODO
317
+ $chatdata // using magento model to insert data into database the proper way
318
+ ->setFacebookChatId($chatId)
319
+ ->setHashKey($hash) // TODO
320
+ ->setCreatedAt(date('Y-m-d H:i:s'))
321
+ ->save();
322
+ //$chatdata->updateChatdata('facebook_chat_id', $chat_id);
323
+ //$chatdata->updateChatdata('hash_key', $hash);
324
+ }
325
+ catch (Exception $e)
326
+ {
327
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage); // TODO
328
+ }
329
+ $facebook->sendChatAction($chatId, "typing_off");
330
+ return $facebook->respondSuccess();
331
+ }
332
+
333
+ // init commands
334
+ //$chatdata->_startCmd['command'] = "Start";
335
+ $chatdata->_listCategoriesCmd = $chatdata->getCommandString(1);
336
+ $chatdata->_searchCmd = $chatdata->getCommandString(2);
337
+ $chatdata->_loginCmd = $chatdata->getCommandString(3);
338
+ $chatdata->_listOrdersCmd = $chatdata->getCommandString(4);
339
+ $chatdata->_reorderCmd = $chatdata->getCommandString(5);
340
+ $chatdata->_add2CartCmd = $chatdata->getCommandString(6);
341
+ $chatdata->_checkoutCmd = $chatdata->getCommandString(7);
342
+ $chatdata->_clearCartCmd = $chatdata->getCommandString(8);
343
+ $chatdata->_trackOrderCmd = $chatdata->getCommandString(9);
344
+ $chatdata->_supportCmd = $chatdata->getCommandString(10);
345
+ $chatdata->_sendEmailCmd = $chatdata->getCommandString(11);
346
+ $chatdata->_cancelCmd = $chatdata->getCommandString(12);
347
+ $chatdata->_helpCmd = $chatdata->getCommandString(13);
348
+ $chatdata->_aboutCmd = $chatdata->getCommandString(14);
349
+ $chatdata->_logoutCmd = $chatdata->getCommandString(15);
350
+ if (!$chatdata->_cancelCmd['command']) $chatdata->_cancelCmd['command'] = "cancel"; // it must always have a cancel command
351
+
352
+ // init messages
353
+ $chatdata->_errorMessage = $magehelper->__("Something went wrong, please try again.");
354
+ $chatdata->_cancelMessage = $magehelper->__("To cancel, send") . ' "' . $chatdata->_cancelCmd['command'] . '"';
355
+ $chatdata->_canceledMessage = $magehelper->__("Ok, canceled.");
356
+ $chatdata->_loginFirstMessage = $magehelper->__("Please login first.");
357
+ array_push($chatdata->_positiveMessages, $magehelper->__("Ok"), $magehelper->__("Okay"), $magehelper->__("Cool"), $magehelper->__("Awesome"));
358
+ // $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)]
359
+
360
+ if ($enablePredict == "1" && !$isPayload) // prediction is enabled and itsn't payload
361
+ {
362
+ if ($conversationState == $chatdata->_startState)
363
+ {
364
+ $cmdarray = array(
365
+ $chatdata->_startCmd['command'],
366
+ $chatdata->_listCategoriesCmd['command'],
367
+ $chatdata->_searchCmd['command'],
368
+ $chatdata->_loginCmd['command'],
369
+ $chatdata->_listOrdersCmd['command'],
370
+ $chatdata->_reorderCmd['command'],
371
+ $chatdata->_add2CartCmd['command'],
372
+ $chatdata->_checkoutCmd['command'],
373
+ $chatdata->_clearCartCmd['command'],
374
+ $chatdata->_trackOrderCmd['command'],
375
+ $chatdata->_supportCmd['command'],
376
+ $chatdata->_sendEmailCmd['command'],
377
+ $chatdata->_cancelCmd['command'],
378
+ $chatdata->_helpCmd['command'],
379
+ $chatdata->_aboutCmd['command'],
380
+ $chatdata->_logoutCmd['command']
381
+ );
382
+
383
+ foreach ($cmdarray as $cmd)
384
+ {
385
+ if (strpos($text, $cmd) !== false)
386
+ {
387
+ $text = $cmd;
388
+ break;
389
+ }
390
+ }
391
+ }
392
+ }
393
+
394
+ // cancel command
395
+ if ($chatdata->checkCommand($text, $chatdata->_cancelCmd))
396
+ {
397
+ if ($conversationState == $chatdata->_listCategoriesState)
398
+ {
399
+ $message = $chatdata->_canceledMessage;
400
+ }
401
+ else if ($conversationState == $chatdata->_supportState)
402
+ {
403
+ $message = $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("exiting support mode.");
404
+ }
405
+ else if ($conversationState == $chatdata->_searchState)
406
+ {
407
+ $message = $chatdata->_canceledMessage;
408
+ }
409
+ else if ($conversationState == $chatdata->_sendEmailState)
410
+ {
411
+ $message = $chatdata->_canceledMessage;
412
+ }
413
+ else if ($conversationState == $chatdata->_listProductsState)
414
+ {
415
+ $message = $chatdata->_canceledMessage;
416
+ }
417
+ else if ($conversationState == $chatdata->_listOrdersState)
418
+ {
419
+ $message = $chatdata->_canceledMessage;
420
+ }
421
+ else
422
+ $message = $chatdata->_errorMessage;
423
+
424
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState))
425
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
426
+ else
427
+ $facebook->sendMessage($chatId, $message);
428
+ $facebook->sendChatAction($chatId, "typing_off");
429
+ return $facebook->respondSuccess();
430
+ }
431
+
432
+ // add2cart commands
433
+ if ($chatdata->checkCommandWithValue($text, $chatdata->_add2CartCmd['command'])) // ignore alias
434
+ {
435
+ $errorFlag = false;
436
+ $cmdvalue = $chatdata->getCommandValue($text, $chatdata->_add2CartCmd['command']);
437
+ if ($cmdvalue) // TODO
438
+ {
439
+ $productName = Mage::getModel('catalog/product')->load($cmdvalue)->getName();
440
+ if (empty($productName))
441
+ $productName = $magehelper->__("this product");
442
+ $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("adding %s to your cart.", $productName));
443
+ $facebook->sendChatAction($chatId, "typing_on");
444
+ if ($chatdata->addProd2Cart($cmdvalue))
445
+ $facebook->sendMessage($chatId, $magehelper->__("Added. To checkout send") . ' "' . $chatdata->_checkoutCmd['command'] . '"');
446
+ else
447
+ $errorFlag = true;
448
+ }
449
+ else
450
+ $errorFlag = true;
451
+
452
+ if ($errorFlag)
453
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
454
+ return $facebook->respondSuccess();
455
+ }
456
+
457
+ // help command
458
+ if ($chatdata->checkCommand($text, $chatdata->_helpCmd))
459
+ {
460
+ $message = Mage::getStoreConfig('chatbot_enable/facebook_config/facebook_help_msg'); // TODO
461
+ if ($message) // TODO
462
+ $facebook->sendMessage($chatId, $message);
463
+ $facebook->sendChatAction($chatId, "typing_off");
464
+ return $facebook->respondSuccess();
465
+ }
466
+
467
+ // about command
468
+ if ($chatdata->checkCommand($text, $chatdata->_aboutCmd))
469
+ {
470
+ $message = Mage::getStoreConfig('chatbot_enable/facebook_config/facebook_about_msg'); // TODO
471
+ $cmdListing = Mage::getStoreConfig('chatbot_enable/facebook_config/enable_command_list');
472
+ if ($cmdListing == 1)
473
+ {
474
+ $message .= "\n\n" . $magehelper->__("Command list") . ":\n";
475
+ $replies = array(); // quick replies limit is 10 options
476
+ // just getting the command string, not checking the command
477
+ if ($chatdata->_listCategoriesCmd['command'])
478
+ {
479
+ array_push($replies, array('content_type' => 'text', 'title' => $chatdata->_listCategoriesCmd['command'], 'payload' => str_replace(' ', '_', $chatdata->_listCategoriesCmd['command'])));
480
+ $message .= $chatdata->_listCategoriesCmd['command'] . " - " . $magehelper->__("List store categories.") . "\n";
481
+ }
482
+ if ($chatdata->_searchCmd['command'])
483
+ {
484
+ array_push($replies, array('content_type' => 'text', 'title' => $chatdata->_searchCmd['command'], 'payload' => str_replace(' ', '_', $chatdata->_searchCmd['command'])));
485
+ $message .= $chatdata->_searchCmd['command'] . " - " . $magehelper->__("Search for products.") . "\n";
486
+ }
487
+ if ($chatdata->_loginCmd['command'])
488
+ {
489
+ array_push($replies, array('content_type' => 'text', 'title' => $chatdata->_loginCmd['command'], 'payload' => str_replace(' ', '_', $chatdata->_loginCmd['command'])));
490
+ $message .= $chatdata->_loginCmd['command'] . " - " . $magehelper->__("Login into your account.") . "\n";
491
+ }
492
+ if ($chatdata->_logoutCmd['command'])
493
+ {
494
+ array_push($replies, array('content_type' => 'text', 'title' => $chatdata->_logoutCmd['command'], 'payload' => str_replace(' ', '_', $chatdata->_loginCmd['command'])));
495
+ $message .= $chatdata->_logoutCmd['command'] . " - " . $magehelper->__("Logout from your account.") . "\n";
496
+ }
497
+ if ($chatdata->_listOrdersCmd['command'])
498
+ {
499
+ array_push($replies, array('content_type' => 'text', 'title' => $chatdata->_listOrdersCmd['command'], 'payload' => str_replace(' ', '_', $chatdata->_listOrdersCmd['command'])));
500
+ $message .= $chatdata->_listOrdersCmd['command'] . " - " . $magehelper->__("List your personal orders.") . "\n";
501
+ }
502
+ //$message .= $chatdata->_reorderCmd['command'] . " - " . $magehelper->__("Reorder a order.") . "\n";
503
+ //$message .= $chatdata->_add2CartCmd['command'] . " - " . $magehelper->__("Add product to cart.") . "\n";
504
+ if ($chatdata->_checkoutCmd['command'])
505
+ {
506
+ array_push($replies, array('content_type' => 'text', 'title' => $chatdata->_checkoutCmd['command'], 'payload' => str_replace(' ', '_', $chatdata->_checkoutCmd['command'])));
507
+ $message .= $chatdata->_checkoutCmd['command'] . " - " . $magehelper->__("Checkout your order.") . "\n";
508
+ }
509
+ if ($chatdata->_clearCartCmd['command'])
510
+ {
511
+ array_push($replies, array('content_type' => 'text', 'title' => $chatdata->_clearCartCmd['command'], 'payload' => str_replace(' ', '_', $chatdata->_clearCartCmd['command'])));
512
+ $message .= $chatdata->_clearCartCmd['command'] . " - " . $magehelper->__("Clear your cart.") . "\n";
513
+ }
514
+ if ($chatdata->_trackOrderCmd['command'])
515
+ {
516
+ array_push($replies, array('content_type' => 'text', 'title' => $chatdata->_trackOrderCmd['command'], 'payload' => str_replace(' ', '_', $chatdata->_trackOrderCmd['command'])));
517
+ $message .= $chatdata->_trackOrderCmd['command'] . " - " . $magehelper->__("Track your order status.") . "\n";
518
+ }
519
+ if ($chatdata->_supportCmd['command'])
520
+ {
521
+ array_push($replies, array('content_type' => 'text', 'title' => $chatdata->_supportCmd['command'], 'payload' => str_replace(' ', '_', $chatdata->_supportCmd['command'])));
522
+ $message .= $chatdata->_supportCmd['command'] . " - " . $magehelper->__("Send message to support.") . "\n";
523
+ }
524
+ if ($chatdata->_sendEmailCmd['command'])
525
+ {
526
+ array_push($replies, array('content_type' => 'text', 'title' => $chatdata->_sendEmailCmd['command'], 'payload' => str_replace(' ', '_', $chatdata->_sendEmailCmd['command'])));
527
+ $message .= $chatdata->_sendEmailCmd['command'] . " - " . $magehelper->__("Send email.") . "\n";
528
+ }
529
+ //$message .= $chatdata->_cancelCmd['command'] . " - " . $magehelper->__("Cancel.");
530
+ if ($chatdata->_helpCmd['command'])
531
+ {
532
+ array_push($replies, array('content_type' => 'text', 'title' => $chatdata->_helpCmd['command'], 'payload' => str_replace(' ', '_', $chatdata->_helpCmd['command'])));
533
+ $message .= $chatdata->_helpCmd['command'] . " - " . $magehelper->__("Get help.") . "\n";
534
+ }
535
+ //$message .= $chatdata->_aboutCmd['command'] . " - " . $magehelper->__("About.");
536
+
537
+ $facebook->sendQuickReply($chatId, $message, $replies);
538
+ }
539
+ else
540
+ $facebook->sendMessage($chatId, $message);
541
+
542
+ $facebook->sendChatAction($chatId, "typing_off");
543
+ return $facebook->respondSuccess();
544
+ }
545
+
546
+ // states
547
+ if ($conversationState == $chatdata->_listCategoriesState) // TODO show only in stock products
548
+ {
549
+ if ($showMore == 0) // show only in the first time
550
+ $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("please wait while I gather all products from %s for you.", $text));
551
+ else
552
+ $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("listing more."));
553
+
554
+ $facebook->sendChatAction($chatId, "typing_on");
555
+ $_category = Mage::getModel('catalog/category')->loadByAttribute('name', $text);
556
+ $errorFlag = false;
557
+ if ($_category) // check if variable isn't false/empty
558
+ {
559
+ if ($_category->getId()) // check if is a valid category
560
+ {
561
+ $noProductFlag = false;
562
+ $productIDs = $_category->getProductCollection()
563
+ ->addAttributeToSelect('*')
564
+ ->addAttributeToFilter('visibility', 4)
565
+ ->addAttributeToFilter('type_id', 'simple')
566
+ ->getAllIds();
567
+
568
+ $elements = array();
569
+ if ($productIDs)
570
+ {
571
+ $i = 0;
572
+ $total = count($productIDs);
573
+
574
+ if ($showMore < $total)
575
+ {
576
+ if ($showMore == 0)
577
+ {
578
+ if ($total == 1)
579
+ $facebook->sendMessage($chatId, $magehelper->__("Done. This category has only one product.", $total));
580
+ else
581
+ $facebook->sendMessage($chatId, $magehelper->__("Done. This category has %s products.", $total));
582
+ }
583
+
584
+ $placeholder = Mage::getSingleton("catalog/product_media_config")->getBaseMediaUrl() . DS . "placeholder" . DS . Mage::getStoreConfig("catalog/placeholder/thumbnail_placeholder");
585
+ foreach ($productIDs as $productID)
586
+ {
587
+ if ($i >= $showMore)
588
+ {
589
+ $product = Mage::getModel('catalog/product')->load($productID);
590
+ $product_url = $product->getProductUrl();
591
+ $product_image = $product->getImageUrl();
592
+ if (empty($product_image))
593
+ $product_image = $placeholder;
594
+
595
+ $button = array(
596
+ array(
597
+ 'type' => 'postback',
598
+ 'title' => $magehelper->__("Add to cart"),
599
+ 'payload' => $chatdata->_add2CartCmd['command'] . $productID
600
+ ),
601
+ array(
602
+ 'type' => 'web_url',
603
+ 'url' => $product_url,
604
+ 'title' => $magehelper->__("Visit product's page")
605
+ )
606
+ );
607
+ $element = array(
608
+ 'title' => $product->getName(),
609
+ 'item_url' => $product_url,
610
+ 'image_url' => $product_image,
611
+ 'subtitle' => $chatdata->excerpt($product->getShortDescription(), 60),
612
+ 'buttons' => $button
613
+ );
614
+ array_push($elements, $element);
615
+
616
+ 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)
617
+ {
618
+ // TODO add option to list more products
619
+ $button = array(
620
+ array(
621
+ 'type' => 'postback',
622
+ 'title' => $magehelper->__("Show more"),
623
+ 'payload' => $listMoreCategories . $text . "," . (string)($i + 1)
624
+ )
625
+ );
626
+ $element = array(
627
+ 'title' => Mage::app()->getStore()->getName(),
628
+ 'item_url' => Mage::getBaseUrl(),
629
+ 'image_url' => $placeholder,
630
+ 'subtitle' => $chatdata->excerpt(Mage::getStoreConfig('design/head/default_description'), 60),
631
+ 'buttons' => $button
632
+ );
633
+ array_push($elements, $element);
634
+ if ($chatdata->getFacebookConvState() != $chatdata->_listProductsState)
635
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_listProductsState))
636
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
637
+ break;
638
+ }
639
+ else if (($i + 1) == $total) // if it's the last one, back to _startState
640
+ {
641
+ $facebook->sendMessage($chatId, $magehelper->__("And that was the last one."));
642
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState))
643
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
644
+ }
645
+ }
646
+ $i++;
647
+ }
648
+ if ($i == 0)
649
+ $noProductFlag = true;
650
+ }
651
+ else
652
+ $errorFlag = true;
653
+ }
654
+ else
655
+ $noProductFlag = true;
656
+
657
+ if ($noProductFlag)
658
+ $facebook->sendMessage($chatId, $magehelper->__("Sorry, no products found in this category."));
659
+ else
660
+ $facebook->sendGenericTemplate($chatId, $elements);
661
+ }
662
+ else
663
+ $errorFlag = true;
664
+ }
665
+ else
666
+ $errorFlag = true;
667
+
668
+ if ($errorFlag)
669
+ {
670
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
671
+ $chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState);
672
+ }
673
+ return $facebook->respondSuccess();
674
+ }
675
+ else if ($conversationState == $chatdata->_searchState)
676
+ {
677
+ if ($showMore == 0) // show only in the first time
678
+ $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("please wait while I search for '%s' for you.", $text));
679
+ else
680
+ $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("listing more."));
681
+
682
+ $facebook->sendChatAction($chatId, "typing_on");
683
+ $errorFlag = false;
684
+ $noProductFlag = false;
685
+ $productIDs = $chatdata->getProductIdsBySearch($text);
686
+ $elements = array();
687
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState))
688
+ {
689
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
690
+ return $facebook->respondSuccess();
691
+ }
692
+ else if ($productIDs)
693
+ {
694
+ $i = 0;
695
+ $total = count($productIDs);
696
+ if ($showMore < $total)
697
+ {
698
+ if ($showMore == 0)
699
+ {
700
+ if ($total == 1)
701
+ $facebook->sendMessage($chatId, $magehelper->__("Done. I've found only one product for your criteria.", $total));
702
+ else
703
+ $facebook->sendMessage($chatId, $magehelper->__("Done. I've found %s products for your criteria.", $total));
704
+ }
705
+
706
+ $placeholder = Mage::getSingleton("catalog/product_media_config")->getBaseMediaUrl() . DS . "placeholder" . DS . Mage::getStoreConfig("catalog/placeholder/thumbnail_placeholder");
707
+ foreach ($productIDs as $productID)
708
+ {
709
+ $message = $chatdata->prepareFacebookProdMessages($productID);
710
+ //Mage::helper('core')->__("Add to cart") . ": " . $this->_add2CartCmd['command'] . $product->getId();
711
+ if ($message) // TODO
712
+ {
713
+ if ($i >= $showMore)
714
+ {
715
+ $product = Mage::getModel('catalog/product')->load($productID);
716
+ $product_url = $product->getProductUrl();
717
+ $product_image = $product->getImageUrl();
718
+ if (empty($product_image))
719
+ $product_image = $placeholder;
720
+
721
+ $button = array(
722
+ array(
723
+ 'type' => 'postback',
724
+ 'title' => $magehelper->__("Add to cart"),
725
+ 'payload' => $chatdata->_add2CartCmd['command'] . $productID
726
+ ),
727
+ array(
728
+ 'type' => 'web_url',
729
+ 'url' => $product_url,
730
+ 'title' => $magehelper->__("Visit product's page")
731
+ )
732
+ );
733
+ $element = array(
734
+ 'title' => $product->getName(),
735
+ 'item_url' => $product_url,
736
+ 'image_url' => $product_image,
737
+ 'subtitle' => $chatdata->excerpt($product->getShortDescription(), 60),
738
+ 'buttons' => $button
739
+ );
740
+ array_push($elements, $element);
741
+
742
+ 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)
743
+ {
744
+ // TODO add option to list more products
745
+ $button = array(
746
+ array(
747
+ 'type' => 'postback',
748
+ 'title' => $magehelper->__("Show more"),
749
+ 'payload' => $listMoreSearch . $text . "," . (string)($i + 1)
750
+ )
751
+ );
752
+ $element = array(
753
+ 'title' => Mage::app()->getStore()->getName(),
754
+ 'item_url' => Mage::getBaseUrl(),
755
+ 'image_url' => $placeholder,
756
+ 'subtitle' => $chatdata->excerpt(Mage::getStoreConfig('design/head/default_description'), 60),
757
+ 'buttons' => $button
758
+ );
759
+ array_push($elements, $element);
760
+ if ($chatdata->getFacebookConvState() != $chatdata->_listProductsState)
761
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_listProductsState))
762
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
763
+ break;
764
+ }
765
+ else if (($i + 1) == $total) // if it's the last one, back to _startState
766
+ {
767
+ $facebook->sendMessage($chatId, $magehelper->__("And that was the last one."));
768
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState))
769
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
770
+ }
771
+ }
772
+ $i++;
773
+ }
774
+ }
775
+ if ($i == 0)
776
+ $noProductFlag = true;
777
+ }
778
+ else
779
+ $errorFlag = true;
780
+ }
781
+ else
782
+ $noProductFlag = true;
783
+
784
+ if ($noProductFlag)
785
+ $facebook->sendMessage($chatId, $magehelper->__("Sorry, no products found for this criteria."));
786
+ else if ($errorFlag)
787
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
788
+ else if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_listProductsState))
789
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
790
+ else
791
+ $facebook->sendGenericTemplate($chatId, $elements);
792
+
793
+ return $facebook->respondSuccess();
794
+ }
795
+ else if ($conversationState == $chatdata->_supportState)
796
+ {
797
+ $errorFlag = true;
798
+ if (!empty($supportGroupId))
799
+ {
800
+ if ($supportGroupId == $chatdata->_tgBot)
801
+ {
802
+ if (Mage::getModel('chatbot/api_telegram_handler')->foreignMessageToSupport($chatId, $originalText, $chatdata->_apiKey, $username)) // send chat id, original text and "facebook"
803
+ $errorFlag = false;
804
+ }
805
+ else // probably have the admin chat id set
806
+ {
807
+ $buttons = array(
808
+ array(
809
+ 'type' => 'postback',
810
+ 'title' => $magehelper->__("End support"),
811
+ 'payload' => $chatdata->_admEndSupportCmd . $chatId
812
+
813
+ ),
814
+ array(
815
+ 'type' => 'postback',
816
+ 'title' => $magehelper->__("Enable/Disable support"),
817
+ 'payload' => $chatdata->_admBlockSupportCmd . $chatId
818
+
819
+ ),
820
+ array(
821
+ 'type' => 'postback',
822
+ 'title' => $magehelper->__("Reply this message"),
823
+ 'payload' => $replyToCustomerMessage . $chatId
824
+
825
+ )
826
+ );
827
+
828
+ $message = $magehelper->__("From") . ": " . $username . "\n" . $magehelper->__("ID") . ": " . $chatId . "\n" . $text;
829
+ $facebook->sendButtonTemplate($supportGroupId, $message, $buttons);
830
+ $errorFlag = false;
831
+ }
832
+ }
833
+
834
+ if ($errorFlag)
835
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
836
+ else
837
+ $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("we have sent your message to support."));
838
+ return $facebook->respondSuccess();
839
+ }
840
+ else if ($conversationState == $chatdata->_sendEmailState)
841
+ {
842
+ $facebook->sendMessage($chatId, $magehelper->__("Trying to send the email..."));
843
+ if ($chatdata->sendEmail($text))
844
+ {
845
+ $facebook->sendMessage($chatId, $magehelper->__("Done."));
846
+ }
847
+ else
848
+ $facebook->sendMessage($chatId, $magehelper->__("Sorry, I wasn't able to send an email this time. Please try again later."));
849
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState))
850
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
851
+ return $facebook->respondSuccess();
852
+ }
853
+ else if ($conversationState == $chatdata->_trackOrderState)
854
+ {
855
+ $errorFlag = false;
856
+ if ($chatdata->getIsLogged() == "1")
857
+ {
858
+ $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("please wait while I check the status for order %s.", $text));
859
+ $facebook->sendChatAction($chatId, "typing_on");
860
+ $order = Mage::getModel('sales/order')->loadByIncrementId($text);
861
+ if ($order->getId())
862
+ {
863
+ if ($order->getCustomerId() == $chatdata->getCustomerId()) // not a problem if customer dosen't exist
864
+ {
865
+ $facebook->sendMessage($chatId, $magehelper->__("Your order status is") . " " . $order->getStatus());
866
+ }
867
+ else
868
+ $errorFlag = true;
869
+ }
870
+ else
871
+ $errorFlag = true;
872
+ }
873
+ else
874
+ $facebook->sendMessage($chatId, $chatdata->_loginFirstMessage);
875
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState))
876
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
877
+ else if ($errorFlag)
878
+ $facebook->sendMessage($chatId, $magehelper->__("Sorry, we couldn't find any order with this information."));
879
+ return $facebook->respondSuccess();
880
+ }
881
+
882
+ //general commands
883
+ if ($chatdata->checkCommand($text, $chatdata->_listCategoriesCmd))
884
+ {
885
+ $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("please wait while I gather all categories for you."));
886
+ $facebook->sendChatAction($chatId, "typing_on");
887
+
888
+ $categoryHelper = Mage::helper('catalog/category');
889
+ $categories = $categoryHelper->getStoreCategories(); // TODO test with a store without categories
890
+ $i = 0;
891
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_listCategoriesState))
892
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
893
+ else if ($categories)
894
+ {
895
+ $replies = array();
896
+ foreach ($categories as $_category) // TODO fix buttons max size
897
+ {
898
+ //array_push($option, $_category->getName());
899
+ if ($enableEmptyCategoriesListing != "1") // unallow empty categories listing
900
+ {
901
+ $category = Mage::getModel('catalog/category')->load($_category->getId()); // reload category because EAV Entity
902
+ $productIDs = $category->getProductCollection()
903
+ ->addAttributeToSelect('*')
904
+ ->addAttributeToFilter('visibility', 4)
905
+ ->addAttributeToFilter('type_id', 'simple')
906
+ ->getAllIds()
907
+ ;
908
+ }
909
+ else
910
+ $productIDs = true;
911
+ if (!empty($productIDs)) // category with no products
912
+ {
913
+ $cat_name = $_category->getName();
914
+ if (!empty($cat_name))
915
+ {
916
+ $reply = array(
917
+ 'content_type' => 'text',
918
+ 'title' => $cat_name,
919
+ 'payload' => 'list_category_' . $_category->getId() // TODO
920
+ );
921
+ array_push($replies, $reply);
922
+ $i++;
923
+ }
924
+ }
925
+ }
926
+ if (!empty($replies))
927
+ {
928
+ $message = $magehelper->__("Select a category") . ". " . $chatdata->_cancelMessage;
929
+ $facebook->sendQuickReply($chatId, $message, $replies);
930
+ }
931
+ }
932
+ else if ($i == 0)
933
+ {
934
+ $facebook->sendMessage($chatId, $magehelper->__("No categories available at the moment, please try again later."));
935
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState))
936
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
937
+ }
938
+ else
939
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
940
+
941
+ return $facebook->respondSuccess();
942
+ }
943
+ else if ($chatdata->checkCommand($text, $chatdata->_checkoutCmd))
944
+ {
945
+ $sessionId = null;
946
+ $quoteId = null;
947
+ $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("please wait while I prepare the checkout for you."));
948
+ $facebook->sendChatAction($chatId, "typing_on");
949
+ if ($chatdata->getIsLogged() == "1")
950
+ {
951
+ if (Mage::getModel('customer/customer')->load((int)$chatdata->getCustomerId())->getId())
952
+ {
953
+ // if user is set as logged, then login using magento singleton
954
+ $customerSession = Mage::getSingleton('customer/session');
955
+ $customerSession->loginById((int)$chatdata->getCustomerId());
956
+ // then set current quote as customer quote
957
+ $customer = Mage::getModel('customer/customer')->load((int)$chatdata->getCustomerId());
958
+ $quote = Mage::getModel('sales/quote')->loadByCustomer($customer);
959
+ // set quote and session ids from logged user
960
+ $quoteId = $quote->getId();
961
+ $sessionId = $customerSession->getEncryptedSessionId();
962
+ }
963
+ }
964
+ if (!($sessionId && $quoteId))
965
+ {
966
+ // set quote and session ids from chatbot class
967
+ $sessionId = $chatdata->getSessionId();
968
+ $quoteId = $chatdata->getQuoteId();
969
+ }
970
+ $emptyCart = true;
971
+ if ($sessionId && $quoteId)
972
+ {
973
+ $cartUrl = Mage::helper('checkout/cart')->getCartUrl();
974
+ if (!isset(parse_url($cartUrl)['SID']))
975
+ $cartUrl .= "?SID=" . $sessionId; // add session id to url
976
+
977
+ $cart = Mage::getModel('checkout/cart')->setQuote(Mage::getModel('sales/quote')->loadByIdWithoutStore((int)$quoteId));
978
+ $ordersubtotal = $cart->getQuote()->getSubtotal();
979
+ if ($ordersubtotal > 0)
980
+ {
981
+ $buttons = array(
982
+ array(
983
+ 'type' => 'web_url',
984
+ 'url' => $cartUrl,
985
+ 'title' => $magehelper->__("Checkout")
986
+ )
987
+ );
988
+ $emptyCart = false;
989
+ $message = $magehelper->__("Products on cart") . ":\n";
990
+ foreach ($cart->getQuote()->getItemsCollection() as $item) // TODO
991
+ {
992
+ $message .= $item->getQty() . "x " . $item->getProduct()->getName() . "\n" .
993
+ $magehelper->__("Price") . ": " . Mage::helper('core')->currency($item->getProduct()->getPrice(), true, false) . "\n\n";
994
+ }
995
+ $message .= $magehelper->__("Total") . ": " . Mage::helper('core')->currency($ordersubtotal, true, false);
996
+
997
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_checkoutState))
998
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
999
+ else
1000
+ $facebook->sendButtonTemplate($chatId, $message, $buttons);
1001
+ }
1002
+ else if (!$chatdata->clearCart()) // try to clear cart
1003
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1004
+ }
1005
+ if ($emptyCart)
1006
+ $facebook->sendMessage($chatId, $magehelper->__("Your cart is empty."));
1007
+ return $facebook->respondSuccess();
1008
+ }
1009
+ else if ($chatdata->checkCommand($text, $chatdata->_clearCartCmd))
1010
+ {
1011
+ $errorFlag = false;
1012
+ if ($chatdata->clearCart())
1013
+ {
1014
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_clearCartState))
1015
+ $errorFlag = true;
1016
+ else
1017
+ $facebook->sendMessage($chatId, $magehelper->__("Cart cleared."));
1018
+ }
1019
+ else
1020
+ $errorFlag = true;
1021
+ if ($errorFlag)
1022
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1023
+ return $facebook->respondSuccess();
1024
+ }
1025
+ else if ($chatdata->checkCommand($text, $chatdata->_searchCmd))
1026
+ {
1027
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_searchState))
1028
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1029
+ else
1030
+ $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("what do you want to search for?") . " " . $chatdata->_cancelMessage);
1031
+ return $facebook->respondSuccess();
1032
+ }
1033
+ else if ($chatdata->checkCommand($text, $chatdata->_loginCmd))
1034
+ {
1035
+ if ($chatdata->getIsLogged() != "1") // customer not logged
1036
+ {
1037
+ $hashlink = Mage::getUrl('chatbot/settings/index/') . "hash" . DS . $chatdata->getHashKey();
1038
+ $buttons = array(
1039
+ array(
1040
+ 'type' => 'web_url',
1041
+ 'url' => $hashlink,
1042
+ 'title' => $magehelper->__("Login")
1043
+ )
1044
+ );
1045
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_loginState))
1046
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1047
+ else
1048
+ $facebook->sendButtonTemplate($chatId, $magehelper->__("To login to your account, access the link below"), $buttons);
1049
+ }
1050
+ else
1051
+ $facebook->sendMessage($chatId, $magehelper->__("You're already logged."));
1052
+ return $facebook->respondSuccess();
1053
+ }
1054
+ else if ($chatdata->checkCommand($text, $chatdata->_logoutCmd)) // TODO
1055
+ {
1056
+ if ($chatdata->getIsLogged() == "1")
1057
+ {
1058
+ $facebook->sendMessage($chatId, $magehelper->__("Ok, logging out."));
1059
+ $errorFlag = false;
1060
+ try
1061
+ {
1062
+ $chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState);
1063
+ $chatdata->updateChatdata('is_logged', "0");
1064
+ $chatdata->updateChatdata('customer_id', ""); // TODO null?
1065
+ $chatdata->clearCart();
1066
+ }
1067
+ catch (Exception $e)
1068
+ {
1069
+ $errorFlag = true;
1070
+ }
1071
+
1072
+ if ($errorFlag)
1073
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1074
+ else
1075
+ $facebook->sendMessage($chatId, $magehelper->__("Done."));
1076
+ }
1077
+ else
1078
+ $facebook->sendMessage($chatId, $magehelper->__("You're not logged."));
1079
+
1080
+ return $facebook->respondSuccess();
1081
+ }
1082
+ else if ($chatdata->checkCommand($text, $chatdata->_listOrdersCmd) || $moreOrders)
1083
+ {
1084
+ if ($chatdata->getIsLogged() == "1")
1085
+ {
1086
+ if ($showMore == 0) // show only in the first time
1087
+ $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("please wait while I gather your orders for listing."));
1088
+ else
1089
+ $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("listing more."));
1090
+
1091
+ $facebook->sendChatAction($chatId, "typing_on");
1092
+ $ordersIDs = $chatdata->getOrdersIdsFromCustomer();
1093
+ $i = 0;
1094
+ if ($ordersIDs)
1095
+ {
1096
+ $flagBreak = false;
1097
+ $total = count($ordersIDs);
1098
+ if ($showMore < $total)
1099
+ {
1100
+ if ($showMore == 0)
1101
+ {
1102
+ if ($total == 1)
1103
+ $facebook->sendMessage($chatId, $magehelper->__("Done. You've only one order.", $total));
1104
+ else
1105
+ $facebook->sendMessage($chatId, $magehelper->__("Done. I've found %s orders.", $total));
1106
+ }
1107
+
1108
+ foreach($ordersIDs as $orderID)
1109
+ {
1110
+ $buttons = array();
1111
+ $message = $chatdata->prepareFacebookOrderMessages($orderID);
1112
+ if ($message) // TODO
1113
+ {
1114
+ $button = array(
1115
+ 'type' => 'postback',
1116
+ 'title' => $magehelper->__("Reorder"),
1117
+ 'payload' => $chatdata->_reorderCmd['command'] . $orderID
1118
+ );
1119
+ array_push($buttons, $button);
1120
+ if ($i >= $showMore)
1121
+ {
1122
+ 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)
1123
+ {
1124
+ // TODO add option to list more orders
1125
+ $button = array(
1126
+ 'type' => 'postback',
1127
+ 'title' => $magehelper->__("Show more orders"),
1128
+ 'payload' => $listMoreOrders . (string)($i + 1)
1129
+ );
1130
+ array_push($buttons, $button);
1131
+ if ($chatdata->getFacebookConvState() != $chatdata->_listOrdersState)
1132
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_listOrdersState))
1133
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1134
+ $flagBreak = true;
1135
+ }
1136
+ else if (($i + 1) == $total) // if it's the last one, back to _startState
1137
+ {
1138
+ $facebook->sendMessage($chatId, $magehelper->__("And that was the last one."));
1139
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_startState))
1140
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1141
+ }
1142
+
1143
+ $facebook->sendButtonTemplate($chatId, $message, $buttons);
1144
+ if ($flagBreak)
1145
+ break;
1146
+ }
1147
+ $i++;
1148
+ }
1149
+ }
1150
+ if ($i == 0)
1151
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1152
+ // else if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_listOrdersState))
1153
+ // $facebook->sendMessage($chat_id, $chatdata->_errorMessage);
1154
+ }
1155
+ }
1156
+ else
1157
+ {
1158
+ $facebook->sendMessage($chatId, $magehelper->__("This account has no orders."));
1159
+ return $facebook->respondSuccess();
1160
+ }
1161
+ }
1162
+ else
1163
+ $facebook->sendMessage($chatId, $chatdata->_loginFirstMessage);
1164
+ return $facebook->respondSuccess();
1165
+ }
1166
+ else if ($chatdata->checkCommandWithValue($text, $chatdata->_reorderCmd['command'])) // ignore alias
1167
+ {
1168
+ if ($chatdata->getIsLogged() == "1")
1169
+ {
1170
+ $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("please wait while I add the products from this order to your cart."));
1171
+ $facebook->sendChatAction($chatId, "typing_on");
1172
+ $errorFlag = false;
1173
+ $cmdvalue = $chatdata->getCommandValue($text, $chatdata->_reorderCmd['command']);
1174
+ if ($cmdvalue)
1175
+ {
1176
+ if ($chatdata->clearCart())
1177
+ {
1178
+ $order = Mage::getModel('sales/order')->load($cmdvalue);
1179
+ if ($order->getId())
1180
+ {
1181
+ foreach($order->getAllVisibleItems() as $item) {
1182
+ if (!$chatdata->addProd2Cart($item->getProductId()))
1183
+ $errorFlag = true;
1184
+ }
1185
+ }
1186
+ else
1187
+ $errorFlag = true;
1188
+ }
1189
+ else
1190
+ $errorFlag = true;
1191
+ }
1192
+ else
1193
+ $errorFlag = true;
1194
+
1195
+ if ($errorFlag)
1196
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1197
+ else if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_reorderState))
1198
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1199
+ else // success!!
1200
+ $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("to checkout send") . ' "' . $chatdata->_checkoutCmd['command'] . '"');
1201
+ }
1202
+ else
1203
+ $facebook->sendMessage($chatId, $chatdata->_loginFirstMessage);
1204
+ return $facebook->respondSuccess();
1205
+ }
1206
+ else if ($chatdata->checkCommand($text, $chatdata->_trackOrderCmd))
1207
+ {
1208
+ if ($chatdata->getIsLogged() == "1")
1209
+ {
1210
+ $ordersIDs = $chatdata->getOrdersIdsFromCustomer();
1211
+ if ($ordersIDs)
1212
+ {
1213
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_trackOrderState))
1214
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1215
+ else
1216
+ $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("send the order number."));
1217
+ }
1218
+ else
1219
+ $facebook->sendMessage($chatId, $magehelper->__("Your account dosen't have any orders."));
1220
+ }
1221
+ else
1222
+ $facebook->sendMessage($chatId, $chatdata->_loginFirstMessage);
1223
+ return $facebook->respondSuccess();
1224
+ }
1225
+ else if ($chatdata->checkCommand($text, $chatdata->_supportCmd))
1226
+ {
1227
+ $supportEnabled = $chatdata->getEnableSupport();
1228
+ $errorFlag = false;
1229
+ if ($supportEnabled == "1")
1230
+ {
1231
+ if ($chatdata->getTelegramConvState() != $chatdata->_supportState) // TODO
1232
+ {
1233
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_supportState))
1234
+ $errorFlag = true;
1235
+ else
1236
+ $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("what do you need support for?") . " " . $chatdata->_cancelMessage);
1237
+ }
1238
+ else
1239
+ $facebook->sendMessage($chatId, $magehelper->__("You're already on support in other chat application, please close it before opening a new one."));
1240
+ }
1241
+ else
1242
+ $facebook->sendMessage($chatId, $magehelper->__("I'm sorry, you can't ask for support now. Please try again later."));
1243
+
1244
+ if ($errorFlag)
1245
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1246
+ return $facebook->respondSuccess();
1247
+ }
1248
+ else if ($chatdata->checkCommand($text, $chatdata->_sendEmailCmd))
1249
+ {
1250
+ if (!$chatdata->updateChatdata('facebook_conv_state', $chatdata->_sendEmailState))
1251
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1252
+ else
1253
+ {
1254
+ $facebook->sendMessage($chatId, $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("write the email content."));
1255
+ $facebook->sendMessage($chatId, $magehelper->__("By doing this you agree that we may contact you directly via chat message.") . " " . $chatdata->_cancelMessage);
1256
+ }
1257
+ return $facebook->respondSuccess();
1258
+ }
1259
+ else
1260
+ {
1261
+ if ($enableFinalMessage2Support == "1")
1262
+ {
1263
+ $errorFlag = true;
1264
+ if ($supportGroupId == $chatdata->_tgBot)
1265
+ if (Mage::getModel('chatbot/api_telegram_handler')->foreignMessageToSupport($chatId, $originalText, $chatdata->_apiKey, $username)) // send chat id, original text and "facebook"
1266
+ {
1267
+ // if ($chatdata->getTelegramConvState() != $chatdata->_supportState) // TODO
1268
+ // $chatdata->updateChatdata('facebook_conv_state', $chatdata->_supportState);
1269
+ $errorFlag = false;
1270
+ }
1271
+
1272
+ if ($errorFlag)
1273
+ $facebook->sendMessage($chatId, $chatdata->_errorMessage);
1274
+ else
1275
+ $facebook->sendMessage($chatId,
1276
+ $magehelper->__("Sorry, I didn't understand that.") . " " .
1277
+ $magehelper->__("Please wait while our support check your message so you can talk to a real person.") . " " .
1278
+ $chatdata->_cancelMessage
1279
+ ); // TODO
1280
+ return $facebook->respondSuccess();
1281
+ }
1282
+ //else if ($enable_witai == "1"){}
1283
+ else
1284
+ $facebook->sendMessage($chatId, $magehelper->__("Sorry, I didn't understand that.")); // TODO
1285
+ }
1286
+ }
1287
+
1288
+ return $facebook->respondSuccess();
1289
+ }
1290
+ }
1291
+
1292
+ ?>
app/code/community/Werules/Chatbot/Model/Api/Facebook/Messenger.php ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Messenger Bot Class.
4
+ * @author Pablo Montenegro
5
+ * @about Based on the Telegram API wrapper by Gabriele Grillo <gabry.grillo@alice.it>
6
+ * TODO:
7
+ * https://developers.facebook.com/docs/messenger-platform/send-api-reference/buy-button
8
+ * https://developers.facebook.com/docs/messenger-platform/send-api-reference/url-button
9
+ * https://developers.facebook.com/docs/messenger-platform/send-api-reference/image-attachment
10
+ * https://developers.facebook.com/docs/messenger-platform/send-api-reference/sender-actions
11
+ * https://developers.facebook.com/docs/messenger-platform/send-api-reference/errors
12
+ */
13
+ class Messenger {
14
+
15
+ private $bot_id = "";
16
+ private $api_version = "v2.8";
17
+ private $data = array();
18
+ private $updates = array();
19
+
20
+ /// Class constructor
21
+ public function __construct($bot_id) {
22
+ $this->bot_id = $bot_id;
23
+ $this->data = $this->getData();
24
+ }
25
+
26
+ /// Verify webhook
27
+ public function verifyWebhook($hub_token) {
28
+ if ($_REQUEST['hub_verify_token'] == $hub_token) {
29
+ return $_REQUEST['hub_challenge'];
30
+ }
31
+ return false;
32
+ }
33
+
34
+ /// Do requests to Messenger Bot API
35
+ public function endpoint($api, array $content, $post = true) {
36
+ $url = 'https://graph.facebook.com/' . $this->api_version . '/' . $api . '?access_token=' . $this->bot_id;
37
+ if ($post)
38
+ $reply = $this->sendAPIRequest($url, $content);
39
+ else
40
+ $reply = $this->sendAPIRequest($url, array(), false);
41
+ return json_decode($reply, true);
42
+ }
43
+
44
+ public function respondSuccess() {
45
+ http_response_code(200);
46
+ return json_encode(array("status" => "success"));
47
+ }
48
+
49
+ // send chat action
50
+ // sender_action:
51
+ // mark_seen
52
+ // typing_on
53
+ // typing_off
54
+ public function sendChatAction($chat_id, $action) {
55
+ return $this->endpoint("me/messages", array(
56
+ 'recipient' => array(
57
+ 'id' => $chat_id
58
+ ),
59
+ 'sender_action' => $action
60
+ )
61
+ );
62
+ }
63
+
64
+ // send message
65
+ // https://developers.facebook.com/docs/messenger-platform/send-api-reference#request
66
+ public function sendMessage($chat_id, $text) {
67
+ return $this->endpoint("me/messages", array(
68
+ 'recipient' => array(
69
+ 'id' => $chat_id
70
+ ),
71
+ 'message' => array(
72
+ 'text' => $text
73
+ )
74
+ )
75
+ );
76
+ }
77
+
78
+ // send message
79
+ // $button = array(
80
+ // array(
81
+ // 'type' => 'web_url',
82
+ // 'url' => 'URL_HERE',
83
+ // 'title' => 'TITLE_HERE'
84
+ // ),
85
+ // array(
86
+ // 'type' => 'web_url',
87
+ // 'url' => 'URL_HERE',
88
+ // 'title' => 'TITLE_HERE'
89
+ // ),
90
+ // ...
91
+ // );
92
+ // $elements = array(
93
+ // array(
94
+ // 'title' => 'TITLE_TEXT_HERE',
95
+ // 'item_url' => 'ITEM_URL_HERE',
96
+ // 'image_url' => 'IMAGE_URL_HERE',
97
+ // 'subtitle' => 'SUBTITLE_HERE',
98
+ // 'buttons' => $buttons
99
+ // )
100
+ // );
101
+ // https://developers.facebook.com/docs/messenger-platform/send-api-reference#request
102
+ public function sendGenericTemplate($chat_id, array $elements) {
103
+ return $this->endpoint("me/messages", array(
104
+ 'recipient' => array(
105
+ 'id' => $chat_id
106
+ ),
107
+ 'message' => array(
108
+ 'attachment' => array(
109
+ 'type' => 'template',
110
+ 'payload' => array(
111
+ 'template_type' => 'generic',
112
+ 'elements' => $elements
113
+ )
114
+ )
115
+ )
116
+ )
117
+ );
118
+ }
119
+
120
+ // send quick reply
121
+ // $replies = array(
122
+ // array(
123
+ // 'content_type' => 'text',
124
+ // 'title' => 'TITLE_HERE',
125
+ // 'payload' => 'DEVELOPER_CUSTOM_PAYLOAD_HERE'
126
+ // ),
127
+ // array(
128
+ // 'content_type' => 'text',
129
+ // 'title' => 'TITLE_HERE',
130
+ // 'payload' => 'DEVELOPER_CUSTOM_PAYLOAD_HERE'
131
+ // ),
132
+ // ...
133
+ // );
134
+ // https://developers.facebook.com/docs/messenger-platform/send-api-reference/quick-replies
135
+ public function sendQuickReply($chat_id, $text, array $replies) {
136
+ return $this->endpoint("me/messages", array(
137
+ 'recipient' => array(
138
+ 'id' => $chat_id
139
+ ),
140
+ 'message' => array(
141
+ 'text' => $text,
142
+ 'quick_replies' => $replies
143
+ )
144
+ )
145
+ );
146
+ }
147
+
148
+ // send button
149
+ // $buttons = array(
150
+ // array(
151
+ // 'type' => 'web_url',
152
+ // 'url' => 'URL_HERE',
153
+ // 'title' => 'TITLE_HERE'
154
+ // ),
155
+ // array(
156
+ // 'type' => 'web_url',
157
+ // 'url' => 'URL_HERE',
158
+ // 'title' => 'TITLE_HERE'
159
+ // ),
160
+ // ...
161
+ // );
162
+ // https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template
163
+ // https://developers.facebook.com/docs/messenger-platform/send-api-reference/share-button <- works only with sendGenericTemplate
164
+ public function sendButtonTemplate($chat_id, $text, array $buttons) {
165
+ return $this->endpoint("me/messages",
166
+ array(
167
+ 'recipient' => array(
168
+ 'id' => $chat_id
169
+ ),
170
+ 'message' => array(
171
+ 'attachment' => array(
172
+ 'type' => 'template',
173
+ 'payload' => array(
174
+ 'template_type' => 'button',
175
+ 'text' => $text,
176
+ 'buttons' => $buttons
177
+ )
178
+ )
179
+ )
180
+ )
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"];
187
+ }
188
+
189
+ /// Get the userdata who sent the message
190
+ public function UserData($chat_id) {
191
+ return $this->endpoint($chat_id, array(), false);
192
+ }
193
+
194
+ /// Get the chat_id of the current message
195
+ public function ChatID() {
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"];
212
+ }
213
+
214
+ /// Get the message_id of the current message
215
+ public function MessageID() {
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) {
227
+ curl_setopt($ch, CURLOPT_POST, 1);
228
+ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($content));
229
+ }
230
+ curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
231
+ if ($response)
232
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
233
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
234
+ $result = curl_exec($ch);
235
+ curl_close($ch);
236
+ return $result;
237
+ }
238
+
239
+ /// Get the data of the current message
240
+ public function getData() {
241
+ if (empty($this->data)) {
242
+ $rawData = file_get_contents("php://input");
243
+ return json_decode($rawData, true);
244
+ } else {
245
+ return $this->data;
246
+ }
247
+ }
248
+ }
249
+
250
+ // Helper for Uploading file using CURL
251
+ if (!function_exists('curl_file_create')) {
252
+
253
+ function curl_file_create($filename, $mimetype = '', $postname = '') {
254
+ return "@$filename;filename="
255
+ . ($postname ? : basename($filename))
256
+ . ($mimetype ? ";type=$mimetype" : '');
257
+ }
258
+ }
259
+ ?>
app/code/community/Werules/Chatbot/Model/Api/Telegram/Handler.php ADDED
@@ -0,0 +1,1122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ $message = $magehelper->__("Message via") . " " . $api_name . ":\n" . $magehelper->__("From") . ": " . $customerName . "\n" . $text;
41
+ $result = $telegram->sendMessage(array('chat_id' => $supportgroup, 'text' => $message));
42
+ $mid = $result['result']['message_id'];
43
+ if (!empty($mid))
44
+ {
45
+ $chatdata->updateChatdata("last_support_message_id", $mid);
46
+ $chatdata->updateChatdata("last_support_chat", $api_name);
47
+ }
48
+ }
49
+ catch (Exception $e){
50
+ return false;
51
+ }
52
+
53
+ return true;
54
+ }
55
+ }
56
+
57
+ return false;
58
+ }
59
+
60
+ public function telegramHandler($apiKey)
61
+ {
62
+ if (empty($apiKey)) // if no apiKey available, break proccess
63
+ return "";
64
+
65
+ // Instances the Telegram class
66
+ $telegram = new Telegram($apiKey);
67
+
68
+ // Take text and chat_id from the message
69
+ $text = $telegram->Text();
70
+ $chatId = $telegram->ChatID();
71
+ $messageId = $telegram->MessageID();
72
+
73
+ // configs
74
+ //$enable_witai = Mage::getStoreConfig('chatbot_enable/witai_config/enable_witai');
75
+ $enabledBot = Mage::getStoreConfig('chatbot_enable/telegram_config/enable_bot');
76
+ $enableReplies = Mage::getStoreConfig('chatbot_enable/telegram_config/enable_default_replies');
77
+ $enableLog = Mage::getStoreConfig('chatbot_enable/general_config/enable_post_log');
78
+ $enableEmptyCategoriesListing = Mage::getStoreConfig('chatbot_enable/general_config/list_empty_categories');
79
+ $enableFinalMessage2Support = Mage::getStoreConfig('chatbot_enable/general_config/enable_support_final_message');
80
+ $supportGroupId = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_support_group');
81
+ $showMore = 0;
82
+ $cat_id = null;
83
+ $moreOrders = false;
84
+ $listingLimit = 5;
85
+ $listMoreCategories = "/lmc_";
86
+ $listMoreSearch = "/lms_";
87
+ $listMoreOrders = "/lmo_";
88
+
89
+ if ($enableLog == "1") // log all posts
90
+ Mage::log("Post Data:\n" . var_export($telegram->getData(), true) . "\n\n", null, 'chatbot_telegram.log');
91
+
92
+ if (!is_null($text) && !is_null($chatId))
93
+ {
94
+ // Instances the model class
95
+ $chatdata = Mage::getModel('chatbot/chatdata')->load($chatId, 'telegram_chat_id');
96
+ $chatdata->_apiType = $chatdata->_tgBot;
97
+
98
+ if ($messageId == $chatdata->getTelegramMessageId()) // prevents to reply the same request twice
99
+ return $telegram->respondSuccess();
100
+ else if ($chatdata->getTelegramChatId())
101
+ $chatdata->updateChatdata('telegram_message_id', $messageId); // if this fails, it may send the same message twice
102
+
103
+ // bot enabled/disabled
104
+ if ($enabledBot != "1")
105
+ {
106
+ $disabledMessage = Mage::getStoreConfig('chatbot_enable/telegram_config/disabled_message');
107
+ if (!empty($disabledMessage))
108
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $disabledMessage));
109
+ return $telegram->respondSuccess();
110
+ }
111
+
112
+ // send feedback to user
113
+ $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
114
+
115
+ // handle default replies
116
+ if ($enableReplies == "1")
117
+ {
118
+ $defaultReplies = Mage::getStoreConfig('chatbot_enable/telegram_config/default_replies');
119
+ if ($defaultReplies)
120
+ {
121
+ $replies = unserialize($defaultReplies);
122
+ if (is_array($replies))
123
+ {
124
+ foreach($replies as $reply)
125
+ {
126
+ $match = $reply["catch_phrase"];
127
+ $similarity = $reply["similarity"];
128
+ if (is_numeric($similarity))
129
+ {
130
+ if (!($similarity >= 1 && $similarity <= 100))
131
+ $similarity = 100;
132
+ }
133
+ else
134
+ $similarity = 100;
135
+
136
+ if ($reply["match_case"] == "0")
137
+ {
138
+ $match = strtolower($match);
139
+ $text = strtolower($text);
140
+ }
141
+
142
+ similar_text($text, $match, $percent);
143
+ if ($percent >= $similarity)
144
+ {
145
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $reply["reply_phrase"]));
146
+ return $telegram->respondSuccess();
147
+ break; // probably useless
148
+ }
149
+ }
150
+ }
151
+ }
152
+ }
153
+
154
+ // show more handler, may change the conversation state
155
+ if ($chatdata->getTelegramConvState() == $chatdata->_listProductsState || $chatdata->getTelegramConvState() == $chatdata->_listOrdersState) // listing products
156
+ {
157
+ if ($chatdata->checkCommandWithValue($text, $listMoreCategories))
158
+ {
159
+ if ($chatdata->updateChatdata('telegram_conv_state', $chatdata->_listCategoriesState))
160
+ {
161
+ $value = $this->getCommandValue($text, $listMoreCategories);
162
+ $arr = explode("_", $value);
163
+ $cat_id = (int)$arr[0]; // get category id
164
+ $showMore = (int)$arr[1]; // get where listing stopped
165
+ }
166
+ }
167
+ else if ($chatdata->checkCommandWithValue($text, $listMoreSearch))
168
+ {
169
+ if ($chatdata->updateChatdata('telegram_conv_state', $chatdata->_searchState))
170
+ {
171
+ $value = $this->getCommandValue($text, $listMoreSearch);
172
+ $arr = explode("_", $value);
173
+ $showMore = (int)end($arr); // get where listing stopped
174
+ $value = str_replace("_" . (string)$showMore, "", $value);
175
+ $text = str_replace("_", " ", $value); // get search criteria
176
+ }
177
+ }
178
+ else if ($chatdata->checkCommandWithValue($text, $listMoreOrders))
179
+ {
180
+ if ($chatdata->updateChatdata('telegram_conv_state', $chatdata->_listOrdersState))
181
+ {
182
+ $value = $this->getCommandValue($text, $listMoreOrders);
183
+ $showMore = (int)$value; // get where listing stopped
184
+ $moreOrders = true;
185
+ }
186
+ }
187
+ // else
188
+ // $chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState);
189
+ }
190
+
191
+ // instances conversation state
192
+ $conversationState = $chatdata->getTelegramConvState();
193
+
194
+ // mage helper
195
+ $magehelper = Mage::helper('core');
196
+
197
+ if ($supportGroupId[0] == "g") // remove the 'g' from groupd id, and add '-'
198
+ $supportGroupId = "-" . ltrim($supportGroupId, "g");
199
+
200
+ // handle admin stuff
201
+ //$isAdmin = $chatdata->getIsAdmin();
202
+ // if it's a group message
203
+ if ($telegram->messageFromGroup())
204
+ {
205
+ if ($chatId == $supportGroupId) // if the group sending the message is the support group
206
+ {
207
+ $replyMessageId = $telegram->ReplyToMessageID();
208
+ if (!empty($replyMessageId)) // if the message is replying another message
209
+ {
210
+ $foreignchatdata = Mage::getModel('chatbot/chatdata')->load($replyMessageId, 'last_support_message_id');
211
+ if (!empty($foreignchatdata->getLastSupportMessageId())) // check if current reply message id is saved on databse
212
+ {
213
+ $api_name = $foreignchatdata->getLastSupportChat();
214
+ if ($api_name == $foreignchatdata->_fbBot)
215
+ Mage::getModel('chatbot/api_facebook_handler')->foreignMessageFromSupport($foreignchatdata->getFacebookChatId(), $text); // send chat id and the original text
216
+ }
217
+ else
218
+ {
219
+ $replyFromUserId = $telegram->ReplyToMessageFromUserID();
220
+ if (!is_null($replyFromUserId))
221
+ {
222
+ $admEndSupport = "/" . $chatdata->_admEndSupportCmd;
223
+ $admBlockSupport = "/" . $chatdata->_admBlockSupportCmd;
224
+ $admEnableSupport = "/" . $chatdata->_admEnableSupportCmd;
225
+
226
+ $customerData = Mage::getModel('chatbot/chatdata')->load($replyFromUserId, 'telegram_chat_id');
227
+ if ($text == $admEndSupport) // finish customer support
228
+ {
229
+ // TODO IMPORTANT remember to switch off all other supports
230
+ $customerData->updateChatdata('telegram_conv_state', $chatdata->_startState);
231
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Done. The customer is no longer on support.")));
232
+ $telegram->sendMessage(array('chat_id' => $replyFromUserId, 'text' => $magehelper->__("Support ended."))); // TODO
233
+ }
234
+ else if ($text == $admBlockSupport) // block user from using support
235
+ {
236
+ $customerData->updateChatdata('enable_support', "0"); // disable support
237
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Done. The customer is no longer able to enter support."))); // TODO
238
+ }
239
+ else if ($text == $admEnableSupport) // block user from using support
240
+ {
241
+ $customerData->updateChatdata('enable_support', "1"); // enable support
242
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Done. The customer is now able to enter support."))); // TODO
243
+ }
244
+ else // if no command, then it's replying the user
245
+ {
246
+ if ($customerData->getTelegramConvState() != $chatdata->_supportState) // if user isn't on support, switch to support
247
+ {
248
+ $customerData->updateChatdata('telegram_conv_state', $chatdata->_supportState);
249
+ $telegram->sendMessage(array('chat_id' => $replyFromUserId, 'text' => $magehelper->__("You're now on support mode.")));
250
+ }
251
+ $telegram->sendMessage(array('chat_id' => $replyFromUserId, 'text' => $magehelper->__("Message from support") . ":\n" . $text)); // send message to customer TODO
252
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Message sent."))); // send message to admin group TODO
253
+ }
254
+ }
255
+ }
256
+ }
257
+ else // proccess other admin commands (that aren't replying messages)
258
+ {
259
+ $admSend2All = "/" . $chatdata->_admSendMessage2AllCmd;
260
+
261
+ if ($chatdata->checkCommandWithValue($text, $admSend2All))
262
+ {
263
+ $message = trim($chatdata->getCommandValue($text, $admSend2All));
264
+ if (!empty($message))
265
+ {
266
+ $chatbotcollection = Mage::getModel('chatbot/chatdata')->getCollection();
267
+ foreach($chatbotcollection as $chatbot)
268
+ {
269
+ $tgChatId = $chatbot->getTelegramChatId();
270
+ if ($tgChatId)
271
+ $telegram->sendMessage(array('chat_id' => $tgChatId, 'text' => $message)); // $magehelper->__("Message from support") . ":\n" .
272
+ }
273
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Message sent.")));
274
+ }
275
+ else
276
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Please use") . ' "' . $admSend2All . " " . $magehelper->__("your message here.") . '"'));
277
+ }
278
+ }
279
+ return $telegram->respondSuccess();
280
+ }
281
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("I don't work with groups."))); // TODO
282
+ return $telegram->respondSuccess(); // ignore all group messages
283
+ }
284
+
285
+ if ($chatdata->getIsLogged() == "1") // check if customer is logged
286
+ {
287
+ if (Mage::getModel('customer/customer')->load((int)$chatdata->getCustomerId())->getId()) // if is a valid customer id
288
+ {
289
+ if ($chatdata->getEnableTelegram() != "1")
290
+ {
291
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("To talk with me, please enable Telegram on your account chatbot settings.")));
292
+ return $telegram->respondSuccess();
293
+ }
294
+ }
295
+ }
296
+
297
+ // init start command
298
+ $chatdata->_startCmd['command'] = "/start";
299
+
300
+ if (is_null($chatdata->getTelegramChatId()) && !$chatdata->checkCommandWithValue($text, $chatdata->_startCmd['command'])) // if user isn't registred, and not using the start command
301
+ {
302
+ $message = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_welcome_msg'); // TODO
303
+ if ($message) // TODO
304
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $message));
305
+ try
306
+ {
307
+ $hash = substr(md5(uniqid($chatId, true)), 0, 150); // TODO
308
+ $chatdata // using magento model to insert data into database the proper way
309
+ ->setTelegramChatId($chatId)
310
+ ->setHashKey($hash) // TODO
311
+ ->save();
312
+ }
313
+ catch (Exception $e)
314
+ {
315
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage)); // TODO
316
+ }
317
+ return $telegram->respondSuccess();
318
+ }
319
+
320
+ // init other commands (for now, no alias for telegram)
321
+ $chatdata->_listCategoriesCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(1)['command']);
322
+ $chatdata->_searchCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(2)['command']);
323
+ $chatdata->_loginCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(3)['command']);
324
+ $chatdata->_listOrdersCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(4)['command']);
325
+ $chatdata->_reorderCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(5)['command']);
326
+ $chatdata->_add2CartCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(6)['command']);
327
+ $chatdata->_checkoutCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(7)['command']);
328
+ $chatdata->_clearCartCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(8)['command']);
329
+ $chatdata->_trackOrderCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(9)['command']);
330
+ $chatdata->_supportCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(10)['command']);
331
+ $chatdata->_sendEmailCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(11)['command']);
332
+ $chatdata->_cancelCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(12)['command']);
333
+ $chatdata->_helpCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(13)['command']);
334
+ $chatdata->_aboutCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(14)['command']);
335
+ $chatdata->_logoutCmd['command'] = $chatdata->validateTelegramCmd("/" . $chatdata->getCommandString(15)['command']);
336
+
337
+ if (!$chatdata->_cancelCmd['command']) $chatdata->_cancelCmd['command'] = "/cancel"; // it must always have a cancel command
338
+
339
+ // init messages
340
+ $chatdata->_errorMessage = $magehelper->__("Something went wrong, please try again.");
341
+ $chatdata->_cancelMessage = $magehelper->__("To cancel, send") . " " . $chatdata->_cancelCmd['command'];
342
+ $chatdata->_canceledMessage = $magehelper->__("Ok, canceled.");
343
+ $chatdata->_loginFirstMessage = $magehelper->__("Please login first.");
344
+ array_push($chatdata->_positiveMessages, $magehelper->__("Ok"), $magehelper->__("Okay"), $magehelper->__("Cool"), $magehelper->__("Awesome"));
345
+ // $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)]
346
+
347
+ // TODO DEBUG COMMANDS
348
+ // $temp_var = $chatdata->_startCmd['command'] . " - " .
349
+ // $chatdata->_listCategoriesCmd['command'] . " - " .
350
+ // $chatdata->_searchCmd['command'] . " - " .
351
+ // $chatdata->_loginCmd['command'] . " - " .
352
+ // $chatdata->_listOrdersCmd['command'] . " - " .
353
+ // $chatdata->_reorderCmd['command'] . " - " .
354
+ // $chatdata->_add2CartCmd['command'] . " - " .
355
+ // $chatdata->_checkoutCmd['command'] . " - " .
356
+ // $chatdata->_clearCartCmd['command'] . " - " .
357
+ // $chatdata->_trackOrderCmd['command'] . " - " .
358
+ // $chatdata->_supportCmd['command'] . " - " .
359
+ // $chatdata->_sendEmailCmd['command'];
360
+ // $telegram->sendMessage(array('chat_id' => $chat_id, 'text' => $temp_var));
361
+ // $telegram->sendMessage(array('chat_id' => $chat_id, 'text' => $conversationState));
362
+
363
+ // start command
364
+ if ($chatdata->checkCommandWithValue($text, $chatdata->_startCmd['command'])) // ignore alias
365
+ //if ($text == $chatdata->_startCmd['command'])
366
+ {
367
+ $startdata = explode(" ", $text);
368
+ if (is_array($startdata) && count($startdata) > 1) // has hash parameter
369
+ {
370
+ $chat_hash = $chatdata->load(trim($startdata[1]), 'hash_key');
371
+ if ($chat_hash->getHashKey())
372
+ {
373
+ try
374
+ {
375
+ $chat_hash->addData(array("telegram_chat_id" => $chatId));
376
+ $chat_hash->save();
377
+ }catch (Exception $e){}
378
+ $message = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_welcome_msg'); // TODO
379
+ if ($message) // TODO
380
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $message));
381
+ }
382
+ }
383
+ else if ($chatdata->getTelegramChatId()) // TODO
384
+ {
385
+ $message = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_about_msg'); // TODO
386
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $message));
387
+
388
+ // $data = array(
389
+ // //'customer_id' => $customerId,
390
+ // 'telegram_chat_id' => $chat_id
391
+ // ); // data to be insert on database
392
+ // $model = Mage::getModel('chatbot/chatdata')->load($chatdata->getId())->addData($data); // insert data on database
393
+ // $model->setId($chatdata->getId())->save(); // save (duh)
394
+ }
395
+ else // if customer id isnt on our database, means that we need to insert his data
396
+ {
397
+ $message = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_welcome_msg'); // TODO
398
+ if ($message) // TODO
399
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $message));
400
+ try
401
+ {
402
+ $hash = substr(md5(uniqid($chatId, true)), 0, 150); // TODO
403
+ Mage::getModel('chatbot/chatdata') // using magento model to insert data into database the proper way
404
+ ->setTelegramChatId($chatId)
405
+ ->setHashKey($hash) // TODO
406
+ ->setCreatedAt(date('Y-m-d H:i:s'))
407
+ ->save();
408
+ }
409
+ catch (Exception $e)
410
+ {
411
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage)); // TODO
412
+ }
413
+ }
414
+ return $telegram->respondSuccess();
415
+ }
416
+
417
+ // help command
418
+ if ($chatdata->checkCommand($text, $chatdata->_helpCmd))
419
+ {
420
+ $message = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_help_msg'); // TODO
421
+ if ($message) // TODO
422
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $message));
423
+ return $telegram->respondSuccess();
424
+ }
425
+
426
+ // about command
427
+ if ($chatdata->checkCommand($text, $chatdata->_aboutCmd))
428
+ {
429
+ $message = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_about_msg'); // TODO
430
+ $cmdListing = Mage::getStoreConfig('chatbot_enable/telegram_config/enable_command_list');
431
+ if ($cmdListing == 1)
432
+ {
433
+ $message .= "\n\n" . $magehelper->__("Command list") . ":\n";
434
+ if ($chatdata->_listCategoriesCmd['command']) $message .= $chatdata->_listCategoriesCmd['command'] . " - " . $magehelper->__("List store categories.") . "\n";
435
+ if ($chatdata->_searchCmd['command']) $message .= $chatdata->_searchCmd['command'] . " - " . $magehelper->__("Search for products.") . "\n";
436
+ if ($chatdata->_loginCmd['command']) $message .= $chatdata->_loginCmd['command'] . " - " . $magehelper->__("Login into your account.") . "\n";
437
+ if ($chatdata->_logoutCmd['command']) $message .= $chatdata->_logoutCmd['command'] . " - " . $magehelper->__("Logout from your account.") . "\n";
438
+ if ($chatdata->_listOrdersCmd['command']) $message .= $chatdata->_listOrdersCmd['command'] . " - " . $magehelper->__("List your personal orders.") . "\n";
439
+ //$message .= $chatdata->_reorderCmd['command'] . " - " . $magehelper->__("Reorder a order.") . "\n";
440
+ //$message .= $chatdata->_add2CartCmd['command'] . " - " . $magehelper->__("Add product to cart.") . "\n";
441
+ if ($chatdata->_checkoutCmd['command']) $message .= $chatdata->_checkoutCmd['command'] . " - " . $magehelper->__("Checkout your order.") . "\n";
442
+ if ($chatdata->_clearCartCmd['command']) $message .= $chatdata->_clearCartCmd['command'] . " - " . $magehelper->__("Clear your cart.") . "\n";
443
+ if ($chatdata->_trackOrderCmd['command']) $message .= $chatdata->_trackOrderCmd['command'] . " - " . $magehelper->__("Track your order status.") . "\n";
444
+ if ($chatdata->_supportCmd['command']) $message .= $chatdata->_supportCmd['command'] . " - " . $magehelper->__("Send message to support.") . "\n";
445
+ if ($chatdata->_sendEmailCmd['command']) $message .= $chatdata->_sendEmailCmd['command'] . " - " . $magehelper->__("Send email.") . "\n";
446
+ //$message .= $chatdata->_cancelCmd['command'] . " - " . $magehelper->__("Cancel.");
447
+ if ($chatdata->_helpCmd['command']) $message .= $chatdata->_helpCmd['command'] . " - " . $magehelper->__("Get help.") . "\n";
448
+ //$message .= $chatdata->_aboutCmd['command'] . " - " . $magehelper->__("About.");
449
+ }
450
+
451
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $message));
452
+ return $telegram->respondSuccess();
453
+ }
454
+
455
+ // cancel command
456
+ if ($chatdata->checkCommand($text, $chatdata->_cancelCmd)) // TODO
457
+ {
458
+ if ($conversationState == $chatdata->_listCategoriesState)
459
+ {
460
+ $keyb = $telegram->buildKeyBoardHide(true); // hide keyboard built on listing categories
461
+ $content = array('chat_id' => $chatId, 'reply_markup' => $keyb, 'text' => $chatdata->_canceledMessage);
462
+ }
463
+ else if ($conversationState == $chatdata->_supportState)
464
+ {
465
+ $content = array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("exiting support mode."));
466
+ //$telegram->sendMessage(array('chat_id' => $chat_id, 'text' => $magehelper->__("Done.")));
467
+ }
468
+ else if ($conversationState == $chatdata->_searchState)
469
+ {
470
+ $content = array('chat_id' => $chatId, 'text' => $chatdata->_canceledMessage);
471
+ }
472
+ else if ($conversationState == $chatdata->_sendEmailState)
473
+ {
474
+ $content = array('chat_id' => $chatId, 'text' => $chatdata->_canceledMessage);
475
+ }
476
+ else if ($conversationState == $chatdata->_listProductsState)
477
+ {
478
+ $content = array('chat_id' => $chatId, 'text' => $chatdata->_canceledMessage);
479
+ }
480
+ else if ($conversationState == $chatdata->_listOrdersState)
481
+ {
482
+ $content = array('chat_id' => $chatId, 'text' => $chatdata->_canceledMessage);
483
+ }
484
+ else
485
+ $content = array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage);
486
+
487
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState))
488
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
489
+ else
490
+ $telegram->sendMessage($content);
491
+ return $telegram->respondSuccess();
492
+ }
493
+
494
+ // add2cart commands
495
+ if ($chatdata->checkCommandWithValue($text, $chatdata->_add2CartCmd['command'])) // ignore alias
496
+ {
497
+ $errorFlag = false;
498
+ $cmdvalue = $chatdata->getCommandValue($text, $chatdata->_add2CartCmd['command']);
499
+ if ($cmdvalue) // TODO
500
+ {
501
+ $productName = Mage::getModel('catalog/product')->load($cmdvalue)->getName();
502
+ if (empty($productName))
503
+ $productName = $magehelper->__("this product");
504
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("adding %s to your cart.", $productName)));
505
+ $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
506
+ if ($chatdata->addProd2Cart($cmdvalue))
507
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Added. To checkout send") . " " . $chatdata->_checkoutCmd['command']));
508
+ else
509
+ $errorFlag = true;
510
+ }
511
+ else
512
+ $errorFlag = true;
513
+
514
+ if ($errorFlag)
515
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
516
+ return $telegram->respondSuccess();
517
+ }
518
+
519
+ // states
520
+ if ($conversationState == $chatdata->_listCategoriesState) // TODO show only in stock products
521
+ {
522
+ if ($cat_id)
523
+ $_category = Mage::getModel('catalog/category')->load($cat_id);
524
+ else
525
+ $_category = Mage::getModel('catalog/category')->loadByAttribute('name', $text);
526
+
527
+ if ($showMore == 0) // show only in the first time
528
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("please wait while I gather all products from %s for you.", $_category->getName())));
529
+ else
530
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("listing more.")));
531
+
532
+ $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
533
+ $keyb = $telegram->buildKeyBoardHide(true); // hide keyboard built on listing categories
534
+ $errorFlag = false;
535
+ if ($_category) // check if variable isn't false/empty
536
+ {
537
+ if ($_category->getId()) // check if is a valid category
538
+ {
539
+ $noProductFlag = false;
540
+ $productCollection = $_category->getProductCollection()
541
+ ->addAttributeToSelect('*')
542
+ ->addAttributeToFilter('visibility', 4)
543
+ ->addAttributeToFilter('type_id', 'simple');
544
+ Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($productCollection);
545
+ $productIDs = $productCollection->getAllIds();
546
+
547
+ if ($productIDs)
548
+ {
549
+ $i = 0;
550
+ $total = count($productIDs);
551
+
552
+ if ($showMore < $total)
553
+ {
554
+ if ($showMore == 0)
555
+ {
556
+ if ($total == 1)
557
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Done. This category has only one product.", $total)));
558
+ else
559
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Done. This category has %s products.", $total)));
560
+ }
561
+
562
+ foreach ($productIDs as $productID)
563
+ {
564
+ $message = $chatdata->prepareTelegramProdMessages($productID);
565
+ if ($message) // TODO
566
+ {
567
+ if ($i >= $showMore)
568
+ {
569
+ $image = $chatdata->loadImageContent($productID);
570
+ if ($image)
571
+ $telegram->sendPhoto(array('chat_id' => $chatId, 'reply_markup' => $keyb, 'photo' => $image, 'caption' => $message));
572
+ else
573
+ $telegram->sendMessage(array('chat_id' => $chatId, 'reply_markup' => $keyb, 'text' => $message));
574
+
575
+ 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)
576
+ {
577
+ // TODO add option to list more products
578
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("To show more, send") . " " . $listMoreCategories . $_category->getId() . "_" . (string)($i + 1)));
579
+ if ($chatdata->getTelegramConvState() != $chatdata->_listProductsState)
580
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_listProductsState))
581
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
582
+ break;
583
+ }
584
+ else if (($i + 1) == $total) // if it's the last one, back to _startState
585
+ {
586
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("And that was the last one.")));
587
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState))
588
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
589
+ }
590
+ }
591
+ $i++;
592
+ }
593
+ }
594
+ if ($i == 0)
595
+ $noProductFlag = true;
596
+ }
597
+ else
598
+ $errorFlag = true;
599
+
600
+ }
601
+ else
602
+ $noProductFlag = true;
603
+
604
+ if ($noProductFlag)
605
+ $telegram->sendMessage(array('chat_id' => $chatId, 'reply_markup' => $keyb, 'text' => $magehelper->__("Sorry, no products found in this category.")));
606
+ }
607
+ else
608
+ $errorFlag = true;
609
+ }
610
+ else
611
+ $errorFlag = true;
612
+
613
+ if ($errorFlag)
614
+ {
615
+ $telegram->sendMessage(array('chat_id' => $chatId, 'reply_markup' => $keyb, 'text' => $chatdata->_errorMessage));
616
+ $chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState);
617
+ }
618
+ return $telegram->respondSuccess();
619
+ }
620
+ else if ($conversationState == $chatdata->_searchState) // TODO
621
+ {
622
+ if ($showMore == 0) // show only in the first time
623
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("please wait while I search for '%s' for you.", $text)));
624
+ else
625
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("listing more.")));
626
+ $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
627
+ $errorFlag = false;
628
+ $noProductFlag = false;
629
+ $productIDs = $chatdata->getProductIdsBySearch($text);
630
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState))
631
+ {
632
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
633
+ return $telegram->respondSuccess();
634
+ }
635
+ else if ($productIDs)
636
+ {
637
+ $i = 0;
638
+ $total = count($productIDs);
639
+
640
+ if ($showMore < $total)
641
+ {
642
+ if ($showMore == 0)
643
+ {
644
+ if ($total == 1)
645
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Done. I've found only %s product for your criteria.", $total)));
646
+ else
647
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Done. I've found %s products for your criteria.", $total)));
648
+ }
649
+
650
+ foreach ($productIDs as $productID)
651
+ {
652
+ $message = $chatdata->prepareTelegramProdMessages($productID);
653
+ if ($message) // TODO
654
+ {
655
+ if ($i >= $showMore)
656
+ {
657
+ $image = $chatdata->loadImageContent($productID);
658
+ if ($image)
659
+ $telegram->sendPhoto(array('chat_id' => $chatId, 'photo' => $image, 'caption' => $message));
660
+ else
661
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $message));
662
+
663
+ 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)
664
+ {
665
+ // TODO add option to list more products
666
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("To show more, send") . " " . $listMoreSearch . str_replace(" ", "_", $text) . "_" . (string)($i + 1)));
667
+ if ($chatdata->getTelegramConvState() != $chatdata->_listProductsState)
668
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_listProductsState))
669
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
670
+ break;
671
+ }
672
+ else if (($i + 1) == $total) // if it's the last one, back to _startState
673
+ {
674
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("And that was the last one.")));
675
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState))
676
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
677
+ }
678
+ }
679
+ $i++;
680
+ }
681
+ }
682
+ if ($i == 0)
683
+ $noProductFlag = true;
684
+ }
685
+ else
686
+ $errorFlag = true;
687
+ }
688
+ else
689
+ $noProductFlag = true;
690
+
691
+ if ($noProductFlag)
692
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Sorry, no products found for this criteria.")));
693
+
694
+ if ($errorFlag)
695
+ {
696
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
697
+ $chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState);
698
+ }
699
+
700
+ return $telegram->respondSuccess();
701
+ }
702
+ else if ($conversationState == $chatdata->_supportState)
703
+ {
704
+ if (!empty($supportGroupId))
705
+ {
706
+ $telegram->forwardMessage(array('chat_id' => $supportGroupId, 'from_chat_id' => $chatId, 'message_id' => $telegram->MessageID())); // Reply to this message to reply to the customer
707
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("we have sent your message to support.")));
708
+ }
709
+ else
710
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
711
+ return $telegram->respondSuccess();
712
+ }
713
+ else if ($conversationState == $chatdata->_sendEmailState)
714
+ {
715
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Trying to send the email...")));
716
+ if ($chatdata->sendEmail($text))
717
+ {
718
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Done.")));
719
+ }
720
+ else
721
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Sorry, I wasn't able to send an email this time. Please try again later.")));
722
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState))
723
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
724
+ return $telegram->respondSuccess();
725
+ }
726
+ else if ($conversationState == $chatdata->_trackOrderState)
727
+ {
728
+ $errorFlag = false;
729
+ if ($chatdata->getIsLogged() == "1")
730
+ {
731
+ $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)));
732
+ $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
733
+ $order = Mage::getModel('sales/order')->loadByIncrementId($text);
734
+ if ($order->getId())
735
+ {
736
+ if ($order->getCustomerId() == $chatdata->getCustomerId()) // not a problem if customer dosen't exist
737
+ {
738
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Your order status is") . " " . $order->getStatus()));
739
+ }
740
+ else
741
+ $errorFlag = true;
742
+ }
743
+ else
744
+ $errorFlag = true;
745
+ }
746
+ else
747
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_loginFirstMessage));
748
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState))
749
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
750
+ else if ($errorFlag)
751
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Sorry, we couldn't find any order with this information.")));
752
+ return $telegram->respondSuccess();
753
+ }
754
+
755
+ // general commands
756
+ if ($chatdata->checkCommand($text, $chatdata->_listCategoriesCmd))
757
+ {
758
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("please wait while I gather all categories for you.")));
759
+ $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
760
+
761
+ $categoryHelper = Mage::helper('catalog/category');
762
+ $categories = $categoryHelper->getStoreCategories(); // TODO test with a store without categories
763
+ $i = 0;
764
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_listCategoriesState))
765
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
766
+ else if ($categories)
767
+ {
768
+ $option = array();
769
+ foreach ($categories as $_category) // TODO fix buttons max size
770
+ {
771
+ if ($enableEmptyCategoriesListing != "1") // unallow empty categories listing
772
+ {
773
+ $category = Mage::getModel('catalog/category')->load($_category->getId()); // reload category because EAV Entity
774
+ $productIDs = $category->getProductCollection()
775
+ ->addAttributeToSelect('*')
776
+ ->addAttributeToFilter('visibility', 4)
777
+ ->addAttributeToFilter('type_id', 'simple')
778
+ ->getAllIds();
779
+ }
780
+ else
781
+ $productIDs = true;
782
+ if (!empty($productIDs)) // category with no products
783
+ {
784
+ $cat_name = $_category->getName();
785
+ array_push($option, $cat_name);
786
+ $i++;
787
+ }
788
+ }
789
+
790
+ $keyb = $telegram->buildKeyBoard(array($option));
791
+ $telegram->sendMessage(array('chat_id' => $chatId, 'reply_markup' => $keyb, 'text' => $magehelper->__("Select a category") . ". " . $chatdata->_cancelMessage));
792
+ }
793
+ else if ($i == 0)
794
+ {
795
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("No categories available at the moment, please try again later.")));
796
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState))
797
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
798
+ }
799
+ else
800
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
801
+
802
+ return $telegram->respondSuccess();
803
+ }
804
+ else if ($chatdata->checkCommand($text, $chatdata->_checkoutCmd)) // TODO
805
+ {
806
+ $sessionId = null;
807
+ $quoteId = null;
808
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("please wait while I prepare the checkout for you.")));
809
+ $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
810
+ if ($chatdata->getIsLogged() == "1")
811
+ {
812
+ if (Mage::getModel('customer/customer')->load((int)$chatdata->getCustomerId())->getId())
813
+ {
814
+ // if user is set as logged, then login using magento singleton
815
+ $customerSession = Mage::getSingleton('customer/session');
816
+ $customerSession->loginById((int)$chatdata->getCustomerId());
817
+ // then set current quote as customer quote
818
+ $customer = Mage::getModel('customer/customer')->load((int)$chatdata->getCustomerId());
819
+ $quote = Mage::getModel('sales/quote')->loadByCustomer($customer);
820
+ // set quote and session ids from logged user
821
+ $quoteId = $quote->getId();
822
+ $sessionId = $customerSession->getEncryptedSessionId();
823
+ }
824
+ }
825
+ if (!($sessionId && $quoteId))
826
+ {
827
+ // set quote and session ids from chatbot class
828
+ $sessionId = $chatdata->getSessionId();
829
+ $quoteId = $chatdata->getQuoteId();
830
+ }
831
+ $emptyCart = true;
832
+ if ($sessionId && $quoteId)
833
+ {
834
+ $cartUrl = Mage::helper('checkout/cart')->getCartUrl();
835
+ if (!isset(parse_url($cartUrl)['SID']))
836
+ $cartUrl .= "?SID=" . $sessionId; // add session id to url
837
+
838
+ $cart = Mage::getModel('checkout/cart')->setQuote(Mage::getModel('sales/quote')->loadByIdWithoutStore((int)$quoteId));
839
+ $ordersubtotal = $cart->getQuote()->getSubtotal();
840
+ if ($ordersubtotal > 0)
841
+ {
842
+ $emptyCart = false;
843
+ $message = $magehelper->__("Products on cart") . ":\n";
844
+ foreach ($cart->getQuote()->getItemsCollection() as $item) // TODO
845
+ {
846
+ $message .= $item->getQty() . "x " . $item->getProduct()->getName() . "\n" .
847
+ $magehelper->__("Price") . ": " . Mage::helper('core')->currency($item->getProduct()->getPrice(), true, false) . "\n\n";
848
+ }
849
+ $message .= $magehelper->__("Total") . ": " .
850
+ Mage::helper('core')->currency($ordersubtotal, true, false) . "\n\n" .
851
+ "[" . $magehelper->__("Checkout Here") . "](" . $cartUrl . ")";
852
+
853
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_checkoutState))
854
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
855
+ else
856
+ $telegram->sendMessage(array('chat_id' => $chatId, 'parse_mode' => 'Markdown', 'text' => $message));
857
+ }
858
+ else if (!$chatdata->clearCart()) // try to clear cart
859
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
860
+ }
861
+ if ($emptyCart)
862
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Your cart is empty.")));
863
+ return $telegram->respondSuccess();
864
+ }
865
+ else if ($chatdata->checkCommand($text, $chatdata->_clearCartCmd))
866
+ {
867
+ $errorFlag = false;
868
+ if ($chatdata->clearCart())
869
+ {
870
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_clearCartState))
871
+ $errorFlag = true;
872
+ else
873
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Cart cleared.")));
874
+ }
875
+ else
876
+ $errorFlag = true;
877
+ if ($errorFlag)
878
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
879
+ return $telegram->respondSuccess();
880
+ }
881
+ else if ($chatdata->checkCommand($text, $chatdata->_searchCmd))
882
+ {
883
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_searchState))
884
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
885
+ else
886
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("what do you want to search for?") . " " . $chatdata->_cancelMessage));
887
+ return $telegram->respondSuccess();
888
+ }
889
+ else if ($chatdata->checkCommand($text, $chatdata->_loginCmd)) // TODO
890
+ {
891
+ if ($chatdata->getIsLogged() != "1") // customer not logged
892
+ {
893
+ $hashlink = Mage::getUrl('chatbot/settings/index/') . "hash" . DS . $chatdata->getHashKey();
894
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_loginState))
895
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
896
+ else
897
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("To login to your account, click this link") . ": " . $hashlink));
898
+ }
899
+ else
900
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("You're already logged.")));
901
+ return $telegram->respondSuccess();
902
+ }
903
+ else if ($chatdata->checkCommand($text, $chatdata->_logoutCmd)) // TODO
904
+ {
905
+ if ($chatdata->getIsLogged() == "1")
906
+ {
907
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Ok, logging out.")));
908
+ $errorFlag = false;
909
+ try
910
+ {
911
+ $chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState);
912
+ $chatdata->updateChatdata('is_logged', "0");
913
+ $chatdata->updateChatdata('customer_id', ""); // TODO null?
914
+ $chatdata->clearCart();
915
+ }
916
+ catch (Exception $e)
917
+ {
918
+ $errorFlag = true;
919
+ }
920
+
921
+ if ($errorFlag)
922
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
923
+ else
924
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Done.")));
925
+ }
926
+ else
927
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("You're not logged.")));
928
+
929
+ return $telegram->respondSuccess();
930
+ }
931
+ else if ($chatdata->checkCommand($text, $chatdata->_listOrdersCmd) || $moreOrders) // TODO
932
+ {
933
+ if ($chatdata->getIsLogged() == "1")
934
+ {
935
+ if ($showMore == 0) // show only in the first time
936
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("please wait while I gather your orders for listing.")));
937
+ else
938
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("listing more.")));
939
+
940
+ $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
941
+ $ordersIDs = $chatdata->getOrdersIdsFromCustomer();
942
+ if ($ordersIDs)
943
+ {
944
+ $i = 0;
945
+ $total = count($ordersIDs);
946
+ if ($showMore < $total)
947
+ {
948
+ if ($showMore == 0)
949
+ {
950
+ if ($total == 1)
951
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Done. You've only one order.", $total)));
952
+ else
953
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Done. I've found %s orders.", $total)));
954
+ }
955
+
956
+ foreach($ordersIDs as $orderID)
957
+ {
958
+ $message = $chatdata->prepareTelegramOrderMessages($orderID);
959
+ if ($message) // TODO
960
+ {
961
+ if ($i >= $showMore)
962
+ {
963
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $message));
964
+ 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)
965
+ {
966
+ // TODO add option to list more orders
967
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("To show more, send") . " " . $listMoreOrders . (string)($i + 1)));
968
+ if ($chatdata->getTelegramConvState() != $chatdata->_listOrdersState)
969
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_listOrdersState))
970
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
971
+ break;
972
+ }
973
+ else if (($i + 1) == $total) // if it's the last one, back to _startState
974
+ {
975
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("And that was the last one.")));
976
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_startState))
977
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
978
+ }
979
+ }
980
+ $i++;
981
+ }
982
+ }
983
+ if ($i == 0)
984
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
985
+ // else if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_listOrdersState))
986
+ // $telegram->sendMessage(array('chat_id' => $chat_id, 'text' => $chatdata->_errorMessage));
987
+ }
988
+ }
989
+ else
990
+ {
991
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("This account has no orders.")));
992
+ return $telegram->respondSuccess();
993
+ }
994
+ }
995
+ else
996
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_loginFirstMessage));
997
+ return $telegram->respondSuccess();
998
+ }
999
+ else if ($chatdata->checkCommandWithValue($text, $chatdata->_reorderCmd['command'])) // ignore alias TODO
1000
+ {
1001
+ if ($chatdata->getIsLogged() == "1")
1002
+ {
1003
+ $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.")));
1004
+ $telegram->sendChatAction(array('chat_id' => $chatId, 'action' => 'typing'));
1005
+ $errorFlag = false;
1006
+ $cmdvalue = $chatdata->getCommandValue($text, $chatdata->_reorderCmd['command']);
1007
+ if ($cmdvalue)
1008
+ {
1009
+ if ($chatdata->clearCart())
1010
+ {
1011
+ $order = Mage::getModel('sales/order')->load($cmdvalue);
1012
+ if ($order->getId())
1013
+ {
1014
+ foreach($order->getAllVisibleItems() as $item) {
1015
+ if (!$chatdata->addProd2Cart($item->getProductId()))
1016
+ $errorFlag = true;
1017
+ }
1018
+ }
1019
+ else
1020
+ $errorFlag = true;
1021
+ }
1022
+ else
1023
+ $errorFlag = true;
1024
+ }
1025
+ else
1026
+ $errorFlag = true;
1027
+
1028
+ if ($errorFlag)
1029
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
1030
+ else if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_reorderState))
1031
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
1032
+ else // success!!
1033
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("to checkout send") . " " . $chatdata->_checkoutCmd['command']));
1034
+ }
1035
+ else
1036
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_loginFirstMessage));
1037
+ return $telegram->respondSuccess();
1038
+ }
1039
+ else if ($chatdata->checkCommand($text, $chatdata->_trackOrderCmd)) // TODO
1040
+ {
1041
+ if ($chatdata->getIsLogged() == "1")
1042
+ {
1043
+ $ordersIDs = $chatdata->getOrdersIdsFromCustomer();
1044
+ if ($ordersIDs)
1045
+ {
1046
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_trackOrderState))
1047
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
1048
+ else
1049
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("send the order number.")));
1050
+ }
1051
+ else
1052
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Your account dosen't have any orders.")));
1053
+ }
1054
+ else
1055
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_loginFirstMessage));
1056
+ return $telegram->respondSuccess();
1057
+ }
1058
+ else if ($chatdata->checkCommand($text, $chatdata->_supportCmd)) // TODO
1059
+ {
1060
+ $supportEnabled = $chatdata->getEnableSupport();
1061
+ $errorFlag = false;
1062
+ if ($supportEnabled == "1")
1063
+ {
1064
+ if ($chatdata->getFacebookConvState() != $chatdata->_supportState)
1065
+ {
1066
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_supportState))
1067
+ $errorFlag = true;
1068
+ else
1069
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("what do you need support for?") . " " . $chatdata->_cancelMessage));
1070
+ }
1071
+ else
1072
+ $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.")));
1073
+ }
1074
+ else
1075
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("I'm sorry, you can't ask for support now. Please try again later.")));
1076
+
1077
+ if ($errorFlag)
1078
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
1079
+ return $telegram->respondSuccess();
1080
+ }
1081
+ else if ($chatdata->checkCommand($text, $chatdata->_sendEmailCmd)) // TODO
1082
+ {
1083
+ if (!$chatdata->updateChatdata('telegram_conv_state', $chatdata->_sendEmailState))
1084
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
1085
+ else
1086
+ {
1087
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_positiveMessages[array_rand($chatdata->_positiveMessages)] . ", " . $magehelper->__("write the email content.")));
1088
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("By doing this you agree that we may contact you directly via chat message.") . " " . $chatdata->_cancelMessage));
1089
+ }
1090
+ return $telegram->respondSuccess();
1091
+ }
1092
+ else
1093
+ {
1094
+ if ($enableFinalMessage2Support == "1")
1095
+ {
1096
+ if (!empty($supportGroupId))
1097
+ {
1098
+ // if ($chatdata->getFacebookConvState() != $chatdata->_supportState) // TODO
1099
+ // $chatdata->updateChatdata('telegram_conv_state', $chatdata->_supportState);
1100
+ $telegram->forwardMessage(array('chat_id' => $supportGroupId, 'from_chat_id' => $chatId, 'message_id' => $telegram->MessageID()));
1101
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' =>
1102
+ $magehelper->__("Sorry, I didn't understand that.") . " " .
1103
+ $magehelper->__("Please wait while our support check your message so you can talk to a real person.")// . " " .
1104
+ //$chatdata->_cancelMessage
1105
+ )); // TODO
1106
+ }
1107
+ else
1108
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $chatdata->_errorMessage));
1109
+ return $telegram->respondSuccess();
1110
+ }
1111
+ //else if ($enable_witai == "1"){}
1112
+ else
1113
+ $telegram->sendMessage(array('chat_id' => $chatId, 'text' => $magehelper->__("Sorry, I didn't understand that."))); // TODO
1114
+ }
1115
+ }
1116
+
1117
+ return $telegram->respondSuccess();
1118
+ }
1119
+ }
1120
+
1121
+
1122
+ ?>
app/code/community/Werules/Chatbot/Model/Api/Telegram/Telegram.php ADDED
@@ -0,0 +1,1570 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Telegram Bot Class.
5
+ * @author Gabriele Grillo <gabry.grillo@alice.it>
6
+ */
7
+ class Telegram {
8
+
9
+ private $bot_id = "";
10
+ private $data = array();
11
+ private $updates = array();
12
+
13
+ /// Class constructor
14
+ /**
15
+ * Create a Telegram instance from the bot token
16
+ * \param $bot_id the bot token
17
+ * \return an instance of the class
18
+ */
19
+ public function __construct($bot_id) {
20
+ $this->bot_id = $bot_id;
21
+ $this->data = $this->getData();
22
+ }
23
+
24
+ /// Do requests to Telegram Bot API
25
+ /**
26
+ * Contacts the various API's endpoints
27
+ * \param $api the API endpoint
28
+ * \param $content the request parameters as array
29
+ * \param $post boolean tells if $content needs to be sends
30
+ * \return the JSON Telegram's reply
31
+ */
32
+ public function endpoint($api, array $content, $post = true) {
33
+ $url = 'https://api.telegram.org/bot' . $this->bot_id . '/' . $api;
34
+ if ($post)
35
+ $reply = $this->sendAPIRequest($url, $content);
36
+ else
37
+ $reply = $this->sendAPIRequest($url, array(), false);
38
+ return json_decode($reply, true);
39
+ }
40
+
41
+ /// A method for testing your bot.
42
+ /**
43
+ * A simple method for testing your bot's auth token. Requires no parameters.
44
+ * Returns basic information about the bot in form of a User object.
45
+ * \return the JSON Telegram's reply
46
+ */
47
+ public function getMe() {
48
+ return $this->endpoint("getMe", array(), false);
49
+ }
50
+
51
+ /// A method for responding http to Telegram.
52
+ /**
53
+ * \return the HTTP 200 to Telegram
54
+ */
55
+ public function respondSuccess() {
56
+ http_response_code(200);
57
+ return json_encode(array("status" => "success"));
58
+ }
59
+
60
+ /// Send a message
61
+ /**
62
+ * Contacts the various API's endpoints<br/>Values inside $content:<br/>
63
+ * <table>
64
+ * <tr>
65
+ * <td><strong>Parameters</strong></td>
66
+ * <td><strong>Type</strong></td>
67
+ * <td><strong>Required</strong></td>
68
+ * <td><strong>Description</strong></td>
69
+ * </tr>
70
+ * <tr>
71
+ * <td>chat_id</td>
72
+ * <td>Integer</td>
73
+ * <td>Yes</td>
74
+ * <td>Unique identifier for the message recipient — User or GroupChat id</td>
75
+ * * </tr>
76
+ * <tr>
77
+ * <td>text</td>
78
+ * <td>String</td>
79
+ * <td>Yes</td>
80
+ * <td>Text of the message to be sent</td>
81
+ * </tr>
82
+ * <tr>
83
+ * <td>parse_mode</td>
84
+ * <td>String</td>
85
+ * <td>Optional</td>
86
+ * <td>Send <em>Markdown</em>, if you want Telegram apps to show bold, italic and inline URLs in your bot's message. For the moment, only Telegram for Android supports this.</td>
87
+ * </tr>
88
+ * <tr>
89
+ * <td>disable_web_page_preview</td>
90
+ * <td>Boolean</td>
91
+ * <td>Optional</td>
92
+ * <td>Disables link previews for links in this message</td>
93
+ * </tr>
94
+ * <tr>
95
+ * <td>reply_to_message_id</td>
96
+ * <td>Integer</td>
97
+ * <td>Optional</td>
98
+ * <td>If the message is a reply, ID of the original message</td>
99
+ * </tr>
100
+ * <tr>
101
+ * <td>reply_markup</td>
102
+ * <td>ReplyKeyboardMarkup or ReplyKeyboardHide or ForceReply</td>
103
+ * <td>Optional</td>
104
+ * <td>Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</td>
105
+ * </tr>
106
+ * </table>
107
+ * \param $content the request parameters as array
108
+ * \return the JSON Telegram's reply
109
+ */
110
+ public function sendMessage(array $content) {
111
+ return $this->endpoint("sendMessage", $content);
112
+ }
113
+
114
+ /// Forward a message
115
+ /**
116
+ * Use this method to forward messages of any kind. On success, the sent Message is returned<br/>Values inside $content:<br/>
117
+ * <table>
118
+ * <tr>
119
+ * <td><strong>Parameters</strong></td>
120
+ * <td><strong>Type</strong></td>
121
+ * <td><strong>Required</strong></td>
122
+ * <td><strong>Description</strong></td>
123
+ * </tr>
124
+ * <tr>
125
+ * <td>chat_id</td>
126
+ * <td>Integer</td>
127
+ * <td>Yes</td>
128
+ * <td>Unique identifier for the message recipient — User or GroupChat id</td>
129
+ * </tr>
130
+ * <tr>
131
+ * <td>from_chat_id</td>
132
+ * <td>Integer</td>
133
+ * <td>Yes</td>
134
+ * <td>Unique identifier for the chat where the original message was sent — User or GroupChat id</td>
135
+ * </tr>
136
+ * <tr>
137
+ * <td>message_id</td>
138
+ * <td>Integer</td>
139
+ * <td>Yes</td>
140
+ * <td>Unique message identifier</td>
141
+ * </tr>
142
+ * </table>
143
+ * \param $content the request parameters as array
144
+ * \return the JSON Telegram's reply
145
+ */
146
+ public function forwardMessage(array $content) {
147
+ return $this->endpoint("forwardMessage", $content);
148
+ }
149
+
150
+ /// Send a photo
151
+ /**
152
+ * Use this method to send photos. On success, the sent Message is returned.<br/>Values inside $content:<br/>
153
+ * <table>
154
+ * <tr>
155
+ * <td><strong>Parameters</strong></td>
156
+ * <td><strong>Type</strong></td>
157
+ * <td><strong>Required</strong></td>
158
+ * <td><strong>Description</strong></td>
159
+ * </tr>
160
+ * <tr>
161
+ * <td>chat_id</td>
162
+ * <td>Integer</td>
163
+ * <td>Yes</td>
164
+ * <td>Unique identifier for the message recipient — User or GroupChat id</td>
165
+ * </tr>
166
+ * <tr>
167
+ * <td>photo</td>
168
+ * <td><a href="https://core.telegram.org/bots/api#inputfile">InputFile</a> or String</td>
169
+ * <td>Yes</td>
170
+ * <td>Photo to send. You can either pass a <em>file_id</em> as String to resend a photo that is already on the Telegram servers, or upload a new photo using multipart/form-data.</td>
171
+ * </tr>
172
+ * <tr>
173
+ * <td>caption</td>
174
+ * <td>String</td>
175
+ * <td>Optional</td>
176
+ * <td>Photo caption (may also be used when resending photos by <em>file_id</em>).</td>
177
+ * </tr>
178
+ * <tr>
179
+ * <td>reply_to_message_id</td>
180
+ * <td>Integer</td>
181
+ * <td>Optional</td>
182
+ * <td>If the message is a reply, ID of the original message</td>
183
+ * </tr>
184
+ * <tr>
185
+ * <td>reply_markup</td>
186
+ * <td>ReplyKeyboardMarkup or >ReplyKeyboardHide or ForceReply</td>
187
+ * <td>Optional</td>
188
+ * <td>Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</td>
189
+ * </tr>
190
+ * </table>
191
+ * \param $content the request parameters as array
192
+ * \return the JSON Telegram's reply
193
+ */
194
+ public function sendPhoto(array $content) {
195
+ return $this->endpoint("sendPhoto", $content);
196
+ }
197
+
198
+ /// Send an audio
199
+ /**
200
+ * Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .mp3 format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
201
+
202
+ * For backward compatibility, when the fields title and performer are both empty and the mime-type of the file to be sent is not audio/mpeg, the file will be sent as a playable voice message. For this to work, the audio must be in an .ogg file encoded with OPUS. This behavior will be phased out in the future. For sending voice messages, use the sendVoice method instead.<br/>Values inside $content:<br/>
203
+ * <table>
204
+ * <tr>
205
+ * <td><strong>Parameters</strong></td>
206
+ * <td><strong>Type</strong></td>
207
+ * <td><strong>Required</strong></td>
208
+ * <td><strong>Description</strong></td>
209
+ * </tr>
210
+ * <tr>
211
+ * <td>chat_id</td>
212
+ * <td>Integer</td>
213
+ * <td>Yes</td>
214
+ * <td>Unique identifier for the message recipient — User or GroupChat id</td>
215
+ * </tr>
216
+ * <tr>
217
+ * <td>audio</td>
218
+ * <td><a href="https://core.telegram.org/bots/api#inputfile">InputFile</a> or String</td>
219
+ * <td>Yes</td>
220
+ * <td>Audio file to send. You can either pass a <em>file_id</em> as String to resend an audio that is already on the Telegram servers, or upload a new audio file using <strong>multipart/form-data</strong>.</td>
221
+ * </tr>
222
+ * <tr>
223
+ * <td>duration</td>
224
+ * <td>Integer</td>
225
+ * <td>Optional</td>
226
+ * <td>Duration of the audio in seconds</td>
227
+ * </tr>
228
+ * <tr>
229
+ * <td>performer</td>
230
+ * <td>String</td>
231
+ * <td>Optional</td>
232
+ * <td>Performer</td>
233
+ * </tr>
234
+ * <tr>
235
+ * <td>title</td>
236
+ * <td>String</td>
237
+ * <td>Optional</td>
238
+ * <td>Track name</td>
239
+ * </tr>
240
+ * <tr>
241
+ * <td>reply_to_message_id</td>
242
+ * <td>Integer</td>
243
+ * <td>Optional</td>
244
+ * <td>If the message is a reply, ID of the original message</td>
245
+ * </tr>
246
+ * <tr>
247
+ * <td>reply_markup</td>
248
+ * <td>ReplyKeyboardMarkup or ReplyKeyboardHide or ForceReply</td>
249
+ * <td>Optional</td>
250
+ * <td>Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</td>
251
+ * </tr>
252
+ * </table>
253
+ * \param $content the request parameters as array
254
+ * \return the JSON Telegram's reply
255
+ */
256
+ public function sendAudio(array $content) {
257
+ return $this->endpoint("sendAudio", $content);
258
+ }
259
+
260
+ /// Send a document
261
+ /**
262
+ * Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.<br/>Values inside $content:<br/>
263
+ * <table>
264
+ * <tr>
265
+ * <td><strong>Parameters</strong></td>
266
+ * <td><strong>Type</strong></td>
267
+ * <td><strong>Required</strong></td>
268
+ * <td><strong>Description</strong></td>
269
+ * </tr>
270
+ * <tr>
271
+ * <td>chat_id</td>
272
+ * <td>Integer</td>
273
+ * <td>Yes</td>
274
+ * <td>Unique identifier for the message recipient — User or GroupChat id</td>
275
+ * </tr>
276
+ * <tr>
277
+ * <td>document</td>
278
+ * <td>InputFile or String</td>
279
+ * <td>Yes</td>
280
+ * <td>File to send. You can either pass a <em>file_id</em> as String to resend a file that is already on the Telegram servers, or upload a new file using <strong>multipart/form-data</strong>.</td>
281
+ * </tr>
282
+ * <tr>
283
+ * <td>reply_to_message_id</td>
284
+ * <td>Integer</td>
285
+ * <td>Optional</td>
286
+ * <td>If the message is a reply, ID of the original message</td>
287
+ * </tr>
288
+ * <tr>
289
+ * <td>reply_markup</td>
290
+ * <td>ReplyKeyboardMarkup or ReplyKeyboardHide or ForceReply</td>
291
+ * <td>Optional</td>
292
+ * <td>Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</td>
293
+ * </tr>
294
+ * </table>
295
+ * \param $content the request parameters as array
296
+ * \return the JSON Telegram's reply
297
+ */
298
+ public function sendDocument(array $content) {
299
+ return $this->endpoint("sendDocument", $content);
300
+ }
301
+
302
+ /// Send a sticker
303
+ /**
304
+ * Use this method to send .webp stickers. On success, the sent Message is returned.<br/>Values inside $content:<br/>
305
+ * <table>
306
+ * <tr>
307
+ * <td><strong>Parameters</strong></td>
308
+ * <td><strong>Type</strong></td>
309
+ * <td><strong>Required</strong></td>
310
+ * <td><strong>Description</strong></td>
311
+ * </tr>
312
+ * <tr>
313
+ * <td>chat_id</td>
314
+ * <td>Integer</td>
315
+ * <td>Yes</td>
316
+ * <td>Unique identifier for the message recipient — User or GroupChat id</td>
317
+ * </tr>
318
+ * <tr>
319
+ * <td>sticker</td>
320
+ * <td><a href="https://core.telegram.org/bots/api#inputfile">InputFile</a> or String</td>
321
+ * <td>Yes</td>
322
+ * <td>Sticker to send. You can either pass a <em>file_id</em> as String to resend a sticker that is already on the Telegram servers, or upload a new sticker using <strong>multipart/form-data</strong>.</td>
323
+ * </tr>
324
+ * <tr>
325
+ * <td>reply_to_message_id</td>
326
+ * <td>Integer</td>
327
+ * <td>Optional</td>
328
+ * <td>If the message is a reply, ID of the original message</td>
329
+ * </tr>
330
+ * <tr>
331
+ * <td>reply_markup</td>
332
+ * <td>ReplyKeyboardMarkup or ReplyKeyboardHide or ForceReply</td>
333
+ * <td>Optional</td>
334
+ * <td>Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</td>
335
+ * </tr>
336
+ * </table>
337
+ * \param $content the request parameters as array
338
+ * \return the JSON Telegram's reply
339
+ */
340
+ public function sendSticker(array $content) {
341
+ return $this->endpoint("sendSticker", $content);
342
+ }
343
+
344
+ /// Send a video
345
+ /**
346
+ * Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.<br/>Values inside $content:<br/>
347
+ * <table>
348
+ * <tr>
349
+ * <td><strong>Parameters</strong></td>
350
+ * <td><strong>Type</strong></td>
351
+ * <td><strong>Required</strong></td>
352
+ * <td><strong>Description</strong></td>
353
+ * </tr>
354
+ * <tr>
355
+ * <td>chat_id</td>
356
+ * <td>Integer</td>
357
+ * <td>Yes</td>
358
+ * <td>Unique identifier for the message recipient — User or GroupChat id</td>
359
+ * </tr>
360
+ * <tr>
361
+ * <td>video</td>
362
+ * <td><a href="https://core.telegram.org/bots/api#inputfile">InputFile</a> or String</td>
363
+ * <td>Yes</td>
364
+ * <td>Video to send. You can either pass a <em>file_id</em> as String to resend a video that is already on the Telegram servers, or upload a new video file using <strong>multipart/form-data</strong>.</td>
365
+ * </tr>
366
+ * <tr>
367
+ * <td>duration</td>
368
+ * <td>Integer</td>
369
+ * <td>Optional</td>
370
+ * <td>Duration of sent video in seconds</td>
371
+ * </tr>
372
+ * <tr>
373
+ * <td>caption</td>
374
+ * <td>String</td>
375
+ * <td>Optional</td>
376
+ * <td>Video caption (may also be used when resending videos by <em>file_id</em>).</td>
377
+ * </tr>
378
+ * <tr>
379
+ * <td>reply_to_message_id</td>
380
+ * <td>Integer</td>
381
+ * <td>Optional</td>
382
+ * <td>If the message is a reply, ID of the original message</td>
383
+ * </tr>
384
+ * <tr>
385
+ * <td>reply_markup</td>
386
+ * <td>ReplyKeyboardMarkup or ReplyKeyboardHide or ForceReply</td>
387
+ * <td>Optional</td>
388
+ * <td>Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</td>
389
+ * </tr>
390
+ * </table>
391
+ * \param $content the request parameters as array
392
+ * \return the JSON Telegram's reply
393
+ */
394
+ public function sendVideo(array $content) {
395
+ return $this->endpoint("sendVideo", $content);
396
+ }
397
+
398
+ /// Send a voice message
399
+ /**
400
+ * Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.<br/>Values inside $content:<br/>
401
+ * <table>
402
+ * <tr>
403
+ * <td><strong>Parameters</strong></td>
404
+ * <td><strong>Type</strong></td>
405
+ * <td><strong>Required</strong></td>
406
+ * <td><strong>Description</strong></td>
407
+ * </tr>
408
+ * <tr>
409
+ * <td>chat_id</td>
410
+ * <td>Integer</td>
411
+ * <td>Yes</td>
412
+ * <td>Unique identifier for the message recipient — User or GroupChat id</td>
413
+ * </tr>
414
+ * <tr>
415
+ * <td>voice</td>
416
+ * <td><a href="https://core.telegram.org/bots/api#inputfile">InputFile</a> or String</td>
417
+ * <td>Yes</td>
418
+ * <td>Audio file to send. You can either pass a <em>file_id</em> as String to resend an audio that is already on the Telegram servers, or upload a new audio file using <strong>multipart/form-data</strong>.</td>
419
+ * </tr>
420
+ * <tr>
421
+ * <td>duration</td>
422
+ * <td>Integer</td>
423
+ * <td>Optional</td>
424
+ * <td>Duration of sent audio in seconds</td>
425
+ * </tr>
426
+ * <tr>
427
+ * <td>reply_to_message_id</td>
428
+ * <td>Integer</td>
429
+ * <td>Optional</td>
430
+ * <td>If the message is a reply, ID of the original message</td>
431
+ * </tr>
432
+ * <tr>
433
+ * <td>reply_markup</td>
434
+ * <td>ReplyKeyboardMarkup</a> or ReplyKeyboardHide or ForceReply</td>
435
+ * <td>Optional</td>
436
+ * <td>Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</td>
437
+ * </tr>
438
+ * </table>
439
+ * \param $content the request parameters as array
440
+ * \return the JSON Telegram's reply
441
+ */
442
+ public function sendVoice(array $content) {
443
+ return $this->endpoint("sendVoice", $content);
444
+ }
445
+
446
+ /// Send a location
447
+ /**
448
+ * Use this method to send point on the map. On success, the sent Message is returned.<br/>Values inside $content:<br/>
449
+ * <table>
450
+ * <tr>
451
+ * <td><strong>Parameters</strong></td>
452
+ * <td><strong>Type</strong></td>
453
+ * <td><strong>Required</strong></td>
454
+ * <td><strong>Description</strong></td>
455
+ * </tr>
456
+ * <tr>
457
+ * <td>chat_id</td>
458
+ * <td>Integer</td>
459
+ * <td>Yes</td>
460
+ * <td>Unique identifier for the message recipient — User or GroupChat id</td>
461
+ * </tr>
462
+ * <tr>
463
+ * <td>latitude</td>
464
+ * <td>Float number</td>
465
+ * <td>Yes</td>
466
+ * <td>Latitude of location</td>
467
+ * </tr>
468
+ * <tr>
469
+ * <td>longitude</td>
470
+ * <td>Float number</td>
471
+ * <td>Yes</td>
472
+ * <td>Longitude of location</td>
473
+ * </tr>
474
+ * <tr>
475
+ * <td>reply_to_message_id</td>
476
+ * <td>Integer</td>
477
+ * <td>Optional</td>
478
+ * <td>If the message is a reply, ID of the original message</td>
479
+ * </tr>
480
+ * <tr>
481
+ * <td>reply_markup</td>
482
+ * <td>ReplyKeyboardMarkup or ReplyKeyboardHide or ForceReply</td>
483
+ * <td>Optional</td>
484
+ * <td>Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</td>
485
+ * </tr>
486
+ * </table>
487
+ * \param $content the request parameters as array
488
+ * \return the JSON Telegram's reply
489
+ */
490
+ public function sendLocation(array $content) {
491
+ return $this->endpoint("sendLocation", $content);
492
+ }
493
+
494
+ /// Send Venue
495
+ /**
496
+ * Use this method to send information about a venue. On success, the sent <a href="https://core.telegram.org/bots/api#message">Message</a> is returned.<br/>Values inside $content:<br/>
497
+ * <table>
498
+ * <tr>
499
+ * <td><strong>Parameters</strong></td>
500
+ * <td><strong>Type</strong></td>
501
+ * <td><strong>Required</strong></td>
502
+ * <td><strong>Description</strong></td>
503
+ * </tr>
504
+ * <tr>
505
+ * <td>chat_id</td>
506
+ * <td>Integer or String</td>
507
+ * <td>Yes</td>
508
+ * <td>Unique identifier for the target chat or username of the target channel (in the format <code>@channelusername</code>)</td>
509
+ * </tr>
510
+ * <tr>
511
+ * <td>latitude</td>
512
+ * <td>Float number</td>
513
+ * <td>Yes</td>
514
+ * <td>Latitude of the venue</td>
515
+ * </tr>
516
+ * <tr>
517
+ * <td>longitude</td>
518
+ * <td>Float number</td>
519
+ * <td>Yes</td>
520
+ * <td>Longitude of the venue</td>
521
+ * </tr>
522
+ * <tr>
523
+ * <td>title</td>
524
+ * <td>String</td>
525
+ * <td>Yes</td>
526
+ * <td>Name of the venue</td>
527
+ * </tr>
528
+ * <tr>
529
+ * <td>address</td>
530
+ * <td>String</td>
531
+ * <td>Yes</td>
532
+ * <td>Address of the venue</td>
533
+ * </tr>
534
+ * <tr>
535
+ * <td>foursquare_id</td>
536
+ * <td>String</td>
537
+ * <td>Optional</td>
538
+ * <td>Foursquare identifier of the venue</td>
539
+ * </tr>
540
+ * <tr>
541
+ * <td>disable_notification</td>
542
+ * <td>Boolean</td>
543
+ * <td>Optional</td>
544
+ * <td>Sends the message <a href="https://telegram.org/blog/channels-2-0#silent-messages">silently</a>. iOS users will not receive a notification, Android users will receive a notification with no sound.</td>
545
+ * </tr>
546
+ * <tr>
547
+ * <td>reply_to_message_id</td>
548
+ * <td>Integer</td>
549
+ * <td>Optional</td>
550
+ * <td>If the message is a reply, ID of the original message</td>
551
+ * </tr>
552
+ * <tr>
553
+ * <td>reply_markup</td>
554
+ * <td><a href="https://core.telegram.org/bots/api#inlinekeyboardmarkup">InlineKeyboardMarkup</a> or <a href="https://core.telegram.org/bots/api#replykeyboardmarkup">ReplyKeyboardMarkup</a> or <a href="https://core.telegram.org/bots/api#replykeyboardhide">ReplyKeyboardHide</a> or <a href="https://core.telegram.org/bots/api#forcereply">ForceReply</a></td>
555
+ * <td>Optional</td>
556
+ * <td>Additional interface options. A JSON-serialized object for an <a href="https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating">inline keyboard</a>, <a href="https://core.telegram.org/bots#keyboards">custom reply keyboard</a>, instructions to hide reply keyboard or to force a reply from the user.</td>
557
+ * </tr>
558
+ * </table>
559
+ * \param $content the request parameters as array
560
+ * \return the JSON Telegram's reply
561
+ */
562
+ public function sendVenue(array $content) {
563
+ return $this->endpoint("sendVenue", $content);
564
+ }
565
+
566
+ //Send contact
567
+ /**Use this method to send phone contacts. On success, the sent <a href="https://core.telegram.org/bots/api#message">Message</a> is returned.</p> <br/>Values inside $content:<br/>
568
+ * <table>
569
+ * <tr>
570
+ * <td><strong>Parameters</strong></td>
571
+ * <td><strong>Type</strong></td>
572
+ * <td><strong>Required</strong></td>
573
+ * <td><strong>Description</strong></td>
574
+ * </tr>
575
+ * <tr>
576
+ * <td>chat_id</td>
577
+ * <td>Integer or String</td>
578
+ * <td>Yes</td>
579
+ * <td>Unique identifier for the target chat or username of the target channel (in the format <code>@channelusername</code>)</td>
580
+ * </tr>
581
+ * <tr>
582
+ * <td>phone_number</td>
583
+ * <td>String</td>
584
+ * <td>Yes</td>
585
+ * <td>Contact&#39;s phone number</td>
586
+ * </tr>
587
+ * <tr>
588
+ * <td>first_name</td>
589
+ * <td>String</td>
590
+ * <td>Yes</td>
591
+ * <td>Contact&#39;s first name</td>
592
+ * </tr>
593
+ * <tr>
594
+ * <td>last_name</td>
595
+ * <td>String</td>
596
+ * <td>Optional</td>
597
+ * <td>Contact&#39;s last name</td>
598
+ * </tr>
599
+ * <tr>
600
+ * <td>disable_notification</td>
601
+ * <td>Boolean</td>
602
+ * <td>Optional</td>
603
+ * <td>Sends the message <a href="https://telegram.org/blog/channels-2-0#silent-messages">silently</a>. iOS users will not receive a notification, Android users will receive a notification with no sound.</td>
604
+ * </tr>
605
+ * <tr>
606
+ * <td>reply_to_message_id</td>
607
+ * <td>Integer</td>
608
+ * <td>Optional</td>
609
+ * <td>If the message is a reply, ID of the original message</td>
610
+ * </tr>
611
+ * <tr>
612
+ * <td>reply_markup</td>
613
+ * <td><a href="https://core.telegram.org/bots/api#inlinekeyboardmarkup">InlineKeyboardMarkup</a> or <a href="https://core.telegram.org/bots/api#replykeyboardmarkup">ReplyKeyboardMarkup</a> or <a href="https://core.telegram.org/bots/api#replykeyboardhide">ReplyKeyboardHide</a> or <a href="https://core.telegram.org/bots/api#forcereply">ForceReply</a></td>
614
+ * <td>Optional</td>
615
+ * <td>Additional interface options. A JSON-serialized object for an <a href="https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating">inline keyboard</a>, <a href="https://core.telegram.org/bots#keyboards">custom reply keyboard</a>, instructions to hide keyboard or to force a reply from the user.</td>
616
+ * </tr>
617
+ * </table>
618
+ * \param $content the request parameters as array
619
+ * \return the JSON Telegram's reply
620
+ */
621
+ public function sendContact(array $content) {
622
+ return $this->endpoint("sendContact", $content);
623
+ }
624
+
625
+ /// Send a chat action
626
+ /**
627
+ * Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status).
628
+
629
+ * Example: The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of “Retrieving image, please wait…”, the bot may use sendChatAction with action = upload_photo. The user will see a “sending photo” status for the bot.
630
+
631
+ * We only recommend using this method when a response from the bot will take a noticeable amount of time to arrive.<br/>Values inside $content:<br/>
632
+ * <table>
633
+ * <tr>
634
+ * <td><strong>Parameters</strong></td>
635
+ * <td><strong>Type</strong></td>
636
+ * <td><strong>Required</strong></td>
637
+ * <td><strong>Description</strong></td>
638
+ * </tr>
639
+ * <tr>
640
+ * <td>chat_id</td>
641
+ * <td>Integer</td>
642
+ * <td>Yes</td>
643
+ * <td>Unique identifier for the message recipient — User or GroupChat id</td>
644
+ * </tr>
645
+ * <tr>
646
+ * <td>action</td>
647
+ * <td>String</td>
648
+ * <td>Yes</td>
649
+ * <td>Type of action to broadcast. Choose one, depending on what the user is about to receive: <em>typing</em> for text messages, <em>upload_photo</em> for photos, <em>record_video</em> or <em>upload_video</em> for videos, <em>record_audio</em> or <em>upload_audio</em> for audio files, <em>upload_document</em> for general files, <em>find_location</em> for location data.</td>
650
+ * </tr>
651
+ * </table>
652
+ * \param $content the request parameters as array
653
+ * \return the JSON Telegram's reply
654
+ */
655
+ public function sendChatAction(array $content) {
656
+ return $this->endpoint("sendChatAction", $content);
657
+ }
658
+
659
+ /// Get a list of profile pictures for a user
660
+ /**
661
+ * Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.<br/>Values inside $content:<br/>
662
+ * <table>
663
+ * <tr>
664
+ * <td><strong>Parameters</strong></td>
665
+ * <td><strong>Type</strong></td>
666
+ * <td><strong>Required</strong></td>
667
+ * <td><strong>Description</strong></td>
668
+ * </tr>
669
+ * <tr>
670
+ * <td>user_id</td>
671
+ * <td>Integer</td>
672
+ * <td>Yes</td>
673
+ * <td>Unique identifier of the target user</td>
674
+ * </tr>
675
+ * <tr>
676
+ * <td>offset</td>
677
+ * <td>Integer</td>
678
+ * <td>Optional</td>
679
+ * <td>Sequential number of the first photo to be returned. By default, all photos are returned.</td>
680
+ * </tr>
681
+ * <tr>
682
+ * <td>limit</td>
683
+ * <td>Integer</td>
684
+ * <td>Optional</td>
685
+ * <td>Limits the number of photos to be retrieved. Values between 1—100 are accepted. Defaults to 100.</td>
686
+ * </tr>
687
+ * </table>
688
+ * \param $content the request parameters as array
689
+ * \return the JSON Telegram's reply
690
+ */
691
+ public function getUserProfilePhotos(array $content) {
692
+ return $this->endpoint("getUserProfilePhotos", $content);
693
+ }
694
+
695
+ /// Use this method to get basic info about a file and prepare it for downloading
696
+ /**
697
+ * Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>, where <file_path> is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again.
698
+ * \param $file_id String File identifier to get info about
699
+ * \return the JSON Telegram's reply
700
+ */
701
+ public function getFile($file_id) {
702
+ $content = array('file_id' => $file_id);
703
+ return $this->endpoint("getFile", $content);
704
+ }
705
+
706
+ /**
707
+ * Use this method to kick a user from a group or a supergroup. In the case of supergroups, the user will not be able to return to the group on their own using invite links, etc., unless <a href="https://core.telegram.org/bots/api#unbanchatmember">unbanned</a> first. The bot must be an administrator in the group for this to work. Returns <em>True</em> on success.<br>
708
+ * Note: This will method only work if the ‘All Members Are Admins’ setting is off in the target group. Otherwise members may only be removed by the group&#39;s creator or by the member that added them.<br/>Values inside $content:<br/>
709
+ * <table>
710
+ * <tbody>
711
+ * <tr>
712
+ * <td><strong>Parameters</strong></td>
713
+ * <td><strong>Type</strong></td>
714
+ * <td><strong>Required</strong></td>
715
+ * <td><strong>Description</strong></td>
716
+ * </tr>
717
+ * <tr>
718
+ * <td>chat_id</td>
719
+ * <td>Integer or String</td>
720
+ * <td>Yes</td>
721
+ * <td>Unique identifier for the target group or username of the target supergroup (in the format <code>@supergroupusername</code>)</td>
722
+ * </tr>
723
+ * <tr>
724
+ * <td>user_id</td>
725
+ * <td>Integer</td>
726
+ * <td>Yes</td>
727
+ * <td>Unique identifier of the target user</td>
728
+ * </tr>
729
+ * </table>
730
+ * \param $content the request parameters as array
731
+ * \return the JSON Telegram's reply
732
+ */
733
+ public function kickChatMember(array $content) {
734
+ return $this->endpoint("kickChatMember", $content);
735
+ }
736
+
737
+ /**
738
+ * Use this method for your bot to leave a group, supergroup or channel. Returns <em>True</em> on success.</p> <br/>Values inside $content:<br/>
739
+ * <table>
740
+ * <tr>
741
+ * <td><strong>Parameters</strong></td>
742
+ * <td><strong>Type</strong></td>
743
+ * <td><strong>Required</strong></td>
744
+ * <td><strong>Description</strong></td>
745
+ * </tr>
746
+ * <tr>
747
+ * <td>chat_id</td>
748
+ * <td>Integer or String</td>
749
+ * <td>Yes</td>
750
+ * <td>Unique identifier for the target chat or username of the target supergroup or channel (in the format <code>@channelusername</code>)</td>
751
+ * </tr>
752
+ * </table>
753
+ * \param $content the request parameters as array
754
+ * \return the JSON Telegram's reply
755
+ */
756
+ public function leaveChat(array $content) {
757
+ return $this->endpoint("leaveChat", $content);
758
+ }
759
+
760
+ /**
761
+ * Use this method to unban a previously kicked user in a supergroup. The user will <strong>not</strong> return to the group automatically, but will be able to join via link, etc. The bot must be an administrator in the group for this to work. Returns <em>True</em> on success.<br/>Values inside $content:<br/>
762
+ * <table>
763
+ * <tr>
764
+ * <td><strong>Parameters</strong></td>
765
+ * <td><strong>Type</strong></td>
766
+ * <td><strong>Required</strong></td>
767
+ * <td><strong>Description</strong></td>
768
+ * </tr>
769
+ * <tr>
770
+ * <td>chat_id</td>
771
+ * <td>Integer or String</td>
772
+ * <td>Yes</td>
773
+ * <td>Unique identifier for the target group or username of the target supergroup (in the format <code>@supergroupusername</code>)</td>
774
+ * </tr>
775
+ * <tr>
776
+ * <td>user_id</td>
777
+ * <td>Integer</td>
778
+ * <td>Yes</td>
779
+ * <td>Unique identifier of the target user</td>
780
+ * </tr>
781
+ * </table>
782
+ * \param $content the request parameters as array
783
+ * \return the JSON Telegram's reply
784
+ */
785
+ public function unbanChatMember(array $content) {
786
+ return $this->endpoint("unbanChatMember", $content);
787
+ }
788
+
789
+ /**
790
+ * Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a <a href="https://core.telegram.org/bots/api#chat">Chat</a> object on success.<br/>Values inside $content:<br/>
791
+ * <table>
792
+ * <tr>
793
+ * <td><strong>Parameters</strong></td>
794
+ * <td><strong>Type</strong></td>
795
+ * <td><strong>Required</strong></td>
796
+ * <td><strong>Description</strong></td>
797
+ * </tr>
798
+ * <tr>
799
+ * <td>chat_id</td>
800
+ * <td>Integer or String</td>
801
+ * <td>Yes</td>
802
+ * <td>Unique identifier for the target chat or username of the target supergroup or channel (in the format <code>@channelusername</code>)</td>
803
+ * </tr>
804
+ * </table>
805
+ * \param $content the request parameters as array
806
+ * \return the JSON Telegram's reply
807
+ */
808
+ public function getChat(array $content) {
809
+ return $this->endpoint("getChat", $content);
810
+ }
811
+
812
+ /**
813
+ * Use this method to get a list of administrators in a chat. On success, returns an Array of <a href="https://core.telegram.org/bots/api#chatmember">ChatMember</a> objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.<br/>Values inside $content:<br/>
814
+ * <table>
815
+ * <tr>
816
+ * <td><strong>Parameters</strong></td>
817
+ * <td><strong>Type</strong></td>
818
+ * <td><strong>Required</strong></td>
819
+ * <td><strong>Description</strong></td>
820
+ * </tr>
821
+ * <tr>
822
+ * <td>chat_id</td>
823
+ * <td>Integer or String</td>
824
+ * <td>Yes</td>
825
+ * <td>Unique identifier for the target chat or username of the target supergroup or channel (in the format <code>@channelusername</code>)</td>
826
+ * </tr>
827
+ * </table>
828
+ * \param $content the request parameters as array
829
+ * \return the JSON Telegram's reply
830
+ */
831
+ public function getChatAdministrators(array $content) {
832
+ return $this->endpoint("getChatAdministrators", $content);
833
+ }
834
+
835
+ /**
836
+ * Use this method to get the number of members in a chat. Returns <em>Int</em> on success.<br/>Values inside $content:<br/>
837
+ * <table>
838
+ * <tr>
839
+ * <td><strong>Parameters</strong></td>
840
+ * <td><strong>Type</strong></td>
841
+ * <td><strong>Required</strong></td>
842
+ * <td><strong>Description</strong></td>
843
+ * </tr>
844
+ * <tr>
845
+ * <td>chat_id</td>
846
+ * <td>Integer or String</td>
847
+ * <td>Yes</td>
848
+ * <td>Unique identifier for the target chat or username of the target supergroup or channel (in the format <code>@channelusername</code>)</td>
849
+ * </tr>
850
+ * </table>
851
+ * \param $content the request parameters as array
852
+ * \return the JSON Telegram's reply
853
+ */
854
+ public function getChatMembersCount(array $content) {
855
+ return $this->endpoint("getChatMembersCount", $content);
856
+ }
857
+
858
+ /**
859
+ * Use this method to get information about a member of a chat. Returns a <a href="https://core.telegram.org/bots/api#chatmember">ChatMember</a> object on success.<br/>Values inside $content:<br/>
860
+ * <table>
861
+ * <tr>
862
+ * <td><strong>Parameters</strong></td>
863
+ * <td><strong>Type</strong></td>
864
+ * <td><strong>Required</strong></td>
865
+ * <td><strong>Description</strong></td>
866
+ * </tr>
867
+ * <tr>
868
+ * <td>chat_id</td>
869
+ * <td>Integer or String</td>
870
+ * <td>Yes</td>
871
+ * <td>Unique identifier for the target chat or username of the target supergroup or channel (in the format <code>@channelusername</code>)</td>
872
+ * </tr>
873
+ * <tr>
874
+ * <td>user_id</td>
875
+ * <td>Integer</td>
876
+ * <td>Yes</td>
877
+ * <td>Unique identifier of the target user</td>
878
+ * </tr>
879
+ * </table>
880
+ * \param $content the request parameters as array
881
+ * \return the JSON Telegram's reply
882
+ */
883
+ public function getChatMember(array $content) {
884
+ return $this->endpoint("getChatMember", $content);
885
+ }
886
+
887
+ /**
888
+ * Use this method to send answers to an inline query. On success, <em>True</em> is returned.<br>No more than <strong>50</strong> results per query are allowed.<br/>Values inside $content:<br/>
889
+ * <table>
890
+ * <tr>
891
+ * <td><strong>Parameters</strong></td>
892
+ * <td><strong>Type</strong></td>
893
+ * <td><strong>Required</strong></td>
894
+ * <td><strong>Description</strong></td>
895
+ * </tr>
896
+ * <tr>
897
+ * <td>inline_query_id</td>
898
+ * <td>String</td>
899
+ * <td>Yes</td>
900
+ * <td>Unique identifier for the answered query</td>
901
+ * </tr>
902
+ * <tr>
903
+ * <td>results</td>
904
+ * <td>Array of <a href="https://core.telegram.org/bots/api#inlinequeryresult">InlineQueryResult</a></td>
905
+ * <td>Yes</td>
906
+ * <td>A JSON-serialized array of results for the inline query</td>
907
+ * </tr>
908
+ * <tr>
909
+ * <td>cache_time</td>
910
+ * <td>Integer</td>
911
+ * <td>Optional</td>
912
+ * <td>The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300.</td>
913
+ * </tr>
914
+ * <tr>
915
+ * <td>is_personal</td>
916
+ * <td>Boolean</td>
917
+ * <td>Optional</td>
918
+ * <td>Pass <em>True</em>, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query</td>
919
+ * </tr>
920
+ * <tr>
921
+ * <td>next_offset</td>
922
+ * <td>String</td>
923
+ * <td>Optional</td>
924
+ * <td>Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don‘t support pagination. Offset length can’t exceed 64 bytes.</td>
925
+ * </tr>
926
+ * <tr>
927
+ * <td>switch_pm_text</td>
928
+ * <td>String</td>
929
+ * <td>Optional</td>
930
+ * <td>If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter <em>switch_pm_parameter</em></td>
931
+ * </tr>
932
+ * <tr>
933
+ * <td>switch_pm_parameter</td>
934
+ * <td>String</td>
935
+ * <td>Optional</td>
936
+ * <td>Parameter for the start message sent to the bot when user presses the switch button<br><br><em>Example:</em> An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a ‘Connect your YouTube account’ button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an oauth link. Once done, the bot can offer a <a href="https://core.telegram.org/bots/api#inlinekeyboardmarkup"><em>switch_inline</em></a> button so that the user can easily return to the chat where they wanted to use the bot&#39;s inline capabilities.</td>
937
+ * </tr>
938
+ * </table>
939
+ * \param $content the request parameters as array
940
+ * \return the JSON Telegram's reply
941
+ */
942
+ public function answerInlineQuery(array $content) {
943
+ return $this->endpoint("answerInlineQuery", $content);
944
+ }
945
+
946
+ /// Set Game Score
947
+ /**
948
+ * Use this method to set the score of the specified user in a game. On success, if the message was sent by the bot, returns the edited Message, otherwise returns <em>True</em>. Returns an error, if the new score is not greater than the user&#39;s current score in the chat and <em>force</em> is <em>False</em>.<br/>
949
+ * <table>
950
+ * <tr>
951
+ * <td><strong>Parameters</strong></td>
952
+ * <td><strong>Type</strong></td>
953
+ * <td><strong>Required</strong></td>
954
+ * <td><strong>Description</strong></td>
955
+ * </tr>
956
+ * <tr>
957
+ * <td>user_id</td>
958
+ * <td>Integer</td>
959
+ * <td>Yes</td>
960
+ * <td>User identifier</td>
961
+ * </tr>
962
+ * <tr>
963
+ * <td>score</td>
964
+ * <td>Integer</td>
965
+ * <td>Yes</td>
966
+ * <td>New score, must be non-negative</td>
967
+ * </tr>
968
+ * <tr>
969
+ * <td>force</td>
970
+ * <td>Boolean</td>
971
+ * <td>Optional</td>
972
+ * <td>Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters</td>
973
+ * </tr>
974
+ * <tr>
975
+ * <td>disable_edit_message</td>
976
+ * <td>Boolean</td>
977
+ * <td>Optional</td>
978
+ * <td>Pass True, if the game message should not be automatically edited to include the current scoreboard</td>
979
+ * </tr>
980
+ * <tr>
981
+ * <td>chat_id</td>
982
+ * <td>Integer</td>
983
+ * <td>Optional</td>
984
+ * <td>Required if <em>inline_message_id</em> is not specified. Unique identifier for the target chat</td>
985
+ * </tr>
986
+ * <tr>
987
+ * <td>message_id</td>
988
+ * <td>Integer</td>
989
+ * <td>Optional</td>
990
+ * <td>Required if <em>inline_message_id</em> is not specified. Identifier of the sent message</td>
991
+ * </tr>
992
+ * <tr>
993
+ * <td>inline_message_id</td>
994
+ * <td>String</td>
995
+ * <td>Optional</td>
996
+ * <td>Required if <em>chat_id</em> and <em>message_id</em> are not specified. Identifier of the inline message</td>
997
+ * </tr>
998
+ * </table>
999
+ * \param $content the request parameters as array
1000
+ * \return the JSON Telegram's reply
1001
+ */
1002
+ public function setGameScore(array $content) {
1003
+ return $this->endpoint("setGameScore", $content);
1004
+ }
1005
+
1006
+ /// Answer a callback Query
1007
+ /**
1008
+ * Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, <em>True</em> is returned.<br/>Values inside $content:<br/>
1009
+ * <table>
1010
+ * <tr>
1011
+ * <td><strong>Parameters</strong></td>
1012
+ * <td><strong>Type</strong></td>
1013
+ * <td><strong>Required</strong></td>
1014
+ * <td><strong>Description</strong></td>
1015
+ * </tr>
1016
+ * <tr>
1017
+ * <td>callback_query_id</td>
1018
+ * <td>String</td>
1019
+ * <td>Yes</td>
1020
+ * <td>Unique identifier for the query to be answered</td>
1021
+ * </tr>
1022
+ * <tr>
1023
+ * <td>text</td>
1024
+ * <td>String</td>
1025
+ * <td>Optional</td>
1026
+ * <td>Text of the notification. If not specified, nothing will be shown to the user</td>
1027
+ * </tr>
1028
+ * <tr>
1029
+ * <td>show_alert</td>
1030
+ * <td>Boolean</td>
1031
+ * <td>Optional</td>
1032
+ * <td>If <em>true</em>, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to <em>false</em>.</td>
1033
+ * </tr>
1034
+ * </table>
1035
+ * \param $content the request parameters as array
1036
+ * \return the JSON Telegram's reply
1037
+ */
1038
+ public function answerCallbackQuery(array $content) {
1039
+ return $this->endpoint("answerCallbackQuery", $content);
1040
+ }
1041
+
1042
+ /**
1043
+ * Use this method to edit text messages sent by the bot or via the bot (for <a href="https://core.telegram.org/bots/api#inline-mode">inline bots</a>). On success, if edited message is sent by the bot, the edited <a href="https://core.telegram.org/bots/api#message">Message</a> is returned, otherwise <em>True</em> is returned.<br/>Values inside $content:<br/>
1044
+ * <table>
1045
+ * <tr>
1046
+ * <td><strong>Parameters</strong></td>
1047
+ * <td><strong>Type</strong></td>
1048
+ * <td><strong>Required</strong></td>
1049
+ * <td><strong>Description</strong></td>
1050
+ * </tr>
1051
+ * <tr>
1052
+ * <td>chat_id</td>
1053
+ * <td>Integer or String</td>
1054
+ * <td>No</td>
1055
+ * <td>Required if <em>inline_message_id</em> is not specified. Unique identifier for the target chat or username of the target channel (in the format <code>@channelusername</code>)</td>
1056
+ * </tr>
1057
+ * <tr>
1058
+ * <td>message_id</td>
1059
+ * <td>Integer</td>
1060
+ * <td>No</td>
1061
+ * <td>Required if <em>inline_message_id</em> is not specified. Unique identifier of the sent message</td>
1062
+ * </tr>
1063
+ * <tr>
1064
+ * <td>inline_message_id</td>
1065
+ * <td>String</td>
1066
+ * <td>No</td>
1067
+ * <td>Required if <em>chat_id</em> and <em>message_id</em> are not specified. Identifier of the inline message</td>
1068
+ * </tr>
1069
+ * <tr>
1070
+ * <td>text</td>
1071
+ * <td>String</td>
1072
+ * <td>Yes</td>
1073
+ * <td>New text of the message</td>
1074
+ * </tr>
1075
+ * <tr>
1076
+ * <td>parse_mode</td>
1077
+ * <td>String</td>
1078
+ * <td>Optional</td>
1079
+ * <td>Send <a href="https://core.telegram.org/bots/api#markdown-style"><em>Markdown</em></a> or <a href="https://core.telegram.org/bots/api#html-style"><em>HTML</em></a>, if you want Telegram apps to show <a href="https://core.telegram.org/bots/api#formatting-options">bold, italic, fixed-width text or inline URLs</a> in your bot&#39;s message.</td>
1080
+ * </tr>
1081
+ * <tr>
1082
+ * <td>disable_web_page_preview</td>
1083
+ * <td>Boolean</td>
1084
+ * <td>Optional</td>
1085
+ * <td>Disables link previews for links in this message</td>
1086
+ * </tr>
1087
+ * <tr>
1088
+ * <td>reply_markup</td>
1089
+ * <td><a href="https://core.telegram.org/bots/api#inlinekeyboardmarkup">InlineKeyboardMarkup</a></td>
1090
+ * <td>Optional</td>
1091
+ * <td>A JSON-serialized object for an <a href="https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating">inline keyboard</a>.</td>
1092
+ * </tr>
1093
+ * </table>
1094
+ * \param $content the request parameters as array
1095
+ * \return the JSON Telegram's reply
1096
+ */
1097
+ public function editMessageText(array $content) {
1098
+ return $this->endpoint("editMessageText", $content);
1099
+ }
1100
+
1101
+ /**
1102
+ * Use this method to edit captions of messages sent by the bot or via the bot (for <a href="https://core.telegram.org/bots/api#inline-mode">inline bots</a>). On success, if edited message is sent by the bot, the edited <a href="https://core.telegram.org/bots/api#message">Message</a> is returned, otherwise <em>True</em> is returned.<br/>Values inside $content:<br/>
1103
+ * <table>
1104
+ * <tr>
1105
+ * <td><strong>Parameters</strong></td>
1106
+ * <td><strong>Type</strong></td>
1107
+ * <td><strong>Required</strong></td>
1108
+ * <td><strong>Description</strong></td>
1109
+ * </tr>
1110
+ * <tr>
1111
+ * <td>chat_id</td>
1112
+ * <td>Integer or String</td>
1113
+ * <td>No</td>
1114
+ * <td>Required if <em>inline_message_id</em> is not specified. Unique identifier for the target chat or username of the target channel (in the format <code>@channelusername</code>)</td>
1115
+ * </tr>
1116
+ * <tr>
1117
+ * <td>message_id</td>
1118
+ * <td>Integer</td>
1119
+ * <td>No</td>
1120
+ * <td>Required if <em>inline_message_id</em> is not specified. Unique identifier of the sent message</td>
1121
+ * </tr>
1122
+ * <tr>
1123
+ * <td>inline_message_id</td>
1124
+ * <td>String</td>
1125
+ * <td>No</td>
1126
+ * <td>Required if <em>chat_id</em> and <em>message_id</em> are not specified. Identifier of the inline message</td>
1127
+ * </tr>
1128
+ * <tr>
1129
+ * <td>caption</td>
1130
+ * <td>String</td>
1131
+ * <td>Optional</td>
1132
+ * <td>New caption of the message</td>
1133
+ * </tr>
1134
+ * <tr>
1135
+ * <td>reply_markup</td>
1136
+ * <td><a href="https://core.telegram.org/bots/api#inlinekeyboardmarkup">InlineKeyboardMarkup</a></td>
1137
+ * <td>Optional</td>
1138
+ * <td>A JSON-serialized object for an <a href="https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating">inline keyboard</a>.</td>
1139
+ * </tr>
1140
+ * </table>
1141
+ * \param $content the request parameters as array
1142
+ * \return the JSON Telegram's reply
1143
+ */
1144
+ public function editMessageCaption(array $content) {
1145
+ return $this->endpoint("editMessageCaption", $content);
1146
+ }
1147
+
1148
+ /**
1149
+ * Use this method to edit only the reply markup of messages sent by the bot or via the bot (for <a href="https://core.telegram.org/bots/api#inline-mode">inline bots</a>). On success, if edited message is sent by the bot, the edited <a href="https://core.telegram.org/bots/api#message">Message</a> is returned, otherwise <em>True</em> is returned.<br/>Values inside $content:<br/>
1150
+ * <table>
1151
+ * <tr>
1152
+ * <td><strong>Parameters</strong></td>
1153
+ * <td><strong>Type</strong></td>
1154
+ * <td><strong>Required</strong></td>
1155
+ * <td><strong>Description</strong></td>
1156
+ * </tr>
1157
+ * <tr>
1158
+ * <td>chat_id</td>
1159
+ * <td>Integer or String</td>
1160
+ * <td>No</td>
1161
+ * <td>Required if <em>inline_message_id</em> is not specified. Unique identifier for the target chat or username of the target channel (in the format <code>@channelusername</code>)</td>
1162
+ * </tr>
1163
+ * <tr>
1164
+ * <td>message_id</td>
1165
+ * <td>Integer</td>
1166
+ * <td>No</td>
1167
+ * <td>Required if <em>inline_message_id</em> is not specified. Unique identifier of the sent message</td>
1168
+ * </tr>
1169
+ * <tr>
1170
+ * <td>inline_message_id</td>
1171
+ * <td>String</td>
1172
+ * <td>No</td>
1173
+ * <td>Required if <em>chat_id</em> and <em>message_id</em> are not specified. Identifier of the inline message</td>
1174
+ * </tr>
1175
+ * <tr>
1176
+ * <td>reply_markup</td>
1177
+ * <td><a href="https://core.telegram.org/bots/api#inlinekeyboardmarkup">InlineKeyboardMarkup</a></td>
1178
+ * <td>Optional</td>
1179
+ * <td>A JSON-serialized object for an <a href="https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating">inline keyboard</a>.</td>
1180
+ * </tr>
1181
+ * </table>
1182
+ * \param $content the request parameters as array
1183
+ * \return the JSON Telegram's reply
1184
+ */
1185
+ public function editMessageReplyMarkup(array $content) {
1186
+ return $this->endpoint("editMessageReplyMarkup", $content);
1187
+ }
1188
+
1189
+ /// Use this method to download a file
1190
+ /**
1191
+ * Use this method to to download a file from the Telegram servers.
1192
+ * \param $telegram_file_path String File path on Telegram servers
1193
+ * \param $local_file_path String File path where save the file
1194
+ */
1195
+ public function downloadFile($telegram_file_path, $local_file_path) {
1196
+ $file_url = "https://api.telegram.org/file/bot" . $this->bot_id . "/" . $telegram_file_path;
1197
+ $in = fopen($file_url, "rb");
1198
+ $out = fopen($local_file_path, "wb");
1199
+
1200
+ while ($chunk = fread($in, 8192)) {
1201
+ fwrite($out, $chunk, 8192);
1202
+ }
1203
+ fclose($in);
1204
+ fclose($out);
1205
+ }
1206
+
1207
+ /// Set a WebHook for the bot
1208
+ /**
1209
+ * Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts.
1210
+
1211
+ * If you'd like to make sure that the Webhook request comes from Telegram, we recommend using a secret path in the URL, e.g. https://www.example.com/<token>. Since nobody else knows your bot‘s token, you can be pretty sure it’s us.
1212
+ * \param $url String HTTPS url to send updates to. Use an empty string to remove webhook integration
1213
+ * \param $certificate InputFile Upload your public key certificate so that the root certificate in use can be checked
1214
+ * \return the JSON Telegram's reply
1215
+ */
1216
+ public function setWebhook($url, $certificate = "") {
1217
+ if ($certificate == "") {
1218
+ $content = array('url' => $url);
1219
+ } else {
1220
+ $content = array('url' => $url, 'certificate' => $certificate);
1221
+ }
1222
+ return $this->endpoint("setWebhook", $content);
1223
+ }
1224
+
1225
+ /// Get the data of the current message
1226
+ /** Get the POST request of a user in a Webhook or the message actually processed in a getUpdates() enviroment.
1227
+ * \return the JSON users's message
1228
+ */
1229
+ public function getData() {
1230
+ if (empty($this->data)) {
1231
+ $rawData = file_get_contents("php://input");
1232
+ return json_decode($rawData, true);
1233
+ } else {
1234
+ return $this->data;
1235
+ }
1236
+ }
1237
+
1238
+ /// Set the data currently used
1239
+ public function setData(array $data) {
1240
+ $this->data = $data;
1241
+ }
1242
+
1243
+ /// Get the text of the current message
1244
+ /**
1245
+ * \return the String users's text
1246
+ */
1247
+ public function Text() {
1248
+ return $this->data["message"] ["text"];
1249
+ }
1250
+
1251
+ /// Get the chat_id of the current message
1252
+ /**
1253
+ * \return the String users's chat_id
1254
+ */
1255
+ public function ChatID() {
1256
+ return $this->data["message"]["chat"]["id"];
1257
+ }
1258
+ /// Get the message_id of the current message
1259
+ /**
1260
+ * \return the String message_id
1261
+ */
1262
+ public function MessageID() {
1263
+ return $this->data["message"]["message_id"];
1264
+ }
1265
+
1266
+ /// Get the reply_to_message message_id of the current message
1267
+ /**
1268
+ * \return the String reply_to_message message_id
1269
+ */
1270
+ public function ReplyToMessageID() {
1271
+ return $this->data["message"]["reply_to_message"]["message_id"];
1272
+ }
1273
+
1274
+ /// Get the text from the replied message
1275
+ /**
1276
+ * \return the String text from the replied message
1277
+ */
1278
+ public function ReplyToMessageText() {
1279
+ return $this->data["message"]["reply_to_message"]["text"];
1280
+ }
1281
+
1282
+ /// Get the reply_to_message forward_from user_id of the current message
1283
+ /**
1284
+ * \return the String reply_to_message forward_from user_id
1285
+ */
1286
+ public function ReplyToMessageFromUserID() {
1287
+ return $this->data["message"]["reply_to_message"]["forward_from"]["id"];
1288
+ }
1289
+
1290
+ /// Get the inline_query of the current update
1291
+ /**
1292
+ * \return the Array inline_query
1293
+ */
1294
+ public function Inline_Query() {
1295
+ return $this->data["inline_query"];
1296
+ }
1297
+ /// Get the callback_query of the current update
1298
+ /**
1299
+ * \return the String callback_query
1300
+ */
1301
+ public function Callback_Query() {
1302
+ return $this->data["callback_query"];
1303
+ }
1304
+
1305
+ /// Get the callback_query id of the current update
1306
+ /**
1307
+ * \return the String callback_query id
1308
+ */
1309
+ public function Callback_ID() {
1310
+ return $this->data["callback_query"]["id"];
1311
+ }
1312
+
1313
+ /// Get the Get the data of the current callback
1314
+ /**
1315
+ * \return the String callback_data
1316
+ */
1317
+ public function Callback_Data() {
1318
+ return $this->data["callback_query"]["data"];
1319
+ }
1320
+
1321
+ /// Get the Get the message of the current callback
1322
+ /**
1323
+ * \return the Message
1324
+ */
1325
+ public function Callback_Message() {
1326
+ return $this->data["callback_query"]["message"];
1327
+ }
1328
+
1329
+ /// Get the Get the chati_id of the current callback
1330
+ /**
1331
+ * \return the String callback_query
1332
+ */
1333
+ public function Callback_ChatID() {
1334
+ return $this->data["callback_query"]["message"]["chat"]["id"];
1335
+ }
1336
+
1337
+ /// Get the date of the current message
1338
+ /**
1339
+ * \return the String message's date
1340
+ */
1341
+ public function Date() {
1342
+ return $this->data["message"]["date"];
1343
+ }
1344
+
1345
+ /// Get the first name of the user
1346
+ public function FirstName() {
1347
+ return $this->data["message"]["from"]["first_name"];
1348
+ }
1349
+
1350
+ /// Get the last name of the user
1351
+ public function LastName() {
1352
+ return $this->data["message"]["from"]["last_name"];
1353
+ }
1354
+
1355
+ /// Get the username of the user
1356
+ public function Username() {
1357
+ return $this->data["message"]["from"]["username"];
1358
+ }
1359
+
1360
+ /// Get the location in the message
1361
+ public function Location() {
1362
+ return $this->data["message"]["location"];
1363
+ }
1364
+
1365
+ /// Get the update_id of the message
1366
+ public function UpdateID() {
1367
+ return $this->data["update_id"];
1368
+ }
1369
+
1370
+ /// Get the number of updates
1371
+ public function UpdateCount() {
1372
+ return count($this->updates["result"]);
1373
+ }
1374
+
1375
+ /// Tell if a message is from a group or user chat
1376
+ /**
1377
+ *
1378
+ * \return BOOLEAN true if the message is from a Group chat, false otherwise
1379
+ */
1380
+ public function messageFromGroup() {
1381
+ if ($this->data["message"]["chat"]["type"] == "private") {
1382
+ return false;
1383
+ }
1384
+ return true;
1385
+ }
1386
+
1387
+ /// Get the title of the group chat
1388
+ /**
1389
+ *
1390
+ * \return a String of the title chat
1391
+ */
1392
+ public function messageFromGroupTitle() {
1393
+ if ($this->data["message"]["chat"]["type"] != "private") {
1394
+ return $this->data["message"]["chat"]["title"];
1395
+ }
1396
+ return null;
1397
+ }
1398
+
1399
+ /// Set a custom keyboard
1400
+ /** This object represents a custom keyboard with reply options
1401
+ * \param $options Array of Array of String; Array of button rows, each represented by an Array of Strings
1402
+ * \param $onetime Boolean Requests clients to hide the keyboard as soon as it's been used. Defaults to false.
1403
+ * \param $resize Boolean Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard.
1404
+ * \param $selective Boolean Use this parameter if you want to show the keyboard to specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message.
1405
+ * \return the requested keyboard as Json
1406
+ */
1407
+ public function buildKeyBoard(array $options, $onetime = false, $resize = false, $selective = true) {
1408
+ $replyMarkup = array(
1409
+ 'keyboard' => $options,
1410
+ 'one_time_keyboard' => $onetime,
1411
+ 'resize_keyboard' => $resize,
1412
+ 'selective' => $selective
1413
+ );
1414
+ $encodedMarkup = json_encode($replyMarkup, true);
1415
+ return $encodedMarkup;
1416
+ }
1417
+
1418
+ /// Set an InlineKeyBoard
1419
+ /** This object represents an inline keyboard that appears right next to the message it belongs to.
1420
+ * \param $options Array of Array of InlineKeyboardButton; Array of button rows, each represented by an Array of InlineKeyboardButton
1421
+ * \return the requested keyboard as Json
1422
+ */
1423
+ public function buildInlineKeyBoard(array $options) {
1424
+ $replyMarkup = array(
1425
+ 'inline_keyboard' => $options,
1426
+ );
1427
+ $encodedMarkup = json_encode($replyMarkup, true);
1428
+ return $encodedMarkup;
1429
+ }
1430
+
1431
+ /// Create an InlineKeyboardButton
1432
+ /** This object represents one button of an inline keyboard. You must use exactly one of the optional fields.
1433
+ * \param $text String; Array of button rows, each represented by an Array of Strings
1434
+ * \param $url String Optional. HTTP url to be opened when button is pressed
1435
+ * \param $callback_data String Optional. Data to be sent in a callback query to the bot when button is pressed
1436
+ * \param $switch_inline_query String Optional. If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot‘s username and the specified inline query in the input field. Can be empty, in which case just the bot’s username will be inserted.
1437
+ * \param $switch_inline_query_current_chat String Optional. Optional. If set, pressing the button will insert the bot‘s username and the specified inline query in the current chat's input field. Can be empty, in which case only the bot’s username will be inserted.
1438
+ * \param $callback_game String Optional. Description of the game that will be launched when the user presses the button.
1439
+ * \return the requested button as Array
1440
+ */
1441
+ public function buildInlineKeyboardButton($text, $url = "", $callback_data = "", $switch_inline_query = "", $switch_inline_query_current_chat = "", $callback_game = "") {
1442
+ $replyMarkup = array(
1443
+ 'text' => $text
1444
+ );
1445
+ if ($url != "") {
1446
+ $replyMarkup['url'] = $url;
1447
+ } else if ($callback_data != "") {
1448
+ $replyMarkup['callback_data'] = $callback_data;
1449
+ } else if ($switch_inline_query != "") {
1450
+ $replyMarkup['switch_inline_query'] = $switch_inline_query;
1451
+ } else if ($switch_inline_query_current_chat != "") {
1452
+ $replyMarkup['switch_inline_query_current_chat'] = $switch_inline_query_current_chat;
1453
+ } else if ($callback_game != "") {
1454
+ $replyMarkup['callback_game'] = $callback_game;
1455
+ }
1456
+ return $replyMarkup;
1457
+ }
1458
+
1459
+ /// Create a KeyboardButton
1460
+ /** This object represents one button of an inline keyboard. You must use exactly one of the optional fields.
1461
+ * \param $text String; Array of button rows, each represented by an Array of Strings
1462
+ * \param $request_contact Boolean Optional. If True, the user's phone number will be sent as a contact when the button is pressed. Available in private chats only
1463
+ * \param $request_location Boolean Optional. If True, the user's current location will be sent when the button is pressed. Available in private chats only
1464
+ * \return the requested button as Array
1465
+ */
1466
+ public function buildKeyboardButton($text, $request_contact = false, $request_location = false) {
1467
+ $replyMarkup = array(
1468
+ 'text' => $text,
1469
+ 'request_contact' => $request_contact,
1470
+ 'request_location' => $request_location
1471
+ );
1472
+ if ($url != "") {
1473
+ $replyMarkup['url'] = $url;
1474
+ } else if ($callback_data != "") {
1475
+ $replyMarkup['callback_data'] = $callback_data;
1476
+ } else if ($switch_inline_query != "") {
1477
+ $replyMarkup['switch_inline_query'] = $switch_inline_query;
1478
+ }
1479
+ return $replyMarkup;
1480
+ }
1481
+
1482
+ /// Hide a custom keyboard
1483
+ /** Upon receiving a message with this object, Telegram clients will hide the current custom keyboard and display the default letter-keyboard. By default, custom keyboards are displayed until a new keyboard is sent by a bot. An exception is made for one-time keyboards that are hidden immediately after the user presses a button.
1484
+ * \param $selective Boolean Use this parameter if you want to show the keyboard to specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message.
1485
+ * \return the requested keyboard hide as Array
1486
+ */
1487
+ public function buildKeyBoardHide($selective = true) {
1488
+ $replyMarkup = array(
1489
+ 'hide_keyboard' => true,
1490
+ 'selective' => $selective
1491
+ );
1492
+ $encodedMarkup = json_encode($replyMarkup, true);
1493
+ return $encodedMarkup;
1494
+ }
1495
+
1496
+ /// Display a reply interface to the user
1497
+ /* Upon receiving a message with this object, Telegram clients will display a reply interface to the user (act as if the user has selected the bot‘s message and tapped ’Reply'). This can be extremely useful if you want to create user-friendly step-by-step interfaces without having to sacrifice privacy mode.
1498
+ * \param $selective Boolean Use this parameter if you want to show the keyboard to specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message.
1499
+ * \return the requested force reply as Array
1500
+ */
1501
+ public function buildForceReply($selective = true) {
1502
+ $replyMarkup = array(
1503
+ 'force_reply' => true,
1504
+ 'selective' => $selective
1505
+ );
1506
+ $encodedMarkup = json_encode($replyMarkup, true);
1507
+ return $encodedMarkup;
1508
+ }
1509
+
1510
+ /// Receive incoming messages using polling
1511
+ /** Use this method to receive incoming updates using long polling.
1512
+ * \param $offset Integer Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id.
1513
+ * \param $limit Integer Limits the number of updates to be retrieved. Values between 1—100 are accepted. Defaults to 100
1514
+ * \param $timeout Integer Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling
1515
+ * \param $update Boolean If true updates the pending message list to the last update received. Default to true.
1516
+ * \return the updates as Array
1517
+ */
1518
+ public function getUpdates($offset = 0, $limit = 100, $timeout = 0, $update = true) {
1519
+ $content = array('offset' => $offset, 'limit' => $limit, 'timeout' => $timeout);
1520
+ $this->updates = $this->endpoint("getUpdates", $content);
1521
+ if ($update) {
1522
+ if(count($this->updates["result"]) >= 1) { //for CLI working.
1523
+ $last_element_id = $this->updates["result"][count($this->updates["result"]) - 1]["update_id"] + 1;
1524
+ $content = array('offset' => $last_element_id, 'limit' => "1", 'timeout' => $timeout);
1525
+ $this->endpoint("getUpdates", $content);
1526
+ }
1527
+ }
1528
+ return $this->updates;
1529
+ }
1530
+
1531
+ /// Serve an update
1532
+ /** Use this method to use the bultin function like Text() or Username() on a specific update.
1533
+ * \param $update Integer The index of the update in the updates array.
1534
+ */
1535
+ public function serveUpdate($update) {
1536
+ $this->data = $this->updates["result"][$update];
1537
+ }
1538
+
1539
+ private function sendAPIRequest($url, array $content, $post = true) {
1540
+ if (isset($content['chat_id'])) {
1541
+ $url = $url . "?chat_id=" . $content['chat_id'];
1542
+ unset($content['chat_id']);
1543
+ }
1544
+ $ch = curl_init();
1545
+ curl_setopt($ch, CURLOPT_URL, $url);
1546
+ curl_setopt($ch, CURLOPT_HEADER, false);
1547
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1548
+ if ($post) {
1549
+ curl_setopt($ch, CURLOPT_POST, 1);
1550
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
1551
+ }
1552
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1553
+ $result = curl_exec($ch);
1554
+ curl_close($ch);
1555
+ return $result;
1556
+ }
1557
+
1558
+ }
1559
+
1560
+ // Helper for Uploading file using CURL
1561
+ if (!function_exists('curl_file_create')) {
1562
+
1563
+ function curl_file_create($filename, $mimetype = '', $postname = '') {
1564
+ return "@$filename;filename="
1565
+ . ($postname ? : basename($filename))
1566
+ . ($mimetype ? ";type=$mimetype" : '');
1567
+ }
1568
+
1569
+ }
1570
+ ?>
app/code/community/Werules/Chatbot/Model/Api/witAI/witAI.php ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ?>
app/code/community/Werules/Chatbot/Model/Chatdata.php ADDED
@@ -0,0 +1,598 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_cat,
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
+ ";
55
+ protected $_startCmd = array();
56
+ protected $_listCategoriesCmd = array();
57
+ protected $_searchCmd = array();
58
+ protected $_loginCmd = array();
59
+ protected $_listOrdersCmd = array();
60
+ protected $_reorderCmd = array();
61
+ protected $_add2CartCmd = array();
62
+ protected $_checkoutCmd = array();
63
+ protected $_clearCartCmd = array();
64
+ protected $_trackOrderCmd = array();
65
+ protected $_supportCmd = array();
66
+ protected $_sendEmailCmd = array();
67
+ protected $_cancelCmd = array();
68
+ protected $_helpCmd = array();
69
+ protected $_aboutCmd = array();
70
+ protected $_logoutCmd = array();
71
+
72
+ // admin cmds
73
+ // protected $adminCmdList =
74
+ // "
75
+ // messagetoall,
76
+ // endsupport,
77
+ // blocksupport
78
+ // ";
79
+ protected $_admSendMessage2AllCmd = "messagetoall";
80
+ protected $_admEndSupportCmd = "endsupport";
81
+ protected $_admBlockSupportCmd = "blocksupport";
82
+ protected $_admEnableSupportCmd = "enablesupport";
83
+
84
+ // REGEX
85
+ protected $_unallowedCharacters = "/[^A-Za-z0-9 _]/";
86
+
87
+ // DEFAULT MESSAGES
88
+ protected $_errorMessage = "";
89
+ protected $_cancelMessage = "";
90
+ protected $_canceledMessage = "";
91
+ protected $_loginFirstMessage = "";
92
+ protected $_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 _construct()
101
+ {
102
+ //parent::_construct();
103
+ $this->_init('chatbot/chatdata'); // this is location of the resource file.
104
+ }
105
+
106
+ // GENERAL FUNCTIONS
107
+ public function requestHandler($action, $webhook) // handle request
108
+ {
109
+ $apiKey = $this->getApikey($action);
110
+ // handle webhook configuration
111
+ if ($webhook && $apiKey && $action == $this->_tgBot) // set telegram webhook
112
+ {
113
+ try
114
+ {
115
+ $telegram = new Telegram($apiKey);
116
+ $webhook_url = Mage::getUrl('chatbot/chatdata/', array('_forced_secure' => true)) . $this->_tgBot;
117
+ $webhook_url = str_replace("http://", "https://", $webhook_url);
118
+ $telegram->setWebhook($webhook_url);
119
+ }
120
+ catch (Exception $e)
121
+ {
122
+ return Mage::helper('core')->__("Something went wrong, please try again.");
123
+ }
124
+
125
+ return Mage::helper('core')->__("Webhook for Telegram configured.");
126
+ } // start to handle conversation
127
+ else if ($action == $this->_tgBot && $apiKey) // telegram api
128
+ {
129
+ // all logic goes here
130
+ return Mage::getModel('chatbot/api_telegram_handler')->telegramHandler($apiKey);
131
+ }
132
+ else if ($action == $this->_fbBot && $apiKey) // facebook api
133
+ {
134
+ // all logic goes here
135
+ return Mage::getModel('chatbot/api_facebook_handler')->facebookHandler($apiKey);
136
+ }
137
+ else
138
+ return "Nothing to see here"; // TODO
139
+ }
140
+
141
+ protected function getApikey($apiType) // check if bot integration is enabled
142
+ {
143
+ if ($apiType == $this->_tgBot) // telegram api
144
+ {
145
+ //$enabled = Mage::getStoreConfig('chatbot_enable/telegram_config/enable_bot');
146
+ $apikey = Mage::getStoreConfig('chatbot_enable/telegram_config/telegram_api_key');
147
+ //if ($enabled == 1 && $apikey) // is enabled and has API
148
+ if ($apikey) // has API
149
+ return $apikey;
150
+ }
151
+ else if ($apiType == $this->_fbBot)
152
+ {
153
+ //$enabled = Mage::getStoreConfig('chatbot_enable/facebook_config/enable_bot');
154
+ $apikey = Mage::getStoreConfig('chatbot_enable/facebook_config/facebook_api_key');
155
+ //if ($enabled == 1 && $apikey) // is enabled and has API
156
+ if ($apikey) // has API
157
+ return $apikey;
158
+ }
159
+ return null;
160
+ }
161
+
162
+ protected function sendEmail($text)
163
+ {
164
+ $storeName = Mage::app()->getStore()->getName();
165
+ $storeEmail = Mage::getStoreConfig('trans_email/ident_general/email');// TODO
166
+ $magehelper = Mage::helper('core');
167
+
168
+ $url = $magehelper->__("Not informed");
169
+ $customerEmail = $magehelper->__("Not informed");
170
+ $customerName = $magehelper->__("Not informed");
171
+
172
+ $mail = new Zend_Mail('UTF-8');
173
+
174
+ if ($this->_apiType == $this->_tgBot)
175
+ {
176
+ $url = $this->_tgUrl . $this->getTelegramChatId();
177
+ if ($this->getCustomerId())
178
+ {
179
+ $customer = Mage::getModel('customer/customer')->load((int)$this->getCustomerId());
180
+ if ($customer->getId())
181
+ {
182
+ $customerEmail = $customer->getEmail();
183
+ $customerName = $customer->getName();
184
+ $mail->setReplyTo($customerEmail);
185
+ }
186
+ }
187
+ }
188
+ else if ($this->_apiType == $this->_fbBot)
189
+ {
190
+ // code here etc
191
+ }
192
+
193
+ $emailBody =
194
+ $magehelper->__("Message from chatbot customer") . "<br><br>" .
195
+ $magehelper->__("Customer name") . ": " .
196
+ $customerName . "<br>" .
197
+ $magehelper->__("Message") . ":<br>" .
198
+ $text . "<br><br>" .
199
+ $magehelper->__("Contacts") . ":<br>" .
200
+ $magehelper->__("Chatbot") . ": " . $url . "<br>" .
201
+ $magehelper->__("Email") . ": " . $customerEmail . "<br>";
202
+
203
+ $mail->setBodyHtml($emailBody);
204
+ $mail->setFrom($storeEmail, $storeName);
205
+ $mail->addTo($storeEmail, $storeName);
206
+ $mail->setSubject(Mage::helper('core')->__("Contact from chatbot"));
207
+
208
+ try
209
+ {
210
+ $mail->send();
211
+ return true;
212
+ }
213
+ catch (Exception $e)
214
+ {
215
+ return false;
216
+ }
217
+ }
218
+
219
+ protected function addProd2Cart($prodId) // TODO add expiration date for sessions
220
+ {
221
+ $stock = Mage::getModel('cataloginventory/stock_item')
222
+ ->loadByProduct($prodId)
223
+ ->getIsInStock();
224
+ if ($stock <= 0) // if not in stock
225
+ return false;
226
+ $checkout = Mage::getSingleton('checkout/session');
227
+ $cart = Mage::getModel("checkout/cart");
228
+ try
229
+ {
230
+ $hasQuote = $this->getSessionId() && $this->getQuoteId(); // has class quote and session ids
231
+ if ($this->getIsLogged() == "1")
232
+ {
233
+ $customer = Mage::getModel('customer/customer')->load((int)$this->getCustomerId());
234
+ if ($customer->getId())
235
+ {
236
+ // if user is set as logged, then login using magento singleton
237
+ Mage::getSingleton('customer/session')->loginById($this->getCustomerId());
238
+ if (!$hasQuote)
239
+ { // if class still dosen't have quote and session ids, init here
240
+ // set current quote as customer quote
241
+ $quote = Mage::getModel('sales/quote')->loadByCustomer($customer);
242
+ $cart->setQuote($quote);
243
+ // attach checkout session to logged customer
244
+ $checkout->setCustomer($customer);
245
+ //$checkout->setSessionId($customersssion->getEncryptedSessionId());
246
+ //$quote = $checkout->getQuote();
247
+ //$quote->setCustomer($customer);
248
+ }
249
+ }
250
+ }
251
+ if ($hasQuote)
252
+ {
253
+ // init quote and session from chatbot class
254
+ $cart->setQuote(Mage::getModel('sales/quote')->loadByIdWithoutStore((int)$this->getQuoteId()));
255
+ $checkout->setSessionId($this->getSessionId());
256
+ }
257
+ // add product and save cart
258
+ // $product = Mage::getModel('catalog/product')->load($prodId);
259
+ // $product->setSkipCheckRequiredOption(true);
260
+ // $cart->addProduct($product);
261
+ $cart->addProduct($prodId);
262
+ $cart->save();
263
+ $checkout->setCartWasUpdated(true);
264
+
265
+ // update chatdata class data with quote and session ids
266
+ $data = array(
267
+ "session_id" => $checkout->getEncryptedSessionId(),
268
+ "quote_id" => $checkout->getQuote()->getId()
269
+ );
270
+ $this->addData($data);
271
+ $this->save();
272
+ }
273
+ catch (Exception $e)
274
+ {
275
+ //Mage::logException($e);
276
+ return false;
277
+ }
278
+
279
+ return true;
280
+ }
281
+
282
+ protected function getCommandString($cmdId)
283
+ {
284
+ $rep = "";
285
+ if ($this->_apiType == $this->_tgBot)
286
+ {
287
+ $rep = "_";
288
+ $confpath = 'chatbot_enable/telegram_config/';
289
+ }
290
+ else if ($this->_apiType == $this->_fbBot)
291
+ {
292
+ $rep = " ";
293
+ $confpath = 'chatbot_enable/facebook_config/';
294
+ }
295
+ // else if ($this->_apiType == $this->_wappBot)
296
+ // $confpath = 'chatbot_enable/whatsapp_config/';
297
+
298
+ $config = Mage::getStoreConfig($confpath . 'enabled_commands');
299
+ $enabledCmds = explode(',', $config);
300
+ if (is_array($enabledCmds))
301
+ {
302
+ if (in_array($cmdId, $enabledCmds))
303
+ {
304
+ $defaultCmds = explode(',', $this->_cmdList);
305
+ if (is_array($defaultCmds))
306
+ {
307
+ $cmdCode = "";
308
+ $alias = array();
309
+ $config = Mage::getStoreConfig($confpath . 'commands_list');
310
+ if ($config)
311
+ {
312
+ $commands = unserialize($config);
313
+ if (is_array($commands))
314
+ {
315
+ foreach($commands as $cmd)
316
+ {
317
+ if ($cmd['command_id'] == $cmdId)
318
+ {
319
+ $cmdCode = $cmd['command_code'];
320
+ $alias = array_map('strtolower', explode(',', $cmd['command_alias_list']));
321
+ break;
322
+ }
323
+ }
324
+ if (empty($cmdCode)) // if no command found, return the default
325
+ $cmdCode = $defaultCmds[$cmdId];
326
+ }
327
+ else // if no command found, return the default
328
+ $cmdCode = $defaultCmds[$cmdId];
329
+ }
330
+ else // if no command found, return the default
331
+ $cmdCode = $defaultCmds[$cmdId];
332
+
333
+ $cmdCode = preg_replace( // remove all non-alphanumerics
334
+ $this->_unallowedCharacters,
335
+ '',
336
+ str_replace( // replace whitespace for underscore
337
+ ' ',
338
+ $rep,
339
+ trim($cmdCode)
340
+ )
341
+ );
342
+
343
+ return array('command' => strtolower($cmdCode), 'alias' => $alias);
344
+ }
345
+ }
346
+ }
347
+ return array('command' => null, 'alias' => null);
348
+ }
349
+
350
+ protected function getCommandValue($text, $cmd)
351
+ {
352
+ if (strlen($text) > strlen($cmd))
353
+ return substr($text, strlen($cmd), strlen($text));
354
+ return null;
355
+ }
356
+
357
+ protected function checkCommand($text, $cmd)
358
+ {
359
+ if ($cmd['command'])
360
+ {
361
+ $t = strtolower($text);
362
+ if ($t == $cmd['command'])
363
+ return true;
364
+ else if ($cmd['alias'])
365
+ {
366
+ //$alias = explode(",", $cmd['alias']);
367
+ $alias = $cmd['alias'];
368
+ if (is_array($alias))
369
+ {
370
+ foreach ($alias as $al)
371
+ {
372
+ if (!empty($al))
373
+ if (strpos($t, $al) !== false)
374
+ return true;
375
+ }
376
+ }
377
+ }
378
+ }
379
+
380
+ return false;
381
+ }
382
+
383
+ protected function checkCommandWithValue($text, $cmd)
384
+ {
385
+ if ($cmd)
386
+ return substr($text, 0, strlen($cmd)) == $cmd;
387
+ return false;
388
+ }
389
+
390
+ protected function clearCart()
391
+ {
392
+ try
393
+ {
394
+ if ($this->getIsLogged() == "1")
395
+ {
396
+ if (Mage::getModel('customer/customer')->load((int)$this->getCustomerId())->getId())
397
+ {
398
+ // if user is set as logged, then login using magento singleton
399
+ //Mage::getSingleton('customer/session')->loginById($this->getCustomerId());
400
+ // load quote from logged user and delete it
401
+ Mage::getModel('sales/quote')->loadByCustomer((int)$this->getCustomerId())->delete();
402
+ // clear checout session quote
403
+ //Mage::getSingleton('checkout/session')->setQuoteId(null);
404
+ //Mage::getSingleton('checkout/cart')->truncate()->save();
405
+ }
406
+ }
407
+ $data = array(
408
+ "session_id" => "",
409
+ "quote_id" => ""
410
+ );
411
+ $this->addData($data);
412
+ $this->save();
413
+ }
414
+ catch (Exception $e)
415
+ {
416
+ return false;
417
+ }
418
+
419
+ return true;
420
+ }
421
+
422
+ public function updateChatdata($datatype, $state)
423
+ {
424
+ try
425
+ {
426
+ $data = array(
427
+ $datatype => $state,
428
+ "updated_at" => date('Y-m-d H:i:s')
429
+ ); // data to be insert on database
430
+ $this->addData($data);
431
+ $this->save();
432
+ }
433
+ catch (Exception $e)
434
+ {
435
+ return false;
436
+ }
437
+
438
+ return true;
439
+ }
440
+
441
+ protected function excerpt($text, $size)
442
+ {
443
+ if (strlen($text) > $size)
444
+ {
445
+ $text = substr($text, 0, $size);
446
+ $text = substr($text, 0, strrpos($text, " "));
447
+ $etc = " ...";
448
+ $text = $text . $etc;
449
+ }
450
+ return $text;
451
+ }
452
+
453
+ protected function getOrdersIdsFromCustomer()
454
+ {
455
+ $ids = array();
456
+ $orders = Mage::getResourceModel('sales/order_collection')
457
+ ->addFieldToSelect('*')
458
+ ->addFieldToFilter('customer_id', $this->getCustomerId()) // not a problem if customer dosen't exist
459
+ ->setOrder('created_at', 'desc');
460
+ foreach ($orders as $_order)
461
+ {
462
+ array_push($ids, $_order->getId());
463
+ }
464
+ if ($ids)
465
+ return $ids;
466
+ return false;
467
+ }
468
+
469
+ protected function getProductIdsBySearch($searchstring)
470
+ {
471
+ // Code to Search Product by $searchstring and get Product IDs
472
+ $product_collection_ids = Mage::getResourceModel('catalog/product_collection')
473
+ ->addAttributeToSelect('*')
474
+ ->addAttributeToFilter('visibility', 4)
475
+ ->addAttributeToFilter('type_id', 'simple')
476
+ ->addAttributeToFilter(
477
+ array(
478
+ array('attribute' => 'sku', 'like' => '%' . $searchstring .'%'),
479
+ array('attribute' => 'name', 'like' => '%' . $searchstring .'%')
480
+ )
481
+ )
482
+ ->getAllIds();
483
+
484
+ if (!empty($product_collection_ids))
485
+ return $product_collection_ids;
486
+
487
+ return false;
488
+ }
489
+
490
+ protected function loadImageContent($productID)
491
+ {
492
+ $imagepath = Mage::getModel('catalog/product')->load($productID)->getSmallImage();
493
+ if ($imagepath && $imagepath != "no_selection")
494
+ {
495
+ $absolutePath =
496
+ Mage::getBaseDir('media') .
497
+ DS . "catalog" . DS . "product" .
498
+ $imagepath;
499
+
500
+ return curl_file_create($absolutePath, 'image/jpg');
501
+ }
502
+ return null;
503
+ }
504
+
505
+ // TELEGRAM FUNCTIONS
506
+ protected function validateTelegramCmd($cmd)
507
+ {
508
+ if ($cmd == "/")
509
+ return null;
510
+ return $cmd;
511
+ }
512
+
513
+ protected function prepareTelegramOrderMessages($orderID) // TODO add link to product name
514
+ {
515
+ $order = Mage::getModel('sales/order')->load($orderID);
516
+ if ($order->getId())
517
+ {
518
+ $message = Mage::helper('core')->__("Order") . " # " . $order->getIncrementId() . "\n\n";
519
+ $items = $order->getAllVisibleItems();
520
+ foreach($items as $item)
521
+ {
522
+ $message .= (int)$item->getQtyOrdered() . "x " .
523
+ $item->getName() . "\n" .
524
+ Mage::helper('core')->__("Price") . ": " . Mage::helper('core')->currency($item->getPrice(), true, false) . "\n\n";
525
+ }
526
+ $message .= Mage::helper('core')->__("Total") . ": " . Mage::helper('core')->currency($order->getGrandTotal(), true, false) . "\n" .
527
+ Mage::helper('core')->__("Zipcode") . ": " . $order->getShippingAddress()->getPostcode();
528
+ if ($this->_reorderCmd['command'])
529
+ $message .= "\n\n" . Mage::helper('core')->__("Reorder") . ": " . $this->_reorderCmd['command'] . $orderID;
530
+ return $message;
531
+ }
532
+ return null;
533
+ }
534
+
535
+ protected function prepareTelegramProdMessages($productID) // TODO add link to product name
536
+ {
537
+ $product = Mage::getModel('catalog/product')->load($productID);
538
+ if ($product->getId())
539
+ {
540
+ if ($product->getStockItem()->getIsInStock() > 0)
541
+ {
542
+ $message = $product->getName() . "\n" .
543
+ $this->excerpt($product->getShortDescription(), 60) . "\n" .
544
+ Mage::helper('core')->__("Add to cart") . ": " . $this->_add2CartCmd['command'] . $product->getId();
545
+ return $message;
546
+ }
547
+ }
548
+ return null;
549
+ }
550
+
551
+ protected function prepareFacebookProdMessages($productID) // TODO add link to product name
552
+ {
553
+ $product = Mage::getModel('catalog/product')->load($productID);
554
+ if ($product->getId())
555
+ {
556
+ if ($product->getStockItem()->getIsInStock() > 0)
557
+ {
558
+ $message = $product->getName() . "\n" .
559
+ $this->excerpt($product->getShortDescription(), 60);
560
+ return $message;
561
+ }
562
+ }
563
+ return null;
564
+ }
565
+
566
+ protected function prepareFacebookOrderMessages($orderID) // TODO add link to product name
567
+ {
568
+ $order = Mage::getModel('sales/order')->load($orderID);
569
+ if ($order->getId())
570
+ {
571
+ $message = Mage::helper('core')->__("Order") . " # " . $order->getIncrementId() . "\n\n";
572
+ $items = $order->getAllVisibleItems();
573
+ foreach($items as $item)
574
+ {
575
+ $message .= (int)$item->getQtyOrdered() . "x " .
576
+ $item->getName() . "\n" .
577
+ Mage::helper('core')->__("Price") . ": " . Mage::helper('core')->currency($item->getPrice(), true, false) . "\n\n";
578
+ }
579
+ $message .= Mage::helper('core')->__("Total") . ": " . Mage::helper('core')->currency($order->getGrandTotal(), true, false) . "\n" .
580
+ Mage::helper('core')->__("Zipcode") . ": " . $order->getShippingAddress()->getPostcode();
581
+
582
+ return $message;
583
+ }
584
+ return null;
585
+ }
586
+
587
+ // // WHATSAPP FUNCTIONS
588
+ // public function whatsappHandler($apiKey)
589
+ // {
590
+ //
591
+ // }
592
+
593
+ // WECHAT FUNCTIONS (maybe)
594
+ // public function wechatHandler($apiKey)
595
+ // {
596
+ //
597
+ // }
598
+ }
app/code/community/Werules/Chatbot/Model/Chats.php ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Werules_Chatbot_Model_Chats
3
+ {
4
+ /**
5
+ * Provide available chats as a value/label array
6
+ *
7
+ * @return array
8
+ */
9
+ public function toOptionArray()
10
+ {
11
+ return array(
12
+ array('value'=>0, 'label'=>'Disable'),
13
+ array('value'=>1, 'label'=>'Telegram Group'),
14
+ array('value'=>2, 'label'=>'Messenger Group')
15
+ // array('value'=>3, 'label'=>'Whatsapp Group')
16
+ // array('value'=>4, 'label'=>'WeChat Group')
17
+ );
18
+ }
19
+ }
app/code/community/Werules/Chatbot/Model/Enable.php ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Werules_Chatbot_Model_Enable
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'=>'Disable'),
13
+ array('value'=>1, 'label'=>'Enable')
14
+ );
15
+ }
16
+ }
app/code/community/Werules/Chatbot/Model/Mysql4/Chatdata.php ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
1
+ <?php
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/Mysql4/Chatdata/Collection.php ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
1
+ <?php
2
+ class Werules_Chatbot_Model_Mysql4_Chatdata_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract {
3
+ protected function _construct()
4
+ {
5
+ $this->_init('chatbot/chatdata');
6
+ }
7
+ }
app/code/community/Werules/Chatbot/Model/Options.php ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Werules_Chatbot_Model_Options
3
+ {
4
+ /**
5
+ * Provide available options as a value/label array
6
+ *
7
+ * @return array
8
+ */
9
+ public function toOptionArray()
10
+ {
11
+ return array(
12
+ // array('value'=>0, 'label'=>'Start'),
13
+ array('value'=>1, 'label'=>'List Categories'),
14
+ array('value'=>2, 'label'=>'Search For Product'),
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'),
23
+ array('value'=>11, 'label'=>'Send Email'),
24
+ array('value'=>12, 'label'=>'Cancel'),
25
+ array('value'=>13, 'label'=>'Help'),
26
+ array('value'=>14, 'label'=>'About'),
27
+ array('value'=>15, 'label'=>'Logout')
28
+ );
29
+ }
30
+ }
app/code/community/Werules/Chatbot/controllers/ChatdataController.php ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Werules_Chatbot_ChatdataController extends Mage_Core_Controller_Front_Action {
3
+ public function indexAction()
4
+ {
5
+ $this->loadLayout();
6
+ $this->getLayout()->getBlock('root')->setTemplate("werules_chatbot_view.phtml"); // use root block to output pure values without html tags
7
+ $this->renderLayout();
8
+ }
9
+
10
+ public function telegramAction()
11
+ {
12
+ $this->loadLayout();
13
+ $this->getLayout()->getBlock('root')->setTemplate("werules_chatbot_view.phtml"); // use root block to output pure values without html tags
14
+ $this->renderLayout();
15
+ }
16
+
17
+ public function facebookAction()
18
+ {
19
+ $this->loadLayout();
20
+ $this->getLayout()->getBlock('root')->setTemplate("werules_chatbot_view.phtml"); // use root block to output pure values without html tags
21
+ $this->renderLayout();
22
+ }
23
+ }
app/code/community/Werules/Chatbot/controllers/IndexController.php ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Werules_Chatbot_IndexController extends Mage_Core_Controller_Front_Action {
3
+ // public function indexAction()
4
+ // {
5
+ // $this->loadLayout();
6
+ // $this->renderLayout();
7
+ // }
8
+ }
app/code/community/Werules/Chatbot/controllers/SettingsController.php ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ {
5
+ parent::preDispatch();
6
+ $loginUrl = Mage::helper('customer')->getLoginUrl();
7
+
8
+ if (!Mage::getSingleton('customer/session')->authenticate($this, $loginUrl)) {
9
+ $this->setFlag('', self::FLAG_NO_DISPATCH, true);
10
+ }
11
+ }
12
+ public function indexAction() // main action, sets layout and page title
13
+ {
14
+ $this->loadLayout();
15
+ // some code
16
+ $this->requestHandler();
17
+
18
+ $this->_initLayoutMessages('customer/session');
19
+ $this->renderLayout();
20
+ }
21
+
22
+ public function saveAction()
23
+ {
24
+ $magehelper = Mage::helper('core');
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
42
+ $data["customer_id"] = $clientid;
43
+ }
44
+ $chatdata->addData($data);
45
+ $chatdata->save();
46
+
47
+ Mage::getSingleton('customer/session')->addSuccess($magehelper->__("Chatbot settings saved successfully.")); // throw success message to the html page
48
+ }
49
+ catch (Exception $e)
50
+ {
51
+ Mage::getSingleton('customer/session')->addError($magehelper->__("Something went wrong, please try again.")); // throw error message to the html page
52
+ }
53
+ }
54
+ $this->_redirect('chatbot/settings/index'); // redirect customer to settings page
55
+ }
56
+
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;
67
+ $error = false;
68
+ $logged = true;
69
+ $data = array();
70
+ $magehelper = Mage::helper('core');
71
+ $chatdataHash = Mage::getModel('chatbot/chatdata')->load($hash, 'hash_key');
72
+ if ($chatdataHash->getIsLogged() == "0")
73
+ {
74
+ $logged = false;
75
+ $customerid = Mage::getSingleton('customer/session')->getCustomer()->getId();
76
+ $chatdata = Mage::getModel('chatbot/chatdata')->load($customerid, 'customer_id');
77
+ if ($chatdata->getCustomerId()) // check if customer already is on chatdata model
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())
84
+ break;
85
+ if ($chatdata->getTelegramChatId()) {
86
+ $data["telegram_chat_id"] = $chatdata->getTelegramChatId();
87
+ $data["telegram_message_id"] = $chatdata->getTelegramMessageId();
88
+ $data["telegram_conv_state"] = $chatdata->getTelegramConvState();
89
+ $data["telegram_support_reply_chat_id"] = $chatdata->getTelegramSupportReplyChatId();
90
+ }
91
+ if ($chatdata->getFacebookChatId()) {
92
+ $data["facebook_chat_id"] = $chatdata->getFacebookChatId();
93
+ $data["facebook_message_id"] = $chatdata->getFacebookMessageId();
94
+ $data["facebook_conv_state"] = $chatdata->getFacebookConvState();
95
+ $data["facebook_support_reply_chat_id"] = $chatdata->getFacebookSupportReplyChatId();
96
+ }
97
+ if ($chatdata->getWhatsappChatId()) {
98
+ $data["whatsapp_chat_id"] = $chatdata->getWhatsappChatId();
99
+ $data["whatsapp_message_id"] = $chatdata->getWhatsappMessageId();
100
+ $data["whatsapp_conv_state"] = $chatdata->getWhatsappConvState();
101
+ $data["whatsapp_support_reply_chat_id"] = $chatdata->getWhatsappSupportReplyChatId();
102
+ }
103
+ if ($chatdata->getWechatChatId()) {
104
+ $data["wechat_chat_id"] = $chatdata->getWechatChatId();
105
+ $data["wechat_message_id"] = $chatdata->getWechatMessageId();
106
+ $data["wechat_conv_state"] = $chatdata->getWechatpConvState();
107
+ $data["wechat_support_reply_chat_id"] = $chatdata->getWechatSupportReplyChatId();
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
+ }
114
+ if (!empty($data)) // if any found, prepare to merge
115
+ {
116
+ $data["updated_at"] = date('Y-m-d H:i:s');
117
+ $data["is_logged"] = "1";
118
+ $data["customer_id"] = $customerid;
119
+
120
+ $chatdata = Mage::getModel('chatbot/chatdata')->load($hash, 'hash_key');
121
+ if (!$chatdata->getHashKey())
122
+ $data["hash_key"] = $hash;
123
+
124
+ $chatdata->addData($data);
125
+ $chatdata->save();
126
+ $success = true;
127
+ }
128
+ else
129
+ $error = true;
130
+ }
131
+ catch (Exception $e)
132
+ {
133
+ $error = true;
134
+ }
135
+ }
136
+ else // if is the first time for this customer, just save it
137
+ {
138
+ try
139
+ {
140
+ $chatdata = Mage::getModel('chatbot/chatdata')->load($hash, 'hash_key');
141
+ if ($chatdata->getHashKey()) {
142
+ $data = array(
143
+ "customer_id" => $customerid,
144
+ "is_logged" => "1",
145
+ "updated_at" => date('Y-m-d H:i:s')
146
+ );
147
+ $chatdata->addData($data);
148
+ $chatdata->save();
149
+ $success = true;
150
+ }
151
+ }
152
+ catch (Exception $e)
153
+ {
154
+ $error = true;
155
+ }
156
+ }
157
+ }
158
+ // messages
159
+ if ($success)
160
+ Mage::getSingleton('customer/session')->addSuccess($magehelper->__("Your account is now attached with our chatbot."));
161
+ else if ($error)
162
+ Mage::getSingleton('customer/session')->addError($magehelper->__("Something went wrong, please try again."));
163
+ else if ($logged)
164
+ Mage::getSingleton('customer/session')->addNotice($magehelper->__("You're already logged."));
165
+ }
166
+ }
app/code/community/Werules/Chatbot/etc/config.xml ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <config>
3
+ <modules>
4
+ <Werules_Chatbot>
5
+ <version>0.0.5</version>
6
+ </Werules_Chatbot>
7
+ </modules>
8
+ <frontend>
9
+ <translate>
10
+ <modules>
11
+ <Werules_Chatbot>
12
+ <files>
13
+ <default>Werules_Chatbot.csv</default>
14
+ </files>
15
+ </Werules_Chatbot>
16
+ </modules>
17
+ </translate>
18
+ <layout>
19
+ <updates>
20
+ <werules_chatbot module="werules_chatbot">
21
+ <file>werules_chatbot.xml</file>
22
+ </werules_chatbot>
23
+ </updates>
24
+ </layout>
25
+ <routers>
26
+ <chatbot>
27
+ <use>standard</use>
28
+ <args>
29
+ <module>Werules_Chatbot</module>
30
+ <frontName>chatbot</frontName>
31
+ </args>
32
+ </chatbot>
33
+ </routers>
34
+ </frontend>
35
+
36
+ <global>
37
+ <models>
38
+ <chatbot>
39
+ <class>Werules_Chatbot_Model</class>
40
+ <resourceModel>chatbot_mysql4</resourceModel>
41
+ </chatbot>
42
+ <chatbot_mysql4>
43
+ <class>Werules_Chatbot_Model_Mysql4</class>
44
+ <entities>
45
+ <chatdata>
46
+ <table>wr_chatbot</table> <!-- Actual table name in sql -->
47
+ </chatdata>
48
+ </entities>
49
+ </chatbot_mysql4>
50
+ </models>
51
+ <blocks>
52
+ <werules_chatbot>
53
+ <class>Werules_Chatbot_Block</class>
54
+ </werules_chatbot>
55
+ </blocks>
56
+ <helpers>
57
+ <werules_chatbot>
58
+ <class>Werules_Chatbot_Helper</class>
59
+ </werules_chatbot>
60
+ </helpers>
61
+ <resources>
62
+ <chatbot_setup>
63
+ <setup>
64
+ <module>Werules_Chatbot</module>
65
+ <class>Mage_Customer_Model_Resource_Setup</class>
66
+ </setup>
67
+ <connection>
68
+ <use>core_setup</use>
69
+ </connection>
70
+ </chatbot_setup>
71
+ <chatbot_write>
72
+ <connection>
73
+ <use>core_write</use>
74
+ </connection>
75
+ </chatbot_write>
76
+ <chatbot_read>
77
+ <connection>
78
+ <use>core_read</use>
79
+ </connection>
80
+ </chatbot_read>
81
+ </resources>
82
+ </global>
83
+ <adminhtml>
84
+ <acl>
85
+ <resources>
86
+ <admin>
87
+ <children>
88
+ <system>
89
+ <children>
90
+ <config>
91
+ <children>
92
+ <chatbot_enable>
93
+ <title>Custom Configuration Section</title>
94
+ </chatbot_enable>
95
+ </children>
96
+ </config>
97
+ </children>
98
+ </system>
99
+ </children>
100
+ </admin>
101
+ </resources>
102
+ </acl>
103
+ </adminhtml>
104
+ </config>
app/code/community/Werules/Chatbot/etc/system.xml ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <config>
3
+ <tabs>
4
+ <werules_chatbot translate="label" module="werules_chatbot">
5
+ <label>Chatbot</label>
6
+ <sort_order>1</sort_order>
7
+ </werules_chatbot>
8
+ </tabs>
9
+ <sections>
10
+ <chatbot_enable translate="label" module="werules_chatbot">
11
+ <label>Chatbot Settings</label>
12
+ <tab>werules_chatbot</tab>
13
+ <frontend_type>text</frontend_type>
14
+ <sort_order>1</sort_order>
15
+ <show_in_default>1</show_in_default>
16
+ <show_in_website>1</show_in_website>
17
+ <show_in_store>1</show_in_store>
18
+ <comment>To Use This Module You'll Need to Have SSL Enabled in Your Store.</comment>
19
+ <groups>
20
+ <general_config translate="label">
21
+ <label>General Configuration</label>
22
+ <frontend_type>text</frontend_type>
23
+ <sort_order>0</sort_order>
24
+ <show_in_default>1</show_in_default>
25
+ <show_in_website>1</show_in_website>
26
+ <show_in_store>1</show_in_store>
27
+ <fields>
28
+ <your_custom_key>
29
+ <label>Your Secret Key</label>
30
+ <frontend_type>text</frontend_type>
31
+ <validate>validate-alphanum</validate>
32
+ <sort_order>0</sort_order>
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 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/telegram/YOUR_CUSTOM_KEY to Set Telegram Webhook.</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>
60
+ <frontend_type>select</frontend_type>
61
+ <source_model>chatbot/enable</source_model>
62
+ <sort_order>3</sort_order>
63
+ <show_in_default>1</show_in_default>
64
+ <show_in_website>1</show_in_website>
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>
76
+ <comment>Log will be at root/var/log/. </comment>
77
+ </enable_post_log>
78
+ </fields>
79
+ </general_config>
80
+ <witai_config translate="label">
81
+ <label>wit.ai Configurations</label>
82
+ <frontend_type>text</frontend_type>
83
+ <sort_order>1</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>
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>
101
+ <frontend_type>text</frontend_type>
102
+ <sort_order>1</sort_order>
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">
111
+ <label>Telegram Configuration</label>
112
+ <frontend_type>text</frontend_type>
113
+ <sort_order>2</sort_order>
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>Telegram Configurations</comment>
118
+ <fields>
119
+ <enable_bot>
120
+ <label>Enable Telegram Bot</label>
121
+ <frontend_type>select</frontend_type>
122
+ <source_model>chatbot/enable</source_model>
123
+ <sort_order>0</sort_order>
124
+ <show_in_default>1</show_in_default>
125
+ <show_in_website>1</show_in_website>
126
+ <show_in_store>1</show_in_store>
127
+ <comment>Enable Telegram Bot</comment>
128
+ </enable_bot>
129
+ <disabled_message>
130
+ <label>Unavailability Message</label>
131
+ <frontend_type>text</frontend_type>
132
+ <sort_order>1</sort_order>
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.</comment>
137
+ </disabled_message>
138
+ <telegram_api_key>
139
+ <label>Telegram Bot API Key</label>
140
+ <frontend_type>text</frontend_type>
141
+ <sort_order>2</sort_order>
142
+ <show_in_default>1</show_in_default>
143
+ <show_in_website>1</show_in_website>
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>
154
+ <comment>ID of Group that the support messages will be forwarded. e.g. g123456789</comment>
155
+ </telegram_support_group>
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.</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>
172
+ <comment>Message Will be Sent When Customer Asks For Help.</comment>
173
+ </telegram_help_msg>
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>
181
+ <comment>Message Will be Sent When Customer Asks For About.</comment>
182
+ </telegram_about_msg>
183
+ <enable_command_list>
184
+ <label>Enable Command Listing</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>
191
+ <comment>Enable Command Listing When Customer Ask For About</comment>
192
+ </enable_command_list>
193
+ <enabled_commands>
194
+ <label>Enabled Commands</label>
195
+ <frontend_type>multiselect</frontend_type>
196
+ <source_model>chatbot/options</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>
201
+ <comment>Enabled Commands</comment>
202
+ </enabled_commands>
203
+ <commands_list>
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>9</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>10</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>
221
+ <comment>Enable Default Replies</comment>
222
+ </enable_default_replies>
223
+ <default_replies>
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>11</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>Default Replies.</comment>
232
+ </default_replies>
233
+ </fields>
234
+ </telegram_config>
235
+ <facebook_config translate="label">
236
+ <label>Facebook Configuration</label>
237
+ <frontend_type>text</frontend_type>
238
+ <sort_order>3</sort_order>
239
+ <show_in_default>1</show_in_default>
240
+ <show_in_website>1</show_in_website>
241
+ <show_in_store>1</show_in_store>
242
+ <comment>Facebook Messenger Configurations</comment>
243
+ <fields>
244
+ <enable_bot>
245
+ <label>Enable Messenger Bot</label>
246
+ <frontend_type>select</frontend_type>
247
+ <source_model>chatbot/enable</source_model>
248
+ <sort_order>0</sort_order>
249
+ <show_in_default>1</show_in_default>
250
+ <show_in_website>1</show_in_website>
251
+ <show_in_store>1</show_in_store>
252
+ <comment>Enable Messenger Bot</comment>
253
+ </enable_bot>
254
+ <disabled_message>
255
+ <label>Unavailability Message</label>
256
+ <frontend_type>text</frontend_type>
257
+ <sort_order>1</sort_order>
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.</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.</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>
297
+ <comment>Message Will be Sent When Customer Asks For Help.</comment>
298
+ </facebook_help_msg>
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>
306
+ <comment>Message Will be Sent When Customer Asks For About.</comment>
307
+ </facebook_about_msg>
308
+ <enable_command_list>
309
+ <label>Enable Command Listing</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>
316
+ <comment>Enable Command Listing When Customer Ask For About</comment>
317
+ </enable_command_list>
318
+ <enable_predict_commands>
319
+ <label>Enable Command Prediction</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>
326
+ <comment>Enable The Bot to Try to Predict What Command The Customer Wants by Looking into What He Wrote</comment>
327
+ </enable_predict_commands>
328
+ <enabled_commands>
329
+ <label>Enabled Commands</label>
330
+ <frontend_type>multiselect</frontend_type>
331
+ <source_model>chatbot/options</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>
336
+ <comment>Enabled Commands</comment>
337
+ </enabled_commands>
338
+ <commands_list>
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>10</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>11</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>
356
+ <comment>Enable Default Replies</comment>
357
+ </enable_default_replies>
358
+ <default_replies>
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>12</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>Default Replies.</comment>
367
+ </default_replies>
368
+ </fields>
369
+ </facebook_config>
370
+ </groups>
371
+ </chatbot_enable>
372
+ </sections>
373
+ </config>
app/code/community/Werules/Chatbot/sql/chatbot_setup/mysql4-install-0.0.5.php ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ $table = 'wr_chatbot';
4
+ $installer = $this;
5
+ $installer->startSetup(); //db installation
6
+
7
+ $installer->run("
8
+ -- DROP TABLE IF EXISTS {$this->getTable($table)};
9
+ CREATE TABLE {$this->getTable($table)} (
10
+ `entity_id` int(11) unsigned NOT NULL auto_increment,
11
+ `created_at` timestamp NULL,
12
+ `updated_at` timestamp NULL,
13
+ `customer_id` int(11) NULL,
14
+ `session_id` varchar(150) NULL,
15
+ `quote_id` varchar(20) NULL,
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
+ ");
45
+
46
+ $installer->endSetup();
app/design/frontend/base/default/layout/werules_chatbot.xml ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <layout>
2
+ <customer_account>
3
+ <reference name="customer_account_navigation">
4
+ <action method="addLink">
5
+ <name>chatbot_settings</name>
6
+ <path>chatbot/settings/index</path>
7
+ <label>Chatbot Settings</label>
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" />
21
+ <remove name="header" />
22
+ <remove name="footer" />
23
+ <reference name="content">
24
+ <block type="core/template" name="chatbot_content" template="werules_chatbot_view.phtml"/>
25
+ </reference>
26
+ </chatbot_chatdata_index>
27
+ <chatbot_chatdata_telegram>
28
+ <remove name="head" />
29
+ <remove name="right" />
30
+ <remove name="left" />
31
+ <remove name="header" />
32
+ <remove name="footer" />
33
+ <reference name="content">
34
+ <block type="core/template" name="chatbot_content" template="werules_chatbot_view.phtml"/>
35
+ </reference>
36
+ </chatbot_chatdata_telegram>
37
+ <chatbot_chatdata_facebook>
38
+ <remove name="head" />
39
+ <remove name="right" />
40
+ <remove name="left" />
41
+ <remove name="header" />
42
+ <remove name="footer" />
43
+ <reference name="content">
44
+ <block type="core/template" name="chatbot_content" template="werules_chatbot_view.phtml"/>
45
+ </reference>
46
+ </chatbot_chatdata_facebook>
47
+ </layout>
app/design/frontend/base/default/template/werules_chatbot_config.phtml ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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() ?>
22
+ <div class="page-title">
23
+ <h1><?php echo $this->__('Chatbot Settings') ?></h1>
24
+ </div>
25
+ <form action="<?php echo $this->getUrl('chatbot/settings/save') ?>" method="post" id="form-validate" autocomplete="off">
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
+ ?>
42
+ <a href="<?php echo $url; ?>" target="_blank"><?php echo $this->__('Here') ?></a>
43
+ </p>
44
+ <?php endif; ?>
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>
59
+ <?php endif; ?>
60
+ </li>
61
+ <?php
62
+ /*
63
+ <li>
64
+ <div class="input-box">
65
+ <input <?php if ($chatdata->getEnableWhatsapp() == "1") echo "checked"; ?> type="checkbox" title="<?php echo $this->__('Enable Whatsapp?') ?>" class="checkbox" name="enable_whatsapp" id="enable_whatsapp" />
66
+ </div>
67
+ <label for="enable_whatsapp" class="required"><em>*</em><?php echo $this->__('Enable Whatsapp?') ?></label>
68
+ </li>
69
+ <li>
70
+ <div class="input-box">
71
+ <input <?php if ($chatdata->getEnableWechat() == "1") echo "checked"; ?> type="checkbox" title="<?php echo $this->__('Enable Wechat?') ?>" class="checkbox" name="enable_wechat" id="enable_wechat" />
72
+ </div>
73
+ <label for="enable_wechat" class="required"><em>*</em><?php echo $this->__('Enable Wechat?') ?></label>
74
+ </li>
75
+ */
76
+ ?>
77
+ </ul>
78
+ </div>
79
+ <!-- buttons -->
80
+ <p class="required"><?php echo $this->__('* Required Fields') ?></p>
81
+ <div class="buttons-set">
82
+ <p class="back-link">
83
+ <a href="<?php echo $this->getBackUrl() ?>">
84
+ <small>&laquo; </small><?php echo $this->__('Back') ?>
85
+ </a>
86
+ </p>
87
+ <button type="submit" title="<?php echo $this->__('Save') ?>" class="button">
88
+ <span>
89
+ <span>
90
+ <?php echo $this->__('Save') ?>
91
+ </span>
92
+ </span>
93
+ </button>
94
+ </div>
95
+ </form>
96
+ </div>
app/design/frontend/base/default/template/werules_chatbot_view.phtml ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ $action = $this->getRequest()->getActionName();
3
+ $webhook = Mage::app()->getRequest()->getParam('webhook');
4
+ $custom_key = Mage::getStoreConfig('chatbot_enable/general_config/your_custom_key');
5
+
6
+ if ($webhook != $custom_key)
7
+ $webhook = null;
8
+ echo Mage::getModel('chatbot/chatdata')->requestHandler($action, $webhook);
9
+ ?>
app/etc/modules/Werules_Chatbot.xml ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <config>
3
+ <modules>
4
+ <Werules_Chatbot>
5
+ <active>true</active>
6
+ <codePool>community</codePool>
7
+ </Werules_Chatbot>
8
+ </modules>
9
+ </config>
app/locale/pt_BR/Werules_Chatbot.csv ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Order","Pedido"
2
+ "Price","Preço"
3
+ "Total","Total"
4
+ "Zipcode","CEP"
5
+ "Reorder","Refazer pedido"
6
+ "Add to cart","Adicionar ao carrinho"
7
+ "Message from support","Mensagem do suporte"
8
+ "Message sent.","Mensagem enviada."
9
+ "I don't work with groups.","Eu não funciono em grupos."
10
+ "Something went wrong, please try again.","Alguma coisa deu errado, por favor tente novamente."
11
+ "Ok","Ok"
12
+ "Okay","Okay"
13
+ "Cool","Beleza"
14
+ "Awesome","Tranquilo"
15
+ "Added. To checkout send","Adicionado. Para finalizar o pedido envie"
16
+ "Sorry, no products found in this category.","Desculpe, essa categoria não possui produtos."
17
+ "Sorry, no products found for this criteria.","Desculpe, não encontramos nenhum produto."
18
+ "we have sent your message to support.","enviamos sua mensagem para o suporte."
19
+ "Select a category","Selecione uma categoria"
20
+ "Products on cart","Produtos no carrinho"
21
+ "Checkout Here","Finalize o pedido"
22
+ "Your cart is empty.","Seu carrinho está vazio."
23
+ "Cart cleared.","Carrinho esvaziado"
24
+ "what do you want to search for?","digite o que você quer procurar."
25
+ "To login to your account, click this link","Para acessar sua conta, clique nesse link"
26
+ "let me fetch that for you.","deixa eu buscar essa informação para você."
27
+ "Please login first.","Por favor, faça o login primeiro."
28
+ "to checkout send","para finalizar o pedido envie"
29
+ "what do you need support for?","precisa de suporte com o que?"
30
+ "exiting support mode.","saindo do modo de suporte."
31
+ "Done.","Feito."
32
+ "Sorry, I didn't understand that.","Desculpe, eu não entendi o que você quis dizer."
33
+ "Ok, canceled.","Ok, cancelado."
34
+ "Your account is now attached with our chatbot.","Sua conta foi conectada com sucesso ao nosso chatbot."
35
+ "Chatbot settings saved successfully.","Configurações salvas com sucesso."
36
+ "List store categories.","Listar categorias."
37
+ "Search for products.","Buscar por produtos."
38
+ "Login into your account.","Acesse sua conta."
39
+ "Logout from your account.","Saia de sua conta."
40
+ "List your personal orders.","Listar pedidos."
41
+ "Reorder a order.","Refazer pedido."
42
+ "Add product to cart.","Adicionar produto ao carrinho."
43
+ "Checkout your order.","Finalizar pedido."
44
+ "Clear your cart.","Limpar carrinho."
45
+ "Track your order status.","Buscar dados do pedido."
46
+ "Send message to support.","Enviar mensagem ao suporte."
47
+ "Send email.","Enviar e-mail."
48
+ "Cancel.","Cancelar."
49
+ "Get help.","Ajuda."
50
+ "About.","Sobre."
51
+ "Webhook for Telegram configured..","Webhook para o Telegram configurado com sucesso."
52
+ "Command list","Lista de comandos"
53
+ "This account has no orders.","Nenhum pedido nessa conta."
54
+ "write the email content.","escreva o conteudo do e-mail."
55
+ "By doing this you agree that we may contact you directly via chat message.","Ao enviar um email, você concorda que poderemos entrar em contato com você por mensagem nesse chat."
56
+ "Trying to send the email...","Tentando enviar o e-mail..."
57
+ "Contact from chatbot","Contado do chatbot"
58
+ "Sorry, I wasn't able to send an email this time. Please try again later.","Desculpe, não consegui enviar o seu e-mail nesse momento. Tente novamente mais tarde."
59
+ "Not informed","Não informado"
60
+ "Message from chatbot customer","Mensagem de cliente no chatbot"
61
+ "Customer name","Nome do cliente"
62
+ "Message","Mensagem"
63
+ "Contacts","Contatos"
64
+ "To cancel, send","Para cancelar, envie"
65
+ "Chatbot","Chatbot"
66
+ "Email","E-mail"
67
+ "send the order number.","envie o número do pedido."
68
+ "Sorry, we couldn't find any order with this information.","Desculpe, não encontramos nenhum pedido com esse número."
69
+ "Your account dosen't have any orders.","Sua conta não possui pedidos"
70
+ "To talk with me, please enable Telegram on your account chatbot settings.","Para conversar comigo, habilite o Telegram nas configurações de chatbot de sua conta."
71
+ "Start a bot conversation on Telegram","Comece uma conversa com nosso bot no Telegram"
72
+ "Start a bot conversation on Facebook Messenger","Comece uma conversa com nosso bot no Facebook Messenger"
73
+ "Here","Aqui"
74
+ "Enable Telegram?","Habilitar Telegram?"
75
+ "Enable Facebook?","Habilitar Facebook?"
76
+ "Enable Whatsapp?","Habilitar Whatsapp?"
77
+ "Enable Wechat?","Habilitar Wechat?"
78
+ "To talk with me, please enable Facebook Messenger on your account chatbot settings.","Para conversar comigo, habilite o Facebook Messenger nas configurações de chatbot de sua conta."
79
+ "Visit product's page","Visitar páginas do produto"
80
+ "Processing...","Processando..."
81
+ "Please wait while I check that for you.","Por favor, aguarde enquanto eu busco essa informação para você."
82
+ "Login","Entrar"
83
+ "To login to your account, click the link below","Para acessar sua conta, clique no link abaixo"
84
+ "You're already logged.","Você já está logado na sua conta."
85
+ "You're not logged.","Você não está logado na sua conta."
86
+ "Message via","Mensagem via"
87
+ "From","De"
88
+ "You're already on support in other chat application, please close it before opening a new one.","Você já está com o suporte aberto em outro aplicativo de conversa, porque favor finalize o suporte antes de abrir um novo."
89
+ "Show more","Mostrar mais"
90
+ "Show more orders","Mostrar mais pedidos"
91
+ "To show more, send","Para exibir mais, envie"
92
+ "No categories available at the moment, please try again later.","Nenhuma categoria disponível no momento, por favor tente novamente mais tarde."
93
+ "Done. This category has %s products.","Pronto. Essa categoria possui %s produtos."
94
+ "Done. This category has only one product.","Pronto. Essa categoria possui apenas um produto."
95
+ "Done. I've found %s products for your criteria.","Pronto. Encontrei %s produtos para sua busca."
96
+ "Done. I've found only one product for your criteria.","Pronto. Encontrei apenas um produto para sua busca."
97
+ "Done. You've only one order.","Pronto. Você tem apenas um pedido na sua conta."
98
+ "Done. I've found %s orders.","Pronto. Encontrei %s pedidos em sua conta."
99
+ "Please wait while our support check your message so you can talk to a real person.","Por favor, aguarde enquanto nosso suporte verifica sua mensagem para que você possa conversar conosco."
100
+ "Please use","Por favor use"
101
+ "your message here.","sua mensagem aqui."
102
+ "We're working on this feature.","Estamos trabalhando nessa funcionalidade."
103
+ "Done. The customer is no longer on support.","Pronto. O cliente não está mais em modo de suporte."
104
+ "Support ended.","Suporte finalizado"
105
+ "You're now on support mode.","Você entrou no modo de suporte."
106
+ "Ok, send me the message and I'll forward it to the customer.","Ok, envie a mensagem e eu encaminharei para o cliente."
107
+ "Done. The customer is no longer able to enter support.","Pronto. O cliente não poderá mais pedir por suporte."
108
+ "Done. The customer is now able to enter support.","Pronto. O cliente poderá pedir por suporte."
109
+ "I'm sorry, you can't ask for support now. Please try again later.","Desculpe, você não pode pedir por suporte agora. Por favor tente novamente mais tarde."
110
+ "Block support","Bloquear supporte"
111
+ "Enable support","Habilitar supporte"
112
+ "End support","Finalizar supporte"
113
+ "Reply this message","Responder essa mensagem"
114
+ "ID","ID"
115
+ "Enable/Disable support","Habilita/desabilita suporte"
116
+ "Ok, logging out.","Ok, saindo de sua conta."
117
+ "please wait while I prepare the checkout for you.","por favor aguarde enquanto eu preparo o seu pedido para ser finalizado."
118
+ "please wait while I gather your orders for listing.","por favor aguarde enquanto eu busco as informações dos seus pedidos para lista-los."
119
+ "please wait while I add the products from this order to your cart.","por favor aguarde enquanto eu adiciono os produtos do seu pedido no carrinho."
120
+ "adding %s to your cart.","adicionando %s ao seu carrinho"
121
+ "please wait while I gather all categories for you.","por favor aguarde enquanto busco todas as categorias para você."
122
+ "please wait while I search for '%s' for you.","por favor aguarde enquanto busco por '%s' para você."
123
+ "please wait while I check the status for order %s.","por favor aguarde enquanto verifico o status do pedido %s."
124
+ "this product","esse produto"
125
+ "listing more.","listando mais."
126
+ "please wait while I gather all products from %s for you.","por favor aguarde euqnaot busco todos os produtos da categoria %s para você."
127
+ "Phrase","Frase"
128
+ "Reply","Resposta"
129
+ "Similarity (%)","Similaridade (%)"
130
+ "Add","Adicionar"
131
+ "Command","Comando"
132
+ "Command Code","Código do Comando"
133
+ "Alias","Aliás"
134
+ "Match Case","Diferenciar Maiúsculas de Minúsculas"
135
+ "And that was the last one.","E esse foi o último."
package.xml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <package><name>Chatbot_Integration</name><version>0.0.5</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
+ &lt;h1&gt;Features&lt;/h1&gt;&lt;br&gt;&#xD;
4
+ - List store categories&lt;br&gt;&#xD;
5
+ - List products from category&lt;br&gt;&#xD;
6
+ - Search for products&lt;br&gt;&#xD;
7
+ - Add product to cart&lt;br&gt;&#xD;
8
+ - Clear cart&lt;br&gt;&#xD;
9
+ - Login/Logout to your account&lt;br&gt;&#xD;
10
+ - List orders&lt;br&gt;&#xD;
11
+ - Track order status&lt;br&gt;&#xD;
12
+ - Reorder&lt;br&gt;&#xD;
13
+ - Send email&lt;br&gt;&#xD;
14
+ - Send message to support&lt;br&gt;&#xD;
15
+ - Reply customer support messages from you favorite chat messenger&lt;br&gt;&#xD;
16
+ - Send message to all customers (promotion messages, etc)&lt;br&gt;&#xD;
17
+ - Force exit customer from support mode&lt;br&gt;&#xD;
18
+ - Block a customer for using support mode&lt;br&gt;&#xD;
19
+ - Use Telegram to receive and reply messages from Facebook&lt;br&gt;&#xD;
20
+ - Set custom reply messages for predetermined phrases&lt;br&gt;&#xD;
21
+ &lt;br&gt;&#xD;
22
+ &lt;b&gt;Currently not working with Configurable Products and products with custom options&lt;/b&gt;&lt;br&gt;&#xD;
23
+ &lt;br&gt;&#xD;
24
+ &lt;h1&gt;Installation&lt;/h1&gt;&lt;br&gt;&#xD;
25
+ 1. Unpack the extension ZIP file in your Magento root directory&lt;br&gt;&#xD;
26
+ 2. Clear the Magento cache: **System &gt; Cache Management**&lt;br&gt;&#xD;
27
+ 3. Log out the Magento admin and log back in to clear the ACL list&lt;br&gt;&#xD;
28
+ 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-11</date><time>15:04:46</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="553475eba0ca5190ae6361d7aaf3c5eb"/><file name="CommandsSelect.php" hash="21d792402bb6758700e08885fc0708b5"/><file name="Enable.php" hash="91137cacb5a60f061deefed4ca8e4f91"/><file name="Replies.php" hash="454254306837abff6f74859df10b8a9f"/></dir><dir name="controllers"><file name="ChatdataController.php" hash="096cabaec4414d91862298a588f5c11a"/><file name="IndexController.php" hash="eae277df370ef69ebd75f72691523154"/><file name="SettingsController.php" hash="d169d06da794fd11ff08b53de4027a54"/></dir><dir name="etc"><file name="config.xml" hash="92c9e97c48d4d7b99f10d9f2cf3d346c"/><file name="system.xml" hash="223c148d353fc56181fa73e01ff3b3fd"/></dir><dir name="Helper"><file name="Data.php" hash="288462ee4ca74138d88e758a602a6311"/></dir><dir name="Model"><file name="Chatdata.php" hash="ea9a741edf1d1ddf953f8339039f40d5"/><file name="Chats.php" hash="174b05d4ceb3e98936a9e87f82b23621"/><file name="Enable.php" hash="c8c53bf3b4237632bb74d7721a1159a4"/><file name="Options.php" hash="092f711eee89759f33d09dec4e90583d"/><dir name="Adminhtml"><file name="Serialized.php" hash="270219dca43a25113933afb8c819e8da"/></dir><dir name="Api"><dir name="Facebook"><file name="Handler.php" hash="e2de02bef6bfaefe093bc34e8cb22306"/><file name="Messenger.php" hash="35c4bbe5df4b43f432b56b54b968bdc7"/></dir><dir name="Telegram"><file name="Handler.php" hash="26bde01c63dbf81bbcd7dcea52698aaf"/><file name="Telegram.php" hash="572289b61adb8ed8a822cf6d142010fd"/></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.5.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="135c293d383f8e700a634eb84aa808f7"/></dir><dir name="template"><file name="werules_chatbot_config.phtml" hash="6a855bcae6c7bb2b914573b3f3081329"/><file name="werules_chatbot_view.phtml" hash="49d9b523d7c69571839695227d29a620"/></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="pt_BR"><file name="Werules_Chatbot.csv" hash="ea4de497a43b613792b3e9f4133f5f06"/></dir></dir></dir></target></contents></package>