-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathindex.ts
754 lines (622 loc) · 24.3 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
import MinecraftData from 'minecraft-data'
import mineflayer, { Bot, createBot } from 'mineflayer'
import { Entity, EntityType } from 'prismarine-entity'
import { Window } from 'prismarine-windows'
import { Item as PrismarineItem } from 'prismarine-item'
import {goals, Movements, pathfinder} from 'mineflayer-pathfinder'
const {GoalBlock, GoalFollow, GoalXZ, GoalY} = goals
import Discord, { AnyChannel, Client, Intents, MessageEmbed, TextChannel } from 'discord.js'
import { NewPingResult, OldPingResult } from 'minecraft-protocol'
import { ChatMessage } from 'prismarine-chat'
import express from 'express'
import fs from 'fs'
import helmet from 'helmet'
import commands from './data/commands'
import bible from './data/bible'
import spam from './data/spam'
import { serverModules } from './modules'
import discordConfig from './discord.json'
import { serverConfigs } from './config'
import ud from "urban-dictionary";
import mc from "minecraft-protocol";
import ErrnoException = NodeJS.ErrnoException;
const inventoryViewer = require('mineflayer-web-inventory')
const tpsPlugin = require('mineflayer-tps')(mineflayer)
const armorManager = require('mineflayer-armor-manager')
const autoEat = require('mineflayer-auto-eat')
const viewer = require('prismarine-viewer').mineflayer
const client: Client = new Discord.Client({ intents: [Intents.FLAGS.GUILDS] })
const app = express()
type serverType = '7b7t'
const server: serverType = process.argv[2] as serverType
const secretsFile = await import('./secrets.json')
const serverSecrets = secretsFile[server]
const modules = serverModules[server]
const config = serverConfigs[server]
let isEating = false
let end = false
const time: number = 10
const bot: PistonBot = createBot({
host: config.host,
username: secretsFile.email,
password: secretsFile.password,
port: config.port,
version: config.version,
checkTimeoutInterval: 300 * 1000
}) as PistonBot
const mcData: MinecraftData.IndexedData = require('minecraft-data')(bot.version)
const weapons: number[] = [
mcData.itemsByName.diamond_sword.id,
mcData.itemsByName.golden_sword.id,
mcData.itemsByName.iron_sword.id,
mcData.itemsByName.stone_sword.id,
mcData.itemsByName.wooden_sword.id
]
bot.loadPlugin(pathfinder)
bot.loadPlugin(tpsPlugin)
bot.loadPlugin(armorManager)
bot.loadPlugin(autoEat)
bot.on('spawn', function () {
fs.writeFile('./time.txt', time.toString(), function (err: ErrnoException | null) {
console.log(err)
})
bot.autoEat.options = {
priority: 'foodPoints',
startAt: 14,
bannedFood: []
}
if (serverSecrets.ingamepassword !== undefined) {
bot.chat(`/login ${serverSecrets.ingamepassword}`)
}
})
function text (username: string, message: string, whisper: boolean): void {
fs.writeFile('./time.txt', time.toString(), function (err: any) {
console.log(err)
})
let playerJoin = require('./data/playerjoin.json')
let playerData: any = require('./data/playerdata.json')
const prefix: string = whisper ? `/tell ${username}` : ''
const args: string[] = message.split(' ').slice(1)
const defaultMove = new Movements(bot, mcData)
console.log(`${username} ${message} (${whisper})`)
if (message.includes('/login')) {
bot.chat(`/login ${serverSecrets.ingamepassword}`)
}
if (username === undefined) return
if (username === 'whispers') return
if (username === 'you') return
if (username === 'queue') return
if (username === bot.username) return
const channel: AnyChannel | undefined = client.channels.cache.get(config.bridge)
if (channel !== undefined && !whisper) {
const embed: MessageEmbed = new Discord.MessageEmbed()
.setColor('#C970D9')
.setURL(discordConfig.website)
.addField(username.replace('@', '(at)'), message.replace('@', '(at)'), true)
.setTimestamp()
.setFooter({
text: 'PistonBot made by Pistonmaster',
iconURL: 'https://avatars0.githubusercontent.com/u/40795980?s=460&v=4'
})
if (channel instanceof TextChannel) {
channel.send({ embeds: [embed] }).then(() => {
console.log('Sent message to Discord')
}).catch(() => {
console.log('Failed to send message to Discord')
})
}
}
// ONLY COMMAND
if (message.startsWith('_hi') && modules.hi) {
bot.chat(`Hi ${username}! Nice to meet you! <3`)
}
if (message.startsWith('_coords') && modules.coords) {
bot.chat(`${prefix} My coords are: ${bot.entity.position.x} ${bot.entity.position.y} ${bot.entity.position.z}`)
}
if (message.startsWith('_tps') && modules.tps) {
bot.chat(`${prefix} Current tps: ${bot.getTps()}`)
}
if ((message.startsWith('_bible') || message.startsWith('_verse')) && modules.bible) {
bot.chat(`${prefix} ${bible.proverbs[Math.round(Math.random() * (bible.proverbs.length - 1))]}`)
}
if (message.startsWith('_about') && modules.about) {
bot.chat(`${prefix} PistonBot coded by Pistonmaster with <3!`)
}
if (message.startsWith('_rules') && modules.rules) {
bot.chat(`${prefix} no`)
}
if (message.startsWith('_no')) {
bot.chat(`${prefix} NO!`)
}
if (message.startsWith('_yes')) {
bot.chat(`${prefix} YES!`)
}
if (message.startsWith('_help')) {
bot.chat(`/tell ${username} PistonBot help: _tps, _ping, _coords, _tpa, _tpy, _rules, _report, _bible, _about, _goto, _come, _stop, _rm, _lm, _fm, _wm, _urban, _discord`)
}
if (message.startsWith('_discord')) {
bot.chat(`/tell ${username} https://discord.gg/zBPKyC5`)
}
if (message.startsWith('_tpa') && modules.tp) {
if (args.length === 1) {
if ((bot.entity.position.x >= 1000 || bot.entity.position.x <= -1000) || (bot.entity.position.z >= 1000 || bot.entity.position.z <= -1000)) {
bot.chat(`/tpa ${args[0]}`)
} else {
bot.chat(`${prefix} Sorry i am not 1000 blocks away from spawn. :(`)
}
} else {
bot.chat(`${prefix} Sorry you should use: _tpa username`)
}
}
if (message.startsWith('_tpy') && modules.tp) {
if (args.length === 1) {
bot.chat(`/tpy ${args[0]}`)
} else {
bot.chat(`${prefix} Sorry you should use: _tpy username`)
}
}
if (message.startsWith('_report') && modules.report) {
if (args.length >= 2) {
bot.chat(`${prefix} Reported ${args[0]} for ${message.replace('_report ' + args[0], '')}`)
} else {
bot.chat(`${prefix} Sorry you should use: _report username reason`)
}
}
if (modules.navigation && !whisper) {
if (message.startsWith('_stop')) {
if (bot.players[username] === undefined || bot.players[username].entity == null) {
bot.chat('Sorry only player, which I see are allowed to use this command')
} else {
bot.chat('Stopping')
bot.pathfinder.setMovements(defaultMove)
bot.pathfinder.setGoal(new GoalBlock(bot.entity.position.x, bot.entity.position.y, bot.entity.position.z))
bot.clearControlStates()
}
}
if (message.startsWith('_follow')) {
if (bot.players[username] === undefined || bot.players[username].entity == null) {
bot.chat(`${username} it seems like your out of range`)
} else {
const target = bot.players[username].entity
bot.chat(`Starting to follow ${username}`)
bot.pathfinder.setMovements(defaultMove)
bot.pathfinder.setGoal(new GoalFollow(target, 3), true)
}
}
if (message.startsWith('_goto')) {
const cmd = message.split(' ')
if (cmd.length === 4) { // goto x y z
const x = parseInt(cmd[1], 10)
const y = parseInt(cmd[2], 10)
const z = parseInt(cmd[3], 10)
bot.pathfinder.setMovements(defaultMove)
bot.pathfinder.setGoal(new GoalBlock(x, y, z))
bot.chat(`Going to x${x} y${y} z${z}`)
} else if (cmd.length === 3) { // goto x z
const x = parseInt(cmd[1], 10)
const z = parseInt(cmd[2], 10)
bot.pathfinder.setMovements(defaultMove)
bot.pathfinder.setGoal(new GoalXZ(x, z))
bot.chat(`Going to x${x} z${z}`)
} else if (cmd.length === 2) { // goto y
const y = parseInt(cmd[1], 10)
bot.pathfinder.setMovements(defaultMove)
bot.pathfinder.setGoal(new GoalY(y))
bot.chat(`Going to y${y}`)
}
}
}
if (message.startsWith('_ping') && modules.ping) {
if (args.length === 0) {
if (bot.players[username]) {
bot.chat(`${prefix} ${username} your ping is: ${bot.players[username].ping}`)
} else {
bot.chat(`${prefix} Sorry I can only ping players`)
}
} else if (args.length >= 1) {
if (bot.players[args[0]]) {
if (args[0] === username) {
if (bot.players[username]) {
bot.chat(`${prefix} ${username} your ping is: ${bot.players[username].ping}`)
} else {
bot.chat(`${prefix} Sorry I can only ping players`)
}
} else {
bot.chat(`${prefix} The ping of ${bot.players[args[0]].username} is: ${bot.players[args[0]].ping}`)
}
} else {
if (bot.players[username]) {
bot.chat(`${prefix} ${username} your ping is: ${bot.players[username].ping}`)
} else {
bot.chat(`${prefix} Sorry I can only ping players`)
}
}
}
}
// PRIVATE COMMANDS
if (message.startsWith('_urban ')) {
const term = message.slice(7)
ud.define(term, (error, entries) => {
if (error) {
console.error(error.message)
} else {
let urbanAnswer = entries[0].definition
urbanAnswer = urbanAnswer.replace(/(\r\n|\r|\n)/g, '').substring(0, 200)
console.log(urbanAnswer)
bot.chat(`/tell ${username} ${urbanAnswer}`)
}
})
}
if (message.startsWith('_wm')) {
playerJoin = require('./data/playerjoin.json')
if (Object.keys(playerJoin).includes(username)) {
console.log('Player is in the database. Reading the state.')
if (playerJoin[username]) {
playerJoin[username] = false
bot.chat(`${prefix} Deactivated welcome message. You can toggle them with: _wm`)
} else {
playerJoin[username] = true
bot.chat(`${prefix} Activated welcome message. You can toggle them with: _wm`)
}
} else {
console.log('Player is not in the database. Adding the player and setting it to true.')
bot.chat(`${prefix} Activated welcome message. You can toggle them with: _wm`)
playerJoin[username] = true
}
fs.writeFileSync('./data/playerjoin.json', JSON.stringify(playerJoin, null, 4))
}
if (message.startsWith('_fm') || message.startsWith('_firstmessage')) {
if (args.length === 0) {
if (Object.keys(playerData).includes(username) && playerData[username][0] !== undefined) {
bot.chat(`${prefix} ${username} your first message, which I recorded was: ${playerData[username][0]}`)
} else {
bot.chat(`${prefix} ${username} sorry I didnt record any messages from you.`)
}
} else if (args.length === 1) {
if (Object.keys(playerData).includes(args[0]) && playerData[args[0]][0] !== undefined) {
bot.chat(`${prefix} ${username} here is the first message, which I recorded from ${args[0]}: ${playerData[args[0]][0]}`)
} else {
bot.chat(`${prefix} ${username} sorry I didnt record any messages from ${args[0]}.`)
}
} else if (args.length > 1) {
bot.chat(`${prefix} Please use: _fm username or _fm`)
}
}
if (message.startsWith('_lm') || message.startsWith('_lastmessage')) {
if (args.length === 0) {
if (Object.keys(playerData).includes(username) && playerData[username][0] !== undefined) {
bot.chat(`${prefix} ${username} your last message, which I recorded was: ${playerData[username][playerData[username].length - 1]}`)
} else {
bot.chat(`${prefix} ${username} sorry I didnt record any messages from you.`)
}
} else if (args.length === 1) {
if (Object.keys(playerData).includes(args[0]) && playerData[args[0]][0] !== undefined) {
bot.chat(`${prefix} ${username} here is the last message, which I recorded from ${args[0]}: ${playerData[args[0]][playerData[args[0]].length - 1]}`)
} else {
bot.chat(`${prefix} ${username} sorry I didnt record any messages from ${args[0]}.`)
}
} else if (args.length > 1) {
bot.chat(`${prefix} Please use: _lm username or _lm`)
}
}
if (message.startsWith('_rm') || message.startsWith('_randommessage')) {
if (args.length === 0) {
if (Object.keys(playerData).includes(username) && playerData[username][0] !== undefined) {
bot.chat(`${prefix} ${username} here is a random message which I recorded from you: ${playerData[username][Math.round(Math.random() * (playerData[username].length - 1))]}`)
} else {
bot.chat(`${prefix} ${username} sorry I didn't record any messages from you.`)
}
} else if (args.length === 1) {
if (Object.keys(playerData).includes(args[0]) && playerData[args[0]][0] !== undefined) {
bot.chat(`${prefix} ${username} here is a random message which I recorded from ${args[0]}: ${playerData[args[0]][Math.round(Math.random() * (playerData[args[0]].length - 1))]}`)
} else {
bot.chat(`${prefix} ${username} sorry I didnt record any messages from ${args[0]}.`)
}
} else if (args.length > 1) {
bot.chat(`${prefix} Please use: _rm username or _rm`)
}
}
if (username === 'Pistonmaster') {
if (message.startsWith('_phrases')) {
playerData = require('./data/playerdata.json')
bot.chat(prefix + 'Calculating amount of all saved phrases.')
let amount1 = 0
for (const player1 in playerData) {
amount1 = amount1 + playerData[player1].length
}
setTimeout(() => bot.chat(`${prefix} Amount of ALL phrases: ${amount1}`), 2000)
}
if (message.startsWith('_words')) {
playerData = require('./data/playerdata.json')
bot.chat(`${prefix} Calculating amount of all saved words.`)
let amount2 = 0
for (const player in playerData) {
for (const phraseIndex in playerData[player]) {
const phraseText = playerData[player][phraseIndex]
const phraseSplit = phraseText.split(' ')
amount2 = amount2 + phraseSplit.length
}
}
setTimeout(() => bot.chat(`${prefix} Amount of ALL words: ${amount2}`), 2000)
}
if (message.startsWith('_say')) {
bot.chat(message.replace('_say ', ''))
}
if (message.startsWith('_killbot')) {
bot.chat('/kill')
}
}
if (!whisper && !message.startsWith('_')) {
if (Object.keys(playerData).includes(username)) {
if (playerData[username].includes(message)) {
console.log('That message is already in the database. Not adding it.')
} else {
console.log('Player is in the database. Adding the message.')
playerData[username].push(message)
}
} else {
console.log('Player is not in the database. Adding the player and the message to the database.')
playerData[username] = [message]
}
fs.writeFileSync('./data/playerdata.json', JSON.stringify(playerData, null, 4))
}
}
bot.on('chat', function (username, message) {
text(username, message, false)
})
bot.on('whisper', function (username, message) {
text(username, message, true)
})
if (modules.web != null) {
app.use(helmet())
app.use('/', (req: any, res: { json: (arg0: any) => void }) => {
res.json(require('./data/playerdata.json'))
})
app.listen(modules.web.port)
}
bot.on('login', function () {
bot.chat(`/login ${serverSecrets.ingamepassword}`)
console.log('I spawned and set everything up.')
})
bot.once('spawn', () => {
if (modules.inventory != null) {
inventoryViewer(bot, { port: modules.inventory.port })
}
if (modules.viewer != null) {
viewer(bot, { port: modules.viewer.port })
// Draw the path followed by the bot
const path = [bot.entity.position.clone()]
bot.on('move', () => {
if (path[path.length - 1].distanceTo(bot.entity.position) > 1) {
path.push(bot.entity.position.clone())
bot.viewer.drawLine('path', path)
}
})
}
setInterval(async () => {
if (!isEating && modules.attack) {
const weapon = checkWeapon(bot.inventory)
if (weapon != null) {
await bot.equip(weapon, 'hand').catch(err => {
if (err != null) {
console.log(err)
}
})
}
}
const entity = nearestEntity(null)
if (entity != null) {
if (entity.type === 'player') {
await bot.lookAt(entity.position.offset(0, 1, 0))
} else if (entity.type === 'mob') {
await bot.lookAt(entity.position)
}
if (entity.type === 'mob' && entity.kind === 'Hostile mobs' && modules.attack) {
bot.attack(entity)
}
}
}, 100)
setInterval(async () => {
if (modules.totem) {
const totem: PrismarineItem | null = bot.inventory.findInventoryItem(mcData.itemsByName.totem_of_undying.id, null, false)
let isTotemInOffHand = false
if (bot.inventory.slots[45] !== null && bot.inventory.slots[45] !== undefined && bot.inventory.slots[45].type === mcData.itemsByName.totem_of_undying.id) {
isTotemInOffHand = true
}
if (totem !== null && totem.slot !== 45 && !isTotemInOffHand) {
await bot.equip(totem, 'off-hand').catch(err => {
if (err != null) {
console.log(err)
}
})
}
}
}, 300)
})
if (modules.spam) {
setInterval(() => {
bot.chat(spam.txt[Math.round(Math.random() * (spam.txt.length - 1))])
}, 30000)
}
if (modules.bchelp) {
setInterval(() => {
bot.chat(commands.bc[Math.round(Math.random() * (commands.bc.length - 1))])
}, 120000)
}
setInterval(() => {
if (end) {
console.log('Ending ...')
process.exit(0)
}
}, 1000)
bot.on('kicked', function (reason) {
console.log(`I got kicked for ${reason}`)
end = true
})
bot.on('end', () => {
console.log('I end now.')
end = true
})
bot.on('error', () => {
})
bot.on('playerJoined', function (player) {
if (require('./data/playerjoin.json')[player.username]) {
bot.chat(`> Welcome ${player.username} to this server!`)
}
})
/*
bot.on('path_update', (results) => {
// console.log('I can get there in ' + results.path.length + ' moves. Computation took ' + results.time.toFixed(2) + ' ms.')
})
*/
bot.on('autoeat_started', () => {
console.log('Auto Eat started!')
isEating = true
})
bot.on('autoeat_stopped', () => {
console.log('Auto Eat stopped!')
isEating = false
})
bot.on('health', () => {
if (bot.food === 20) bot.autoEat.disable()
// Disable the plugin if the bot is at 20 food points
else bot.autoEat.enable() // Else enable the plugin again
})
function nearestEntity (type: EntityType | null): Entity | null {
let best: Entity | null = null
let bestDistance: number | null = null
for (const id in bot.entities) {
const entity: Entity = bot.entities[id]
if (type && entity.type !== type) continue
if (entity === bot.entity) continue
const dist: number = bot.entity.position.distanceTo(entity.position)
if ((best == null) || (bestDistance == null || dist < bestDistance)) {
best = entity
bestDistance = dist
}
}
return best
}
function checkWeapon (window: Window): PrismarineItem | null {
let index: number = weapons.length
let weapon: PrismarineItem | null = null
window.items().forEach(item => {
if (weapons.includes(item.type)) {
if (weapons.indexOf(item.type) < index) {
index = weapons.indexOf(item.type)
weapon = item
}
}
})
return weapon
}
client.on('ready', async () => {
if (client.user === null) {
return
}
console.log(`Logged in as ${client.user.tag}!`)
await client.user.setPresence({
status: 'online',
activities: [{
type: 'PLAYING',
url: discordConfig.website,
name: discordConfig.status
}]
})
})
client.on('message', async msg => {
if (msg.member !== null && msg.member.user !== client.user) {
if (msg.channel.id !== config.bridge) {
// Commands that should only be triggered once!
if (discordConfig.primaryserver === server) {
if (msg.content.startsWith('_help')) {
await msg.reply('PistonBot Discord help: `_help, _discord, _invite, _info <server>, _playercount <server>, _players <server>, _tps <server>, _servers`')
} else if (msg.content.startsWith('_discord')) {
await msg.reply('PistonBot Discord: https://discord.gg/CDrcxzH')
} else if (msg.content.startsWith('_invite')) {
await msg.reply('Add PistonBot to YOUR discord server: https://bit.ly/33nSkz1')
} else if (msg.content.startsWith('_dservercount')) {
await msg.reply(`PistonBot is on ${client.guilds.cache.size} servers.`)
}
}
if (msg.content.startsWith('_playercount ' + server)) {
let playerCount = 0
for (const count in bot.players) {
if (count) {
playerCount++
}
}
await msg.reply(`${server}'s playercount: \`${playerCount}\``)
} else if (msg.content.startsWith('_players ' + server)) {
let reply = 'Players on ' + server + ': \n```'
for (const player in bot.players) {
reply = reply + player + '\n'
}
reply = reply + '```'
await msg.reply(reply)
} else if (msg.content.startsWith('_info ' + server)) {
await mc.ping({
host: config.host,
port: config.port,
version: config.version
}, function (err: Error, pingResult: NewPingResult | OldPingResult) {
if (!isNewResult(pingResult)) return;
if (err) {
console.log(err)
msg.reply('Sorry something went wrong. :(')
} else {
if (pingResult.favicon === undefined) { return }
const base64Image: string | undefined = pingResult.favicon.split(';base64,').pop()
if (base64Image === undefined) {
return
}
fs.writeFile(server + '.png', base64Image, { encoding: 'base64' }, function (err: NodeJS.ErrnoException | null) {
if (err != null) {
console.log(err)
}
console.log('File created')
})
console.log(new ChatMessage(JSON.parse(String(pingResult.description))).toString())
const favicon = new Discord.MessageAttachment('./' + server + '.png', server + '.png')
const embed = new Discord.MessageEmbed()
.setTitle(server + '\'s Status')
.setColor('#C970D9')
.setThumbnail('attachment://' + server + '.png')
.addField('Players:', pingResult.players.online.toString() + ' / ' + pingResult.players.max.toString())
.addField('Motd:', replaceColor(new ChatMessage(JSON.parse(String(pingResult.description))).toString()))
.setFooter({ text: 'PistonBot made by Pistonmaster', iconURL: 'https://avatars0.githubusercontent.com/u/40795980?s=460&v=4' })
.setURL(discordConfig.website)
.setTimestamp(Date.now())
msg.channel.send({ embeds: [embed], files: [favicon] })
}
})
} else if (msg.content.startsWith('_tps ' + server)) {
await msg.reply(`Current tps: ${bot.getTps()}`)
} else if (msg.content.startsWith('_servers')) {
await msg.channel.send(`\`${server}\``)
}/* else if (msg.content.startsWith('_setupbridge ' + server)) {
} */
} else {
if (msg.content.startsWith('_restart')) {
if (msg.author.id === discordConfig.ownerid) {
end = true
}
} else {
bot.chat('> [ChatBridge] ' + msg.author.username + ': ' + msg.content)
}
}
}
})
function isNewResult(pingResult: any): pingResult is NewPingResult {
return pingResult.latency !== undefined
}
client.login(secretsFile.token).catch(console.error)
function replaceColor (msg: string): string {
return msg.replace(/§4/gi, '').replace(/§c/gi, '').replace(/§6/gi, '').replace(/§e/gi, '').replace(/§2/gi, '').replace(/§a/gi, '').replace(/§b/gi, '').replace(/§3/gi, '').replace(/§1/gi, '').replace(/§9/gi, '').replace(/§d/gi, '').replace(/§5/gi, '').replace(/§f/gi, '').replace(/§7/gi, '').replace(/§8/gi, '').replace(/§0/gi, '').replace(/§r/gi, '').replace(/§l/gi, '').replace(/§o/gi, '').replace(/§n/gi, '').replace(/§m/gi, '').replace(/§k/gi, '').replace('@', '(at)')
}
interface PistonBot extends Bot {
viewer: any
autoEat: any
getTps: () => number
on: (event: string, listener: (...args: any[]) => void) => this
}