Skip to content

Commit

Permalink
first upload
Browse files Browse the repository at this point in the history
  • Loading branch information
GogaNotClown committed Jun 6, 2024
1 parent b6ec05a commit bff599f
Show file tree
Hide file tree
Showing 10 changed files with 911 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
DISCORD_TOKEN=BOT_TOKEN
CLIENT_ID=BOT_CLIENT_ID
GUILD_ID=DISCORD_SERVER_ID
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules/
.idea
.env
84 changes: 84 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# greg_bot [RU](README_RU.md)

The bot is designed to provide users with entertaining content through slash commands, offering features such as
sending random cat images and NSFW content in dm. It is tailored for use on a single server.

[![Project Preview](https://i.postimg.cc/wB3GS5Gy/image.png)](https://postimg.cc/67JcZZwt)

## Table of Contents

- [Installation](#installation)
- [Config](#config)
- [Important](#important)
- [Technologies Used](#technologies-used)
- [Contact](#contact)
- [Project Status](#project-status)

## Installation

To use this project, follow these steps:

1. **Clone the Repository:**
Ensure that Git is installed on your system.
```bash
git clone https://github.com/GogaNotClown/greg_bot.git
cd greg_bot
```

2. **Download NPM packages:**
Ensure that Node.js is installed on your system.
```bash
npm install
```

3. **Start the Bot:**
To activate the bot, run the following command. Before executing, ensure you have inserted your bot token, client ID,
and guild ID in the .env file.
```bash
node index.js
```

## Config

The configuration for this bot is stored in the .env file, where you need to set up the following environment variables:

```bash
DISCORD_TOKEN: Your Discord bot token.
CLIENT_ID: Your Discord bot client ID.
GUILD_ID: Your Discord server ID.
```

## Important

To add your Discord bot to your server, please follow the steps outlined below. This process is crucial because the bot
utilizes the latest version of discord.js and implements slash commands, thus requiring a different approach to inviting
it:

1. **Intents:**
Once you've created your Discord Bot on the [Discord Developer Portal](https://discord.com/developers/applications),
navigate to the `Bot` tab. From there, toggle on the `PRESENCE`, `SERVER MEMBERS`, and `MESSAGE CONTENT` intents.
Enabling these intents allows your Discord bot to respond to slash commands effectively.

[![Intents Screen](https://i.postimg.cc/jjz7qm9G/image.png)](https://postimg.cc/2qS62cCw)

2. **OAuth2**
Next, navigate to the `OAuth2` tab and select the checkboxes labeled `bot` and `applications.commands` in the OAuth2
URL Generator (scopes) section. Then, in the OAuth2 URL Generator (bot permissions) section, check
the `Administrator` permission. Ensure that the Integration type is set to "Guild Install," and you'll find the bot
link below.

[![OAuth2 Screen](https://i.postimg.cc/ZY1v3TS1/image.png)](https://postimg.cc/Z0xqzz0c)

## Technologies Used

- [Node.js](https://nodejs.org/en)
- [Discord.js](https://discord.js.org/)
- [Axios](https://axios-http.com/)

## Contact

For questions or suggestions, you can contact [GogaNotClown](https://github.com/GogaNotClown/) via GitHub

## Project Status

Completed
84 changes: 84 additions & 0 deletions README_RU.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# greg_bot [EN](README.md)

Бот разработан для предоставления пользователям развлекательного контента через команды slash, предлагая такие функции,
как отправка случайных изображений с котами и NSFW-контента в личные сообщения. Он настроен для использования только на
одном сервере.

[![Превью проекта](https://i.postimg.cc/wB3GS5Gy/image.png)](https://postimg.cc/67JcZZwt)

## Содержание

- [Установка](#установка)
- [Конфигурация](#конфигурация)
- [Важно](#важно)
- [Используемые технологии](#используемые-технологии)
- [Контакты](#контакты)
- [Статус проекта](#статус-проекта)

## Установка

Чтобы использовать этот проект, следуйте этим шагам:

1. **Клонируйте репозиторий:**
Убедитесь, что Git установлен на вашей системе.
```bash
git clone https://github.com/GogaNotClown/greg_bot.git
cd greg_bot
```

2. **Скачивание пакетов NPM:**
Убедитесь, что Node.js установлен на вашей системе.
```bash
npm install
```

3. **Запуск бота:**
Чтобы активировать бота, выполните следующую команду. Прежде чем выполнить ее, убедитесь, что вы вставили токен бота,
ID клиента и ID сервера (гильдии) в файл .env.
```bash
node index.js
```

## Конфигурация

Конфигурация для этого бота хранится в файле .env, где вы должны настроить следующие переменные среды:

```bash
DISCORD_TOKEN: Токен вашего дискорд бота.
CLIENT_ID: ID вашего Discord бота.
GUILD_ID: ID вашего сервера в Discord.
```

## Важно

Чтобы добавить вашего Discord бота на сервер, пожалуйста, следуйте указанным ниже шагам. Этот процесс крайне важен,
поскольку бот использует последнюю версию discord.js и внедряет команды через слеш (/), что требует особого подхода к
его приглашению:

1. **Интенты:**
После создания вашего Discord бота на [Портале разработчиков Discord](https://discord.com/developers/applications),
перейдите на вкладку `Bot`. Затем переключите на ВКЛЮЧЕНО опции `PRESENCE`, `SERVER MEMBERS` и `MESSAGE CONTENT`.
Включение этих опций позволит вашему Discord боту эффективно отвечать на команды через слеш (/).

[![Скрин интентов](https://i.postimg.cc/jjz7qm9G/image.png)](https://postimg.cc/2qS62cCw)

2. **OAuth2**
Затем перейдите на вкладку `OAuth2` и выберите флажки `bot` и `applications.commands` в разделе OAuth2 URL
Generator (scopes). Затем, в разделе OAuth2 URL Generator (bot permissions), отметьте разрешение `Administrator`.
Убедитесь, что тип интеграции установлен как "Установка на сервер," и вы найдете ссылку на бота ниже.

[![Скрин OAuth2](https://i.postimg.cc/ZY1v3TS1/image.png)](https://postimg.cc/Z0xqzz0c)

## Используемые технологии

- [Node.js](https://nodejs.org/en)
- [Discord.js](https://discord.js.org/)
- [Axios](https://axios-http.com/)

## Контакты

Для вопросов или предложений вы можете связаться с [GogaNotClown](https://github.com/GogaNotClown/) через GitHub

## Статус проекта

Завершён
87 changes: 87 additions & 0 deletions commands/randomcat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
const {SlashCommandBuilder} = require('@discordjs/builders'); // Import SlashCommandBuilder from discord.js builders
const axios = require('axios'); // Import axios for making HTTP requests
const {parseTime} = require('../utils.js'); // Import function parseTime function from utils.js file

async function getRandomCatImage() {
try {
const response = await axios.get('https://api.thecatapi.com/v1/images/search'); // Fetch a random cat image from TheCatAPI
if (response.data && response.data[0] && response.data[0].url) {
return {success: true, url: response.data[0].url}; // Return the image URL if successful
}
return {success: false, error: 'Failed to fetch a cat image.'};
} catch (error) {
console.error('Error fetching cat image:', error); // Log error if fetching failed
return {success: false, error: 'Failed to fetch a cat image.'};
}
}

module.exports = {
data: new SlashCommandBuilder()
.setName('randomcat')
.setDescription('Send a random cat image in a private message')
.addStringOption(option =>
option.setName('interval')
.setDescription('Interval for sending cat images (e.g., 5m, 1h)')
.setRequired(false))
.addStringOption(option =>
option.setName('action')
.setDescription('Action (start or stop)')
.setRequired(false)),
async execute(interaction, client) {
const interval = interaction.options.getString('interval');
const action = interaction.options.getString('action');

if (action === 'stop') {
const timer = client.catTimers.get(interaction.user.id);
if (timer) {
clearInterval(timer);
client.catTimers.delete(interaction.user.id);
await interaction.reply('Subscription stopped.');
} else {
await interaction.reply('You do not have an active subscription.');
}
return;
}

if (interval) {
const duration = parseTime(interval);
if (!duration) {
await interaction.reply('Invalid time format. Use m (minutes), h (hours), d (days), w (weeks).');
return;
}

if (client.catTimers.has(interaction.user.id)) {
await interaction.reply('You already have an active subscription.');
return;
}

const catImageResult = await getRandomCatImage();
if (!catImageResult.success) {
await interaction.reply(catImageResult.error);
return;
}

await interaction.user.send({content: catImageResult.url});

const timer = setInterval(async () => {
const catImageResult = await getRandomCatImage();
if (catImageResult.success) {
await interaction.user.send({content: catImageResult.url});
} else {
console.error('Error fetching cat image:', catImageResult.error);
}
}, duration);

client.catTimers.set(interaction.user.id, timer);
await interaction.reply(`Cat image subscription set to every ${interval}.`);
} else {
const catImageResult = await getRandomCatImage();
if (catImageResult.success) {
await interaction.user.send({content: catImageResult.url});
await interaction.reply('Enjoy your cat image.');
} else {
await interaction.reply(catImageResult.error);
}
}
},
};
84 changes: 84 additions & 0 deletions commands/randomnsfw.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
const {SlashCommandBuilder} = require('@discordjs/builders'); // Import SlashCommandBuilder from discord.js builders
const akaneko = require('akaneko'); // Import akaneko for fetching NSFW images
const {parseTime} = require('../utils.js'); // Import function parseTime function from utils.js file

async function getRandomNSFWImage() {
try {
const nsfwImage = await akaneko.nsfw.hentai(); // Fetch a random NSFW image using akaneko
return {success: true, url: nsfwImage};
} catch (error) {
console.error('Error fetching NSFW image:', error); // Log error if fetching failed
return {success: false, error: 'Failed to fetch an NSFW image.'};
}
}

module.exports = {
data: new SlashCommandBuilder()
.setName('randomnsfw')
.setDescription('Send a random NSFW image in a private message')
.addStringOption(option =>
option.setName('interval')
.setDescription('Interval for sending NSFW images (e.g., 5m, 1h)')
.setRequired(false))
.addStringOption(option =>
option.setName('action')
.setDescription('Action (start or stop)')
.setRequired(false)),
async execute(interaction, client) {
const interval = interaction.options.getString('interval');
const action = interaction.options.getString('action');

if (action === 'stop') {
const timer = client.nsfwTimers.get(interaction.user.id);
if (timer) {
clearInterval(timer);
client.nsfwTimers.delete(interaction.user.id);
await interaction.reply('Subscription stopped.');
} else {
await interaction.reply('You do not have an active subscription.');
}
return;
}

if (interval) {
const duration = parseTime(interval);
if (!duration) {
await interaction.reply('Invalid time format. Use m (minutes), h (hours), d (days), w (weeks).');
return;
}

if (client.nsfwTimers.has(interaction.user.id)) {
await interaction.reply('You already have an active subscription.');
return;
}

const nsfwImageResult = await getRandomNSFWImage();
if (!nsfwImageResult.success) {
await interaction.reply(nsfwImageResult.error);
return;
}

await interaction.user.send({content: nsfwImageResult.url});

const timer = setInterval(async () => {
const nsfwImageResult = await getRandomNSFWImage();
if (nsfwImageResult.success) {
await interaction.user.send({content: nsfwImageResult.url});
} else {
console.error('Error fetching NSFW image:', nsfwImageResult.error);
}
}, duration);

client.nsfwTimers.set(interaction.user.id, timer);
await interaction.reply(`NSFW image subscription set to every ${interval}.`);
} else {
const nsfwImageResult = await getRandomNSFWImage();
if (nsfwImageResult.success) {
await interaction.user.send({content: nsfwImageResult.url});
await interaction.reply('Enjoy your NSFW image.');
} else {
await interaction.reply(nsfwImageResult.error);
}
}
},
};
Loading

0 comments on commit bff599f

Please sign in to comment.