Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

V14 update #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
shiffman merged 5 commits into main from v14-update
Oct 5, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions 01-discordjs/env-sample → 01-discordjs/.env-example
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
SERVERID=1234
CLIENTID=1234
TOKEN=1234
TENORKEY=1234
TOKEN=abcd1234
101 changes: 34 additions & 67 deletions 01-discordjs/README.md
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,98 +1,65 @@
# Choo Choo Discord Bot!
# Choo Choo Discord Bot! (Setting Up Your Bot)

[<img src="https://i.ytimg.com/vi/7A-bnPlxj4k/maxresdefault.jpg" alt="Discord Bot Tutorial" width="320">](https://www.youtube.com/playlist?list=PLRqwX-V7Uu6avBYxeBSwF48YhAnSn_sA4)

🚂🌈💖🤖 All aboard! [Coding Train Tutorial Videos](https://www.youtube.com/playlist?list=PLRqwX-V7Uu6avBYxeBSwF48YhAnSn_sA4) 🚂🌈💖🤖

## Steps to create new bot
## Steps to create new bot

1. Create node project and install discord.js module.
1. Create node project and install discord.js and dotenv module.

```
```bash
$ npm init
$ npm install discord.js
$ npm install discord.js dotenv
```

2. [Create an application](https://discord.com/developers/applications/) - optionally set name, description, avatar.

3. Select Bot from left navigation and "Add Bot" - set name and icon.
3. [Create an application](https://discord.com/developers/applications/) - optionally set name, description, avatar.

4. Add bot to the A2Z server with the url: `https://discord.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&scope=bot`
4. Select Bot from left navigation and "Add Bot" - set name and icon.

5. Write the code!
5. Add bot to the A2Z server with the url: `https://discord.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&scope=bot`

Login to bot account:
```javascript
const Discord = require('discord.js');
const client = new Discord.Client();
client.login('YOUR BOT TOKEN');
```
6. Write the code!

Callback for when the bot is connected and ready:
```javascript
client.once('ready', () => {
console.log('Ready!');
});
```
Load environment variables using `dotenv` and `.env`:

Callback for when a message is posted:
```javascript
client.on('message', gotMessage);
1. Create `.env` file:

function gotMessage(msg) {
console.log(msg.content);
}
```dotenv
CLIENTID=123456789
SERVERID=123456789
TOKEN=123456789
```

9. Run the bot!
2. Use `process.env` to access `.env` variables in your javascript:

```
$ node index.js
```
```javascript
constdotenv=require("dotenv");
Copy link
Collaborator

@supercrafter100 supercrafter100 Sep 20, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you only required dotenv, never called dotenv.config() before reading the process.env.TOKEN variable

Copy link
Member

@shiffman shiffman Oct 5, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

consolidated everything into one README

constTOKEN=process.env.TOKEN;

## Limit to one server and one channel
// We'll use these later when we deploy commands
const clientID = process.env.CLIENTID;
const serverID = process.env.SERVERID;
```

1. Enable developer mode in Discord (Settings->Appearance->Enable Developer Mode).
2. Copy server ID.
3. Copy channel ID.
Login to bot account:

```javascript
const serverID = 'SERVER ID';
const channelID = 'CHANNEL ID';

client.on('message', gotMessage);

function gotMessage(msg) {
// Only for this server and this channel
if (msg.guild.id === serverID && msg.channel.id === channelID) {
// Reply to the message ping!
if (msg.content === 'ping') {
msg.channel.send('pong');
}
}
}
const { Client, Events, GatewayIntentBits } = require("discord.js");
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.login(TOKEN);
```

## Store token and other secrets in .env file.
Callback for when the bot is connected and ready:

1. Install [dotenv package](https://www.npmjs.com/package/dotenv).
```
$ npm install dotenv
```javascript
client.once(Events.ClientReady, () => {
console.log("Ready!");
});
```

2. Create `.env` file:
9. Run the bot!

```
SERVERID=123456789
CHANNELID=123456789
TOKEN=123456789
```

3. Load environment variables using `dotenv` and `.env`:

```javascript
require('dotenv').config();
const serverID = process.env.SERVERID;
const channelID = process.env.CHANNELID;
const TOKEN = process.env.TOKEN;
$ node index.js
```
73 changes: 52 additions & 21 deletions 01-discordjs/deploy-commands.js
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,25 +1,56 @@
require('dotenv').config();
// Slash Commands Deployment Script
// https://discordjs.guide/creating-your-bot/command-deployment.html#guild-commands/

const { SlashCommandBuilder } = require('@discordjs/builders');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { REST, Routes } = require("discord.js");
require("dotenv").config();
Copy link
Collaborator

@supercrafter100 supercrafter100 Sep 20, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To keep consistent with the other code, wouldn't something like the following:

const dotenv = require('dotenv');
dotenv.config();

make more sense here?

const fs = require("node:fs");
const path = require("node:path");

// Note to self: define options for command arguments
const commands = [
new SlashCommandBuilder().setName('choochoo').setDescription('Replies with a random message!'),
new SlashCommandBuilder()
.setName('gif')
.setDescription('Replies with a gif!')
.addStringOption((option) =>
option.setName('keywords').setDescription('The gif to search for').setRequired(false)
),
].map((command) => command.toJSON());
const commands = [];

const rest = new REST({ version: '9' }).setToken(process.env.TOKEN);
// Grab all the command files from the commands directory
const foldersPath = path.join(__dirname, "commands");
const commandFolders = fs.readdirSync(foldersPath);

rest
.put(Routes.applicationGuildCommands(process.env.CLIENTID, process.env.SERVERID), {
body: commands,
})
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);
for (const folder of commandFolders) {
// Grab all the command files from the commands directory you created earlier
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs
.readdirSync(commandsPath)
.filter((file) => file.endsWith(".js"));
// Grab the SlashCommandBuilder#toJSON() output of each commands's data for deployment
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
if ("data" in command && "execute" in command) {
commands.push(command.data.toJSON());
} else {
console.log(
`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property`
);
}
}
}

// Construct and prepare an insance of the REST module
const rest = new REST().setToken(token);
Copy link
Collaborator

@supercrafter100 supercrafter100 Sep 20, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

token isn’t defined here from what I can see?

Copy link
Member

@shiffman shiffman Oct 5, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated!


// and deploy your commands!
async () => {
try {
console.log(
`Started refreshing ${commands.length} application (/) commands.`
);
// The put method is used to fully refresh all commands in the guild with the current set
const data = await rest.put(
Routes.applicationGuildCommands(
process.env.CLIENTID,
process.env.SERVERID
),
{ body: commands }
);
} catch (error) {
// And of course, make sure you catch and log any errors!
console.error(error);
}
};
56 changes: 11 additions & 45 deletions 01-discordjs/index.js
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -4,58 +4,24 @@
// https://thecodingtrain.com/learning/bots/discord/03-discordjs.html
// https://youtu.be/8k-zyUyuvlM

require('dotenv').config();
// Setup dotenv and tell it to look for `.env` in the same folder as our main file
const dotenv = require("dotenv");
dotenv.config();

const fetch = require('node-fetch');

console.log('Beep beep! 🤖');
console.log("Beep beep! 🤖");

// Require the necessary discord.js classes
const { Client, Intents } = require('discord.js');
const { Client, Events, GatewayIntentBits } = require("discord.js");

// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });

// Login to Discord with your client's token
client.login(process.env.TOKEN);

// When the client is ready, run this code (only once)
client.once('ready', readyDiscord);
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

function readyDiscord() {
// require('./deploy-commands');
console.log('💖');
console.log("💖");
}

const replies = ['🚂🌈💖', 'Choo choo!', 'Ding! 🛎', 'Never forget this dot!'];

client.on('interactionCreate', async (interaction) => {
if (!interaction.isCommand()) return;

const { commandName, user, options } = interaction;
console.log(commandName, user.username);

if (commandName === 'choochoo') {
const index = Math.floor(Math.random() * replies.length);
await interaction.reply({
content: replies[index],
// ephemeral: true,
});
} else if (commandName === 'gif') {
let keywords = options.getString('keywords') || 'coding train';

// Avoiding the 3 second issue?
await interaction.deferReply();
let url = `https://api.tenor.com/v1/search?q=${keywords}&key=${process.env.TENORKEY}&contentfilter=high`;
let response = await fetch(url);
let json = await response.json();
const index = Math.floor(Math.random() * json.results.length);

await interaction.editReply({
content: `GIF from Tenor: ${keywords}\n${json.results[index].url}`,
});
// When the client is ready, run this code (only once)
client.once(Events.ClientReady, readyDiscord);

// NOTE TO SELF: look at embeds
// https://discordjs.guide/popular-topics/embeds.html#embed-preview
}
});
// Login to Discord with your client's token
client.login(process.env.TOKEN);
Loading

AltStyle によって変換されたページ (->オリジナル) /