├── .npmrc ├── Procfile ├── .dockerignore ├── .gitignore ├── combine.js ├── data ├── basicCards.js ├── myCards.js ├── basicCardsFiltered └── bronzeTopUsers.js ├── cards.js ├── .env-example ├── package.json ├── src └── Battle │ ├── database.js │ ├── sql commands │ └── Battle.js ├── leaderboardUsers.js ├── Dockerfile ├── getCards.js ├── quests.js ├── helper.js ├── battlesGet.js ├── cluster.js ├── splinterlandsPage.js ├── main.js ├── user.js ├── battlesGetData.js ├── crawlBattlesData.js ├── battles.js ├── README.md ├── possibleTeams.js ├── index.js └── LICENSE /.npmrc: -------------------------------------------------------------------------------- 1 | engine-strict=true -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | worker: npm start -p $PORT -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | package-lock.json -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | .env 3 | package-lock.json -------------------------------------------------------------------------------- /combine.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | 3 | const history1 = require("./data/history.json"); 4 | const history2 = require("./data/newHistory.json"); 5 | 6 | const newHistory = history1.concat(history2) 7 | 8 | fs.writeFile(`./data/newHistory.json`, JSON.stringify(newHistory), function (err) { 9 | if (err) { 10 | console.log(err); 11 | } 12 | }); 13 | -------------------------------------------------------------------------------- /data/basicCards.js: -------------------------------------------------------------------------------- 1 | module.exports = [157,158,159,160,395,396,397,398,399,161,162,163,167,400,401,402,403,440,168,169,170,171,381,382,383,384,385,172,173,174,178,386,387,388,389,437,179,180,181,182,334,367,368,369,370,371,183,184,185,189,372,373,374,375,439,146,147,148,149,409,410,411,412,413,150,151,152,156,414,415,416,417,135,135,136,137,138,353,354,355,356,357,139,140,141,145,358,359,360,361,438,224,190,191,192,157,423,424,425,426,194,195,196,427,428,429,441,''] -------------------------------------------------------------------------------- /cards.js: -------------------------------------------------------------------------------- 1 | const cardsDetails = require("./data/cardsDetails.json"); //saved json from api endpoint https://game-api.splinterlands.com/cards/get_details? 2 | 3 | const makeCardId = (id) => id; 4 | 5 | const color = (id) => { 6 | const card = cardsDetails.find(o => parseInt(o.id) === parseInt(id)); 7 | const color = card && card.color ? card.color : ''; 8 | return color; 9 | } 10 | 11 | exports.makeCardId = makeCardId; 12 | exports.color = color; -------------------------------------------------------------------------------- /.env-example: -------------------------------------------------------------------------------- 1 | ###remove the initial #to uncomment a line 2 | #CHROME_EXEC=/usr/bin/google-chrome-stable 3 | QUEST_PRIORITY=true 4 | MINUTES_BATTLES_INTERVAL=30 5 | CLAIM_SEASON_REWARD=false 6 | CLAIM_DAILY_QUEST_REWARD=true 7 | #ECR_STOP_LIMIT=50 8 | #ECR_RECOVER_TO=99 9 | #SKIP_QUEST=life,snipe,neutral 10 | #FAVOURITE_DECK=dragon #choose only one splinter among: fire, life, earth, water, death, dragon 11 | #MULTI_ACCOUNT=false 12 | FORCE_LOCAL_HISTORY=true 13 | ACCOUNT=lowercase_username 14 | PASSWORD=postingkey 15 | #DELEGATED_CARDS_PRIORITY=true -------------------------------------------------------------------------------- /data/myCards.js: -------------------------------------------------------------------------------- 1 | module.exports = [157,158,159,160,161,162,163,167,168,169,170,171,172,173,174,178,179,180,181,182,183,184,185,189,146,147,148,149,150,151,152,156,135,136,137,138,139,140,141,145,224,190,191,192,193,194,195,196,'',24, 2 | 34, 3 | 35, 4 | 83, 5 | 85, 6 | 86, 7 | 87, 8 | 90, 9 | 91, 10 | 94, 11 | 97, 12 | 103, 13 | 104, 14 | 106, 15 | 114, 16 | 131, 17 | 133, 18 | 134, 19 | 208, 20 | 216, 21 | 218, 22 | 225, 23 | 226, 24 | 226, 25 | 227, 26 | 227, 27 | 229, 28 | 232, 29 | 233 ] -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "splinterlands-bot", 3 | "version": "1.14.1", 4 | "description": "", 5 | "main": "main.js", 6 | "engines": { 7 | "node": ">=14.18.0" 8 | }, 9 | "scripts": { 10 | "test": "echo \"Error: no test specified\" && exit 1", 11 | "start": "node main.js" 12 | }, 13 | "author": "", 14 | "license": "ISC", 15 | "dependencies": { 16 | "chalk": "^4.1.2", 17 | "dimas-kmeans": "^1.0.3", 18 | "dotenv": "^8.2.0", 19 | "hierarchical-clustering": "^1.1.0", 20 | "minimist": ">=1.2.3", 21 | "moment": "^2.29.1", 22 | "node-fetch": "^2.6.7", 23 | "pg": "^8.0.3", 24 | "puppeteer": "^10.1.0" 25 | }, 26 | "overrides": { 27 | "puppeteer": { 28 | "node-fetch": "^2.6.7" 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Battle/database.js: -------------------------------------------------------------------------------- 1 | const { Client } = require('pg') 2 | const client = new Client({ 3 | user: 'postgres', 4 | host: 'localhost', 5 | database: 'splinterlands', 6 | password: 'docker', 7 | port: 5432, 8 | }); 9 | 10 | client.connect() 11 | 12 | const getBattles = () => client.query('select * from battles', (err, res) => { 13 | console.log(err ? err.stack : res.rows) 14 | client.end() 15 | 16 | return res; 17 | }) 18 | console.log(getBattles()); 19 | 20 | // const writeBattle = client.query( 21 | // "INSERT INTO battles (firstname, lastname, age, address, email)VALUES('Mary Ann', 'Wilters', 20, '74 S Westgate St', 'mroyster@royster.com')",' 22 | 23 | // , (err, res) => { 24 | // console.log(err ? err.stack : res.rowCount) // Hello World! 25 | // client.end() 26 | // }) -------------------------------------------------------------------------------- /leaderboardUsers.js: -------------------------------------------------------------------------------- 1 | const fetch = require("node-fetch"); 2 | 3 | async function getList() { 4 | const res = await fetch('https://api2.splinterlands.com/players/leaderboard_with_player?season=69&leaderboard=0') 5 | .then((response) => { 6 | if (!response.ok) { 7 | throw new Error('Network response was not ok'); 8 | } 9 | return response; 10 | }) 11 | .then((leaderboard) => { 12 | return leaderboard.json(); 13 | }) 14 | .catch((error) => { 15 | console.error('There has been a problem with your fetch operation:', error); 16 | }); 17 | 18 | return res.leaderboard.map(elem=>elem.player) 19 | } 20 | 21 | //printUsersFromLeaderboard().then(x=> console.log(x)) 22 | module.exports.getList = getList; 23 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:16.13.0-bullseye 2 | 3 | 4 | # Install wget, vim, and Google Chrome 5 | ARG CHROME_VERSION=96.0.4664.45-1 6 | ARG CHROME_URL="http://dl.google.com/linux/chrome/deb/pool/main/g/google-chrome-stable/google-chrome-stable_${CHROME_VERSION}_amd64.deb" 7 | RUN apt-get update && apt-get install -y wget vim nano --no-install-recommends \ 8 | && wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add \ 9 | && sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \ 10 | && apt-get update && apt-get install -y google-chrome-stable --no-install-recommends \ 11 | && rm -rf /var/lib/apt/lists/* \ 12 | && apt-get -y purge google-chrome-stable \ 13 | && wget -O /tmp/google-chrome-stable.deb $CHROME_URL \ 14 | && dpkg -i /tmp/google-chrome-stable.deb \ 15 | && rm -f /tmp/google-chrome-stable.deb 16 | 17 | WORKDIR /app 18 | 19 | COPY . /app 20 | 21 | RUN npm install -------------------------------------------------------------------------------- /data/basicCardsFiltered: -------------------------------------------------------------------------------- 1 | card_detail_id="157" 2 | card_detail_id="158" 3 | card_detail_id="159" 4 | card_detail_id="160" 5 | card_detail_id="161" 6 | card_detail_id="162" 7 | card_detail_id="163" 8 | card_detail_id="167" 9 | card_detail_id="168" 10 | card_detail_id="169" 11 | card_detail_id="170" 12 | card_detail_id="171" 13 | card_detail_id="172" 14 | card_detail_id="173" 15 | card_detail_id="174" 16 | card_detail_id="178" 17 | card_detail_id="179" 18 | card_detail_id="180" 19 | card_detail_id="181" 20 | card_detail_id="182" 21 | card_detail_id="183" 22 | card_detail_id="184" 23 | card_detail_id="185" 24 | card_detail_id="189" 25 | card_detail_id="146" 26 | card_detail_id="147" 27 | card_detail_id="148" 28 | card_detail_id="149" 29 | card_detail_id="150" 30 | card_detail_id="151" 31 | card_detail_id="152" 32 | card_detail_id="156" 33 | card_detail_id="135" 34 | card_detail_id="136" 35 | card_detail_id="137" 36 | card_detail_id="138" 37 | card_detail_id="139" 38 | card_detail_id="140" 39 | card_detail_id="141" 40 | card_detail_id="145" 41 | card_detail_id="224" 42 | card_detail_id="190" 43 | card_detail_id="191" 44 | card_detail_id="192" 45 | card_detail_id="193" 46 | card_detail_id="194" 47 | card_detail_id="195" 48 | card_detail_id="196" -------------------------------------------------------------------------------- /src/Battle/sql commands: -------------------------------------------------------------------------------- 1 | CREATE TABLE IF NOT EXISTS battles ( 2 | battle_queue_id text PRIMARY KEY, 3 | inactive text, 4 | ruleset text, 5 | mana_cap text, 6 | match_type text, 7 | created_date text, 8 | player_rating_initial text, 9 | player_rating_final text, 10 | winner text, 11 | summoner_id text, 12 | summoner_level text, 13 | monster_1_id text, 14 | monster_1_level text, 15 | monster_1_abilities text, 16 | monster_2_id text, 17 | monster_2_level text, 18 | monster_2_abilities text, 19 | monster_3_id text, 20 | monster_3_level text, 21 | monster_3_abilities text, 22 | monster_4_id text, 23 | monster_4_level text, 24 | monster_4_abilities text, 25 | monster_5_id text, 26 | monster_5_level text, 27 | monster_5_abilities text, 28 | monster_6_id text, 29 | monster_6_level text, 30 | monster_6_abilities text 31 | ); 32 | 33 | CREATE TABLE IF NOT EXISTS users ( 34 | player text PRIMARY KEY, 35 | rating text, 36 | battles text, 37 | wins text, 38 | longest_streak text, 39 | max_rating text, 40 | rank text, 41 | reward_claim_tx text, 42 | guild_id text, 43 | guild_name text, 44 | guild_data text, 45 | avatar_id text, 46 | display_name text 47 | ); -------------------------------------------------------------------------------- /getCards.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const fetch = require("node-fetch"); 3 | 4 | async function getCards() { 5 | return await fetch("https://api2.splinterlands.com/cards/get_details?v=1582322601277", {"credentials":"omit","headers":{"accept":"application/json, text/javascript, */*; q=0.01","accept-language":"en-GB,en-US;q=0.9,en;q=0.8"},"referrer":"https://splinterlands.com/?p=collection&a=a1492dc","referrerPolicy":"no-referrer-when-downgrade","body":null,"method":"GET","mode":"cors"}) 6 | .then((response) => { 7 | if (!response.ok) { 8 | throw new Error('Network response was not ok'); 9 | } 10 | return response; 11 | }) 12 | .then((cards) => { 13 | return cards.json(); 14 | }) 15 | .catch((error) => { 16 | console.error('There has been a problem with your fetch operation:', error); 17 | }); 18 | } 19 | 20 | const cardByIds = (ids = []) => { 21 | return getCards() 22 | .then(inventory => inventory.filter(card => ids.includes(card.id)) 23 | ).then(x=> x.map((y) => ({ 24 | 'id': y.id, 25 | 'name': y.name, 26 | 'color': y.color}) 27 | )).then(x=> console.log(x)); 28 | } 29 | 30 | //example get card id [1,145,167] 31 | //cards([1,145,167]); 32 | 33 | exports.cardByIds = cardByIds; -------------------------------------------------------------------------------- /data/bronzeTopUsers.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | 'archime', 3 | 'exegus', 4 | 'dteles', 5 | 'maxim4444', 6 | 'wherelambo', 7 | 'anti-spiral', 8 | 'shin92', 9 | 'ryukin', 10 | 'lechatsplinter', 11 | 'roguex', 12 | 'wewew', 13 | 'nonkew', 14 | 'optimalprime', 15 | 'aubryd', 16 | 'gabbli', 17 | 'salsal69', 18 | 'paytowin', 19 | 'hotchili', 20 | 'ryzenpro', 21 | 'eco-worrier', 22 | 'tomazas35', 23 | 'vasilas', 24 | 'juggernaut27', 25 | 'herox', 26 | 'ferooz', 27 | 'riverwind', 28 | 'rambo54321', 29 | 'bkwrestler', 30 | 'bruno09', 31 | 'bajadera', 32 | 'yeshuathehighest', 33 | 'maynard69', 34 | 'kane15', 35 | 'forcer577', 36 | 'gioruspa', 37 | 'weinerdrizzle', 38 | 'bugoy', 39 | 'itine05', 40 | 'a1b2z', 41 | 'ronin-skill', 42 | 'primelodi', 43 | 'lerkfrend', 44 | 'muonicspace', 45 | 'anaxyrus', 46 | 'kurchan', 47 | 'cnburning', 48 | 'dahiasl', 49 | 'dimp', 50 | 'itine07', 51 | 'ilg4', 52 | 'codyg91', 53 | 'vicente009', 54 | 'wasara', 55 | 'kingjulian007', 56 | 'landofgames', 57 | 'unf41', 58 | 'perazart', 59 | 'fiiii', 60 | 'the-most-high', 61 | 'azaleah18', 62 | 'nutoly', 63 | 'lriddlerl', 64 | 'jsangeles1', 65 | 'bigtittedman', 66 | 'unknown251', 67 | 'robbydk', 68 | 'deadlyburner', 69 | 'joedang04', 70 | 'p1ncher', 71 | 'ocojoco', 72 | 'dcouncilor', 73 | 'choiny', 74 | 'babykristel05', 75 | 'bessemer', 76 | 'dice127', 77 | 'splinterlord124', 78 | 'johnnylovve', 79 | 'pythes', 80 | 'alexfly5', 81 | 'srpopa', 82 | 'bikoloy', 83 | 'nerdbeast', 84 | 'fiduh', 85 | 'eggsytv', 86 | 'dn0myar', 87 | 'k04k1n', 88 | 'dreadlord', 89 | 'vadan', 90 | 'hybra', 91 | 'notafriend', 92 | 'shock3r', 93 | 'str-001', 94 | 'londonbridge', 95 | 'capu11', 96 | 'dash07', 97 | 'izumi1910', 98 | 'merl1n', 99 | 'alvin26', 100 | 'bomskii', 101 | 'pulpnft' 102 | ] -------------------------------------------------------------------------------- /quests.js: -------------------------------------------------------------------------------- 1 | const fetch = require("node-fetch"); 2 | 3 | const quests = [ 4 | {name: "defend", element: "life"}, 5 | {name: "pirate", element: "water"}, 6 | {name: "High Priority Targets", element: "snipe"}, 7 | {name: "lyanna", element: "earth"}, 8 | {name: "stir", element: "fire"}, 9 | {name: "rising", element: "death"}, 10 | {name: "Stubborn Mercenaries", element: "neutral"}, 11 | {name: "gloridax", element: "dragon"}, 12 | {name: "Stealth Mission", element: "sneak"}, 13 | ] 14 | 15 | const getQuestSplinter = (questName) => { 16 | const playerQuest = quests.find(quest=> quest.name === questName) 17 | return playerQuest.element; 18 | } 19 | 20 | const getPlayerQuest = (username) => (fetch(`https://api2.splinterlands.com/players/quests?username=${username}`, 21 | { "credentials": "omit", "headers": { "accept": "application/json, text/javascript, */*; q=0.01" }, "referrer": `https://splinterlands.com/?p=collection&a=${username}`, "referrerPolicy": "no-referrer-when-downgrade", "body": null, "method": "GET", "mode": "cors" }) 22 | .then(x => x && x.json()) 23 | .then(x => { 24 | if (x[0]) { 25 | const questDetails = {name: x[0].name, splinter: getQuestSplinter(x[0].name), total: x[0].total_items, completed: x[0].completed_items} 26 | return questDetails; 27 | }}) 28 | .catch(() => { 29 | console.log('Error: game-api.splinterlands did not respond trying api.slinterlands... '); 30 | fetch(`https://api.splinterlands.io/players/quests?username=${username}`, 31 | { "credentials": "omit", "headers": { "accept": "application/json, text/javascript, */*; q=0.01" }, "referrer": `https://splinterlands.com/?p=collection&a=${username}`, "referrerPolicy": "no-referrer-when-downgrade", "body": null, "method": "GET", "mode": "cors" }) 32 | .then(x => x && x.json()) 33 | .then(x => { 34 | if (x[0]) { 35 | const questDetails = {name: x[0].name, splinter: getQuestSplinter(x[0].name), total: x[0].total_items, completed: x[0].completed_items} 36 | return questDetails; 37 | }}) 38 | .catch(e => console.log('[ERROR QUEST] Check if Splinterlands is down. Are you using username or email? please use username')) 39 | }) 40 | ) 41 | 42 | module.exports.getPlayerQuest = getPlayerQuest; 43 | -------------------------------------------------------------------------------- /helper.js: -------------------------------------------------------------------------------- 1 | 2 | const cardsDetails = require("./data/cardsDetails.json"); 3 | const card = require("./cards") 4 | 5 | // const teamIdsArray = [167, 192, 160, 161, 163, 196, '', 'fire']; 6 | 7 | //cardColor = (id) => cardsDetails.find(o => o.id === id) ? cardsDetails.find(o => o.id === id).color : ''; 8 | 9 | const validDecks = ['Red', 'Blue', 'White', 'Black', 'Green'] 10 | const colorToDeck = { 'Red': 'Fire', 'Blue': 'Water', 'White': 'Life', 'Black': 'Death', 'Green': 'Earth' } 11 | 12 | // const tes = teamIdsArray.forEach(id => { 13 | // console.log('DEBUG', id, cardColor(id)) 14 | // if (validDecks.includes(cardColor(id))) { 15 | // return colorToDeck[cardColor(id)]; 16 | // } 17 | // }) 18 | 19 | const deckValidColor = (accumulator, currentValue) => validDecks.includes(card.color(currentValue)) ? colorToDeck[card.color(currentValue)] : accumulator; 20 | 21 | const reload = async (page) => { console.log('reloading page...') ; await page.reload(); } 22 | 23 | const sleep = (ms) => { 24 | return new Promise((resolve) => { 25 | setTimeout(resolve, ms); 26 | }); 27 | } 28 | 29 | const teamActualSplinterToPlay = (teamIdsArray) => teamIdsArray.reduce(deckValidColor, '') 30 | 31 | const clickOnElement = async (page, selector, timeout=20000, delayBeforeClicking = 0) => { 32 | try { 33 | const elem = await page.waitForSelector(selector, {timeout: timeout }); 34 | if(elem) { 35 | await sleep(delayBeforeClicking); 36 | console.log('Clicking element', selector); 37 | await elem.click(); 38 | return true; 39 | } 40 | } catch (e) { 41 | } 42 | console.log('No element', selector, 'to be closed'); 43 | return false; 44 | } 45 | 46 | const getElementText = async (page, selector, timeout=15000) => { 47 | const element = await page.waitForSelector(selector, {timeout: timeout }); 48 | const text = await element.evaluate(el => el.textContent); 49 | return text; 50 | } 51 | 52 | const getElementTextByXpath = async (page, selector, timeout=20000) => { 53 | try { 54 | const element = await page.waitForXPath(selector, { timeout: timeout }); 55 | const text = await element.evaluate(el => el.textContent); 56 | return text; 57 | } catch (e) { 58 | console.log('Get text by xpath error.', e); 59 | return false 60 | } 61 | } 62 | 63 | module.exports.teamActualSplinterToPlay = teamActualSplinterToPlay; 64 | module.exports.clickOnElement = clickOnElement; 65 | module.exports.getElementText = getElementText; 66 | module.exports.getElementTextByXpath = getElementTextByXpath; 67 | module.exports.sleep = sleep; 68 | module.exports.reload = reload; -------------------------------------------------------------------------------- /battlesGet.js: -------------------------------------------------------------------------------- 1 | const fetch = require("node-fetch"); 2 | const fs = require('fs'); 3 | 4 | 5 | const distinct = (value, index, self) => { 6 | return self.indexOf(value) === index; 7 | } 8 | 9 | async function getBattleHistory(player = '', data = {}) { 10 | const battleHistory = await fetch('https://api.steemmonsters.io/battle/history?player=' + player) 11 | .then((response) => { 12 | if (!response.ok) { 13 | throw new Error('Network response was not ok'); 14 | } 15 | return response; 16 | }) 17 | .then((battleHistory) => { 18 | return battleHistory.json(); 19 | }) 20 | .catch((error) => { 21 | console.error('There has been a problem with your fetch operation:', error); 22 | }); 23 | return battleHistory.battles; 24 | } 25 | 26 | users = []; 27 | player = 'berindon' 28 | const battles = getBattleHistory(player) 29 | .then(battles => battles.map( 30 | x => { 31 | const details = JSON.parse(x.details); 32 | return { 33 | battle_queue_id_1: x.battle_queue_id_1, 34 | battle_queue_id_2: x.battle_queue_id_2, 35 | player_1_rating_initial: x.player_1_rating_initial, 36 | player_2_rating_initial: x.player_2_rating_initial, 37 | winner: x.winner, 38 | player_1_rating_final: x.player_1_rating_final, 39 | player_2_rating_final: x.player_2_rating_final, 40 | player_1: x.player_1, 41 | player_2: x.player_2, 42 | created_date: x.created_date, 43 | match_type: x.match_type, 44 | mana_cap: x.mana_cap, 45 | current_streak: x.current_streak, 46 | ruleset: x.ruleset, 47 | inactive: x.inactive, 48 | settings: x.settings, 49 | block_num: x.block_num, 50 | rshares: x.rshares, 51 | dec_info: x.dec_info, 52 | details_team1: details.team1, 53 | details_team2: details.team2, 54 | details_prebattle: details.prebattle 55 | } 56 | }) 57 | ).then( 58 | x => { 59 | fs.writeFile(`data/${player}_Raw.json`, JSON.stringify(x), function (err) { 60 | if (err) { 61 | console.log(err); 62 | } 63 | }); 64 | x.map(element => { 65 | users.push(element.player_2); 66 | users.push(element.player_1); 67 | } 68 | ); 69 | console.log(users.filter(distinct)) 70 | } 71 | ) -------------------------------------------------------------------------------- /cluster.js: -------------------------------------------------------------------------------- 1 | // var cluster = require('hierarchical-clustering'); 2 | var colors = [ [ 167, 162, 159, 157, 158, 160, 190, 'fire' ], 3 | [ 145, 190, 194, 139, 138, 195, 196, 'death' ], 4 | [ 189, 184, 179, 183, 180, 192, 182, 'earth' ], 5 | [ 178, 170, 191, 196, 194, 193, 168, 'water' ], 6 | [ 189, 184, 180, 183, 185, 195, 192, 'earth' ], 7 | [ 167, 194, 192, 196, 158, 161, 195, 'fire' ], 8 | [ 145, 196, 192, 141, 139, 195, 194, 'death' ], 9 | [ 145, 190, 194, 139, 138, 195, 196, 'death' ], 10 | [ 145, 190, 195, 193, 141, 194, 135, 'death' ], 11 | [ 189, 184, 193, 195, 185, 194, 180, 'earth' ], 12 | [ 167, 162, 158, 161, 163, 159, 157, 'fire' ], 13 | [ 167, 162, 191, 158, 192, 161, 157, 'fire' ], 14 | [ 167, 162, 157, 158, 159, 161, 163, 'fire' ], 15 | [ 189, 184, 192, 179, 185, 183, 181, 'earth' ], 16 | [ 156, 147, 193, 150, 194, 196, 149, 'life' ], 17 | [ 145, 140, 136, 135, 190, 139, 194, 'death' ], 18 | [ 156, 190, 146, 149, 150, 193, 194, 'life' ], 19 | [ 145, 190, 138, 141, 194, 135, 140, 'death' ], 20 | [ 167, 162, 192, 161, 160, 196, 157, 'fire' ], 21 | [ 189, 184, 182, 179, 185, 181, 183, 'earth' ], 22 | [ 167, 162, 196, 194, 158, 161, 159, 'fire' ], 23 | [ 167, 162, 160, 158, 192, 161, 196, 'fire' ], 24 | [ 145, 196, 192, 141, 195, 194, 139, 'death' ], 25 | [ 189, 184, 180, 192, 183, 194, 195, 'earth' ], 26 | [ 189, 190, 194, 183, 192, 185, 196, 'earth' ], 27 | [ 167, 162, 158, 196, 161, 193, 194, 'fire' ], 28 | [ 167, 162, 192, 160, 158, 194, 195, 'fire' ], 29 | [ 167, 162, 194, 195, 161, 160, 157, 'fire' ], 30 | [ 145, 140, 135, 141, 194, 192, 139, 'death' ], 31 | [ 167, 162, 193, 192, 158, 194, 157, 'fire' ], 32 | [ 189, 190, 185, 192, 179, 194, 180, 'earth' ], 33 | [ 189, 180, 196, 192, 195, 185, 194, 'earth' ], 34 | [ 145, 137, 191, 194, 141, 139, 196, 'death' ], 35 | [ 167, 162, 191, 158, 161, 195, 157, 'fire' ] ] 36 | 37 | const data = colors.map(x => x.slice(0,7)) 38 | console.log(data) 39 | 40 | // // Euclidean distance 41 | // function distance(a, b) { 42 | // var d = 0; 43 | // for (var i = 0; i < a.length; i++) { 44 | // d += Math.pow(a[i] - b[i], 2); 45 | // } 46 | // return Math.sqrt(d); 47 | // } 48 | 49 | // // Single-linkage clustering 50 | // function linkage(distances) { 51 | // return Math.min.apply(null, distances); 52 | // } 53 | 54 | // var levels = cluster({ 55 | // input: colors, 56 | // distance: distance, 57 | // linkage: linkage, 58 | // minClusters: 2, // only want two clusters 59 | // }); 60 | 61 | // var clusters = levels[levels.length - 1].clusters; 62 | // console.log(clusters); 63 | // // => [ [ 2 ], [ 3, 1, 0 ] ] 64 | // clusters = clusters.map(function (cluster) { 65 | // return cluster.map(function (index) { 66 | // return colors[index]; 67 | // }); 68 | // }); 69 | // console.log(clusters); 70 | // // => [ [ [ 250, 255, 253 ] ], 71 | // // => [ [ 100, 54, 255 ], [ 22, 22, 90 ], [ 20, 20, 80 ] ] ] 72 | 73 | var kmeans = require('dimas-kmeans') 74 | 75 | var clusterskmeans = kmeans.getClusters(data); 76 | console.log(clusterskmeans) 77 | console.log(clusterskmeans.map(x=> x.data.length)) 78 | console.log(clusterskmeans[0].data) 79 | console.log(clusterskmeans[1].data) -------------------------------------------------------------------------------- /splinterlandsPage.js: -------------------------------------------------------------------------------- 1 | async function login(page, account, password) { 2 | try { 3 | page.waitForSelector('#log_in_button > button').then(() => page.click('#log_in_button > button')) 4 | await page.waitForSelector('#email') 5 | .then(() => page.waitForTimeout(3000)) 6 | .then(() => page.focus('#email')) 7 | .then(() => page.type('#email', account)) 8 | .then(() => page.focus('#password')) 9 | .then(() => page.type('#password', password)) 10 | 11 | // .then(() => page.waitForSelector('#login_dialog_v2 > div > div > div.modal-body > div > div > form > div > div.col-sm-offset-1 > button', { visible: true }).then(() => page.click('#login_dialog_v2 > div > div > div.modal-body > div > div > form > div > div.col-sm-offset-1 > button'))) 12 | .then(() => page.click("#loginBtn")) 13 | .then(() => page.waitForTimeout(5000)) 14 | .then(() => page.reload()) 15 | .then(() => page.waitForTimeout(5000)) 16 | .then(() => page.reload()) 17 | .then(() => page.waitForTimeout(3000)) 18 | .then(async () => { 19 | await page.waitForSelector('#log_in_text', { 20 | visible: true, timeout: 3000 21 | }) 22 | .then(()=>{ 23 | console.log('logged in!') 24 | }) 25 | .catch(()=>{ 26 | console.log('didnt login'); 27 | throw new Error('Didnt login'); 28 | }) 29 | }) 30 | .then(() => page.waitForTimeout(2000)) 31 | .then(() => page.reload()) 32 | } catch (e) { 33 | throw new Error('Check that you used correctly username and posting key. (dont use email and password)'); 34 | } 35 | } 36 | 37 | async function checkMana(page) { 38 | var manas = await page.evaluate(() => { 39 | var manaCap = document.querySelectorAll('div.mana-total > span.mana-cap')[0].innerText; 40 | var manaUsed = document.querySelectorAll('div.mana-total > span.mana-used')[0].innerText; 41 | var manaLeft = manaCap - manaUsed 42 | return { manaCap, manaUsed, manaLeft }; 43 | }); 44 | console.log('manaLimit', manas); 45 | return manas; 46 | } 47 | 48 | async function checkMatchMana(page) { 49 | const mana = await page.$$eval("div.mana-cap__icon", el => el.map(x => x.getAttribute("data-original-title"))); 50 | const manaValue = parseInt(mana[mana.length -1].split(':')[1], 10); 51 | return manaValue; 52 | } 53 | 54 | async function checkMatchRules(page) { 55 | const rules = await page.$$eval("div.combat__rules > div > div > img", el => el.map(x => x.getAttribute("data-original-title"))); 56 | return rules.map(x => x.split(':')[0]).join('|') 57 | } 58 | 59 | async function checkMatchActiveSplinters(page) { 60 | const splinterUrls = await page.$$eval("div.active_element_list > img", el => el.map(x => x.getAttribute("src"))); 61 | return splinterUrls.map(splinter => splinterIsActive(splinter)).filter(x => x); 62 | } 63 | 64 | //UNUSED ? 65 | const splinterIsActive = (splinterUrl) => { 66 | const splinter = splinterUrl.split('/').slice(-1)[0].replace('.svg', '').replace('icon_splinter_', ''); 67 | return splinter.indexOf('inactive') === -1 ? splinter : ''; 68 | } 69 | 70 | exports.login = login; 71 | exports.checkMana = checkMana; 72 | exports.checkMatchMana = checkMatchMana; 73 | exports.checkMatchRules = checkMatchRules; 74 | exports.checkMatchActiveSplinters = checkMatchActiveSplinters; 75 | exports.splinterIsActive = splinterIsActive; -------------------------------------------------------------------------------- /main.js: -------------------------------------------------------------------------------- 1 | require('dotenv').config(); 2 | const { run, setupAccount } = require('./index'); 3 | const { sleep } = require('./helper'); 4 | const chalk = require('chalk'); 5 | 6 | const isMultiAccountMode = (process.env.MULTI_ACCOUNT?.toLowerCase() === 'true') ? true : false; 7 | 8 | 9 | async function startMulti() { 10 | const sleepingTimeInMinutes = process.env.MINUTES_BATTLES_INTERVAL || 30; 11 | const sleepingTime = sleepingTimeInMinutes * 60000; 12 | let missingValue = false; 13 | let accounts = process.env.ACCOUNT.split(','); 14 | let passwords = process.env.PASSWORD.split(','); 15 | let count = 1; 16 | 17 | // trim account and password 18 | accounts = accounts.map(e => e.trim()); 19 | passwords = passwords.map(e => e.trim()); 20 | // split @ to prevent email use 21 | accounts = accounts.map(e => e.split('@')[0]); 22 | // accounts count 23 | console.log(chalk.bold.redBright(`Accounts count: ${accounts.length}, passwords count: ${passwords.length}`)) 24 | if (accounts.length !== passwords.length) { 25 | throw new Error('The number of accounts and passwords do not match. Too many commas?') 26 | } 27 | 28 | if (accounts.length < 2) { 29 | throw new Error('MULTI_ACCOUNT set to true, but less than two accounts detected.') 30 | } 31 | 32 | console.log(chalk.bold.white('List of accounts to run:')) 33 | for (let i = 0; i < accounts.length; i++) { 34 | let msg = 'This account'; 35 | console.log(chalk.bold.whiteBright(`${i+1}. ${accounts[i]}`)); 36 | 37 | if (accounts[i].length === 0 && passwords[i].length === 0) { 38 | missingValue = true; 39 | msg += ' is missing account and password value.'; 40 | } else if (accounts[i].length === 0) { 41 | missingValue = true; 42 | msg += ' is missing account value.'; 43 | } else if (passwords[i].length === 0) { 44 | missingValue = true; 45 | msg += ' is missing password value.'; 46 | } else { 47 | msg += ' has all the required value.' 48 | } 49 | console.log(msg); 50 | } 51 | 52 | if (missingValue) throw new Error('Fix your ACCOUNT and/or PASSWORD value in .env file.') 53 | 54 | while(true) { 55 | console.log(chalk.bold.whiteBright.bgGreen(`Running bot iter-[${count}]`)) 56 | for (let i = 0; i < accounts.length; i++) { 57 | setupAccount(accounts[i], passwords[i], isMultiAccountMode); 58 | try { 59 | await run(); 60 | } catch (e) { 61 | console.log('Error on main:', e) 62 | } 63 | 64 | console.log(`Finished running ${accounts[i]} account...\n`); 65 | } 66 | console.log('waiting for the next battle in', sleepingTime / 1000 / 60 , 'minutes at', new Date(Date.now() + sleepingTime).toLocaleString(), '\n'); 67 | await sleep(sleepingTime); 68 | count++; 69 | } 70 | } 71 | 72 | async function startSingle() { 73 | let account = process.env.ACCOUNT.split('@')[0]; // split @ to prevent email use 74 | let password = process.env.PASSWORD; 75 | 76 | if (account.includes(',')) { 77 | console.error('There is a comma in your account name. Are you trying to run multiple account?') 78 | console.error('If yes, then you need to set MULTI_ACCOUNT=true in the .env file.') 79 | throw new Error('Invalid account value.') 80 | } 81 | 82 | setupAccount(account, password, isMultiAccountMode); 83 | await run(); 84 | } 85 | 86 | (async()=> { 87 | console.log(`isMultiAccountMode: ${isMultiAccountMode}`) 88 | if (isMultiAccountMode) { 89 | console.log('Running mode: multi') 90 | await startMulti(); 91 | } else { 92 | console.log('Running mode: single') 93 | await startSingle(); 94 | } 95 | })() -------------------------------------------------------------------------------- /user.js: -------------------------------------------------------------------------------- 1 | const fetch = require("node-fetch"); 2 | const basicCards = require('./data/basicCards');//phantom cards available for the players but not visible in the api endpoint 3 | const moment = require("moment"); 4 | 5 | const isPlayable = (username, card) => { 6 | if ((card.delegated_to === username || card.delegated_to === null || card.delegated_to === '') && //card delegated to player or owned 7 | (card.market_listing_status === null || card.market_listing_status === '' || (card.market_listing_status != null && card.delegated_to === username)) && // not listed to market 8 | (card.unlock_date === null || card.unlock_date === '') && // not locked 9 | ((card.last_used_player === username || card.last_used_player === null) || (card.last_used_player !== username && moment.duration(moment().diff(card.last_used_date)).days() > 1)) && // rented not locked 10 | card.edition != 6 // not a gladiator (not playable in ranked battle) 11 | ) { 12 | return true 13 | } 14 | else { 15 | return false 16 | } 17 | } 18 | 19 | const isRented = (username, card) => { 20 | if ((card.delegated_to === username && card.player !== username) && //card is delegated to player 21 | (card.unlock_date === null || card.unlock_date === '') && 22 | ((card.last_used_player === username || card.last_used_player === null) || (card.last_used_player !== username && moment.duration(moment().diff(card.last_used_date)).days() > 1))) // not locked 23 | { 24 | return true 25 | } 26 | else { 27 | return false 28 | } 29 | } 30 | 31 | getPlayerCards = (username) => (fetch(`https://api2.splinterlands.com/cards/collection/${username}`, 32 | { "credentials": "omit", "headers": { "accept": "application/json, text/javascript, */*; q=0.01" }, "referrer": `https://splinterlands.com/?p=collection&a=${username}`, "referrerPolicy": "no-referrer-when-downgrade", "body": null, "method": "GET", "mode": "cors" }) 33 | .then(x => x && x.json()) 34 | .then(x => x['cards'] ? x['cards'].filter(x=>isPlayable(username,x)).map(card => card.card_detail_id) : '') 35 | .then(advanced => basicCards.concat(advanced)) 36 | .catch(e=> { 37 | console.log('Error: game-api.splinterlands did not respond trying api.slinterlands... '); 38 | fetch(`https://api.splinterlands.io/cards/collection/${username}`, 39 | { "credentials": "omit", "headers": { "accept": "application/json, text/javascript, */*; q=0.01" }, "referrer": `https://splinterlands.com/?p=collection&a=${username}`, "referrerPolicy": "no-referrer-when-downgrade", "body": null, "method": "GET", "mode": "cors" }) 40 | .then(x => x && x.json()) 41 | .then(x => x['cards'] ? x['cards'].filter(x=>isPlayable(username,x)).map(card => card.card_detail_id) : '') 42 | .then(advanced => basicCards.concat(advanced)) 43 | .catch(e => { 44 | console.log('Using only basic cards due to error when getting user collection from splinterlands: ',e); 45 | return basicCards 46 | }) 47 | }) 48 | ) 49 | 50 | getRentedCards = (username) => (fetch(`https://api2.splinterlands.com/cards/collection/${username}`, 51 | { "credentials": "omit", "headers": { "accept": "application/json, text/javascript, */*; q=0.01" }, "referrer": `https://splinterlands.com/?p=collection&a=${username}`, "referrerPolicy": "no-referrer-when-downgrade", "body": null, "method": "GET", "mode": "cors" }) 52 | .then(x => x && x.json()) 53 | .then(x => x['cards'] ? x['cards'].filter(x=>isRented(username, x)).map(card => card.card_detail_id) : '') 54 | .catch(e=> { 55 | console.log('Error: game-api.splinterlands did not respond trying api.slinterlands... '); 56 | fetch(`https://api.splinterlands.io/cards/collection/${username}`, 57 | { "credentials": "omit", "headers": { "accept": "application/json, text/javascript, */*; q=0.01" }, "referrer": `https://splinterlands.com/?p=collection&a=${username}`, "referrerPolicy": "no-referrer-when-downgrade", "body": null, "method": "GET", "mode": "cors" }) 58 | .then(x => x && x.json()) 59 | .then(x => x['cards'] ? x['cards'].filter(x=>isRented(username, x)).map(card => card.card_detail_id) : '') 60 | .then(advanced => basicCards.concat(advanced)) 61 | .catch(e => { 62 | console.log('Using only basic cards due to error when getting user collection from splinterlands: ',e); 63 | return basicCards 64 | }) 65 | }) 66 | ) 67 | 68 | module.exports.getPlayerCards = getPlayerCards; 69 | module.exports.getRentedCards = getRentedCards; -------------------------------------------------------------------------------- /battlesGetData.js: -------------------------------------------------------------------------------- 1 | const fetch = require("node-fetch"); 2 | const fs = require('fs'); 3 | const leaderboardUsers = require('./leaderboardUsers'); 4 | 5 | const distinct = (value, index, self) => { 6 | return self.indexOf(value) === index; 7 | } 8 | 9 | async function getBattleHistory(player = '', data = {}) { 10 | const battleHistory = await fetch('https://api2.splinterlands.com/battle/history?player=' + player) 11 | .then((response) => { 12 | if (!response.ok) { 13 | throw new Error('Network response was not ok'); 14 | } 15 | return response; 16 | }) 17 | .then((battleHistory) => { 18 | return battleHistory.json(); 19 | }) 20 | .catch((error) => { 21 | console.error('There has been a problem with your fetch operation:', error); 22 | }); 23 | return battleHistory.battles; 24 | } 25 | 26 | const extractGeneralInfo = (x) => { 27 | return { 28 | created_date: x.created_date ? x.created_date : '', 29 | match_type: x.match_type ? x.match_type : '', 30 | mana_cap: x.mana_cap ? x.mana_cap : '', 31 | ruleset: x.ruleset ? x.ruleset : '', 32 | inactive: x.inactive ? x.inactive : '' 33 | } 34 | } 35 | 36 | const extractMonster = (team) => { 37 | const monster1 = team.monsters[0]; 38 | const monster2 = team.monsters[1]; 39 | const monster3 = team.monsters[2]; 40 | const monster4 = team.monsters[3]; 41 | const monster5 = team.monsters[4]; 42 | const monster6 = team.monsters[5]; 43 | 44 | return { 45 | summoner_id: team.summoner.card_detail_id, 46 | summoner_level: team.summoner.level, 47 | monster_1_id: monster1 ? monster1.card_detail_id : '', 48 | monster_1_level: monster1 ? monster1.level : '', 49 | monster_1_abilities: monster1 ? monster1.abilities : '', 50 | monster_2_id: monster2 ? monster2.card_detail_id : '', 51 | monster_2_level: monster2 ? monster2.level : '', 52 | monster_2_abilities: monster2 ? monster2.abilities : '', 53 | monster_3_id: monster3 ? monster3.card_detail_id : '', 54 | monster_3_level: monster3 ? monster3.level : '', 55 | monster_3_abilities: monster3 ? monster3.abilities : '', 56 | monster_4_id: monster4 ? monster4.card_detail_id : '', 57 | monster_4_level: monster4 ? monster4.level : '', 58 | monster_4_abilities: monster4 ? monster4.abilities : '', 59 | monster_5_id: monster5 ? monster5.card_detail_id : '', 60 | monster_5_level: monster5 ? monster5.level : '', 61 | monster_5_abilities: monster5 ? monster5.abilities : '', 62 | monster_6_id: monster6 ? monster6.card_detail_id : '', 63 | monster_6_level: monster6 ? monster6.level : '', 64 | monster_6_abilities: monster6 ? monster6.abilities : '' 65 | } 66 | } 67 | 68 | let battlesList = []; 69 | let usersToGrab = [] 70 | 71 | const generateHistory = async () => { 72 | if(usersToGrab?.length === 0) { 73 | usersToGrab = await leaderboardUsers.getList() 74 | } 75 | const battles = usersToGrab.map(user => 76 | getBattleHistory(user) 77 | .then(battles => battles.map( 78 | battle => { 79 | const details = JSON.parse(battle.details); 80 | if (details.type != 'Surrender') { 81 | if (battle.winner && battle.winner == battle.player_1) { 82 | const monstersDetails = extractMonster(details.team1) 83 | const info = extractGeneralInfo(battle) 84 | return { 85 | ...monstersDetails, 86 | ...info, 87 | battle_queue_id: battle.battle_queue_id_1, 88 | player_rating_initial: battle.player_1_rating_initial, 89 | player_rating_final: battle.player_1_rating_final, 90 | winner: battle.player_1, 91 | 92 | } 93 | } else if (battle.winner && battle.winner == battle.player_2) { 94 | const monstersDetails = extractMonster(details.team2) 95 | const info = extractGeneralInfo(battle) 96 | return { 97 | ...monstersDetails, 98 | ...info, 99 | battle_queue_id: battle.battle_queue_id_2, 100 | player_rating_initial: battle.player_2_rating_initial, 101 | player_rating_final: battle.player_2_rating_final, 102 | winner: battle.player_2, 103 | } 104 | } 105 | } 106 | 107 | }) 108 | ).then(x => battlesList = [...battlesList, ...x]) 109 | ) 110 | 111 | Promise.all(battles).then(() => { 112 | const cleanBattleList = battlesList.filter(x => x != undefined) 113 | fs.writeFile(`data/history.json`, JSON.stringify(cleanBattleList), function (err) { 114 | if (err) { 115 | console.log(err); 116 | } 117 | }); 118 | }); 119 | } 120 | 121 | generateHistory(); -------------------------------------------------------------------------------- /crawlBattlesData.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const puppeteer = require('puppeteer'); 4 | 5 | async function login(page) { 6 | try { 7 | //await page.click('.navbar-toggle.collapsed'); //FIRST STEP NEEDED IF PAGE SIZE TOO SMALL 8 | //await page.waitFor(1000); 9 | 10 | page.waitForSelector('#log_in_button > button').then(() => page.click('#log_in_button > button')) 11 | await page.waitForSelector('#account') 12 | .then(() => page.waitForTimeout(1000)) 13 | .then(() => page.focus('#account')) 14 | .then(() => page.type('#account', process.env.ACCOUNT.split('@')[0], {delay: 100})) 15 | .then(() => page.focus('#key')) 16 | .then(() => page.type('#key', process.env.PASSWORD, {delay: 100})) 17 | .then(() => page.click('#btn_login')) 18 | .then(() => page.waitForTimeout(2000) 19 | .then(() => page.waitForSelector('.modal-close-new'))) 20 | .then(() => page.click('.modal-close-new')) 21 | } catch (e) { 22 | console.log(e); 23 | } 24 | } 25 | 26 | async function checkMana(page) { 27 | var manas = await page.evaluate(() => { 28 | var manaCap = document.querySelectorAll('div.mana-total > span.mana-cap')[0].innerText; 29 | var manaUsed = document.querySelectorAll('div.mana-total > span.mana-used')[0].innerText; 30 | var manaLeft = manaCap - manaUsed 31 | return {manaCap, manaUsed, manaLeft}; 32 | }); 33 | console.log('manaLimit',manas); 34 | return manas; 35 | } 36 | 37 | 38 | async function openSplinter() { 39 | const browser = await puppeteer.launch({headless: false}); 40 | const page = await browser.newPage(); 41 | await page.setViewport({ 42 | width: 1500, 43 | height: 800, 44 | deviceScaleFactor: 1, 45 | }); 46 | 47 | await page.goto('https://splinterlands.com/?p=battle_history'); 48 | await page.waitForTimeout(2000); 49 | await login(page) 50 | await page.waitForTimeout(2000); 51 | const [button] = await page.$x("//button[contains(., 'BATTLE LOG')]"); 52 | button ? await button.click() : null; 53 | 54 | var battlesList = await pdocument.querySelectorAll('.history-table > table > tbody > tr'); 55 | 56 | battlesList.forEach(x=>console.log(x.querySelector('td:nth-child(8) > img').getAttribute('data-original-title'))) 57 | // var battle = await page.evaluate(() => { 58 | // var battlesList = document.querySelectorAll('.history-table > table > tbody > tr'); 59 | // var battlesArray = []; 60 | // for (var i = 0; i < battlesList.length; i++) { 61 | // // battlesList[i].querySelector('td:nth-child(9) > img:nth-child(1)').click() 62 | // // .then(()=> { 63 | // // const battleModal = document.querySelector('div#battle_result_content'); 64 | // // battlesArray[i] = { 65 | // // mana: battleModal.querySelector('div.mana-cap-value')[0].innerText, 66 | // // rules: battleModal.querySelector('div.ruleset > div.rules').innerText, 67 | // // //splinters: battleModal.querySelector('div.splinters').map().innerText, //todo 68 | // // loser: battleModal.querySelector('div.details-team:not(.winner) > .details-player-name').innerText, 69 | // // winner: battleModal.querySelector('div.details-team.winner > .details-player-name').innerText, 70 | // // //loserTeam: battleModal.querySelector('div.details-team:not(.winner) > div.profile-team-container').innerText, 71 | // // //winnerTeam: battleModal.querySelector('div.details-team:not(.winner) > div.profile-team-container').innerText, 72 | // // link: battleModal.querySelector('div.battle-id > input').getAttribute('value'), 73 | // // } 74 | 75 | // // }) 76 | 77 | // battlesArray[i] = { 78 | // //mana: battlesList[i].querySelector('td:nth-child(7)').innerText, 79 | // rulesSet: battlesList[i].querySelector('td:nth-child(8) > img').getAttribute('data-original-title'), 80 | // id: battlesList[i].querySelector('td:nth-child(9) > img:nth-child(3)').getAttribute('data-battle'), 81 | // }; 82 | // } 83 | // return battlesArray; 84 | // }); 85 | console.log('Battles',battlesList); 86 | 87 | // await page.waitFor(5000).then( 88 | // ()=>{ 89 | // if (Number(mana.manaCap) > 14) { 90 | // console.log('14plus') 91 | // page.click('#card_162') 92 | // .then(() => page.waitFor(1000)) 93 | // .then(() => page.click('#card_196')) 94 | // .then(() => page.click('#card_194')); 95 | // mana = checkMana(page).then((mana)=>console.log('mana promise', mana)); 96 | // } else { 97 | // page.click('#card_162') 98 | // .then(() => page.waitFor(1000)) 99 | // .then(() => page.click('#card_196')) 100 | // .then(() => page.click('#card_194')); 101 | // } 102 | // }); 103 | 104 | 105 | 106 | 107 | // card id card_167 108 | 109 | // battle_container 110 | // btn-green 111 | 112 | // id btnRumble 113 | 114 | //exit battle 115 | //button.btn-battle 116 | 117 | 118 | //await page.waitForSelector('.algolia__results'); 119 | 120 | //await browser.close(); 121 | } 122 | 123 | openSplinter(); -------------------------------------------------------------------------------- /src/Battle/Battle.js: -------------------------------------------------------------------------------- 1 | const fetch = require("node-fetch"); 2 | const { Pool } = require('pg') 3 | 4 | async function getPlayerBattlesHistory(player = '') { 5 | return await fetch('https://api.steemmonsters.io/battle/history?player=' + player + '&v=1582143214911&token=5C9VPKBVV4&username=' + process.env.ACCOUNT.split('@')[0]) 6 | .then((response) => { 7 | if (!response.ok) { 8 | throw new Error('Network response was not ok'); 9 | } 10 | return response.json(); 11 | }) 12 | .then((response) => { 13 | if (!response.battles || !response.battles.length) { 14 | throw new Error('No battles'); 15 | } 16 | return response.battles; 17 | }) 18 | .catch((error) => { 19 | console.error('There has been a problem with your fetch operation:', error); 20 | }); 21 | } 22 | 23 | const extractGeneralInfo = (x) => { 24 | return { 25 | created_date: x.created_date ? x.created_date : '', 26 | match_type: x.match_type ? x.match_type : '', 27 | mana_cap: x.mana_cap ? x.mana_cap : '', 28 | ruleset: x.ruleset ? x.ruleset : '', 29 | inactive: x.inactive ? x.inactive : '' 30 | } 31 | } 32 | 33 | const extractMonster = (team) => { 34 | const monster1 = team.monsters[0]; 35 | const monster2 = team.monsters[1]; 36 | const monster3 = team.monsters[2]; 37 | const monster4 = team.monsters[3]; 38 | const monster5 = team.monsters[4]; 39 | const monster6 = team.monsters[5]; 40 | 41 | return { 42 | summoner_id: team.summoner.card_detail_id, 43 | summoner_level: team.summoner.level, 44 | monster_1_id: monster1 ? monster1.card_detail_id : '', 45 | monster_1_level: monster1 ? monster1.level : '', 46 | monster_1_abilities: monster1 ? monster1.abilities : '', 47 | monster_2_id: monster2 ? monster2.card_detail_id : '', 48 | monster_2_level: monster2 ? monster2.level : '', 49 | monster_2_abilities: monster2 ? monster2.abilities : '', 50 | monster_3_id: monster3 ? monster3.card_detail_id : '', 51 | monster_3_level: monster3 ? monster3.level : '', 52 | monster_3_abilities: monster3 ? monster3.abilities : '', 53 | monster_4_id: monster4 ? monster4.card_detail_id : '', 54 | monster_4_level: monster4 ? monster4.level : '', 55 | monster_4_abilities: monster4 ? monster4.abilities : '', 56 | monster_5_id: monster5 ? monster5.card_detail_id : '', 57 | monster_5_level: monster5 ? monster5.level : '', 58 | monster_5_abilities: monster5 ? monster5.abilities : '', 59 | monster_6_id: monster6 ? monster6.card_detail_id : '', 60 | monster_6_level: monster6 ? monster6.level : '', 61 | monster_6_abilities: monster6 ? monster6.abilities : '' 62 | } 63 | } 64 | 65 | const extractBattleDetails = (battle) => { 66 | const details = JSON.parse(battle.details); 67 | if (details.type != 'Surrender') { 68 | if (battle.winner && battle.winner == battle.player_1) { 69 | const monstersDetails = extractMonster(details.team1) 70 | const info = extractGeneralInfo(battle) 71 | return { 72 | ...monstersDetails, 73 | ...info, 74 | battle_queue_id: battle.battle_queue_id_1, 75 | player_rating_initial: battle.player_1_rating_initial, 76 | player_rating_final: battle.player_1_rating_final, 77 | winner: battle.player_1, 78 | 79 | } 80 | } else if (battle.winner && battle.winner == battle.player_2) { 81 | const monstersDetails = extractMonster(details.team2) 82 | const info = extractGeneralInfo(battle) 83 | return { 84 | ...monstersDetails, 85 | ...info, 86 | battle_queue_id: battle.battle_queue_id_2, 87 | player_rating_initial: battle.player_2_rating_initial, 88 | player_rating_final: battle.player_2_rating_final, 89 | winner: battle.player_2, 90 | } 91 | } 92 | } 93 | } 94 | 95 | const pool = new Pool({ 96 | user: 'postgres', 97 | host: 'localhost', 98 | database: 'splinterlands', 99 | password: 'docker', 100 | port: 5432, 101 | max: 100, 102 | idleTimeoutMillis: 30000, 103 | connectionTimeoutMillis: 2000, 104 | }); 105 | 106 | const makeInsertQuery = (battleDetails) => "INSERT INTO battles (summoner_id, summoner_level, monster_1_id, monster_1_level,monster_1_abilities, monster_2_id, monster_2_level, monster_2_abilities, monster_3_id, monster_3_level, monster_3_abilities, monster_4_id, monster_4_level, monster_4_abilities, monster_5_id, monster_5_level, monster_5_abilities, monster_6_id, monster_6_level, monster_6_abilities, created_date, match_type, mana_cap, ruleset, inactive, battle_queue_id, player_rating_initial, player_rating_final, winner) VALUES('" + Object.values(battleDetails).join("','") + "') ON CONFLICT (battle_queue_id) DO NOTHING;" 107 | 108 | async function writeDB() { 109 | await pool.connect(); 110 | await getPlayerBattlesHistory(process.env.ACCOUNT.split('@')[0]) 111 | .then((result) => { 112 | console.log('TOTAL ROWS: ', result.length) 113 | result.map( 114 | async battle => { 115 | if (extractBattleDetails(battle)) { 116 | console.log(makeInsertQuery(extractBattleDetails(battle))) 117 | await pool.query(makeInsertQuery(extractBattleDetails(battle))) 118 | .then(dbResult => console.log(dbResult.rowCount)) 119 | .catch(e => console.error('ERR: ', e.stack)) 120 | } 121 | } 122 | ) 123 | }) 124 | .then((res) => console.log("OK: ", res)) 125 | .catch(e => console.log('ERROR: ', e)) 126 | await pool.end() 127 | } 128 | 129 | writeDB(); 130 | -------------------------------------------------------------------------------- /battles.js: -------------------------------------------------------------------------------- 1 | 2 | const mostWinningSummonerTank = (possibleTeamsList) => { 3 | mostWinningDeck = { fire: 0, death: 0, earth: 0, water: 0, life: 0 } 4 | const mostWinningSummoner = {}; 5 | const mostWinningTank = {}; 6 | const mostWinningBackline = {}; 7 | const mostWinningSecondBackline = {}; 8 | const mostWinningThirdBackline = {}; 9 | const mostWinningForthBackline = {}; 10 | possibleTeamsList.forEach(x => { 11 | const summoner = x[0]; 12 | mostWinningSummoner[summoner] = mostWinningSummoner[summoner] ? mostWinningSummoner[summoner] + 1 : 1; 13 | }) 14 | const bestSummoner = Object.keys(mostWinningSummoner).length && Object.keys(mostWinningSummoner).reduce((a, b) => mostWinningSummoner[a] > mostWinningSummoner[b] ? a : b); 15 | console.log('BESTSUMMONER: ', bestSummoner) 16 | if (bestSummoner) { 17 | possibleTeamsList.filter(team => team[0] == bestSummoner).forEach(team => { 18 | const tank = team[1]; 19 | mostWinningTank[tank] = mostWinningTank[tank] ? mostWinningTank[tank] + 1 : 1; 20 | }) 21 | const bestTank = mostWinningTank && Object.keys(mostWinningTank).length && Object.keys(mostWinningTank).reduce((a, b) => mostWinningTank[a] > mostWinningTank[b] ? a : b); 22 | 23 | if (bestTank) { 24 | possibleTeamsList.filter(team => team[0] == bestSummoner && team[1] == bestTank).forEach(team => { 25 | const backline = team[2]; 26 | mostWinningBackline[backline] = mostWinningBackline[backline] ? mostWinningBackline[backline] + 1 : 1; 27 | }) 28 | const bestBackline = mostWinningBackline && Object.keys(mostWinningBackline).length && Object.keys(mostWinningBackline).reduce((a, b) => mostWinningBackline[a] > mostWinningBackline[b] ? a : b); 29 | 30 | if (bestBackline) { 31 | possibleTeamsList.filter(team => team[0] == bestSummoner && team[1] == bestTank && team[2] == bestBackline).forEach(team => { 32 | const secondBackline = team[3]; 33 | mostWinningSecondBackline[secondBackline] = mostWinningSecondBackline[secondBackline] ? mostWinningSecondBackline[secondBackline] + 1 : 1; 34 | }) 35 | const bestSecondBackline = mostWinningSecondBackline && Object.keys(mostWinningSecondBackline).length && Object.keys(mostWinningSecondBackline).reduce((a, b) => mostWinningSecondBackline[a] > mostWinningSecondBackline[b] ? a : b); 36 | 37 | if (bestSecondBackline) { 38 | possibleTeamsList.filter(team => team[0] == bestSummoner && team[1] == bestTank && team[2] == bestBackline && team[3] == bestSecondBackline).forEach(team => { 39 | const thirdBackline = team[4]; 40 | mostWinningThirdBackline[thirdBackline] = mostWinningThirdBackline[thirdBackline] ? mostWinningThirdBackline[thirdBackline] + 1 : 1; 41 | }) 42 | const bestThirdBackline = mostWinningThirdBackline && Object.keys(mostWinningThirdBackline).length && Object.keys(mostWinningThirdBackline).reduce((a, b) => mostWinningThirdBackline[a] > mostWinningThirdBackline[b] ? a : b); 43 | 44 | if (bestThirdBackline) { 45 | possibleTeamsList.filter(team => team[0] == bestSummoner && team[1] == bestTank && team[2] == bestBackline && team[3] == bestSecondBackline && team[4] == bestThirdBackline).forEach(team => { 46 | const forthBackline = team[5]; 47 | mostWinningForthBackline[forthBackline] = mostWinningForthBackline[forthBackline] ? mostWinningForthBackline[forthBackline] + 1 : 1; 48 | }) 49 | const bestForthBackline = mostWinningForthBackline && Object.keys(mostWinningForthBackline).length && Object.keys(mostWinningForthBackline).reduce((a, b) => mostWinningForthBackline[a] > mostWinningForthBackline[b] ? a : b); 50 | 51 | return { 52 | bestSummoner: bestSummoner, 53 | summonerWins: mostWinningSummoner[bestSummoner], 54 | tankWins: mostWinningTank[bestTank], 55 | bestTank: bestTank, 56 | bestBackline: bestBackline, 57 | backlineWins: mostWinningBackline[bestBackline], 58 | bestSecondBackline: bestSecondBackline, 59 | secondBacklineWins: mostWinningSecondBackline[bestSecondBackline], 60 | bestThirdBackline: bestThirdBackline, 61 | thirdBacklineWins: mostWinningThirdBackline[bestThirdBackline], 62 | bestForthBackline: bestForthBackline, 63 | forthBacklineWins: mostWinningForthBackline[bestForthBackline] 64 | } 65 | } 66 | 67 | return { 68 | bestSummoner: bestSummoner, 69 | summonerWins: mostWinningSummoner[bestSummoner], 70 | tankWins: mostWinningTank[bestTank], 71 | bestTank: bestTank, 72 | bestBackline: bestBackline, 73 | backlineWins: mostWinningBackline[bestBackline], 74 | bestSecondBackline: bestSecondBackline, 75 | secondBacklineWins: mostWinningSecondBackline[bestSecondBackline], 76 | bestThirdBackline: bestThirdBackline, 77 | thirdBacklineWins: mostWinningThirdBackline[bestThirdBackline] 78 | } 79 | } 80 | 81 | return { 82 | bestSummoner: bestSummoner, 83 | summonerWins: mostWinningSummoner[bestSummoner], 84 | tankWins: mostWinningTank[bestTank], 85 | bestTank: bestTank, 86 | bestBackline: bestBackline, 87 | backlineWins: mostWinningBackline[bestBackline], 88 | bestSecondBackline: bestSecondBackline, 89 | secondBacklineWins: mostWinningSecondBackline[bestSecondBackline] 90 | } 91 | } 92 | 93 | return { 94 | bestSummoner: bestSummoner, 95 | summonerWins: mostWinningSummoner[bestSummoner], 96 | tankWins: mostWinningTank[bestTank], 97 | bestTank: bestTank, 98 | bestBackline: bestBackline, 99 | backlineWins: mostWinningBackline[bestBackline] 100 | } 101 | } 102 | 103 | return { 104 | bestSummoner: bestSummoner, 105 | summonerWins: mostWinningSummoner[bestSummoner], 106 | tankWins: mostWinningTank[bestTank], 107 | bestTank: bestTank 108 | } 109 | } 110 | return { 111 | bestSummoner: bestSummoner, 112 | summonerWins: mostWinningSummoner[bestSummoner] 113 | } 114 | } 115 | 116 | module.exports.mostWinningSummonerTank = mostWinningSummonerTank; -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # splinterlands-bot 2 | 3 | This is my personal project of a BOT to play the game [Splinterlands](https://www.splinterlands.com). It requires [NodeJs](https://nodejs.org/it/download/) installed to run. 4 | 5 | 6 | ## How to start the BOT: 7 | 8 | REQUIREMENT: You need to install NodeJS from https://nodejs.org/en/download/ (at least the last stable version 14.18.0) 9 | 10 | Once NodeJS is installed and you downloaded the bot in a specific folder, you need to set your configuration in the .env file: 11 | 12 | you need to create the .env file and include the username and posting key (file with no name, only starting dot to create a hidden file) in the bot folder, 13 | 14 | Example: 15 | 16 | - `ACCOUNT=youraccountname` 17 | - `PASSWORD=yourpostingkey` 18 | 19 | You can also use the file `.env-example` as a template, but remember to remove `-example` from the filename. 20 | 21 | __IMPORTANT:__ the bot needs the __username and posting key__ in order to login. __Don't use the email and password__. If you don't have the posting key, you need to _'Request Keys'_ from the top right menu in Splinterlands. You will receive a link to follow where you will get your Hive private keys. __Store them safely and don't share them with anyone!__ 22 | 23 | Once the file is created, open cmd (for windows) or terminal (for Mac and Linux) and run: 24 | 25 | `npm install` 26 | 27 | and then 28 | 29 | `npm start` 30 | 31 | There is also a youtube video made by a user that can help windows users with the setup [here](https://youtu.be/MFxV6XeDKec) 32 | 33 | 34 | If you face issue related to the browser when you run the bot for the first time, be sure you have installed chromium browser. For Linux: 35 | #### install chromium 36 | sudo apt-get install chromium-browser 37 | 38 | #### run this if running chromium still fails 39 | sudo apt-get install libpangocairo-1.0-0 libx11-xcb1 libxcomposite1 libxcursor1 libxdamage1 libxi6 libxtst6 libnss3 libcups2 libxss1 libxrandr2 libgconf2-4 libasound2 libatk1.0-0 libgtk-3-0 libgbm-dev 40 | 41 | 42 | 43 | ### Optional variables: 44 | 45 | The BOT will make a battle every 30 minutes by default, you can change the custom value specifying in the .env the variable `MINUTES_BATTLES_INTERVAL`. 46 | The BOT will also try to select team to complete the daily quest by default. If you want to remove this option to increase the winning rate, you can set the variable `QUEST_PRIORITY` as false. 47 | By default, the BOT doesn't check for season rewards but it can automatically click on the seasons reward claim button if available and the `CLAIM_SEASON_REWARD` is set to true. The default option is false. 48 | By default, the BOT checks automatically for daily quest rewards but the claim option can be deactivated with the option `CLAIM_DAILY_QUEST_REWARD` is set to false. The default option is true. 49 | By default, the BOT will run as headless. Set `HEADLESS` to false to see your browser. The default option is true 50 | By default, the BOT will run no matter the ECR level. Set `ECR_STOP_LIMIT` to a specific value you want the bot to rest and recover the ECR. The bot will recover until the `ECR_RECOVER_TO` is reached or until 100% ECR. 51 | If you want the bot to play only one color (when it's possible), use the variable `FAVOURITE_DECK` and specify the splinter by choosing only one among: fire, life, earth, water, death, dragon. 52 | If you want the bot to try to skip specific quest types you can include multiple quest in the variable `SKIP_QUEST` separated by the comma (`SKIP_QUEST=life,snipe,neutral`). whenever it's possible, the bot will click to ask for a new one. Remember you can only ask for a new one once based on the game rules. 53 | If you want the bot to prioritize teams that uses delegated cards, set the variable `DELEGATED_CARDS_PRIORITY` equal to `true`. 54 | To avoid to sue the API solution and rely only on your local history json file created as per instructions below (Local History backup), you can set the variable `FORCE_LOCAL_HISTORY=true`. 55 | 56 | Example: 57 | 58 | - `QUEST_PRIORITY=false` 59 | 60 | - `MINUTES_BATTLES_INTERVAL=30` 61 | 62 | - `CLAIM_SEASON_REWARD=true` 63 | 64 | - `CLAIM_DAILY_QUEST_REWARD=false` 65 | 66 | - `HEADLESS=false` 67 | 68 | - `ECR_STOP_LIMIT=50` 69 | 70 | - `ECR_RECOVER_TO=99` 71 | 72 | - `FAVOURITE_DECK=dragon` 73 | 74 | - `SKIP_QUEST=life,snipe,neutral` 75 | 76 | - `DELEGATED_CARDS_PRIORITY=true` 77 | 78 | - `FORCE_LOCAL_HISTORY=true` 79 | 80 | 81 | ### Running bot with multiaccount setting 82 | 83 | in order to run multple accounts launching the script only once, you can simply add the list of usernames and posting keys in the .env file and set the variable `MULTI_ACCOUNT` as true: 84 | 85 | - `MULTI_ACCOUNT=true` 86 | - `ACCOUNT=user1,user2,user,...` 87 | - `PASSWORD=postingkey1,postingkey2,postingkey3,...` 88 | 89 | ### Running bot as a daemon with PM2 90 | 91 | To run your bot as a daemon (background process) you can use NPM package PM2. PM2 is daemon process manager, that works on Linux, MacOS, and Windows. To install PM2 globally, you need to run: 92 | 93 | # `npm install pm2 -g` 94 | 95 | To start a bot, do all the preparation steps from the above, but instead of `npm start`, run this: 96 | 97 | `pm2 start main.js` 98 | 99 | You can now run `pm2 list` command to see your bot up and running. It will automatically start on system startup now. You can control the bot with these commands: 100 | 101 | `pm2 start ` 102 | 103 | `pm2 stop ` 104 | 105 | `pm2 restart ` 106 | 107 | `pm2 delete ` 108 | 109 | You can find more information on PM2 usage options at their [official webiste](https://pm2.keymetrics.io/). 110 | 111 | 112 | ### Running the bot in a docker container 113 | 114 | docker instructions: 115 | 116 | 1. first, you need to install docker https://docs.docker.com/get-docker/ 117 | 2. open your terminal/command line 118 | 3. cd into your bot directory 119 | 4. build the image 120 | -> `docker build -t your_image_name -f Dockerfile .` 121 | 5. then run a container based on the image 122 | -> `docker run -it your_image_name bash` 123 | 6. the 5th step will get you inside your container, use nano or vim to edit your .env file and make sure to uncomment CHROME_EXEC 124 | 7. finally, run 125 | -> `npm start` 126 | 127 | 128 | 129 | ## Local History backup (battlesGetData.js) 130 | 131 | The BOT leverages an API on a free server but in case the traffic is heavy or it doesn't work, it is possible to have locally an history as a backup solution that the bot will read automatically. 132 | To generate the file 'history.json' with a unique array with the history of the battles of an array of users specified in the file. 133 | 134 | [ OPTIONAL ] run this command from the terminal: 135 | 136 | `node battlesGetData.js` 137 | 138 | Once the script is done, it will create a file 'history.json' in the data folder. To makes the bot using it, you have to rename it in: 'newHistory.json' 139 | 140 | **How to get history data from users of my choice?** 141 | 142 | 1. Open battlesGetData.js in notepad and change the usersToGrab on line 69 to aa list of users of your choice like: `let usersToGrab = ['player1','player2']` 143 | 2. Run `node battlesGetData.js` in the bot folder 144 | 3. File history.json is created, rename it to newHistory.json to replace the existing history data OR extend the newHistory.json file with `combine.js` (see below) 145 | 146 | **How to extend the newHistory.json without deleting existing data?** 147 | 148 | 1. Backup newHistory.json in case something goes wrong 149 | 2. Run `node combine.js` to add the new data from history.json to the newHistory.json file that will be used by the bot 150 | 151 | 152 | # FAQ 153 | 154 | 155 | Q: Can I make the bot running a battle every 2 minutes? 156 | A: Technically yes, but playing too often will decrease the Capture Rate making the rewards very low and insignificant. Try to play a battle every 20 minutes MAX to maintain high level of rewards. Trust me, you keep the ROI higher. Don't be greedy. 157 | 158 | Q: Does it play for the daily quest? 159 | A: At the moment the bot consider only the splinters quests (death, dragon, earth, fire, life, water) but not the special one (snipe, sneak, neutral,...). Therefore yes, the bot prioritize the splinter for the quest. Nonetheless if the bot consider more probable to win a battle with another splinter (because for example there are not many possible team for the splinter of the quest), you may see a different card selection sometimes 160 | 161 | Q: Can I play multiple accounts? 162 | A: Technically yes, but don't be greedy. 163 | 164 | Q: I got the error "cannot read property split of undefined" 165 | A: check that the credentials file doesn't contain any but ".env" in the name. (no .txt or anything else) and check that there is nothing but ACCOUNT=yourusername and PASSWORD=yourpass in 2 lines with no spaces. Also you must use the username with the posting key, and not the email address. 166 | 167 | Q: Why the bot doesn't use my best card I paid 1000$? 168 | A: Because the bot select cards based on the statistics of the previous battles choosing the most winning team for your cards. it's a bot, not a thinking human being! 169 | 170 | Q: Why the bot doesn't use the Furious Chicken? 171 | A: same as above 172 | 173 | 174 | # Donations 175 | 176 | I've created using my personal free time so if you like it or you benefit from it and would like to be grateful and offer me a beer 🍺 I'll appreciate: 177 | 178 | - DEC into the game to the player **splinterlava** 179 | - Bitcoin bc1qpluvvtty822dsvfza4en9d3q3sl5yhj2qa2dtn 180 | - Ethereum 0x8FA3414DC2a2F886e303421D07bda5Ef45C84A3b 181 | - Tron TRNjqiovkkfxVSSpHSfGPQoGby1FgvcSaY 182 | - BUSD(ERC20) 0xE4B06BE863fD9bcE1dA30433151662Ea0ecA4a7e 183 | 184 | Cheers! 185 | 186 | where you can find some support from other people using it: 187 | 188 | [Discord]( 189 | https://discord.gg/bR6cZDsFSX) 190 | 191 | [Telegram chat](https://t.me/splinterlandsbot) 192 | 193 | -------------------------------------------------------------------------------- /possibleTeams.js: -------------------------------------------------------------------------------- 1 | require('dotenv').config() 2 | const card = require('./cards'); 3 | const helper = require('./helper'); 4 | const battles = require('./battles'); 5 | const fetch = require("node-fetch"); 6 | 7 | const summoners = [{260: 'fire'}, 8 | {257: 'water'}, 9 | {437: 'water'}, 10 | {224: 'dragon'}, 11 | {189: 'earth'}, 12 | {145: 'death'}, 13 | {240: 'dragon'}, 14 | {167: 'fire'}, 15 | {438: 'death'}, 16 | {156: 'life'}, 17 | {440: 'fire'}, 18 | {114: 'dragon'}, 19 | {441: 'life'}, 20 | {439: 'earth'}, 21 | {262: 'dragon'}, 22 | {261: 'life'}, 23 | {178: 'water'}, 24 | {258: 'death'}, 25 | {27: 'earth'}, 26 | {38: 'life'}, 27 | {49: 'death'}, 28 | {5: 'fire'}, 29 | {70: 'fire'}, 30 | {38: 'life'}, 31 | {73: 'life'}, 32 | {259: 'earth'}, 33 | {74: 'death'}, 34 | {72: 'earth'}, 35 | {442: 'dragon'}, 36 | {71: 'water'}, 37 | {88: 'dragon'}, 38 | {78: 'dragon'}, 39 | {200: 'dragon'}, 40 | {16: 'water'}, 41 | {239: 'life'}, 42 | {254: 'water'}, 43 | {235: 'death'}, 44 | {113: 'life'}, 45 | {109: 'death'}, 46 | {110: 'fire'}, 47 | {291: 'dragon'}, 48 | {278: 'earth'}, 49 | {236: 'fire'}, 50 | {56: 'dragon'}, 51 | {112: 'earth'}, 52 | {111: 'water'}, 53 | {56: 'dragon'}, 54 | {205: 'dragon'}, 55 | {130: 'dragon'}] 56 | 57 | const splinters = ['fire', 'life', 'earth', 'water', 'death', 'dragon'] 58 | 59 | const getSummoners = (myCards, splinters) => { 60 | try { 61 | const sumArray = summoners.map(x=>Number(Object.keys(x)[0])) 62 | const mySummoners = myCards.filter(value => sumArray.includes(Number(value))); 63 | const myAvailableSummoners = mySummoners.filter(id=>splinters.includes(summonerColor(id))) 64 | return myAvailableSummoners || mySummoners; 65 | } catch(e) { 66 | console.log(e); 67 | return []; 68 | } 69 | } 70 | 71 | const summonerColor = (id) => { 72 | const summonerDetails = summoners.find(x => x[id]); 73 | return summonerDetails ? summonerDetails[id] : ''; 74 | } 75 | 76 | const historyBackup = require("./data/newHistory.json"); 77 | const basicCards = require('./data/basicCards.js'); 78 | 79 | let availabilityCheck = (base, toCheck) => toCheck.slice(0, 7).every(v => base.includes(v)); 80 | let account = ''; 81 | 82 | const getBattlesWithRuleset = (ruleset, mana, summoners) => { 83 | try { 84 | const rulesetEncoded = encodeURIComponent(ruleset); 85 | const host = process.env.API || 'http://95.179.236.23/' 86 | let url = '' 87 | if (process.env.API_VERSION == 2) { 88 | url = `V2/battlesruleset?ruleset=${rulesetEncoded}&mana=${mana}&player=${account}&token=${process.env.TOKEN}&summoners=${summoners ? JSON.stringify(summoners) : ''}`; 89 | } else { 90 | url = `V1/battlesruleset?ruleset=${rulesetEncoded}&mana=${mana}&player=${account}&token=${process.env.TOKEN}&summoners=${summoners ? JSON.stringify(summoners) : ''}`; 91 | } 92 | console.log('API call: ', host+url) 93 | return fetch(host+url, { timeout: 10000 }) 94 | .then(x => x && x.json()) 95 | .then(data => data) 96 | .catch((e) => console.log('fetch ', e)) 97 | 98 | } catch (e) { 99 | console.log('Error API did not return') 100 | } 101 | 102 | } 103 | 104 | const battlesFilterByManacap = async (mana, ruleset, summoners) => { 105 | let forceLocalHistory = process.env.FORCE_LOCAL_HISTORY === 'false' ? false : true; 106 | let history = []; 107 | if(!forceLocalHistory) { 108 | history = await getBattlesWithRuleset(ruleset, mana, summoners); 109 | } 110 | 111 | if (history && history?.length) { 112 | console.log('API battles returned ', history.length) 113 | return history.filter( 114 | battle => 115 | battle.mana_cap == mana && 116 | (ruleset ? battle.ruleset === ruleset : true) 117 | ) 118 | } 119 | const backupLength = historyBackup && historyBackup.length 120 | console.log('API battles did not return ', history) 121 | console.log('Using Backup ', backupLength) 122 | 123 | return historyBackup.filter( 124 | battle => 125 | battle.mana_cap == mana && 126 | (ruleset ? battle.ruleset === ruleset : true) 127 | ) 128 | } 129 | 130 | function compare(a, b) { 131 | const totA = a[9]; 132 | const totB = b[9]; 133 | 134 | let comparison = 0; 135 | if (totA < totB) { 136 | comparison = 1; 137 | } else if (totA > totB) { 138 | comparison = -1; 139 | } 140 | return comparison; 141 | } 142 | 143 | const cardsIdsforSelectedBattles = (mana, ruleset, splinters, summoners) => battlesFilterByManacap(mana, ruleset, summoners) 144 | .then(x => { 145 | return x.map( 146 | (x) => { 147 | return [ 148 | x.summoner_id ? parseInt(x.summoner_id) : '', 149 | x.monster_1_id ? parseInt(x.monster_1_id) : '', 150 | x.monster_2_id ? parseInt(x.monster_2_id) : '', 151 | x.monster_3_id ? parseInt(x.monster_3_id) : '', 152 | x.monster_4_id ? parseInt(x.monster_4_id) : '', 153 | x.monster_5_id ? parseInt(x.monster_5_id) : '', 154 | x.monster_6_id ? parseInt(x.monster_6_id) : '', 155 | summonerColor(x.summoner_id) ? summonerColor(x.summoner_id) : '', 156 | x.tot ? parseInt(x.tot) : '', 157 | x.ratio ? parseInt(x.ratio) : '', 158 | ] 159 | } 160 | ).filter( 161 | team => splinters.includes(team[7]) 162 | ).sort(compare) 163 | }) 164 | 165 | const askFormation = function (matchDetails) { 166 | const cards = matchDetails.myCards || basicCards; 167 | const mySummoners = getSummoners(cards,matchDetails.splinters); 168 | console.log('INPUT: ', matchDetails.mana, matchDetails.rules, matchDetails.splinters, cards.length) 169 | return cardsIdsforSelectedBattles(matchDetails.mana, matchDetails.rules, matchDetails.splinters, mySummoners) 170 | .then(x => x.filter( 171 | x => availabilityCheck(cards, x)) 172 | .map(element => element)//cards.cardByIds(element) 173 | ) 174 | 175 | } 176 | 177 | const possibleTeams = async (matchDetails, acc) => { 178 | let possibleTeams = []; 179 | while (matchDetails.mana > 10) { 180 | if (matchDetails.mana === 98) { 181 | matchDetails.mana = 45; 182 | } 183 | console.log('check battles based on mana: '+matchDetails.mana); 184 | account = acc; 185 | possibleTeams = await askFormation(matchDetails); 186 | if (possibleTeams.length > 0) { 187 | return possibleTeams; 188 | } 189 | matchDetails.mana--; 190 | } 191 | return possibleTeams; 192 | } 193 | 194 | const mostWinningSummonerTankCombo = async (possibleTeams, matchDetails) => { 195 | const bestCombination = await battles.mostWinningSummonerTank(possibleTeams) 196 | console.log('BEST SUMMONER and TANK', bestCombination) 197 | if (bestCombination.summonerWins >= 1 && bestCombination.tankWins > 1 && bestCombination.backlineWins > 1 && bestCombination.secondBacklineWins > 1 && bestCombination.thirdBacklineWins > 1 && bestCombination.forthBacklineWins > 1) { 198 | const bestTeam = await possibleTeams.find(x => x[0] == bestCombination.bestSummoner && x[1] == bestCombination.bestTank && x[2] == bestCombination.bestBackline && x[3] == bestCombination.bestSecondBackline && x[4] == bestCombination.bestThirdBackline && x[5] == bestCombination.bestForthBackline) 199 | console.log('BEST TEAM', bestTeam) 200 | const summoner = bestTeam[0].toString(); 201 | return [summoner, bestTeam]; 202 | } 203 | if (bestCombination.summonerWins >= 1 && bestCombination.tankWins > 1 && bestCombination.backlineWins > 1 && bestCombination.secondBacklineWins > 1 && bestCombination.thirdBacklineWins > 1) { 204 | const bestTeam = await possibleTeams.find(x => x[0] == bestCombination.bestSummoner && x[1] == bestCombination.bestTank && x[2] == bestCombination.bestBackline && x[3] == bestCombination.bestSecondBackline && x[4] == bestCombination.bestThirdBackline) 205 | console.log('BEST TEAM', bestTeam) 206 | const summoner = bestTeam[0].toString(); 207 | return [summoner, bestTeam]; 208 | } 209 | if (bestCombination.summonerWins >= 1 && bestCombination.tankWins > 1 && bestCombination.backlineWins > 1 && bestCombination.secondBacklineWins > 1) { 210 | const bestTeam = await possibleTeams.find(x => x[0] == bestCombination.bestSummoner && x[1] == bestCombination.bestTank && x[2] == bestCombination.bestBackline && x[3] == bestCombination.bestSecondBackline) 211 | console.log('BEST TEAM', bestTeam) 212 | const summoner = bestTeam[0].toString(); 213 | return [summoner, bestTeam]; 214 | } 215 | if (bestCombination.summonerWins >= 1 && bestCombination.tankWins > 1 && bestCombination.backlineWins > 1) { 216 | const bestTeam = await possibleTeams.find(x => x[0] == bestCombination.bestSummoner && x[1] == bestCombination.bestTank && x[2] == bestCombination.bestBackline) 217 | console.log('BEST TEAM', bestTeam) 218 | const summoner = bestTeam[0].toString(); 219 | return [summoner, bestTeam]; 220 | } 221 | if (bestCombination.summonerWins >= 1 && bestCombination.tankWins > 1) { 222 | const bestTeam = await possibleTeams.find(x => x[0] == bestCombination.bestSummoner && x[1] == bestCombination.bestTank) 223 | console.log('BEST TEAM', bestTeam) 224 | const summoner = bestTeam[0].toString(); 225 | return [summoner, bestTeam]; 226 | } 227 | if (bestCombination.summonerWins >= 1) { 228 | const bestTeam = await possibleTeams.find(x => x[0] == bestCombination.bestSummoner) 229 | console.log('BEST TEAM', bestTeam) 230 | const summoner = bestTeam[0].toString(); 231 | return [summoner, bestTeam]; 232 | } 233 | } 234 | 235 | const filterOutUnplayableDragonsAndUnplayableSplinters = (teams = [], matchDetails) => { 236 | const filteredTeamsForAvailableSplinters = Array.isArray(teams) && teams.filter(team=>(team[7]!=='dragon' && matchDetails.splinters.includes(team[7])) || (team[7]==='dragon' && matchDetails.splinters.includes(helper.teamActualSplinterToPlay(team?.slice(0, 6)).toLowerCase()))) 237 | return filteredTeamsForAvailableSplinters || teams; 238 | } 239 | 240 | const filterPreferredCardsTeams = (teams = [], preferredCards = []) => teams.filter(team => team.slice(0,6).some(card => preferredCards.includes(card))) 241 | 242 | const teamSelection = async (possibleTeams, matchDetails, quest, favouriteDeck) => { 243 | let priorityToTheQuest = process.env.QUEST_PRIORITY === 'false' ? false : true; 244 | console.log('quest custom option set as:', priorityToTheQuest) 245 | const availableTeamsToPlay = await filterOutUnplayableDragonsAndUnplayableSplinters(possibleTeams ,matchDetails); 246 | let filterPreferredTeams = []; 247 | if(process.env.DELEGATED_CARDS_PRIORITY === 'true') filterPreferredTeams = await filterPreferredCardsTeams(availableTeamsToPlay,matchDetails?.preferredCards) 248 | 249 | //CHECK FOR QUEST: 250 | if(priorityToTheQuest && availableTeamsToPlay.length > 10 && quest && quest.total) { 251 | const left = quest.total - quest.completed; 252 | const questCheck = matchDetails.splinters.includes(quest.splinter) && left > 0; 253 | const filteredTeamsForQuest = availableTeamsToPlay.filter(team=>team[7]===quest.splinter) 254 | const filteredTeamsPreferredCardsForQuest = filterPreferredTeams.filter(team=>team[7]===quest.splinter) 255 | console.log(left + ' battles left for the '+quest.splinter+' quest') 256 | console.log('play for the quest ',quest.splinter,'? ',questCheck) 257 | 258 | //QUEST FOR V2 259 | if (process.env.API_VERSION == 2 && availableTeamsToPlay[0][8]) { 260 | console.log('V2 try to play for the quest?') 261 | if(left > 0 && filteredTeamsPreferredCardsForQuest?.length >= 1 && questCheck && filteredTeamsPreferredCardsForQuest[0][8]) { 262 | console.log('PLAY for the quest with Teams choice of size (V2): ',filteredTeamsPreferredCardsForQuest.length, 'PLAY this with preferred cards: ', filteredTeamsPreferredCardsForQuest[0]) 263 | return { summoner: filteredTeamsPreferredCardsForQuest[0][0], cards: filteredTeamsPreferredCardsForQuest[0] }; 264 | } else if(left > 0 && filteredTeamsForQuest?.length >= 1 && questCheck && filteredTeamsForQuest[0][8]) { 265 | console.log('PLAY for the quest with Teams choice of size (V2): ',filteredTeamsForQuest.length, 'PLAY this: ', filteredTeamsForQuest[0]) 266 | return { summoner: filteredTeamsForQuest[0][0], cards: filteredTeamsForQuest[0] }; 267 | } else { 268 | console.log('quest already completed or not enough teams for the quest (V2)') 269 | } 270 | } else if (process.env.API_VERSION!=2 && availableTeamsToPlay[0][0]) { 271 | // QUEST FOR V1 272 | console.log('play quest for V1') 273 | if(left > 0 && filteredTeamsPreferredCardsForQuest?.length) { 274 | console.log('Try to play for the quest with Teams size (V1): ',filteredTeamsPreferredCardsForQuest.length) 275 | console.log("TEAMS:", filteredTeamsPreferredCardsForQuest) 276 | const res = await mostWinningSummonerTankCombo(filteredTeamsPreferredCardsForQuest, matchDetails); 277 | if (res[0] && res[1]) { 278 | console.log('Play this with preferred cards for the quest:', res) 279 | return { summoner: res[0], cards: res[1] }; 280 | } 281 | } 282 | 283 | if(left > 0 && filteredTeamsForQuest?.length > 3 && splinters.includes(quest.splinter)) { 284 | console.log('Try to play for the quest with Teams size (V1): ',filteredTeamsForQuest.length) 285 | const res = await mostWinningSummonerTankCombo(filteredTeamsForQuest, matchDetails); 286 | if (res[0] && res[1]) { 287 | console.log('Play this for the quest:', res) 288 | return { summoner: res[0], cards: res[1] }; 289 | } else { 290 | console.log('not enough teams for the quest (V1)') 291 | } 292 | } 293 | } 294 | } 295 | 296 | //CHECK for Favourite DECK 297 | const favDeckfilteredTeams = availableTeamsToPlay.filter(team=>team[7]===favouriteDeck) 298 | if(favDeckfilteredTeams?.length && favouriteDeck && matchDetails.splinters.includes(favouriteDeck?.toLowerCase())) { 299 | //FAV DECK FOR V2 300 | if (process.env.API_VERSION == 2 && availableTeamsToPlay?.[0]?.[8]) { 301 | console.log('play splinter:', favouriteDeck, 'from ', favDeckfilteredTeams?.length, 'teams fro V2') 302 | if(favDeckfilteredTeams && favDeckfilteredTeams?.length >= 1 && favDeckfilteredTeams[0][8]) { 303 | console.log('play this as favourite deck for V2:', favDeckfilteredTeams[0]) 304 | return { summoner: favDeckfilteredTeams[0][0], cards: favDeckfilteredTeams[0] }; 305 | } 306 | console.log('No possible teams for splinter ',favouriteDeck, ' V2') 307 | } else if (process.env.API_VERSION!=2 && favDeckfilteredTeams[0][0]) { 308 | // FAV DECK FOR V1 309 | console.log('play splinter:', favouriteDeck, 'from ', favDeckfilteredTeams?.length, 'teams from V1') 310 | if(favDeckfilteredTeams && favDeckfilteredTeams?.length >= 1 && favDeckfilteredTeams[0][0]) { 311 | 312 | 313 | const res = await mostWinningSummonerTankCombo(favDeckfilteredTeams, matchDetails); 314 | if (res[0] && res[1]) { 315 | console.log('play this as favourite deck for V1:', res) 316 | return { summoner: res[0], cards: res[1] }; 317 | } else { 318 | console.log('not enough teams for the favourite deck (V1)') 319 | } 320 | } 321 | console.log('No possible teams for splinter ',favouriteDeck, ' V1') 322 | } 323 | } 324 | 325 | //V2 Strategy ONLY FOR PRIVATE API 326 | if (process.env.API_VERSION == 2 && availableTeamsToPlay?.[0]?.[8]) { 327 | if(filterPreferredTeams?.length) { 328 | console.log('play the highest winning rate team with preferred cards: ', filterPreferredTeams[0]) 329 | return { summoner: filterPreferredTeams[0][0], cards: filterPreferredTeams[0] }; 330 | } 331 | else if(availableTeamsToPlay?.length) { 332 | console.log('play the highest winning rate team: ', availableTeamsToPlay[0]) 333 | return { summoner: availableTeamsToPlay[0][0], cards: availableTeamsToPlay[0] }; 334 | } 335 | else { 336 | console.log('NO available team to be played for V2'); 337 | return null; 338 | } 339 | } else if (process.env.API_VERSION!=2 && availableTeamsToPlay[0][0]) { 340 | //V1 Strategy 341 | //find best combination (most used) 342 | if(filterPreferredTeams?.length) { 343 | const res = await mostWinningSummonerTankCombo(filterPreferredTeams, matchDetails); 344 | if (res[0] && res[1]) { 345 | console.log('Dont play for the quest, and play this with preferred cards:', res) 346 | return { summoner: res[0], cards: res[1] }; 347 | } 348 | } 349 | const res = await mostWinningSummonerTankCombo(availableTeamsToPlay, matchDetails); 350 | if (res[0] && res[1]) { 351 | console.log('Dont play for the quest, and play this:', res) 352 | return { summoner: res[0], cards: res[1] }; 353 | } 354 | } 355 | 356 | 357 | console.log('No available team to be played...') 358 | return null 359 | } 360 | 361 | 362 | module.exports.possibleTeams = possibleTeams; 363 | module.exports.teamSelection = teamSelection; -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | //'use strict'; 2 | const puppeteer = require('puppeteer'); 3 | 4 | const splinterlandsPage = require('./splinterlandsPage'); 5 | const user = require('./user'); 6 | const card = require('./cards'); 7 | const { clickOnElement, getElementText, getElementTextByXpath, teamActualSplinterToPlay, sleep, reload } = require('./helper'); 8 | const quests = require('./quests'); 9 | const ask = require('./possibleTeams'); 10 | const chalk = require('chalk'); 11 | 12 | let isMultiAccountMode = false; 13 | let account = ''; 14 | let password = ''; 15 | let totalSPS = 0; 16 | let winTotal = 0; 17 | let loseTotal = 0; 18 | let undefinedTotal = 0; 19 | const ecrRecoveryRatePerHour = 1.04; 20 | 21 | // LOAD MY CARDS 22 | async function getCards() { 23 | const myCards = await user.getPlayerCards(account) 24 | return myCards; 25 | } 26 | 27 | // LOAD RENTED CARDS AS PREFERRED 28 | async function getPreferredCards() { 29 | const myPreferredCards = await user.getRentedCards(account) 30 | return myPreferredCards; 31 | } 32 | 33 | async function getQuest() { 34 | return quests.getPlayerQuest(account) 35 | .then(x=>x) 36 | .catch(e=>console.log('No quest data, splinterlands API didnt respond, or you are wrongly using the email and password instead of username and posting key')) 37 | } 38 | 39 | async function closePopups(page) { 40 | console.log('check if any modal needs to be closed...') 41 | if (await clickOnElement(page, '.close', 4000) ) return; 42 | await clickOnElement(page, '.modal-close-new', 1000, 2000); 43 | await clickOnElement(page, '.modal-close', 4000, 2000); 44 | } 45 | 46 | async function checkEcr(page) { 47 | try { 48 | const ecr = await getElementTextByXpath(page, "//div[@class='sps-options'][1]/div[@class='value'][2]/div", 100).catch((e)=> { console.log(e.message); return 1; });; 49 | if(ecr) { 50 | console.log(chalk.bold.whiteBright.bgMagenta('Your current Energy Capture Rate is ' + ecr?.split('.')[0] + "%")); 51 | return parseFloat(ecr) 52 | } 53 | } catch (e) { 54 | console.log(chalk.bold.redBright.bgBlack('ECR not defined')); 55 | } 56 | } 57 | 58 | async function findSeekingEnemyModal(page, visibleTimeout=10000) { 59 | let findOpponentDialogStatus = 0; 60 | /* findOpponentDialogStatus value list 61 | 0: modal #find_opponent_dialog has not appeared 62 | 1: modal #find_opponent_dialog has appeared and not closed 63 | 2: modal #find_opponent_dialog has appeared and closed 64 | */ 65 | 66 | console.log('check #find_opponent_dialog modal visibility'); 67 | findOpponentDialogStatus = await page.waitForSelector('#find_opponent_dialog', { timeout: visibleTimeout, visible: true }) 68 | .then(()=> { console.log('find_opponent_dialog visible'); return 1; }) 69 | .catch((e)=> { console.log(e.message); return 0; }); 70 | 71 | if (findOpponentDialogStatus === 1) { 72 | console.log('waiting for an opponent...'); 73 | findOpponentDialogStatus = await page.waitForSelector('#find_opponent_dialog', { timeout: 50000, hidden: true }) 74 | .then(()=> { console.log('find_opponent_dialog has closed'); return 2; }) 75 | .catch(async (e)=> { 76 | console.log(e.message); 77 | await reload(page); // reload the page, in case the page is not responding 78 | return 1; 79 | }); 80 | } 81 | 82 | return findOpponentDialogStatus 83 | } 84 | 85 | async function findCreateTeamButton(page, findOpponentDialogStatus=0, btnCreateTeamTimeout=5000) { 86 | console.log(`waiting for create team button`); 87 | return await page.waitForSelector('.btn--create-team', { timeout: btnCreateTeamTimeout }) 88 | .then(()=> { console.log('start the match'); return true; }) 89 | .catch(async ()=> { 90 | if (findOpponentDialogStatus === 2) console.error('Is this account timed out from battle?'); 91 | console.error('btn--create-team not detected'); 92 | return false; 93 | }); 94 | } 95 | 96 | async function launchBattle(page) { 97 | const maxRetries = 3; 98 | let retriesNum = 1; 99 | let btnCreateTeamTimeout = 50000; 100 | let findOpponentDialogStatus = await findSeekingEnemyModal(page); 101 | let isStartBattleSuccess = await findCreateTeamButton(page, findOpponentDialogStatus); 102 | 103 | while (!isStartBattleSuccess && retriesNum <= maxRetries) { 104 | console.log(`Launch battle iter-[${retriesNum}]`) 105 | if (findOpponentDialogStatus === 0) { 106 | console.log('waiting for battle button') 107 | isStartBattleSuccess = await page.waitForXPath("//button[contains(., 'BATTLE')]", { timeout: 20000 }) 108 | .then(button => { button.click(); console.log('Battle button clicked'); return true }) 109 | .catch(()=> { console.error('[ERROR] waiting for Battle button. is Splinterlands in maintenance?'); return false; }); 110 | if (!isStartBattleSuccess) { await reload(page); await sleep(5000); retriesNum++; continue } 111 | 112 | findOpponentDialogStatus = await findSeekingEnemyModal(page); 113 | } 114 | 115 | if (findOpponentDialogStatus === 1 || findOpponentDialogStatus === 2) { 116 | if (findOpponentDialogStatus === 2) { 117 | console.log('opponent found?'); 118 | btnCreateTeamTimeout = 5000; 119 | } 120 | isStartBattleSuccess = await findCreateTeamButton(page, findOpponentDialogStatus, btnCreateTeamTimeout); 121 | } 122 | 123 | if (!isStartBattleSuccess) { 124 | console.error('Refreshing the page and retrying to retrieve a battle'); 125 | await reload(page); 126 | await sleep(5000); 127 | } 128 | 129 | retriesNum++; 130 | } 131 | 132 | return isStartBattleSuccess 133 | } 134 | 135 | async function clickSummonerCard(page, teamToPlay) { 136 | let clicked = true; 137 | await sleep(3000) 138 | await page.waitForXPath(`//div[@card_detail_id="${teamToPlay.summoner}"]`, { timeout: 10000 }) 139 | .then(card => { card.click(); console.log(chalk.bold.greenBright(teamToPlay.summoner, 'clicked')); }) 140 | .catch(()=>{ 141 | clicked = false; 142 | console.log(chalk.bold.redBright('Summoner not clicked.')) 143 | }); 144 | 145 | return clicked 146 | } 147 | 148 | async function clickFilterElement(page, teamToPlay, matchDetails) { 149 | let clicked = true; 150 | const playTeamColor = teamActualSplinterToPlay(teamToPlay.cards.slice(0, 6)) || matchDetails.splinters[0] 151 | await sleep(2000) 152 | console.log('Dragon play TEAMCOLOR', playTeamColor) 153 | await page.waitForSelector('#splinter_selection_modal', { visible: true, timeout: 10000 }) 154 | .then(()=> console.log('filter element visible')) 155 | .catch(()=> console.log('filter element not visible')); 156 | 157 | await page.waitForXPath(`//div[@data-original-title="${playTeamColor}"]`, { timeout: 8000 }) 158 | .then(selector => { selector.click(); console.log(chalk.bold.greenBright('filter element clicked')) }) 159 | .catch(()=> { console.log(chalk.bold.redBright('filter element not clicked')); clicked = false; }) 160 | if (!clicked) return clicked 161 | 162 | await page.waitForSelector('#splinter_selection_modal', { hidden: true, timeout: 10000 }) 163 | .then(()=> console.log('filter element closed')) 164 | .catch(()=> { console.log('filter element not closed'); }); 165 | 166 | return clicked 167 | } 168 | 169 | async function clickMembersCard(page, teamToPlay) { 170 | let clicked = true; 171 | 172 | for (i = 1; i <= 6; i++) { 173 | console.log('play: ', teamToPlay.cards[i].toString()); 174 | if (teamToPlay.cards[i]) { 175 | await page.waitForXPath(`//div[@card_detail_id="${teamToPlay.cards[i].toString()}"]`, { timeout: 10000 }) 176 | .then(card => { card.click();console.log(chalk.bold.greenBright(teamToPlay.cards[i], 'clicked')) }) 177 | .catch(()=> { 178 | clicked = false; 179 | console.log(chalk.bold.redBright(teamToPlay.cards[i], 'not clicked')); 180 | }); 181 | if (!clicked) break 182 | } else { 183 | console.log('nocard ', i); 184 | } 185 | await page.waitForTimeout(1000); 186 | } 187 | 188 | return clicked 189 | } 190 | 191 | async function clickCreateTeamButton(page) { 192 | let clicked = true; 193 | 194 | await page.waitForSelector('.btn--create-team', { timeout: 10000 }) 195 | .then(e=> { e.click(); console.log('btn--create-team clicked'); }) 196 | .catch(()=>{ 197 | clicked = false; 198 | console.log('Create team didnt work. Did the opponent surrender?'); 199 | }); 200 | 201 | return clicked 202 | } 203 | 204 | async function clickCards(page, teamToPlay, matchDetails) { 205 | const maxRetries = 6; 206 | let retriesNum = 1; 207 | let allCardsClicked = false; 208 | 209 | while (!allCardsClicked && retriesNum <= maxRetries) { 210 | console.log(`Click cards iter-[${retriesNum}]`); 211 | if (retriesNum > 1) { 212 | await reload(page); 213 | await page.waitForTimeout(5000); 214 | if (!await clickCreateTeamButton(page)) { 215 | retriesNum++; 216 | continue 217 | } 218 | } 219 | 220 | if (!await clickSummonerCard(page, teamToPlay)) { 221 | retriesNum++; 222 | continue 223 | } 224 | 225 | if (card.color(teamToPlay.cards[0]) === 'Gold' && !await clickFilterElement(page, teamToPlay, matchDetails)) { 226 | retriesNum++; 227 | continue 228 | } 229 | await page.waitForTimeout(5000); 230 | 231 | if (!await clickMembersCard(page, teamToPlay)) { 232 | retriesNum++; 233 | continue 234 | } 235 | allCardsClicked = true; 236 | } 237 | 238 | return allCardsClicked 239 | } 240 | 241 | async function findBattleResultsModal(page) { 242 | let isBattleResultVisible = false; 243 | 244 | console.log('check div.battle-results modal visibility'); 245 | isBattleResultVisible = await page.waitForSelector('div.battle-results', { timeout: 5000, visible: true }) 246 | .then(()=> { console.log('battle results visible'); return true; }) 247 | .catch(()=> { console.log('battle results not visible'); return false; }); 248 | 249 | if (!isBattleResultVisible) return 250 | 251 | try { 252 | const winner = await getElementText(page, 'section.player.winner .bio__name__display', 15000); 253 | console.log('the winner is:',winner) 254 | if (winner.trim() == account) { 255 | const spsWon = await getElementText(page, 'section.player.winner span.sps-reward span', 1000).catch(()=> { console.log('No Rewards Found'); return 0; });; 256 | console.log(chalk.green('You won! Reward: ' + spsWon + ' SPS')); 257 | totalSps += !isNaN(parseFloat(spsWon)) ? parseFloat(spsWon) : 0 ; 258 | winTotal += 1; 259 | } 260 | else { 261 | console.log(chalk.red('You lost')); 262 | loseTotal += 1; 263 | } 264 | } catch (e) { 265 | console.log('Could not find winner - draw?', e); 266 | undefinedTotal += 1; 267 | } 268 | await clickOnElement(page, '.btn--done', 20000, 10000); 269 | await clickOnElement(page, '#menu_item_battle', 20000, 10000); 270 | 271 | console.log('Total Battles: ' + (winTotal + loseTotal + undefinedTotal) + chalk.green(' - Win Total: ' + winTotal) + chalk.yellow(' - Draw? Total: ' + undefinedTotal) + chalk.red(' - Lost Total: ' + loseTotal)); 272 | console.log(chalk.green('Total Earned: ' + totalSps + ' SPS')); 273 | 274 | return true 275 | } 276 | 277 | async function commenceBattle(page) { 278 | let waitForOpponentDialogStatus = 0; 279 | /* waitForOpponentDialogStatus value list 280 | 0: modal #wait_for_opponent_dialog has not appeared 281 | 1: modal #wait_for_opponent_dialog has appeared and not closed 282 | */ 283 | let btnSkipTimeout = 20000; 284 | 285 | console.log('check #wait_for_opponent_dialog modal visibility'); 286 | waitForOpponentDialogStatus = await page.waitForSelector('#wait_for_opponent_dialog', { timeout: 10000, visible: true }) 287 | .then(()=> { console.log('wait_for_opponent_dialog visible'); return 1; }) 288 | .catch(()=> { console.log('wait_for_opponent_dialog not visible'); return 0; }); 289 | 290 | if (waitForOpponentDialogStatus === 1) { 291 | await page.waitForSelector('#wait_for_opponent_dialog', { timeout: 100000, hidden: true }) 292 | .then(()=> { console.log('wait_for_opponent_dialog has closed'); btnSkipTimeout = 5000; }) 293 | .catch((e)=> console.log(e.message)); 294 | } 295 | 296 | await page.waitForTimeout(5000); 297 | const isBtnSkipVisible = await page.waitForSelector('#btnSkip', { timeout: btnSkipTimeout }) 298 | .then(()=> { console.log('btnRumble visible'); return true; }) 299 | .catch(()=> { console.log('btnRumble not visible'); return false; }); 300 | // if btnRumble not visible, check battle results modal in case the opponent surrendered 301 | if (!isBtnSkipVisible && await findBattleResultsModal(page)) return 302 | else if (!isBtnSkipVisible) return 303 | 304 | //await page.waitForTimeout(5000); 305 | //await page.$eval('#btnRumble', elem => elem.click()).then(()=>console.log('btnRumble clicked')).catch(()=>console.log('btnRumble didnt click')); //start rumble 306 | await page.waitForSelector('#btnSkip', { timeout: 30000 }).then(()=>console.log('btnSkip visible')).catch(()=>console.log('btnSkip not visible')); 307 | await page.$eval('#btnSkip', elem => elem.click()).then(()=>console.log('btnSkip clicked')).catch(()=>console.log('btnSkip not visible')); //skip rumble 308 | await page.waitForTimeout(5000); 309 | 310 | await findBattleResultsModal(page); 311 | } 312 | 313 | async function startBotPlayMatch(page, browser) { 314 | 315 | console.log( new Date().toLocaleString(), 'opening browser...') 316 | try { 317 | await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3163.100 Safari/537.36'); 318 | await page.setViewport({ 319 | width: 1800, 320 | height: 1500, 321 | deviceScaleFactor: 1, 322 | }); 323 | 324 | await page.goto('https://splinterlands.com/'); 325 | await page.waitForTimeout(5000); 326 | 327 | let item = await page.waitForSelector('#log_in_button > button', { 328 | visible: true, 329 | }) 330 | .then(res => res) 331 | .catch(()=> console.log('Already logged in')) 332 | 333 | if (item != undefined) 334 | {console.log('Login attempt...') 335 | await splinterlandsPage.login(page, account, password).catch(e=>{ 336 | console.log(e); 337 | throw new Error('Login Error'); 338 | }); 339 | } 340 | 341 | await page.goto('https://splinterlands.com/?p=battle_history'); 342 | await page.waitForTimeout(8000); 343 | await closePopups(page); 344 | await closePopups(page); 345 | await clickOnElement(page, '#bh_wild_toggle', 1000, 2000); 346 | 347 | const ecr = await checkEcr(page); 348 | if (ecr === undefined) throw new Error('Fail to get ECR.') 349 | 350 | if (process.env.ECR_STOP_LIMIT && process.env.ECR_RECOVER_TO && ecr < parseFloat(process.env.ECR_STOP_LIMIT)) { 351 | if (ecr < parseFloat(process.env.ECR_STOP_LIMIT)) { 352 | console.log(chalk.bold.red(`ECR lower than limit ${process.env.ECR_STOP_LIMIT}%. reduce the limit in the env file config or wait until ECR will be at ${process.env.ECR_RECOVER_TO || '100'}%`)); 353 | } else if (ecr < parseFloat(process.env.ECR_RECOVER_TO)) { 354 | console.log(chalk.bold.red(`ECR Not yet Recovered to ${process.env.ECR_RECOVER_TO}`)); 355 | } 356 | 357 | // calculating time needed for recovery 358 | ecrNeededToRecover = parseFloat(process.env.ECR_RECOVER_TO) - parseFloat(ecr); 359 | recoveryTimeInHours = Math.ceil(ecrNeededToRecover / ecrRecoveryRatePerHour); 360 | 361 | console.log(chalk.bold.white(`Time needed to recover ECR, approximately ${recoveryTimeInHours * 60} minutes.`)); 362 | await closeBrowser(browser); 363 | console.log(chalk.bold.white(`Initiating sleep mode. The bot will awaken at ${new Date(Date.now() + recoveryTimeInHours * 3600 * 1000).toLocaleString()}`)); 364 | await sleep(recoveryTimeInHours * 3600 * 1000); 365 | 366 | throw new Error(`Restart needed.`); 367 | } 368 | 369 | console.log('getting user quest info from splinterlands API...') 370 | const quest = await getQuest(); 371 | if(!quest) { 372 | console.log('Error for quest details. Splinterlands API didnt work or you used incorrect username, remove @ and dont use email') 373 | } 374 | 375 | if(process.env.SKIP_QUEST && quest?.splinter && process.env.SKIP_QUEST.split(',').includes(quest?.splinter) && quest?.total !== quest?.completed) { 376 | try { 377 | await page.click('#focus_new_btn') 378 | .then(async a=>{ 379 | await page.reload(); 380 | console.log('New quest requested')}) 381 | .catch(e=>console.log('Cannot click on new quest')) 382 | 383 | } catch(e) { 384 | console.log('Error while skipping new quest') 385 | } 386 | } 387 | 388 | console.log('getting user cards collection from splinterlands API...') 389 | const myCards = await getCards() 390 | .then((x)=>{console.log('cards retrieved:',x?.length); return x}) 391 | .catch(()=>console.log('cards collection api didnt respond. Did you use username? avoid email!')); 392 | 393 | const myPreferredCards = await getPreferredCards() 394 | .then((x)=>{console.log('delegated cards size:', x?.length, x); return x}) 395 | .catch(()=>console.log('cards collection api didnt respond. Did you use username? avoid email!')); 396 | 397 | if(myCards) { 398 | console.log(account, ' deck size: '+myCards.length) 399 | } else { 400 | console.log(account, ' playing only basic cards') 401 | } 402 | 403 | //check if season reward is available 404 | if (process.env.CLAIM_SEASON_REWARD === 'true') { 405 | try { 406 | console.log('Season reward check: '); 407 | await page.waitForSelector('#claim-btn', { visible:true, timeout: 3000 }) 408 | .then(async (button) => { 409 | button.click(); 410 | console.log(`claiming the season reward. you can check them here https://peakmonsters.com/@${account}/explorer`); 411 | await page.waitForTimeout(20000); 412 | await page.reload(); 413 | 414 | }) 415 | .catch(()=>console.log(`no season reward to be claimed, but you can still check your data here https://peakmonsters.com/@${account}/explorer`)); 416 | await page.waitForTimeout(3000); 417 | await page.reload(); 418 | } 419 | catch (e) { 420 | console.info('no season reward to be claimed') 421 | } 422 | } 423 | 424 | //if quest done claim reward. default to true. to deactivate daily quest rewards claim, set CLAIM_DAILY_QUEST_REWARD false in the env file 425 | console.log('claim daily quest setting:', process.env.CLAIM_DAILY_QUEST_REWARD, 'Quest details: ', quest); 426 | const isClaimDailyQuestMode = process.env.CLAIM_DAILY_QUEST_REWARD === 'false' ? false : true; 427 | if (isClaimDailyQuestMode === true) { 428 | try { 429 | await page.waitForSelector('#quest_claim_btn', { timeout: 5000 }) 430 | .then(button => button.click()) 431 | .then(async a=>{ 432 | await page.waitForTimeout(15000); 433 | await page.reload(); 434 | console.log('Quest claimed')}) 435 | .then(()=>page.goto('https://splinterlands.com/?p=battle_history')); 436 | } catch (e) { 437 | console.info('no quest reward to be claimed waiting for the battle...') 438 | } 439 | } 440 | await page.waitForTimeout(5000); 441 | 442 | // LAUNCH the battle 443 | if (!await launchBattle(page)) throw new Error('The Battle cannot start'); 444 | 445 | // GET MANA, RULES, SPLINTERS, AND POSSIBLE TEAM 446 | await page.waitForTimeout(10000); 447 | let [mana, rules, splinters] = await Promise.all([ 448 | splinterlandsPage.checkMatchMana(page).then((mana) => mana).catch(() => 'no mana'), 449 | splinterlandsPage.checkMatchRules(page).then((rulesArray) => rulesArray).catch(() => 'no rules'), 450 | splinterlandsPage.checkMatchActiveSplinters(page).then((splinters) => splinters).catch(() => 'no splinters') 451 | ]); 452 | 453 | const matchDetails = { 454 | mana: mana, 455 | rules: rules, 456 | splinters: splinters, 457 | myCards: myCards, 458 | preferredCards: myPreferredCards 459 | } 460 | await page.waitForTimeout(2000); 461 | const possibleTeams = await ask.possibleTeams(matchDetails, account).catch(e=>console.log('Error from possible team API call: ',e)); 462 | 463 | if (possibleTeams && possibleTeams.length) { 464 | console.log('Possible Teams based on your cards: ', possibleTeams.length); 465 | } else { 466 | console.log('Error:', matchDetails, possibleTeams) 467 | throw new Error('NO TEAMS available to be played'); 468 | } 469 | 470 | //TEAM SELECTION 471 | const teamToPlay = await ask.teamSelection(possibleTeams, matchDetails, quest, page.favouriteDeck); 472 | let startFight = false; 473 | if (teamToPlay) { 474 | startFight = await clickCreateTeamButton(page); 475 | if (!startFight) { 476 | // if click create team button fails, check battle results in case the opponent surrendered 477 | if (await findBattleResultsModal(page)) { 478 | return 479 | } else { 480 | console.log('Create team didnt work, waiting 5 sec and retry'); 481 | await page.reload(); 482 | await page.waitForTimeout(5000); 483 | startFight = await clickCreateTeamButton(page); 484 | } 485 | } 486 | 487 | if (!startFight) { 488 | // if click create team button fails, check battle results in case the opponent surrendered 489 | await findBattleResultsModal(page); 490 | return 491 | } 492 | } else { 493 | console.log(teamToPlay) 494 | throw new Error('Team Selection error: no possible team to play'); 495 | } 496 | 497 | await page.waitForTimeout(5000); 498 | 499 | // Click cards based on teamToPlay value. 500 | startFight = await clickCards(page, teamToPlay, matchDetails); 501 | if (!startFight) return 502 | 503 | // start fight 504 | await page.waitForTimeout(5000); 505 | await page.waitForSelector('.btn-green', { timeout: 1000 }).then(()=>console.log('btn-green visible')).catch(()=>console.log('btn-green not visible')); 506 | await page.$eval('.btn-green', elem => elem.click()) 507 | .then(()=>console.log('btn-green clicked')) 508 | .catch(async ()=>{ 509 | console.log('Start Fight didnt work, waiting 5 sec and retry'); 510 | await page.waitForTimeout(5000); 511 | await page.$eval('.btn-green', elem => elem.click()) 512 | .then(()=>console.log('btn-green clicked')) 513 | .catch(()=>{ 514 | startFight = false; 515 | console.log('Start Fight didnt work. Did the opponent surrender?'); 516 | }); 517 | }); 518 | 519 | if (startFight) await commenceBattle(page); 520 | else await findBattleResultsModal(page); 521 | } catch (e) { 522 | console.log('Error handling browser not opened, internet connection issues, or battle cannot start:', e) 523 | } 524 | } 525 | 526 | // 30 MINUTES INTERVAL BETWEEN EACH MATCH (if not specified in the .env file) 527 | const sleepingTimeInMinutes = process.env.MINUTES_BATTLES_INTERVAL || 30; 528 | const sleepingTime = sleepingTimeInMinutes * 60000; 529 | const isHeadlessMode = process.env.HEADLESS === 'false' ? false : true; 530 | const executablePath = process.env.CHROME_EXEC || null; 531 | let puppeteer_options = { 532 | headless: isHeadlessMode, // default is true 533 | args: ['--no-sandbox', 534 | '--disable-setuid-sandbox', 535 | //'--disable-dev-shm-usage', 536 | //'--disable-accelerated-2d-canvas', 537 | // '--disable-canvas-aa', 538 | // '--disable-2d-canvas-clip-aa', 539 | //'--disable-gl-drawing-for-tests', 540 | // '--no-first-run', 541 | // '--no-zygote', 542 | '--disable-dev-shm-usage', 543 | // '--use-gl=swiftshader', 544 | // '--single-process', // <- this one doesn't works in Windows 545 | // '--disable-gpu', 546 | // '--enable-webgl', 547 | // '--hide-scrollbars', 548 | '--mute-audio', 549 | // '--disable-infobars', 550 | // '--disable-breakpad', 551 | '--disable-web-security'] 552 | } 553 | if (executablePath) { 554 | puppeteer_options['executablePath'] = executablePath; 555 | } 556 | 557 | 558 | const blockedResources = [ 559 | 'splinterlands.com/players/item_details', 560 | 'splinterlands.com/players/event', 561 | 'splinterlands.com/market/for_sale_grouped', 562 | 'splinterlands.com/battle/history2', 563 | 'splinterlands.com/players/messages', 564 | 'facebook.com', 565 | 'google-analytics.com', 566 | 'twitter.com', 567 | ]; 568 | 569 | async function run() { 570 | let start = true 571 | 572 | console.log('START ', account, new Date().toLocaleString()) 573 | const browser = await puppeteer.launch(puppeteer_options); 574 | 575 | //const page = await browser.newPage(); 576 | let [page] = await browser.pages(); 577 | 578 | // NOT WORKING on ALL the machines 579 | // await page.setRequestInterception(true); 580 | // page.on('request', (interceptedRequest) => { 581 | // // console.log("URL: " + interceptedRequest.url()) 582 | // // page.on('request', (request) => { 583 | // // BLOCK CERTAIN DOMAINS 584 | // if (blockedResources.some(resource => interceptedRequest.url().includes(resource))){ 585 | // // console.log("Blocked: " + interceptedRequest.url()); 586 | // interceptedRequest.abort(); 587 | // // ALLOW OTHER REQUESTS 588 | // } else { 589 | // interceptedRequest.continue(); 590 | // } 591 | // }); 592 | await page.setDefaultNavigationTimeout(500000); 593 | await page.on('dialog', async dialog => { 594 | await dialog.accept(); 595 | }); 596 | await page.on('error', function(err) { 597 | const errorMessage = err.toString(); 598 | console.log('browser error: ', errorMessage) 599 | }); 600 | await page.on('pageerror', function(err) { 601 | const errorMessage = err.toString(); 602 | console.log('browser page error: ', errorMessage) 603 | }); 604 | page.goto('https://splinterlands.com/'); 605 | page.recoverStatus = 0; 606 | page.favouriteDeck = process.env.FAVOURITE_DECK || ''; 607 | while (start) { 608 | console.log('Recover Status: ', page.recoverStatus) 609 | if(!process.env.API) { 610 | console.log(chalk.bold.redBright.bgBlack('Dont pay scammers!')); 611 | console.log(chalk.bold.whiteBright.bgBlack('If you need support for the bot, join the telegram group https://t.me/splinterlandsbot and discord https://discord.gg/bR6cZDsFSX')); 612 | console.log(chalk.bold.greenBright.bgBlack('If you interested in a higher winning rate with the private API, contact the owner via discord or telegram')); 613 | } 614 | await startBotPlayMatch(page, browser) 615 | .then(async () => { 616 | console.log('Closing battle', new Date().toLocaleString()); 617 | 618 | if (isMultiAccountMode) { 619 | start = false; 620 | await closeBrowser(browser); 621 | } else { 622 | await page.waitForTimeout(5000); 623 | console.log(account, 'waiting for the next battle in', sleepingTime / 1000 / 60 , 'minutes at', new Date(Date.now() + sleepingTime).toLocaleString()); 624 | await sleep(sleepingTime); 625 | } 626 | }) 627 | .catch((e) => { 628 | console.log(e); 629 | start = false; 630 | }) 631 | } 632 | if (!isMultiAccountMode) { 633 | await restart(browser); 634 | } 635 | } 636 | 637 | async function closeBrowser(browser) { 638 | console.log('Closing browser...') 639 | await browser.close() 640 | .then(()=>{console.log('Browser closed.')}) 641 | .catch((e)=>{console.log(chalk.bold.redBright.bgBlack('Fail to close browser. Reason:'), chalk.bold.whiteBright.bgBlack(e.message))}); 642 | } 643 | 644 | async function restart(browser) { 645 | console.log(chalk.bold.redBright.bgBlack('Restarting bot...')) 646 | await closeBrowser(browser); 647 | await run(); 648 | } 649 | 650 | function setupAccount(uname, pword, multiAcc) { 651 | account = uname; 652 | password = pword; 653 | isMultiAccountMode = multiAcc; 654 | } 655 | 656 | exports.run = run; 657 | exports.setupAccount = setupAccount; -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------