· 5 years ago · Jun 02, 2020, 08:44 PM
1const {VK} = require('vk-io');
2const {Keyboard} = require('vk-io');
3const vk = new VK();
4const {updates, api, snippets} = vk;
5const fs = require('fs');
6const { upload } = vk;
7const base = require('./base.json');
8var chats = ['https://vk.me/join/AJQ1d2lN4BdL1EaqSelltO0p']
9
10function getRandomInRange(min, max) {
11 return Math.floor(Math.random() * (max - min + 1)) + min;
12}; //Функция выбора рандомного числа
13
14const VKCOINAPI = require('node-vkcoinapi');
15const vkcoin = new VKCOINAPI({
16 token: "7bf839092e0942645dfd9a8d0d9c5f8fdfd0d477b285eac96ab52ff78d63632b1559f987fe7d89a661af5",
17 key: "5z9U;ql[sDgoJIu#4VYqUPbKsBo=68aH-PcTK5ThAXv7SifKlX",
18 userId: 387863062
19});
20
21const link = vkcoin.api.getLink(1000000, false);
22
23function nols(num) {
24 if(num < 10) return('0' + num)
25 if(num > 9) return(num)
26}
27
28function getRandomInRange(min, max) {
29 return Math.floor(Math.random() * (max - min + 1)) + min;
30}; //Функция выбора рандомного числа
31
32vkcoin.updates.onTransfer((event) => {
33 if(!base.players[event.fromId]) return
34 if(event.amount < 1000) return
35 let amount = Math.floor(event.amount / 1000)
36 base.players[event.fromId].money += Number(amount)
37 vk.api.messages.send({
38 message: `На баланс поступило ${utils.sp(amount)} коинов.`,
39 user_id: event.fromId
40 })
41})
42
43const utils = {
44 sp: (int) => {
45 int = int.toString();
46 return int.split('').reverse().join('').match(/[0-9]{1,3}/g).join('.').split('').reverse().join('');
47 }
48}
49
50vk.setOptions({
51 token: "0931b8b7a98160f619d93e817f2ddfccbaf75e61a745a61f9b5151a59dbcce73454f3495fee1a5cda21ee",
52 apiMode: "parallel",
53 pollingGroupId: 596881619
54});
55
56updates.use(async (context, next) => {
57 if(context.isGroup) return;
58 if(context.senderId == undefined) return;
59 if(/\[цифр ид группы|(.*)\]/i.test(context.text)) context.text = context.text.replace(/\[цифр ид группы|(.*)\]/ig, '').trim();
60 if(!base.players[context.senderId]) {
61 let user = await vk.api.users.get({
62 user_id: context.senderId
63 })
64 base.players[context.senderId] = {
65 money: 0,
66 ban: 0,
67 rank: 0,
68 vvod: 0,
69 nick: `*id${context.senderId} (${user[0].first_name})`
70 };
71 context.send(base.players[context.senderId].nick + ", регистрация прошла успешно.")
72 };
73 if(base.players[context.senderId].vvod == 1 && context.isChat){
74 let money = context.text;
75 while(money.includes("к")){
76 money = money.replace("к", "000");
77 };
78 while(money.includes(".")){
79 money = money.replace(".", "");
80 };
81 while(money.includes(",")){
82 money = money.replace(",", "");
83 };
84 while(money.includes(" ")){
85 money = money.replace(" ", "");
86 };
87 if(!Number(money)){
88 base.players[context.senderId].vvod = 0;
89 return next();
90 };
91 if(money < 100) {
92 base.players[context.senderId].vvod = 0;
93 return context.send(`${base.players[context.senderId].nick}, разрешается ставить только от 100 коинов.`);
94 }
95 if(Number(money) > Number(base.players[context.senderId].money)) {
96 base.players[context.senderId].vvod = 0;
97 return context.send(`${base.players[context.senderId].nick}, не хватает ${utils.sp(Math.round(money-base.players[context.senderId].money))} коинов.`)
98 };
99 var proc = Math.round(money / 100 * 3);
100 base.players[context.senderId].money -= Number(money);
101 money -= Number(proc);
102 if(!base.chat[context.chatId].players[context.senderId]){
103 base.chat[context.chatId].players[context.senderId] = {
104 money: Number(money)
105 };
106 } else {
107 base.chat[context.chatId].players[context.senderId].money += Number(money);
108 };
109 base.players[context.senderId].vvod = 0;
110
111 return context.send(`${base.players[context.senderId].nick}, сделка успешно совершенна. (-${utils.sp(proc)} коинов со ставки, комиссия: 3%)`);
112 };
113 await next();
114});
115
116updates.hear(/^?$/i, async (context) => {
117 base.players[context.senderId].vvod = 1;
118 return context.send(`${base.players[context.senderId].nick}, введите сумму ставки. (Пример: 1к || 1к = 1.000) ?`);
119});
120
121updates.hear(/^банк$/i, async (context) => {
122 if(!context.isChat) return context.send(`Это можно использовать только в беседе!`)
123 let text = ``
124 let mass = [];
125 for(let i in base.chat[context.chatId].players){
126 mass.push({
127 id: i,
128 money: Number(base.chat[context.chatId].players[i].money)
129 });
130 //text += `${base.players[i].nick} || ${utils.sp(base.chats[context.chatId].players[i].money)} коинов.`
131 }
132 mass.sort(function(a, b) {
133 if (b.money > a.money) return 1
134 if (b.money < a.money) return -1
135 return 0
136 });
137 if(mass.length == 0) {
138 text += `\nВ этом раунде не было ставок.`
139 } else {
140 for(let i = 0; i < mass.length; i++){
141 text += `${base.players[mass[i].id].nick} || ${utils.sp(base.chat[context.chatId].players[mass[i].id].money)} коинов.`;
142 };
143 };
144 return context.send(`${base.players[context.senderId].nick}, банк раунда:${text}\nВремя до результатов ${nols(Math.trunc(base.chat[context.chatId].time / 60 % 60))}:${nols(Math.trunc(base.chat[context.chatId].time % 60))}`);
145});
146
147updates.hear(/^пополнить|пополнение$/i, async (context) => {
148 if(!context.isChat) return context.send(`Это можно использовать только в беседе!`);
149 return context.send(`${base.players[context.senderId].nick}, ссылка на пополнение: ${link}`);
150});
151
152updates.hear(/^вывести|вывод$/i, async (context) => {
153 if(!context.isChat) return context.send(`Это можно использовать только в беседе!`)
154 if(base.players[context.senderId].money < 1) return context.send(`${base.players[context.senderId].nick}, недостаточно средств для вывода`)
155 let amount = Number(base.players[context.senderId].money)
156 const result = await vkcoin.api.sendPayment(context.senderId, Number(base.players[context.senderId].money)*1000, true)
157 base.players[context.senderId].money = 0
158 return context.send(`${base.players[context.senderId].nick}, был произведён вывод на сумму ${utils.sp(amount)} коинов`)
159})
160
161setInterval(function(){
162 fs.writeFileSync("./base.json", JSON.stringify(base, null, "\t"));
163}, 2000); // обновление базы данных
164
165setInterval(function() {
166 for(let i in base.chat){
167 base.chat[i].time -= Number(1);
168 if(base.chat[i].time < 1) {
169 base.chat[i].time = 89;
170 let mass = [];
171 let sum = 0;
172 for(let j in base.chat[i].players){
173 mass.push({
174 id: j,
175 money: Number(base.chat[i].players[j].money)
176 });
177 sum += Number(base.chat[i].players[j].money);
178 delete base.chat[i].players[j];
179 };
180 if(mass.length == 0) return;
181 mass.sort(function(a, b) {
182 if (b.money > a.money) return 1
183 if (b.money < a.money) return -1
184 return 0
185 });
186
187 let rand = Math.floor(Math.random() * sum);
188
189 let ww = 0;
190 for (let s = mass[0].money; s <= rand; s += mass[ww].money) {
191 ww++;
192 }
193 base.players[mass[ww].id].money += Number(sum);
194 vk.api.messages.send({
195 chat_id: i,
196 message: `|| Итоги раунда:\n${base.players[mass[ww].id].nick} (+${sum} коинов)`
197 });
198 };
199 };
200}, 1000);
201
202updates.hear(/^баланс$/i, async (context) => {
203 if(!context.isChat) return context.send(`Это можно использовать только в беседе!`);
204 return context.send(`${base.players[context.senderId].nick}, баланс: ${utils.sp(base.players[context.senderId].money)} коинов.`)
205})
206
207updates.hear(/^как играть\?$/i, async (context) => {
208 return context.send(`Статья: ссылка на статью`)
209})
210
211updates.hear(/^найти беседу$/i, async (context) => {
212 let random = getRandomInRange(1, chats.length);
213 return context.send(`Беседа: ${chats[random-1]}`)
214})
215
216updates.hear(/^клава$/i, (context) => {
217 if(!context.isChat) return;
218 return context.send({
219 message: "открываю",
220 keyboard: Keyboard.keyboard([
221 [
222 Keyboard.textButton({
223 label: "Банк",
224 color: Keyboard.PRIMARY_COLOR
225 })
226 ],
227 [
228 Keyboard.textButton({
229 label: "Пополнить",
230 color: Keyboard.PRIMARY_COLOR
231 }),
232 Keyboard.textButton({
233 label: "?",
234 color: Keyboard.POSITIVE_COLOR
235 }),
236 Keyboard.textButton({
237 label: "Вывод",
238 color: Keyboard.PRIMARY_COLOR
239 })
240 ],
241 [
242 Keyboard.textButton({
243 label: "Баланс",
244 color: Keyboard.POSITIVE_COLOR
245 })
246 ]
247 ])
248 })
249})
250
251vk.updates.setHearFallbackHandler(async (context) => {
252 if(context.isChat) return;
253 return context.send({
254 message: `Играть можно только в беседе! (ЛКМ: найти беседу)`,
255 keyboard: Keyboard.keyboard([
256 [
257 Keyboard.textButton({
258 label: `Как играть?`,
259 color: Keyboard.POSITIVE_COLOR
260 })
261 ],
262 [
263 Keyboard.textButton({
264 label: "Найти беседу",
265 color: Keyboard.PRIMARY_COLOR
266 })
267 ]
268 ])
269 })
270})
271
272async function run() {
273 await vk.updates.startPolling();
274 await vkcoin.updates.startPolling();
275 const result = await vkcoin.api.setShopName('Web of bots');
276 console.log('bot run')
277}
278
279run().catch(console.error);
280
281/*run().catch(console.error);
282
283let a = [{id: 1, int: 300}, {id: 333, int: 1000}, {id: 672, int: 5000}];
284
285let sum = 0;
286for (let i = 0; i < a.length; i++) {
287 sum += a[i].int;
288}
289
290let rand = Math.floor(Math.random() * sum);
291
292let i = 0;
293for (let s = a[0].int; s <= rand; s += a[i].int) {
294 i++;
295}
296
297console.log(a[i].id);*/