-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathjadge.js
321 lines (285 loc) · 8.78 KB
/
jadge.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
const config = require('./config.json');
const request = require('request');
var CronJob = require('cron').CronJob;
const Twit = require('twit');
const Discord = require("discord.js");
const client = new Discord.Client();
var gameCount = 0;
const isDebug = false; //true: ツイートOFF,1分間隔で更新,同じ試合でもカウント
const isTweeting = false;
const isDiscording = true;
var isChecking = false;
var T = new Twit({
consumer_key:config.consumer_key,
consumer_secret:config.consumer_secret,
access_token:config.access_token,
access_token_secret:config.access_token_secret,
timeout_ms:60*1000, // optional HTTP request timeout to apply to all requests.
})
const gachiPowConst = 50;
var iksmSession;
function httpRequest(options) {
return new Promise(function (resolve, reject) {
request(options, function (error, res, body) {
if (!error && (res.statusCode == 200)) {
body['res'] = res;
resolve(res);
} else if(res.statusCode == 204){
resolve();
} else {
console.log('not 200 code : ',res.statusCode);
reject(error);
}
});
});
}
function postDiscord(mes){
httpRequest({
url: config.discord_webhook,
method: 'POST',
headers: {"Accept": "application/json"},
json:{"content":mes}
});
}
async function getIksmSession(){
var client_id = config.client_id;
var resource_id = config.resource_id;
var init_session_token = config.init_session_token;
var apiTokenRes = await httpRequest({
url: 'https://accounts.nintendo.com/connect/1.0.0/api/token',
method: 'POST',
headers: {'Accept': 'application/json'},
json:{
'client_id': client_id,
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer-session-token',
'session_token': init_session_token
}
});
var apiToken = apiTokenRes['body'];
var someTokensRes = await httpRequest({
url: 'https://api-lp1.znc.srv.nintendo.net/v1/Account/GetToken',
method: 'POST',
headers: {'Accept': 'application/json',
'Authorization': 'Bearer ' + apiToken['access_token']},
json:{"parameter": {
"language": "null",
"naBirthday": "null",
"naCountry": "null",
"naIdToken": apiToken["id_token"]}
}
});
var tokens = someTokensRes['body']['result'];
var authRes = await httpRequest({
url: "https://api-lp1.znc.srv.nintendo.net/v1/Game/GetWebServiceToken",
method: 'POST',
headers: {"Accept": "application/json",
"Authorization": "Bearer "+tokens["webApiServerCredential"]["accessToken"]},
json:{"parameter": {"id": resource_id}}
});
if(authRes['body'].status != 0){
return new Promise(function (resolve, reject) {
reject('Nintendo Account Auth Error!!');
});
}
var accessToken = authRes['body']["result"]["accessToken"]
var session = await httpRequest({
url: "https://app.splatoon2.nintendo.net/?lang=ja-JP",
method: 'GET',
headers: {"Accept": "application/json",
"X-gamewebtoken": accessToken}
});
var session_id = session.caseless.dict['set-cookie'][0].split(';')[0];
return new Promise(function (resolve, reject) {
resolve(session_id);
});
}
function Players(){
//プレイヤーデータ(モデル)
this.players = {};
function _ObjArraySort(ary, key, order) {
var reverse = 1;
if(order && order.toLowerCase() == "desc")
reverse = -1;
ary.sort(function(a, b) {
if(a[key] < b[key])
return -1 * reverse;
else if(a[key] == b[key])
return 0;
else
return 1 * reverse;
});
return ary
}
return {
isEmpty:()=>{
if(Object.keys(this.players).length === 0){
return true
}
return false
},
getGachiPow:(battleDataTeam)=>{
var sumPow = 0;
for(var i=0;i<battleDataTeam.length;i++){
if(this.players[battleDataTeam[i].nickname]){
sumPow += this.players[battleDataTeam[i].nickname].point;
}else{
sumPow += 2000;
}
}
return sumPow
},
addGachiPow:(team,point)=>{
for(var i = 0;i<team.length;i++){
var name = team[i].nickname;
if(!this.players[name]){
console.log("created ",team[i].nickname," profile.");
this.players[name] = {name:name,point:2000,win:0,lose:0};
}
this.players[name]["point"] += point;
if(point>0)
this.players[name].win++;
if(point<0)
this.players[name].lose++;
}
},
makeTweet:()=>{
var tweet = "";
var tmpAry = [];
for(key in this.players){
tmpAry.push(this.players[key]);
}
//console.log(tmpAry);
var ary = _ObjArraySort(tmpAry,"point","desc");
//console.log("ButtleResult:(",gameCount,"試合目)");
for(var i = 0; i < ary.length;i++){
tweet = tweet+ary[i].name+"("+ary[i].point+")\n";
}
return tweet
},
clearData:()=>{
this.players = {};
},
showData:()=>{
console.log(this.players);
}
}
}
async function getPlayersResult(gameId){
if(!iksmSession)
return 0;
var res = await httpRequest({
url: "https://app.splatoon2.nintendo.net/api/results/"+gameId,
method: 'GET',
headers: {"Accept": "application/json",
"Cookie": iksmSession,
"referer": "https://app.splatoon2.nintendo.net/results/"+gameId}
});
var resData = JSON.parse(res.body);
//console.log(resData);
if(resData.my_team_result.name == 'WIN!'){
var winner = resData.my_team_members;
if(resData.player_result)
winner.push(resData.player_result);
var loser = resData.other_team_members;
}else{
var winner = resData.other_team_members;
var loser = resData.my_team_members;
if(resData.player_result)
loser.push(resData.player_result);
}
//console.log(winner);
var winPlayer = [winner[0].player,winner[1].player,winner[2].player,winner[3].player];
var losePlayer = [loser[0].player,loser[1].player,loser[2].player,loser[3].player];
return new Promise(function (resolve, reject) {
resolve({winPlayer:winPlayer,losePlayer:losePlayer});
});
}
var latestGameId = 0;
var players = new Players();
async function main(){
if(!iksmSession)
iksmSession = await getIksmSession();
var res = await httpRequest({
url: "https://app.splatoon2.nintendo.net/api/results",
method: 'GET',
headers: {"Accept": "*/*",
"Cookie": iksmSession}
});
if(latestGameId != JSON.parse(res.body).results[0].battle_number || isDebug){
gameCount++;
latestGameId = JSON.parse(res.body).results[0].battle_number;
var battleResult = await getPlayersResult(latestGameId);
//ウデマエアルゴリズム
//TODO: addGachiPowを個別にする(今後のため)
var winPowAvg = players.getGachiPow(battleResult.winPlayer);
var losePowAvg = players.getGachiPow(battleResult.losePlayer);
players.showData();
var diffPowAvg = winPowAvg-losePowAvg;
console.log("diffPowAvg ",diffPowAvg);
if(diffPowAvg < gachiPowConst*-1){
//弱いチームが逆転
players.addGachiPow(battleResult.winPlayer,20);
players.addGachiPow(battleResult.losePlayer,-20);
}else if(diffPowAvg < gachiPowConst){
//特に差分なし
players.addGachiPow(battleResult.winPlayer,10);
players.addGachiPow(battleResult.losePlayer,-10);
}else{
//弱いチームがさらに負け
players.addGachiPow(battleResult.winPlayer,5);
players.addGachiPow(battleResult.losePlayer,-5);
}
var tweet = players.makeTweet();
//console.log(tweet);
if(!isDebug&&isTweeting){
T.post('statuses/update', { status: tweet }, function(err, data, response) {
console.log("tweeted");
if(err){
console.log(err);
}
});
}
if(isDiscording){
postDiscord("【"+gameCount+"試合目】\n"+tweet);
}
}
}
client.login(config.discord_token);
client.on('message', msg => {
if (msg.content === '<@349624831001624576> start' && isChecking == false) {
isChecking = true;
var today = new Date();
postDiscord("監視開始\n"+today);
main();
}else if (msg.content === '<@349624831001624576> stop' && isChecking == true) {
isChecking = false;
players.clearData();
latestGameId = 0;
gameCount=0;
postDiscord("終わり〜\nみんなおつかれさま");
}else if(msg.content === '<@349624831001624576> status'){
var statMes = "";
if(isChecking){
statMes = "起動中";
}else{
statMes = "停止中";
}
postDiscord("今は"+statMes+"だよ!");
}
});
if(!isDebug){
new CronJob('*/30 * * * * *', function() {
if(isChecking){
main();
}
}, null, true, 'Asia/Tokyo');
}
if(isDebug){
new CronJob('00 */1 * * * *', function() {
console.log('tick');
players.clearData();
if(isChecking){
main();
}
}, null, true, 'Asia/Tokyo');
}