Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 4 additions & 0 deletions 01-discordjs/.env-example
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
SERVERID=1234
CLIENTID=1234
TOKEN=abcd1234
TENORKEY=abcd2345
98 changes: 0 additions & 98 deletions 01-discordjs/README.md

This file was deleted.

31 changes: 31 additions & 0 deletions 01-discordjs/bot.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Import the necessary discord.js classes using ES6 syntax
import { Client, Events, GatewayIntentBits } from 'discord.js';
import dotenv from 'dotenv';
import * as choochoo from './commands/choochoo.js';
import * as gif from './commands/gif.js';

dotenv.config();

// Create a new client instance
const client = new Client({
intents: [GatewayIntentBits.Guilds],
});

// When the client is ready, run this code (only once)
client.once(Events.ClientReady, readyDiscord);

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

function readyDiscord() {
console.log('💖');
}

client.on('interactionCreate', async (interaction) => {
if (!interaction.isCommand()) return;
if (interaction.commandName === 'choochoo') {
await choochoo.execute(interaction);
} else if (interaction.commandName === 'gif') {
await gif.execute(interaction);
}
});
14 changes: 14 additions & 0 deletions 01-discordjs/commands/choochoo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Importing modules using ES6 syntax
import { SlashCommandBuilder } from 'discord.js';

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

// Command Builder export
export const data = new SlashCommandBuilder().setName('choochoo').setDescription('Replies with a random phrase!');

// Execute function export
export async function execute(interaction) {
const index = Math.floor(Math.random() * replies.length);
await interaction.reply(replies[index]);
}
39 changes: 39 additions & 0 deletions 01-discordjs/commands/gif.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Importing modules using ES6 syntax
import fetch from 'node-fetch';
Copy link
Collaborator

Choose a reason for hiding this comment

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

I totally forgot to mention but fetch is now natively supported in node. There isn't a need to actually install the package anymore. Since v18.18.0 it is implemented, see https://nodejs.org/dist/latest-v18.x/docs/api/globals.html for detailed information. This removes the need for this dependency.

import { SlashCommandBuilder, EmbedBuilder } from 'discord.js';

export const data = new SlashCommandBuilder()
.setName('gif')
.setDescription('Searches Tenor for gifs!')
.addStringOption((option) => option.setName('keywords').setDescription('The keywords to search Tenor with'));

// Execute function to interact with Tenor API and reply with a GIF
export async function execute(interaction) {
// Default keyword set to 'kitten' if none provided
let defaultKeyword = 'kitten';
const keywords = interaction.options.getString('keywords') ?? defaultKeyword;

// URL constructed with the provided or default keyword
let url = `https://tenor.googleapis.com/v2/search?q=${keywords}&key=${process.env.TENORKEY}&client_key=a2z_discord_bot&contentfilter=high`;

// Fetching data from Tenor API
let response = await fetch(url);
let json = await response.json();
console.log(json);
console.log(json.results[0].media_formats);

// Randomly select a GIF from the response
const index = Math.floor(Math.random() * json.results.length);

// Creating an embed to display the GIF in the Discord message
const embed = new EmbedBuilder().setImage(json.results[index].media_formats.gif.url);

// Initially acknowledging the command interaction with a hidden (ephemeral) reply
await interaction.deferReply({ ephemeral: false });

// Following up with the selected GIF embedded in the message
await interaction.followUp({
embeds: [embed],
content: 'GIF from Tenor: ' + keywords,
});
}
67 changes: 42 additions & 25 deletions 01-discordjs/deploy-commands.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,42 @@
require('dotenv').config();

const { SlashCommandBuilder } = require('@discordjs/builders');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');

// 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 rest = new REST({ version: '9' }).setToken(process.env.TOKEN);

rest
.put(Routes.applicationGuildCommands(process.env.CLIENTID, process.env.SERVERID), {
body: commands,
})
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);
// Slash Commands Deployment Script
// https://discordjs.guide/creating-your-bot/command-deployment.html#guild-commands/

// Importing modules using ES6 syntax
import { REST, Routes } from 'discord.js';
import { config } from 'dotenv';
import fs from 'node:fs';

config(); // Using dotenv config function directly

const commands = [];
const commandFiles = fs.readdirSync('./commands').filter((file) => file.endsWith('.js'));

// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {
const command = await import(`./commands/${file}`); // Using dynamic import
if ('data' in command && 'execute' in command) {
commands.push(command.data.toJSON());
} else {
console.log(`[WARNING] The command ${file} is missing a required "data" or "execute" property.`);
}
}

// Construct and prepare an insance of the REST module
const rest = new REST().setToken(process.env.TOKEN);

// 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,
});

console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
// And of course, make sure you catch and log any errors!
console.error(error);
}
})();
4 changes: 0 additions & 4 deletions 01-discordjs/env-sample

This file was deleted.

61 changes: 0 additions & 61 deletions 01-discordjs/index.js

This file was deleted.

Loading