· 5 years ago · Mar 16, 2020, 06:08 PM
1<?php
2
3require_once 'connect_bd.php';
4try {
5 $dbh = connect_db();
6}catch (\Exception $ex){
7 file_put_contents($fp, "ОШИБКА " . $ex, FILE_APPEND);
8}
9
10if (!isset($_REQUEST)) {return;}
11// Строка, которую должен вернуть сервер (См. Callback API->Настройки сервера)
12$confirmationToken = '374581c9';
13// Ключ доступа сообщества (длинная строчка которую получили нажав "создать ключ")
14$token = 'f010a6d39ea008c9b06e97cf5b17a7d4079b0d407d88999dbe7b428baa9e3b46c3fe09814ba5bb9e610df';
15// Секретный ключ. (Задаем в Callback API->Настройки сервера)
16$secretKey = 'lunevsashaivanov';
17// Подключение к vk_api
18$fp = "log.txt";
19// Получаем и декодируем уведомление
20$data = json_decode(file_get_contents('php://input'));
21// проверяем secretKey
22if (strcmp($data->secret, $secretKey) !== 0 && strcmp($data->type, 'confirmation') !== 0) {return;}
23
24 // Массив обой
25 $img = array('photo207871954_457243508', 'photo207871954_457243509', 'photo207871954_457243510', 'photo207871954_457243511', 'photo207871954_457243512', 'photo207871954_457243513', 'photo207871954_457243514', 'photo207871954_457243515', 'photo207871954_457243516', 'photo207871954_457243517', 'photo207871954_457243518', 'photo207871954_457243519', 'photo207871954_457243520', 'photo207871954_457243521');
26 // Массив обой для парней
27 $img_b = array('photo207871954_457243522', 'photo207871954_457243523', 'photo207871954_457243524', 'photo207871954_457243525', 'photo207871954_457243526', 'photo207871954_4572435227', 'photo207871954_457243528', 'photo207871954_457243529', 'photo207871954_457243530', 'photo207871954_457243531', 'photo207871954_457243532', 'photo207871954_457243533', 'photo207871954_457243534', 'photo207871954_457243535', 'photo207871954_457243536');
28 // Массив обой для девушек
29 $img_g = array('photo207871954_457243537', 'photo207871954_457243538', 'photo207871954_457243539', 'photo207871954_457243540', 'photo207871954_457243541', 'photo207871954_457243542', 'photo207871954_457243543', 'photo207871954_457243544', 'photo207871954_457243545', 'photo207871954_457243546', 'photo207871954_457243547', 'photo207871954_457243548', 'photo207871954_457243549', 'photo207871954_457243550');
30
31 // Рандом обой
32 $rd = rand(0, count($img));
33 // Рандом обой
34 $rdb = rand(0, count($img_b));
35 // Рандом обой
36 $rdg = rand(0, count($img_g));
37
38 CONST COLOR_negative='negative';
39 CONST COLOR_positive='positive';
40 CONST COLOR_default='default';
41 CONST COLOR_primary='primary';
42
43 /////// Клавиатуры ///////
44 $keyboardO = '{"one_time": false, "buttons": [[{ "action": { "type": "text", "payload": "{\"button\": \"1\"}", "label": "Следующие" }, "color": "negative" }, { "action": { "type": "text", "payload": "{\"button\": \"2\"}", "label": "Назад" }, "color": "positive" }, { "action": { "type": "text", "payload": "{\"button\": \"2\"}", "label": "Для парней?" }, "color": "primary" }, { "action": { "type": "text", "payload": "{\"button\": \"2\"}", "label": "Для девушек?" }, "color": "secondary" } ] ] }';
45 $keyboardR = '{"one_time": false,"buttons": [[{"action": {"type": "text","payload": "{\"button\": \"1\"}","label": "Следующий"},"color": "negative"},{"action": {"type": "text","payload": "{\"button\": \"2\"}","label": "Назад"},"color": "positive"}]]}';
46 $keyboardB = '{"one_time": false,"buttons": [[{"action": {"type": "text","payload": "{\"button\": \"1\"}","label": "Следующие🚶"},"color": "secondary"},{"action": {"type": "text","payload": "{\"button\": \"2\"}","label": "Назад"},"color": "positive"}]]}';
47 $keyboardG = '{"one_time": false,"buttons": [[{"action": {"type": "text","payload": "{\"button\": \"1\"}","label": "Следующие💃"},"color": "secondary"},{"action": {"type": "text","payload": "{\"button\": \"2\"}","label": "Назад"},"color": "positive"}]]}';
48 $keyboardS = '{"one_time": false, "buttons": [[{ "action": { "type": "text", "payload": "{\"button\": \"1\"}", "label": "100" }, "color": "negative" }, { "action": { "type": "text", "payload": "{\"button\": \"2\"}", "label": "200" }, "color": "positive" }, { "action": { "type": "text", "payload": "{\"button\": \"2\"}", "label": "300" }, "color": "primary" }, { "action": { "type": "text", "payload": "{\"button\": \"2\"}", "label": "400" }, "color": "secondary" } ] ] }';
49 $kbd1 = '{"one_time": false, "buttons": [[{ "action": { "type": "text", "payload": "{\"button\": \"1\"}", "label": "1" }, "color": "secondary" }, { "action": { "type": "text", "payload": "{\"button\": \"2\"}", "label": "2" }, "color": "secondary" }, { "action": { "type": "text", "payload": "{\"button\": \"2\"}", "label": "3" }, "color": "secondary" }, { "action": { "type": "text", "payload": "{\"button\": \"2\"}", "label": "4" }, "color": "secondary" } ], [{ "action": { "type": "text", "payload": "{\"button\": \"2\"}", "label": "5" }, "color": "secondary" }, { "action": { "type": "text", "payload": "{\"button\": \"2\"}", "label": "6" }, "color": "secondary" }, { "action": { "type": "text", "payload": "{\"button\": \"2\"}", "label": "7" }, "color": "secondary" }, { "action": { "type": "text", "payload": "{\"button\": \"2\"}", "label": "8" }, "color": "secondary" } ], [{ "action": { "type": "text", "payload": "{\"button\": \"2\"}", "label": "9" }, "color": "secondary" }, { "action": { "type": "text", "payload": "{\"button\": \"2\"}", "label": "10" }, "color": "secondary" }, { "action": { "type": "text", "payload": "{\"button\": \"2\"}", "label": "11" }, "color": "secondary" }, { "action": { "type": "text", "payload": "{\"button\": \"2\"}", "label": "12" }, "color": "secondary" } ] ] }';
50
51
52// Проверяем, что находится в поле "type"
53 switch ($data->type)
54 {
55 // Запрос для подтверждения адреса сервера (посылает ВК)
56 case 'confirmation':
57 echo $confirmationToken; // отправляем строку для подтверждения адреса
58 break;
59 // Если это уведомление о новом сообщении...
60 case 'message_new':
61 // получаем id автора сообщения
62 $userId = $data->object->message->from_id;
63 // Че то делаем
64 $user = $dbh->query('SELECT * FROM `vk_users` WHERE `id` ='.$userId)->fetch(\PDO::FETCH_ASSOC);
65 // Баланс
66 $balance = 0;
67 // получаем текст сообщения
68 $text = $data->object->message->text;
69 // через users.get получаем данные об авторе
70 $userInfo = json_decode(file_get_contents("https://api.vk.com/method/users.get?user_ids={$userId}&access_token={$token}&v=5.103"));
71 //$bug = file_get_contents("https://api.vk.com/method/users.get?user_ids={$userId}&access_token={$token}&v=5.103");
72 //file_put_contents($fp, $bug . "\n", FILE_APPEND);
73 // Вытаскиваем имя отправителя
74 $user_name = $userInfo->response[0]->first_name;
75 // Проверка пользователя в базе
76 if(!$user)
77 {
78 try {
79 $dbh->query("INSERT INTO `vk_users`(`id`, `firstname`) VALUES ({$userId},'{$user_name}')")->fetch(\PDO::FETCH_ASSOC);
80 $balance = 0;
81 }catch (\Exception $ex){
82 file_put_contents($fp, 'Ошибка БД - ' . $ex, FILE_APPEND);
83 }
84 } else
85 {
86 $balance = $user['balance'];
87 }
88
89 $rd = rand(0, 10);
90
91 // Через messages.send используя токен сообщества отправляем ответ
92 $request_params = array(
93 'peer_id' => $userId,
94 'random_id' => rand(1, 2147483647),
95 'message' => 'Я не понял твоей команды',
96 'attachment' => '',
97 'access_token' => $token,
98 'keyboard' => '{"one_time": false,"buttons": [[{"action": {"type": "text","payload": "{\"button\": \"1\"}","label": "Обои"},"color": "negative"},{"action": {"type": "text","payload": "{\"button\": \"2\"}","label": "Рингтоны"},"color": "positive"},{"action": {"type": "text","payload": "{\"button\": \"2\"}","label": "Оценить"},"color": "primary"}]]}',
99 'v' => '5.103'
100 );
101
102
103 if($text == "Начать игру")
104 {
105 $request_params['message'] = "Чтобы начать игру отправьте сумму ставки";
106 $request_params['keyboard'] = $keyboardS;
107 try {
108 $dbh->query('UPDATE `vk_users` SET `susid`= 1 WHERE `id`=' . $userId);
109 } catch (\Exception $ex) {
110 file_put_contents($fp, 'Ошибка БД при выборе пользователем сервиса другого чела - ' . $ex, FILE_APPEND);
111 }
112 }
113
114 $suma = 0;
115 $vg = 0;
116 if($text == "100" || $text == "200" || $text == "300" || $text == "400")
117 {
118 /*try {
119 $dbh->query("INSERT INTO `vk_users`(`suma`) VALUES ({$text})");
120 $user['suma'] = $suma;
121 } catch (\Exception $ex){
122 file_put_contents($fp, $suma);
123 } */
124 $request_params['message'] = "Ставка принята. Выберите координату, где не заминировано:";
125 $request_params['keyboard'] = $kbd1;
126 file_put_contents($fp, "До" . $text);
127 intval($text);
128 file_put_contents($fp, "После" . $text);
129 $suma = $text;
130 file_put_contents($fp, "Привет" . $suma);
131 $vg = $suma * 2;
132 file_put_contents($fp, "Привет" . $vg);
133 }
134 if($text == "1" || $text == "2" || $text == "3" || $text == "4" || $text == "5" || $text == "6" || $text == "7" || $text == "8" || $text == "9" || $text == "10")
135 {
136 if($rd > 5)
137 {
138 $vg = $suma * 2;
139 $request_params['message'] = "✅ Успех! Мины тут нет. \n ?+ " . $vg . "\n ? На счету: " . $vg;
140 //$request_params['keyboard'] = $kbd;
141 } elseif ($rd < 4)
142 {
143 //$vg = $suma * 2;
144 $request_params['message'] = "? Ой! Ты подорвался на мине. \n ? На счету: " . $vg;
145 //$request_params['keyboard'] = $kbd;
146 }
147 }
148
149
150 if($text == "Назад")
151 {
152 $request_params['message'] = "Возвращаемся в главное меню";
153 }
154 if($text == "Оценить")
155 {
156 $request_params['message'] = "Если не сложно, оцените нашего бота?? \n https://vk.cc/aqYphz";
157 }
158 if($text == "Баланс")
159 {
160 $request_params['message'] = "Ваш баланс: " . $balance;
161 }
162
163 // Обои
164 if($text == "Обои")
165 {
166 $request_params['message'] = "Как вам этот вариант?";
167 $request_params['attachment'] = $img[$rd];
168 $request_params['keyboard'] = $keyboardO;
169 }
170 if($text == "Следующие")
171 {
172 $request_params['message'] = "Может быть, подойдут эти?";
173 $request_params['attachment'] = $img[$rd];
174 $request_params['keyboard'] = $keyboardO;
175 }
176
177 // Парни
178 if($text == "Для парней?")
179 {
180 $request_params['message'] = "Как вам этот вариант, сэр?";
181 $request_params['attachment'] = $img_b[$rdb];
182 $request_params['keyboard'] = $keyboardB;
183 }
184 if($text == "Следующие?")
185 {
186 $request_params['message'] = "Может быть, подойдут эти?";
187 $request_params['attachment'] = $img_b[$rdb];
188 $request_params['keyboard'] = $keyboardB;
189 }
190
191 // Девушки
192 if($text == "Для девушек?")
193 {
194 $request_params['message'] = "Как вам этот вариант, мадам?";
195 $request_params['attachment'] = $img_g[$rdg];
196 $request_params['keyboard'] = $keyboardG;
197 }
198 if($text == "Следующие?")
199 {
200 $request_params['message'] = "Может быть, подойдут эти?";
201 $request_params['attachment'] = $img_g[$rdg];
202 $request_params['keyboard'] = $keyboardG;
203 }
204
205 // Рингтоны
206 if($text == "Рингтоны")
207 {
208 $request_params['message'] = "Как вам такой?";
209 $request_params['attachment'] = $img[$rd];
210 $request_params['keyboard'] = $keyboardR;
211 }
212 if($text == "Следующий")
213 {
214 $request_params['message'] = "Может быть, подойдёт этот?";
215 $request_params['attachment'] = $img[$rd];
216 $request_params['keyboard'] = $keyboardR;
217 }
218
219
220
221 $get_params = http_build_query($request_params);
222 file_get_contents('https://api.vk.com/method/messages.send?'. $get_params);
223 echo('ok'); // Возвращаем "ok" серверу Callback API
224 break;
225 }
226
227 ?>