· 5 years ago · Jan 08, 2020, 05:58 PM
1const tmi = require("tmi.js");
2const fs = require("fs");
3
4let bettingStarted = "False";
5let bettingEnded = "False";
6
7let totalBlueShrooms = 0;
8let totalRedShrooms = 0;
9let totalBlueBets = 0;
10let totalRedBets = 0;
11
12let betTime;
13let betStartDate;
14let betStartTime;
15
16let didBet = "False";
17let betAmount = 0;
18let underdog = "none";
19let currentBalance = 0;
20
21// Define configuration options
22const opts = {
23 identity: {
24 username: "username",
25 password: "oauth:token"
26 },
27 connection: {
28 secure: true,
29 reconnect: true
30 },
31 channels: ["saltyteemo"]
32};
33
34// Create a client with our options
35const client = new tmi.client(opts);
36
37// Register our event handlers (defined below)
38client.on("message", onMessageHandler);
39client.on("connected", onConnectedHandler);
40
41// Connect to Twitch:
42client.connect();
43
44// Called every time a message comes in
45function onMessageHandler(target, context, message, self) {
46 // // Ignore messages from the bot
47 // if (self) {
48 // return;
49 // }
50
51 // Remove whitespace from chat message
52 const messageContent = message.trim();
53
54 /*
55 #######################################################
56 ###### Handling messages from user "xxsaltbotxx" ######
57 #######################################################
58 */
59
60 if (context.username.trim() === "xxsaltbotxx") {
61 // read balance from chat if toggled
62 if (
63 messageContent.includes("@" + opts.identity.username + " - You have ")
64 ) {
65 parseCurrentBalance(messageContent);
66 }
67
68 // Handling bet messages from users
69 if (messageContent.includes("Bet complete")) {
70 // check if it is the first bet this round
71 if (!bettingStarted.includes("True")) {
72 handleFirstBet(target);
73 }
74 // Parses user messages to extract bet details
75 handleUserBets(messageContent);
76 }
77 }
78
79 // Bet if current bet cycle reached 160 seconds
80 if (betTime >= 155000 && didBet.includes("False")) {
81 console.log("Starting betting sequence");
82 console.log("didBet: " + didBet + "betTime: " + betTime);
83 bet(target);
84 }
85
86 // Detect End of Betting Phase
87 if (
88 (context.username.trim() === "xxsaltbotxx" &&
89 messageContent.includes("Betting has ended")) ||
90 betTime > 220000
91 ) {
92 if (!bettingEnded.includes("True")) {
93 console.log("Betting Has Ended!");
94 //processMatchHistory();
95 }
96 // Mark current betting round as ended and reset bet cycle variables
97 resetBetCycle();
98 }
99}
100
101function parseCurrentBalance(msg) {
102 let balanceSplit = msg.split(" ");
103 currentBalance = parseInt(balanceSplit[4]);
104 console.log("Current Balance: " + currentBalance);
105}
106
107function handleFirstBet(channel) {
108 console.log("Betting Has Started");
109 client.say(channel, "!balance");
110 // Determine timestamp of the first bet
111 betStartDate = new Date();
112 betStartTime = betStartDate.getTime();
113
114 // Mark current betting round as started
115 bettingStarted = "True";
116 bettingEnded = "False";
117}
118
119function handleUserBets(msg) {
120 let splits = msg.split(" ");
121 let team = splits[5].substring(0, splits[5].length - 1);
122 let amount = parseInt(splits[6].substring(0, splits[6].length - 1));
123 if (team.includes("BLUE")) {
124 totalBlueShrooms += amount;
125 totalBlueBets += 1;
126 } else {
127 totalRedShrooms += amount;
128 totalRedBets += 1;
129 }
130
131 // Prints total bets and amounts for each team after each bet
132 console.log(
133 "Blue: " + totalBlueShrooms + " Shrooms | " + totalBlueBets + " Bets"
134 );
135 console.log(
136 "Red: " + totalRedShrooms + " Shrooms | " + totalRedBets + " Bets\n"
137 );
138
139 // Calculate duration of current bet cycle
140 currentDate = new Date();
141 currentTime = currentDate.getTime();
142 betTime = currentTime - betStartTime;
143
144 console.log("Bet Timer: " + Math.floor(betTime / 1000));
145}
146
147function bet(channel) {
148 underdog = totalBlueShrooms > totalRedShrooms ? "red" : "blue";
149 betAmount = Math.floor(currentBalance / 10);
150 console.log("BEFORE BETTING");
151 client.say(channel, `!${underdog} ${betAmount}`);
152 console.log("AFTER BETTING");
153 console.log(`Bot bet ${betAmount} on ${underdog}`);
154 didBet = "True";
155}
156
157function processMatchHistory() {
158 // calculate pay out ratio if successful
159 let payOutRatio = underdog.includes("blue")
160 ? totalRedShrooms / totalBlueShrooms
161 : totalBlueShrooms / totalRedShrooms;
162 // read match-history.json and parse it as JSON
163 let rawdata = fs.readFileSync("match-history.json");
164 let matchHistoryJSON = JSON.parse(rawdata);
165
166 // Determine winner of previous match by comparing current balance with balance before last bet
167 let previousMatch = matchHistoryJSON.games[matchHistoryJSON.games.length - 1];
168 previousMatch.winner =
169 previousMatch.balance < currentBalance
170 ? previousMatch.betOn
171 : previousMatch.betOn.includes("red")
172 ? "blue"
173 : "red";
174
175 // populate match data to be stored in JSON
176 let jsonString = {
177 balance: currentBalance,
178 betTime: betTime,
179 blueShrooms: totalBlueShrooms,
180 redShrooms: totalRedShrooms,
181 blueBets: totalBlueBets,
182 redBets: totalRedBets,
183 payOutRatio: payOutRatio,
184 betOn: underdog,
185 amountBet: betAmount,
186 winner: "na"
187 };
188 // store match data in JSON object
189 matchHistoryJSON.games.push(jsonString);
190 // write JSON object to file
191 fs.writeFileSync("match-history.json", JSON.stringify(matchHistoryJSON));
192}
193
194function resetBetCycle() {
195 bettingEnded = "True";
196 bettingStarted = "False";
197 betTime = 0;
198 totalRedShrooms = 0;
199 totalBlueShrooms = 0;
200 totalBlueBets = 0;
201 totalRedBets = 0;
202 didBet = "False";
203}
204
205// Called every time the bot connects to Twitch chat
206function onConnectedHandler(addr, port) {
207 console.log(`* Connected to ${addr}:${port}`);
208}