CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PrismarineJS

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: PrismarineJS/mineflayer
Path: blob/master/examples/discord.js
Views: 789
1
/*
2
* This example is a very simple way how to connect a discord bot with a mineflayer bot.
3
* For this example you will need discord.js installed. You can install with: npm install discord.js
4
* This example uses discord.js v14
5
* You need to do this before running this example:
6
* - You need to get a discord bot token
7
* - You need to get the id of the channel you want to use
8
*
9
* Original credit to U9G, updated by Jovan04 12/19/2022
10
*/
11
12
if (process.argv.length < 6 || process.argv.length > 8) {
13
console.log('Usage : node discord.js <discord bot token> <channel id> <host> <port> [<name>] [<auth>]')
14
process.exit(1)
15
}
16
17
// load discord.js
18
const { Client, GatewayIntentBits } = require('discord.js')
19
const { MessageContent, GuildMessages, Guilds } = GatewayIntentBits
20
21
let channel = process.argv[3]
22
const token = process.argv[2]
23
24
// create new discord client that can see what servers the bot is in, as well as the messages in those servers
25
const client = new Client({ intents: [Guilds, GuildMessages, MessageContent] })
26
client.login(token)
27
28
// load mineflayer
29
const mineflayer = require('mineflayer')
30
31
// bot options
32
const options = {
33
host: process.argv[4],
34
port: parseInt(process.argv[5]),
35
username: process.argv[6] || 'discord',
36
auth: process.argv[7] || 'offline'
37
}
38
39
// join server
40
const bot = mineflayer.createBot(options)
41
bot.on('spawn', () => {
42
console.log(`Mineflayer bot logged in as ${bot.username}`)
43
})
44
45
// when discord client is ready, send login message
46
client.once('ready', (c) => {
47
console.log(`Discord bot logged in as ${c.user.tag}`)
48
channel = client.channels.cache.get(channel)
49
if (!channel) {
50
console.log(`I could not find the channel (${process.argv[3]})!`)
51
console.log('Usage : node discord.js <discord bot token> <channel id> <host> <port> [<name>] [<auth>]')
52
process.exit(1)
53
}
54
})
55
56
client.on('messageCreate', (message) => {
57
// Only handle messages in specified channel
58
if (message.channel.id !== channel.id) return
59
// Ignore messages from the bot itself
60
if (message.author.id === client.user.id) return
61
// console.log(message)
62
bot.chat(`${message.author.username}: ${message.content}`)
63
})
64
65
// Redirect in-game messages to Discord channel
66
bot.on('chat', (username, message) => {
67
// Ignore messages from the bot itself
68
if (username === bot.username) return
69
70
channel.send(`${username}: ${message}`)
71
})
72
73