· 7 years ago · Dec 24, 2017, 04:08 PM
1import SteamTotp from 'steam-totp';
2import SteamCommunity from 'steamcommunity';
3import TradeOfferManager from 'steam-tradeoffer-manager';
4import models from '../models/index';
5import config from '../config';
6import bluebird from 'bluebird';
7
8bluebird.promisifyAll(SteamCommunity.prototype);
9
10/**
11 * Создает ÑкземплÑÑ€ Tradebot.
12 *
13 * @constructor
14 * @this {Tradebot}
15 */
16class Tradebot {
17 constructor() {
18 this.trader = [];
19 this.startBots();
20 }
21
22 async reloadInventory() {
23
24 models.inventory.destroy({
25 where: {
26 id: {
27 [models.Op.ne]: 0
28 }
29 }
30 });
31
32 models.items.update({
33 counts: 0
34 }, {
35 where: {
36 id: {
37 [models.Op.ne]: 0
38 }
39 }
40 });
41
42 for (let id in this.trader) {
43 try{
44
45 let items = await this.trader[id].community.getUserInventoryContentsAsync(this.trader[id].user.steamid, 730, 2, true);
46
47 let inventory = [];
48 let check = {};
49 for (let key in items) {
50 let out = await serv.getAsync('out:' + items[key].assetid);
51 if (out === null) {
52 let matches = items[key].market_hash_name.toString().match(/\(([^\(\)]+)\)$/);
53 let stattrak = (items[key].market_hash_name.toString().indexOf('StatTrakâ„¢') !== -1) ? 1 : 0;
54 inventory.push({
55 assetid: items[key].assetid,
56 bot: parseInt(id),
57 name: items[key].name.toString().replace('StatTrakâ„¢ ', ''),
58 quality: (matches[1] !== undefined ? matches[1] : ''),
59 stattrak: stattrak
60 });
61 if (check[items[key].name.toString().replace('StatTrakâ„¢ ', '')] === undefined) check[items[key].name.toString().replace('StatTrakâ„¢ ', '')] = 0;
62 check[items[key].name.toString().replace('StatTrakâ„¢ ', '')] += 1;
63 }
64 }
65
66 let data = await models.inventory.bulkCreate(inventory);
67
68 for (let key in check) {
69 await models.items.update({
70 counts: check[key]
71 }, {
72 where: {
73 name_en: {
74 [models.Op.like]: '%' + key + '%'
75 }
76 }
77 });
78 }
79 console.info(`Бот ${this.trader[id].user.accountName}`, `Обновили инв! ${this.trader[id].id}, предметов : ${items.length}`);
80
81} catch(e){
82
83console.log(e);
84
85}
86
87 }
88
89 models.casegame.findAll().then(data => {
90 data.map(async _case => {
91 try {
92 if (JSON.parse(_case.items).length > 0) {
93 let counts = await models.items.sum('counts', {
94 where: {
95 id: JSON.parse(_case.items)
96 }
97 });
98 _case.update({
99 counts
100 })
101 }
102 } catch (e) {
103 // console.log(e);
104 }
105 })
106 });
107
108 };
109
110 reloadBotSessions() {
111 for (let id in this.trader) {
112 this.trader[id].webLogOn(this.trader[id]);
113 }
114 }
115
116 start(bot, cookies, type = false) {
117 bot.manager.setCookies(cookies, (err) => {
118 if (err) {
119 console.log(`Бот ${bot.user.accountName}`, 'webSession-error', err);
120 return;
121 }
122 this.reloadInventory();
123 console.info(`Бот ${bot.user.accountName}`, `Got API key: ${bot.manager.apiKey}`, `ÐвторизовалÑÑ ${type ? 'токен' : 'пароль'} Код ${SteamTotp.getAuthCode(bot.user.twoFactorCode)}`);
124 bot.community.setCookies(cookies);
125 });
126 }
127
128 async startBots() {
129
130 let bots = await models.bots.findAll();
131
132 bots.map(bot => {
133
134 let community = new SteamCommunity();
135
136 this.trader[bot.id] = {
137 community: community,
138 manager: new TradeOfferManager({
139 community: community,
140 domain: config.site,
141 language: 'ru'
142 }),
143 login: {
144 accountName: bot.accountName,
145 password: bot.password,
146 twoFactorCode: SteamTotp.getAuthCode(bot.twoFactorCode),
147 },
148 user: bot,
149 id: bot.id,
150 };
151
152 this.trader[bot.id]['webLogOn'] = (bot) => bot.user.steamguard !== null ? bot.community.oAuthLogin(bot.user.steamguard, bot.user.oAuthToken, (err, sessionID, cookies) => {
153 if (err) {
154 console.log(`Бот ${bot.user.accountName}`, 'community-login-error', err);
155 return;
156 }
157 this.start(bot, cookies, true);
158 }) : bot.community.login(bot.login, (err, sessionID, cookies, steamguard, oAuthToken) => {
159 if (err) {
160 console.log(`Бот ${bot.user.accountName}`, 'community-login-error', err);
161 return;
162 }
163 bot.user.update({ steamguard, oAuthToken });
164 this.start(bot, cookies);
165 });
166
167 this.trader[bot.id].webLogOn(this.trader[bot.id]);
168
169 });
170
171 this.addBotListeners();
172
173 setInterval(() => {
174 this.reloadInventory();
175 }, 5200000);
176 setInterval(() => {
177 this.reloadBotSessions();
178 }, 3600000);
179
180 }
181
182 addBotListeners() {
183 this.listen('manager', 'newOffer', (offer, bot) => {
184 if (config.admin.indexOf(offer.partner.getSteamID64()) !== -1) {
185
186 if (offer.itemsToGive.length == 0) {
187 setTimeout(() => {
188 offer.accept();
189 }, 30000);
190 return;
191 } else {
192 setTimeout(() => {
193 offer.accept(() => {
194 bot.community.acceptConfirmationForObject(bot.user.identitySecret, offer.id, (err) => {
195 if (err) {
196 console.log(err);
197 }
198 });
199 });
200 }, 30000);
201 return;
202 }
203 }
204 setTimeout(() => {
205 offer.decline();
206 }, 30000);
207 });
208
209 this.listen('community', 'sessionExpired', (_, bot) => {
210 bot.webLogOn(bot);
211 });
212
213 }
214
215 listen(obj, listen, fn) {
216 for (let id in this.trader) {
217 this.trader[id][obj].on(listen, (call) => {
218 fn(call, this.trader[id]);
219 });
220 }
221 }
222
223 async SendOffers(botId, trade, user, item, gameid) {
224
225 let game = await models.games.findById(parseInt(gameid));
226
227 let bot = this.trader[botId];
228
229 let offer;
230
231 try {
232 offer = bot.manager.createOffer(trade);
233 } catch (err) {
234 game.update({
235 status: 4,
236 }).then(data => {
237 serv.publish('inf', '{"status":"error", "msg": "Произошла ошибка. ОбратитеÑÑŒ в поддержку.", "user": "' + user + '"}');
238 console.log(bot.user.accountName, err);
239 });
240 return;
241 }
242
243 offer.addMyItem({
244 appid: 730,
245 contextid: 2,
246 amount: 1,
247 assetid: item
248 });
249
250 offer.setMessage(`Ваш дроп Ñ playdrop.ru`);
251
252 offer.send(async (err, status) => {
253 if (err) {
254 if (err === 'Error: Not Logged In') {
255 bot.webLogOn(bot);
256 }
257 let status = 0;
258 if (parseInt(game.errcnt) > 1) status = 4;
259 game.update({
260 status: status,
261 errcnt: game.errcnt + 1
262 }).then(data => {
263 serv.publish('inf', '{"status":"error", "msg": "' + err + '", "user": "' + user + '"}');
264 console.log(bot.user.accountName, err.message + ' UserID:' + user);
265 });
266 } else {
267 console.log(`Бот ${bot.user.accountName}`, status);
268 console.log(`Бот ${bot.user.accountName}`, bot.user.id, 'Трейд отправлен! #' + offer.id);
269 bot.community.acceptConfirmationForObject(bot.user.identitySecret, offer.id, async (err) => {
270 if (err) {
271 game.update({
272 status: 4
273 }).then(data => {
274 serv.publish('inf', '{"status":"error", "msg": "Произошла ошибка при подтверждении трейда. ОбратитеÑÑŒ в поддержку.", "user": "' + user + '"}');
275 console.log(bot.user.accountName, err.message + ' UserID:' + user);
276 });
277 return;
278 }
279
280 await game.update({
281 status: 3
282 });
283
284 serv.publish('inf', '{"status":"success", "msg": "Трейд отправлен! #' + offer.id + ' <br><a class=link target=_blank href=//steamcommunity.com/tradeoffer/' + offer.id + '>ПринÑть трейд</a></div></div>", "user": "' + user + '"}');
285
286 });
287 }
288 });
289 }
290
291}
292
293export default new Tradebot;