Compare commits

..

173 Commits
0.1.0 ... 0.3.1

Author SHA1 Message Date
0f4e0b952b Merge pull request #34 from warengroup/develop
Version 0.3.1
2021-09-03 01:55:50 +03:00
3ec1892a09 Updated ready.js 2021-09-03 01:26:00 +03:00
7d4fb50351 Update startTime when changing stations in play.js 2021-09-03 01:24:21 +03:00
179914a2f2 Updated statisticsUpdate.js 2021-09-03 01:23:35 +03:00
a8fc38ffca Updated ready.js 2021-09-03 01:23:17 +03:00
329986be53 Added restoreradio.js 2021-09-03 01:22:47 +03:00
5ec4ea6aae Updated SIGINT.js 2021-09-03 01:22:25 +03:00
e546001be8 Added saveState & loadState functions 2021-09-03 01:21:55 +03:00
f2158ba8ae Updated datastore.js 2021-09-03 01:21:11 +03:00
a1f85a0d19 Updated SIGINT.js 2021-09-02 19:25:04 +03:00
430e0f9e51 Added SIGTERM event 2021-09-02 19:18:20 +03:00
45b23722fa Updated maintenance command 2021-09-02 18:58:23 +03:00
66ace838c6 Remove unnecessary lines in SIGINT.js 2021-09-02 18:45:45 +03:00
8e9546097f Updated Client.ts 2021-09-02 18:18:37 +03:00
61981a5b0b Updated SIGINT event 2021-09-02 17:58:31 +03:00
65f83bc522 Updated SIGINT event 2021-09-02 17:57:37 +03:00
74239f71a7 Updated SIGINT event 2021-09-02 17:37:07 +03:00
46237fd91e Updated ready.js 2021-09-02 16:50:45 +03:00
bf0811945a Fixed statisticsUpdate in maintenance.js 2021-09-02 16:50:16 +03:00
706e65bc06 Added SIGINT event 2021-09-02 16:50:01 +03:00
12337f499b Updated list command 2021-09-02 15:00:04 +03:00
da71137f68 Updated stop.js 2021-09-02 14:40:55 +03:00
45bd690c05 Updated logger function 2021-09-02 14:40:26 +03:00
eba7551329 Edited loggers in ready.js 2021-09-02 14:40:12 +03:00
fea24ec1aa Edited message in play.js 2021-09-02 14:39:52 +03:00
1fd6c2c691 Added messageDelete event 2021-09-02 14:39:23 +03:00
492df398ff Removed unnecessary messages in messages.js 2021-09-02 13:16:42 +03:00
a1d4e356a6 Removed comment in interactionCreate.js 2021-09-02 13:12:52 +03:00
c4fb1d5147 Updated interactionCreate & messageCreate events 2021-09-02 12:54:39 +03:00
b6c47d7c6f Updated messageCommandsDeprecatedDescription in messages.js 2021-09-02 12:49:08 +03:00
5208a3feb1 Remove deprecation message after 30 seconds. 2021-09-02 12:11:16 +03:00
8a10697edd Adding deprecation message when using message commands. 2021-09-02 12:08:19 +03:00
f786abebe4 Restoring capability to use messageCreate event. 2021-09-02 12:07:08 +03:00
5e53a908e7 Removed prefix from code 2021-09-02 09:38:15 +03:00
0d795a6efb Added radio.message?.delete in voiceStateUpdate 2021-09-01 17:56:27 +03:00
01514454bf Updated Invite link 2021-09-01 17:55:28 +03:00
3dd5b9d36e Updated Dependencies 2021-09-01 17:55:03 +03:00
0f184a9fc6 Merge pull request #25 from warengroup/develop
Version 0.3.0
2021-08-31 17:39:49 +03:00
ec651a681c Updated list.js 2021-08-31 15:55:36 +03:00
fe165f03c6 List developers in ready.js 2021-08-31 13:59:38 +03:00
73e2427a21 Updated ready.js 2021-08-31 13:53:23 +03:00
47ed5b7e04 Merge branch 'master' into develop 2021-08-31 12:48:54 +03:00
34b7bf8f19 Merge pull request #31 from warengroup/v0.2.4
Version 0.2.4
2021-08-31 12:33:31 +03:00
18a03d50ee Updated Dependencies 2021-08-31 12:20:47 +03:00
6c89770d16 Removed createDiscordJSAdapter 2021-08-31 12:18:58 +03:00
79acdc9687 Changed button style in play.js 2021-08-31 12:13:49 +03:00
0c93814013 Added selectMenu when no query in play.js 2021-08-31 11:56:50 +03:00
1c9ad75b8e Updated interactionCreate event 2021-08-31 11:55:57 +03:00
277b67e3df Making interaction.options nullable in play.js 2021-08-31 10:48:04 +03:00
b5d5ca1fe6 Updated interactionCreate event 2021-08-31 10:47:39 +03:00
5df88494b0 Updated logger in ready.js line 30 2021-08-31 10:38:48 +03:00
7a93cd001f Edited embed message and delete components when stopping radio 2021-08-31 10:38:21 +03:00
bdc76b73a7 Edited options & added buttons in play.js 2021-08-31 10:37:47 +03:00
25e9ebbd4e Added new emojis 2021-08-31 10:37:20 +03:00
c4c2461175 Updated Dependencies 2021-08-31 10:37:12 +03:00
e2d74c10ea Updated Dependencies 2021-08-28 18:21:50 +03:00
f0dcd76033 Update 2021-08-28 11:07:47 +03:00
5f5b164e0d Updated stop.js 2021-08-27 04:59:23 +03:00
1358787793 Updated play.js 2021-08-27 04:59:15 +03:00
42591791c3 Fixed typos in ready.ts 2021-08-27 02:52:30 +03:00
c539a63011 Updated Dependencies 2021-08-27 02:52:19 +03:00
33c41233da Updated Dockerfile 2021-08-27 02:11:49 +03:00
32ac31a8af Updated TypeScript Build workflow (Github Workflows) 2021-08-27 02:11:09 +03:00
0b7da1937b Removed createDiscordJSAdapter 2021-08-27 01:38:33 +03:00
ee13f11f71 Ephemeral reply to nowplaying.js 2021-08-27 00:34:17 +03:00
a6d1f68191 Small fix in play.js 2021-08-26 23:33:28 +03:00
0ac8491a96 Customizing searchStation function in play.js 2021-08-26 23:15:55 +03:00
a36f3bf90d Updated TypeScript Build workflow (Github Workflows) 2021-08-26 22:55:08 +03:00
c08d5650ec Fixed nowplaying command 2021-08-26 22:25:31 +03:00
3488d8e737 Updated nowplaying.js 2021-08-26 22:06:41 +03:00
96e1ce82ae Updated logger function 2021-08-26 22:06:26 +03:00
4498efcdcd Ephemeral replies 2021-08-26 22:06:15 +03:00
294aa28849 Fix commands.js 2021-08-26 21:50:15 +03:00
f0887514af Fixing indentations in multiple commands 2021-08-26 18:14:15 +03:00
8d15567f85 Removed comments in interactionCreate.js 2021-08-26 18:10:45 +03:00
fbbd901cbd Updated Dependencies 2021-08-26 18:05:44 +03:00
fcb5f4f6e6 Moved SlashCommandBuilder to commands.js 2021-08-26 18:00:04 +03:00
bd70f2bedc Removed comments in help.js 2021-08-26 17:02:11 +03:00
4ba582295b Removed second variable from msToTime in multiple files 2021-08-25 23:05:06 +03:00
d524649ad5 Updated msToTime function 2021-08-25 22:45:37 +03:00
ca494df400 Updated msToTime function 2021-08-25 22:39:44 +03:00
6ec4a068f9 Updated Dependencies 2021-08-25 22:21:15 +03:00
b8c1816b1c Added logger to voiceStateUpdate.js 2021-08-22 20:51:02 +03:00
c5f269c0a7 Added logger to ready.js 2021-08-22 20:50:48 +03:00
b979d26425 Added logger to stop.js 2021-08-22 20:50:14 +03:00
f18776ce1a Added logger to play.js 2021-08-22 20:50:02 +03:00
8168650f69 Updated maintenance command 2021-08-22 20:49:43 +03:00
dd37b3447f Added logging to commands.js 2021-08-22 20:49:11 +03:00
b03c6fd3b0 Created logger function 2021-08-22 20:47:40 +03:00
7810f6fff8 Updated help command 2021-08-22 19:00:19 +03:00
2fec81e84d Updated code 2021-08-22 18:48:40 +03:00
606dcc0ab3 Hiding help subcommands 2021-08-22 14:54:40 +03:00
727cae13b4 Merge branch 'master' into develop 2021-08-21 19:43:57 +03:00
dc5a9d4e71 Merge pull request #29 from warengroup/v0.2.3
Version 0.2.3
2021-08-21 19:31:46 +03:00
e479e5a82a Updated Dependencies 2021-08-21 19:17:31 +03:00
6afe6c30f9 Fixed help command 2021-08-21 19:12:52 +03:00
17161b72b9 Updated helpDescription message 2021-08-21 19:12:18 +03:00
3cb54c9470 Nulling connection after bot is disconnected 2021-08-21 18:29:59 +03:00
9533748f0f Added version to console.log in ready.js 2021-08-21 17:56:33 +03:00
42b8f52834 Required commands to load when bot is ready 2021-08-21 17:55:52 +03:00
8785d0c715 Updated commands.js 2021-08-21 17:55:10 +03:00
1706007088 Updated Dependencies 2021-08-21 15:58:07 +03:00
7ccd72cc6d Merge branch 'master' into develop 2021-08-21 15:24:33 +03:00
751f9989eb Merge pull request #27 from warengroup/v0.2.2
Version 0.2.2
2021-08-21 15:19:30 +03:00
6c860b6b23 Fixed #26 in voiceStateUpdate.js 2021-08-21 15:15:32 +03:00
0bfb34c1dd Updated Dependencies 2021-08-21 14:49:07 +03:00
0a269aac94 Updated commands.js 2021-08-19 02:01:06 +03:00
4b10736508 Updated check.js 2021-08-19 01:59:55 +03:00
97317449f9 Updated play.js 2021-08-19 01:59:47 +03:00
0b7c04d242 Updated check.js 2021-08-19 01:53:04 +03:00
63e99dd2b3 Updated ready.js 2021-08-19 01:52:55 +03:00
d5b8d67064 Removed message event 2021-08-19 01:52:46 +03:00
ce5351c3f4 Added interactionCreate event 2021-08-19 01:52:31 +03:00
2d68eb1ffd Updated commands 2021-08-19 01:52:16 +03:00
cecadb2bef Updated commands.js 2021-08-19 01:50:56 +03:00
c5d5d28475 Updated config.js 2021-08-19 01:50:45 +03:00
9e6d60bde8 Updated Client.ts 2021-08-19 01:50:35 +03:00
76fe1aaae9 Added new dependencies 2021-08-19 01:50:03 +03:00
684a87c398 Disabled message commands 2021-08-19 00:01:13 +03:00
8c35d71818 Updated Invite Link 2021-08-18 23:57:59 +03:00
03248bcfa8 Updated dependencies 2021-08-18 23:46:35 +03:00
9a84a3c938 Merge pull request #20 from warengroup/develop
Version 0.2.1
2021-08-18 12:46:50 +03:00
510f2c5b50 Updated Dockerfile 2021-08-17 18:54:22 +03:00
e571194eac Updated package.json & Updated dependencies 2021-08-17 18:50:48 +03:00
ca02f95500 Updated Dockerfile 2021-08-17 18:48:13 +03:00
28e7476f70 Added Docker Build workflow (Github Workflows) 2021-08-17 18:38:40 +03:00
95e8b17ddd Updated statisticsUpdate function 2021-08-08 20:06:30 +03:00
6a11482110 Fix typo in datastore.js 2021-08-08 19:20:20 +03:00
202674cb53 Update job name in TypeScript Build workflow (Github) 2021-08-08 17:39:51 +03:00
64f97b990a Added TypeScript Build (Github Workflow) 2021-08-08 03:04:54 +03:00
7dc0a6d3b9 Added .env example 2021-08-08 00:09:20 +03:00
8f685a0676 Updated adapter.ts 2021-08-07 23:56:58 +03:00
ce7d3d633b Updated Dockerfile 2021-08-07 23:56:43 +03:00
177a405f08 Updated Dependencies 2021-08-07 23:56:23 +03:00
40490d80dc Updated stop.js & voiceStateUpdate.js 2021-08-04 17:46:06 +03:00
ef18a08cc6 Updated play 2021-08-04 15:18:14 +03:00
378fe97ea3 Updated voiceStateUpdate 2021-08-04 15:14:12 +03:00
39d7acaa9e Updated voiceStateUpdate 2021-08-04 15:03:58 +03:00
0ef9cad101 Updated voiceStateUpdate 2021-08-04 14:57:02 +03:00
07e45ae54d Updated voiceStateUpdate 2021-08-04 14:47:27 +03:00
f437797bed Updated voiceStateUpdate 2021-08-04 14:42:37 +03:00
e267b06cf1 Updated voiceStateUpdate 2021-08-04 14:40:06 +03:00
a5ffaadf31 Updated voiceStateUpdate 2021-08-04 14:34:41 +03:00
251eb7f5a1 Fix VoiceStateUpdate 2021-08-04 13:52:30 +03:00
b2ae9ef6f0 Stop audioPlayer in maintenance.js 2021-08-04 13:07:48 +03:00
db409ac6d2 Stop audioPlayer in stop.js 2021-08-04 13:07:09 +03:00
fb2c18b9b0 Removed commented code in play.js 2021-08-04 13:06:09 +03:00
5efb68b717 Removed radio.voiceChannel.leave() and replaced with radio.connection.destroy() in maintenance.js 2021-08-04 12:56:08 +03:00
f543cd3267 Removed radio.voiceChannel.leave() and replaced with radio.connection.destroy() 2021-08-04 12:48:59 +03:00
0515f0f5e3 Updated Dependencies 2021-08-04 12:26:52 +03:00
59796ff002 Added libsodium-wrappers to dependencies 2021-08-04 12:25:42 +03:00
bf70276d7f Fix typo 2021-08-04 11:29:49 +03:00
7db92969af Fix embed sending part 3 2021-08-04 11:17:30 +03:00
3520e86f0b Fix embed sending part 2 2021-08-04 11:12:07 +03:00
bb07884ab4 Fix embed sending 2021-08-04 10:52:56 +03:00
2de365770d Updated event message to messageCreate 2021-08-04 10:18:43 +03:00
0c5fdcd651 Updated Dependencies 2021-08-04 10:07:29 +03:00
b01ee3b380 Create datastore folder 2021-08-04 10:07:11 +03:00
308afd9f96 Updated play command 2021-06-24 14:05:30 +03:00
31baeeab45 Made invite URL dynamic 2021-06-23 18:48:55 +03:00
c17900b618 Removed volume command 2021-06-23 18:48:38 +03:00
10c6a8c589 Stopped using dispatcher 2021-06-23 01:25:45 +03:00
284f0e9f0c Updated Dependencies 2021-06-22 23:31:44 +03:00
1f259d95ac Defined devID variable in isDev.js 2021-06-16 04:50:15 +03:00
9b67506558 Removed static directory address in datastore.js 2021-06-16 04:49:45 +03:00
f9ba5a3117 Removed static directory address in Client.ts 2021-06-16 04:49:11 +03:00
f1f16c4f9a Updated Dockerfile 2021-06-16 04:46:46 +03:00
5147c6455f Updated Dockerfile 2021-06-15 21:02:59 +03:00
3b8ae4fd4b Merge pull request #18 from warengroup/discord.js-v13-update
Version 0.2.0
2021-06-15 20:56:29 +03:00
471f345026 Merge branch 'master' into discord.js-v13-update 2021-06-08 12:02:36 +03:00
0d63c1920e Version 0.2.0 2021-06-08 12:02:22 +03:00
3cb07107d5 Updated src 2021-06-08 12:01:56 +03:00
acef9404b2 Updated misc 2021-06-08 12:01:32 +03:00
57 changed files with 8108 additions and 1046 deletions

2
.env_example Normal file
View File

@ -0,0 +1,2 @@
DISCORD_TOKEN=
RADIOX_STATIONSLISTURL=https://gitea.cwinfo.org/cwchristerw/radio/raw/branch/master/playlist.json

13
.eslintrc Normal file
View File

@ -0,0 +1,13 @@
{
"parser": "@typescript-eslint/parser",
"extends": [
"plugin:@typescript-eslint/recommended",
"prettier/@typescript-eslint",
"plugin:prettier/recommended"
],
"parserOptions": {
"ecmaVersion": 2019,
"sourceType": "module"
},
"rules": {}
}

19
.github/workflows/docker-build.yml vendored Normal file
View File

@ -0,0 +1,19 @@
name: Docker Build
on:
pull_request:
jobs:
buildx:
name: Docker Build
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup Docker Buildx
uses: docker/setup-buildx-action@v1.5.1
id: buildx
with:
install: true
- name: Build
run: docker build . # will run buildx

19
.github/workflows/typescript-build.yml vendored Normal file
View File

@ -0,0 +1,19 @@
name: TypeScript Build
on:
push:
jobs:
tsc:
name: TypeScript Build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: install node v16
uses: actions/setup-node@v2.3.1
with:
node-version: 16
- name: npm install
run: npm install
- name: tsc
uses: icrawl/action-tsc@v1

1
.gitignore vendored
View File

@ -3,3 +3,4 @@ node_modules/
npm-debug.log
.vscode/
.env
build/

5
.prettierrc Normal file
View File

@ -0,0 +1,5 @@
{
"printWidth": 100,
"tabWidth": 4,
"semi": true
}

View File

@ -1,10 +1,10 @@
FROM node:14.15.4-alpine
FROM node:16-alpine
#Dependencies
RUN apk add --virtual .build-deps python make g++ gcc
RUN apk add --virtual .build-deps python3 make g++ gcc git
#Dependencies for RadioX Bot
RUN apk add --virtual .radiox-deps ffmpeg
#Code Dependencies
RUN apk add --virtual .code-deps ffmpeg
WORKDIR /usr/src/app
@ -12,4 +12,6 @@ COPY / /usr/src/app/
RUN npm install
RUN npm run build
CMD [ "npm", "start" ]

View File

@ -4,12 +4,9 @@ Internet Radio to your Discord guild
## [Radio Stations List](https://gitea.cwinfo.org/cwchristerw/radio)
This bot is using Gitea repo to get radio stations from [playlist.json](https://gitea.cwinfo.org/cwchristerw/radio/raw/branch/master/playlist.json) file. List is currently maintained by Christer Warén. You can use alternative list with same format when using RADIOX_STATIONSLISTURL environment variable.
## PREFIX
Default prefix is "rx-" and you can change it with using RADIOX_PREFIX environment variable.
## Docker
1. `docker build -t warengroup/eximiabots-radiox .`
2. `docker run --name radiox-dev -d --net host -e DISCORD_TOKEN= -e RADIOX_PREFIX="rx-" -v "$PWD/datastore":/usr/src/app/datastore/ warengroup/eximiabots-radiox`
2. `docker run --name radiox-dev -d --net host -e DISCORD_TOKEN= -v "$PWD/datastore":/usr/src/app/datastore/ warengroup/eximiabots-radiox`
## Join our Discord Server
https://discord.gg/rRA65Mn

View File

@ -1,62 +0,0 @@
const { Client, Collection } = require('discord.js');
const Discord = require('discord.js');
const fs = require('fs');
const path = require('path');
const events = './events/';
const Datastore = require('./datastore.js');
const GatewayIntents = new Discord.Intents();
GatewayIntents.add(
1 << 0, // GUILDS
1 << 7, // GUILD_VOICE_STATES
1 << 9 // GUILD_MESSAGES
);
module.exports = class extends Client {
constructor() {
super({
disableEveryone: true,
disabledEvents: ['TYPING_START'],
ws: {
intents: GatewayIntents
}
});
this.commands = new Collection();
this.commandAliases = new Collection();
this.radio = new Map();
this.funcs = {};
this.funcs.check = require('./funcs/check.js');
this.funcs.checkFetchStatus = require('./funcs/checkFetchStatus.js');
this.funcs.isDev = require('./funcs/isDev.js');
this.funcs.msToTime = require('./funcs/msToTime.js');
this.funcs.statisticsUpdate = require('./funcs/statisticsUpdate.js');
this.config = require('../config.js');
this.messages = require('./messages.js');
const commandFiles = fs.readdirSync('./client/commands/').filter(f => f.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
command.uses = 0;
this.commands.set(command.name, command);
this.commandAliases.set(command.alias, command);
}
this.on('ready', () => {
require(`${events}ready`).execute(this, Discord);
this.datastore = new Datastore();
});
this.on('message', (msg) => {
require(`${events}msg`).execute(this, msg, Discord);
});
this.on('voiceStateUpdate', (oldState, newState) => {
require(`${events}voiceStateUpdate`).execute(this, oldState, newState);
});
this.on('error', (error) => {
console.error(error);
});
this.login(this.config.token).catch(err => console.log('Failed to login: ' + err));
}
};

View File

@ -1,51 +0,0 @@
module.exports = {
name: 'help',
alias: 'h',
usage: '<command(opt)>',
description: 'Get help using bot',
permission: 'none',
category: 'info',
execute(msg, args, client, Discord, command) {
let message = {};
if (args[1]) {
if (!client.commands.has(args[1]) || (client.commands.has(args[1]) && client.commands.get(args[1]).omitFromHelp === true)) return msg.channel.send('That command does not exist');
const command = client.commands.get(args[1]);
message.helpCommandTitle = client.messages.helpCommandTitle.replace("%client.config.prefix%", client.config.prefix);
message.helpCommandTitle = message.helpCommandTitle.replace("%command.name%", command.name);
message.helpCommandTitle = message.helpCommandTitle.replace("%command.usage%", command.usage);
message.helpCommandDescription = client.messages.helpCommandDescription.replace("%command.description%", command.description);
message.helpCommandDescription = message.helpCommandDescription.replace("%command.alias%", command.alias);
const embed = new Discord.MessageEmbed()
.setTitle(message.helpCommandTitle)
.setThumbnail("https://cdn.discordapp.com/emojis/" + client.messageEmojis["logo"].replace(/[^0-9]+/g, ''))
.setColor(client.config.embedColor)
.setDescription(message.helpCommandDescription)
.setFooter(client.messages.footerText, "https://cdn.discordapp.com/emojis/" + client.messageEmojis["eximiabots"].replace(/[^0-9]+/g, ''));
msg.channel.send(embed);
} else {
const categories = [];
for (let i = 0; i < client.commands.size; i++) {
if (!categories.includes(client.commands.array()[i].category)) categories.push(client.commands.array()[i].category);
}
let commands = '';
for (let i = 0; i < categories.length; i++) {
commands += `**» ${categories[i].toUpperCase()}**\n${client.commands.filter(x => x.category === categories[i] && !x.omitFromHelp).map(x => `\`${x.name}\``).join(', ')}\n`;
}
message.helpTitle = client.messages.helpTitle.replace("%client.user.username%", client.user.username);
message.helpDescription = client.messages.helpDescription.replace("%commands%", commands);
message.helpDescription = message.helpDescription.replace("%client.config.prefix%", client.config.prefix);
const embed = new Discord.MessageEmbed()
.setTitle(message.helpTitle)
.setThumbnail("https://cdn.discordapp.com/emojis/" + client.messageEmojis["logo"].replace(/[^0-9]+/g, ''))
.setColor(client.config.embedColor)
.setDescription(message.helpDescription)
.setFooter(client.messages.footerText, "https://cdn.discordapp.com/emojis/" + client.messageEmojis["eximiabots"].replace(/[^0-9]+/g, ''));
msg.channel.send(embed);
}
}
};

View File

@ -1,28 +0,0 @@
module.exports = {
name: 'list',
alias: 'l',
usage: '',
description: 'List radio stations.',
permission: 'none',
category: 'radio',
execute(msg, args, client, Discord, command) {
let message = {};
if(!client.stations) {
message.errorToGetPlaylist = client.messages.errorToGetPlaylist.replace("%client.config.supportGuild%", client.config.supportGuild);
return msg.channel.send(client.messageEmojis["error"] + message.errorToGetPlaylist);
}
let stations = `${client.stations.map(s => `**#** ${s.name}`).join('\n')}`
const hashs = stations.split('**#**').length;
for (let i = 0; i < hashs; i++) {
stations = stations.replace('**#**', `**${i + 1}**`);
}
const embed = new Discord.MessageEmbed()
.setTitle(client.messages.listTitle)
.setThumbnail("https://cdn.discordapp.com/emojis/" + client.messageEmojis["list"].replace(/[^0-9]+/g, ''))
.setColor(client.config.embedColor)
.setDescription(stations)
.setFooter(client.messages.footerText, "https://cdn.discordapp.com/emojis/" + client.messageEmojis["eximiabots"].replace(/[^0-9]+/g, ''));
return msg.channel.send(embed);
}
};

View File

@ -1,158 +0,0 @@
module.exports = {
name: 'play',
alias: 'p',
usage: '<song name>',
description: 'Play some music.',
permission: 'none',
category: 'radio',
async execute(msg, args, client, Discord, command) {
let message = {};
let url = args[1] ? args[1].replace(/<(.+)>/g, "$1") : "";
const radio = client.radio.get(msg.guild.id);
const voiceChannel = msg.member.voice.channel;
if (!radio) {
if (!msg.member.voice.channel) return msg.channel.send(client.messageEmojis["error"] + client.messages.noVoiceChannel);
} else {
if (voiceChannel !== radio.voiceChannel) return msg.channel.send(client.messageEmojis["error"] + client.messages.wrongVoiceChannel);
}
if(!client.stations) {
message.errorToGetPlaylist = client.messages.errorToGetPlaylist.replace("%client.config.supportGuild%", client.config.supportGuild);
return msg.channel.send(client.messageEmojis["error"] + message.errorToGetPlaylist);
}
if (!args[1]) return msg.channel.send(client.messages.noQuery);
const permissions = voiceChannel.permissionsFor(msg.client.user);
if (!permissions.has('CONNECT')) {
return msg.channel.send(client.messageEmojis["error"] + client.messages.noPermsConnect);
}
if (!permissions.has('SPEAK')) {
return msg.channel.send(client.messageEmojis["error"] + client.messages.noPermsSpeak);
}
let station;
const number = parseInt(args[1] - 1);
if (url.startsWith('http')) {
return msg.channel.send(client.messageEmojis["error"] + client.messages.errorStationURL);
} else if (!isNaN(number)) {
if (number > client.stations.length - 1) {
return msg.channel.send(client.messageEmojis["error"] + client.messages.wrongStationNumber);
} else {
url = client.stations[number].stream[client.stations[number].stream.default];
station = client.stations[number];
}
} else {
if (args[1].length < 3) return msg.channel.send(client.messageEmojis["error"] + client.messages.tooShortSearch);
const sstation = await searchStation(args.slice(1).join(' '), client);
if (!sstation) return msg.channel.send(client.messageEmojis["error"] + client.messages.noSearchResults);
url = sstation.stream[sstation.stream.default];
station = sstation;
}
if (radio) {
client.funcs.statisticsUpdate(client, msg.guild, radio);
radio.connection.dispatcher.destroy();
radio.station = station;
radio.textChannel = msg.channel;
play(msg.guild, client, url);
return;
}
const construct = {
textChannel: msg.channel,
voiceChannel: voiceChannel,
connection: null,
station: station,
volume: 5,
};
client.radio.set(msg.guild.id, construct);
try {
const connection = await voiceChannel.join();
construct.connection = connection;
let date = new Date();
construct.startTime = date.getTime();
play(msg.guild, client, url);
client.datastore.checkEntry(msg.guild.id);
construct.currentGuild = client.datastore.getEntry(msg.guild.id);
if(!construct.currentGuild.statistics[construct.station.name]){
construct.currentGuild.statistics[construct.station.name] = {};
construct.currentGuild.statistics[construct.station.name].time = 0;
construct.currentGuild.statistics[construct.station.name].used = 0;
client.datastore.updateEntry(msg.guild, construct.currentGuild);
}
} catch (error) {
console.log(error);
client.radio.delete(msg.guild.id);
return msg.channel.send(client.messageEmojis["error"] + `An error occured: ${error}`);
}
}
};
function play(guild, client, url) {
let message = {};
const radio = client.radio.get(guild.id);
const dispatcher = radio.connection
.play(url, { bitrate: "auto", volume: 1 })
.on("finish", () => {
console.log("Stream finished");
client.funcs.statisticsUpdate(client, guild, radio);
radio.voiceChannel.leave();
client.radio.delete(guild.id);
return;
});
dispatcher.on('error', error => {
console.error(error);
radio.voiceChannel.leave();
client.radio.delete(guild.id);
return radio.textChannel.send(client.messages.errorPlaying);
});
dispatcher.setVolume(radio.volume / 10);
message.play = client.messages.play.replace("%radio.station.name%", radio.station.name);
radio.textChannel.send(client.messageEmojis["play"] + message.play);
};
function searchStation(key, client) {
if (client.stations === null) return false;
let foundStations = [];
if (!key) return false;
if (key == 'radio') return false;
if (key.startsWith("radio ")) key = key.slice(6);
const probabilityIncrement = 100 / key.split(' ').length / 2;
for (let i = 0; i < key.split(' ').length; i++) {
client.stations.filter(x => x.name.toUpperCase().includes(key.split(' ')[i].toUpperCase()) || x === key).forEach(x => foundStations.push({ station: x, name: x.name, probability: probabilityIncrement }));
}
if (foundStations.length === 0) return false;
for (let i = 0; i < foundStations.length; i++) {
for (let j = 0; j < foundStations.length; j++) {
if (foundStations[i] === foundStations[j] && i !== j) foundStations.splice(i, 1);
}
}
for (let i = 0; i < foundStations.length; i++) {
if (foundStations[i].name.length > key.length) {
foundStations[i].probability -= (foundStations[i].name.split(' ').length - key.split(' ').length) * (probabilityIncrement * 0.5);
} else if (foundStations[i].name.length === key.length) {
foundStations[i].probability += (probabilityIncrement * 0.9);
}
for (let j = 0; j < key.split(' ').length; j++) {
if (!foundStations[i].name.toUpperCase().includes(key.toUpperCase().split(' ')[j])) {
foundStations[i].probability -= (probabilityIncrement * 0.5);
}
}
}
let highestProbabilityStation;
for (let i = 0; i < foundStations.length; i++) {
if (!highestProbabilityStation || highestProbabilityStation.probability < foundStations[i].probability) highestProbabilityStation = foundStations[i];
if (highestProbabilityStation && highestProbabilityStation.probability === foundStations[i].probability) {
highestProbabilityStation = foundStations[i].station;
}
}
return highestProbabilityStation;
};

View File

@ -1,18 +0,0 @@
module.exports = {
name: 'stop',
description: 'Stop command.',
alias: 's',
usage: '',
permission: 'none',
category: 'radio',
execute(msg, args, client, Discord, command) {
const radio = client.radio.get(msg.guild.id);
if (client.funcs.check(client, msg, command)) {
client.funcs.statisticsUpdate(client, msg.guild, radio);
radio.connection.dispatcher.destroy();
radio.voiceChannel.leave();
client.radio.delete(msg.guild.id);
msg.channel.send(client.messageEmojis["stop"] + client.messages.stop);
}
}
};

View File

@ -1,27 +0,0 @@
module.exports = {
name: 'volume',
description: 'Volume command.',
alias: 'none',
usage: '<volume>',
permission: 'MANAGE_MESSAGES',
category: 'radio',
execute(msg, args, client, Discord, command) {
let message = {};
const radio = client.radio.get(msg.guild.id);
if (!args[1] && radio) {
message.currentVolume = client.messages.currentVolume.replace("%radio.volume%", radio.volume)
return msg.channel.send(message.currentVolume);
}
const volume = parseFloat(args[1]);
if (client.funcs.check(client, msg, command)) {
if (isNaN(volume)) return msg.channel.send(client.messages.invalidVolume);
if (volume > 100) return msg.channel.send(client.messages.maxVolume);
if (volume < 0) return msg.channel.send(client.messages.negativeVolume);
radio.volume = volume;
radio.connection.dispatcher.setVolume(volume / 5);
message.newVolume = client.messages.newVolume.replace("%volume%", volume);
return msg.channel.send(message.newVolume);
}
}
};

View File

@ -1,27 +0,0 @@
module.exports = {
name: 'message',
async execute(client, msg, Discord) {
if (msg.author.bot || !msg.guild) return;
let prefix = client.config.prefix;
if(msg.mentions.members.first()){
if(msg.mentions.members.first().user.id === client.user.id){
prefix = "<@!" + client.user.id + "> ";
}
}
const args = msg.content.slice(prefix.length).split(' ');
if (!msg.content.startsWith(prefix)) return;
if (!args[0]) return;
const commandName = args[0].toLowerCase();
if (commandName === 'none') return;
const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName)) || client.commandAliases.get(commandName);
if (!command && msg.content !== `${prefix}`) return;
const permissions = msg.channel.permissionsFor(msg.client.user);
if (!permissions.has('EMBED_LINKS')) return msg.channel.send(client.messages.noPermsEmbed);
try {
command.execute(msg, args, client, Discord, command);
} catch (error) {
msg.reply(client.messages.runningCommandFailed);
console.error(error);
}
}
}

View File

@ -1,48 +0,0 @@
const fetch = require('node-fetch');
module.exports = {
name: 'ready',
async execute(client, Discord) {
console.log('RadioX');
console.log('Internet Radio to your Discord guild');
console.log('(c)2020-2021 EximiaBots by Warén Group');
client.developers = "";
let user = "";
for (i = 0; i < client.config.devId.length; i++) {
user = await client.users.fetch(client.config.devId[i]);
if (i == client.config.devId.length - 1) {
client.developers += user.tag;
} else {
client.developers += user.tag + " & ";
}
}
try {
client.stations = await fetch(client.config.stationslistUrl)
.then(client.funcs.checkFetchStatus)
.then(response => response.json());
} catch (error) {
console.error(error);
}
setInterval(async () => {
try {
client.stations = await fetch(client.config.stationslistUrl)
.then(client.funcs.checkFetchStatus)
.then(response => response.json());
} catch (error) {
console.error(error);
}
}, 3600000);
if(!client.stations) {
client.user.setStatus('dnd');
}
client.datastore.calculateGlobal(client);
require(`../emojis.js`).execute(client);
}
}

View File

@ -1,20 +0,0 @@
module.exports = function (client, msg, command) {
let message = {};
const radio = client.radio.get(msg.guild.id);
const permissions = msg.channel.permissionsFor(msg.author);
if (!radio) {
msg.channel.send(client.messageEmojis["error"] + client.messages.notPlaying);
return false;
}
if (msg.member.voice.channel !== radio.voiceChannel) {
msg.channel.send(client.messageEmojis["error"] + client.messages.wrongVoiceChannel);
return false;
}
if(!command.permission == 'none'){
if (!permissions.has(command.permission)) {
message.noPerms = client.messages.noPerms.replace("%command.permission%", command.permission);
msg.channel.send(client.messageEmojis["error"] + message.noPerms);
return false;
} else return true;
} else return true;
};

View File

@ -1,17 +0,0 @@
module.exports = function msToTime(duration, format) {
var seconds = Math.floor((duration / 1000) % 60),
minutes = Math.floor((duration / (1000 * 60)) % 60),
hours = Math.floor((duration / (1000 * 60 * 60)) % 24),
days = Math.floor((duration / (1000 * 60 * 60 * 24)));
days = (days < 10) ? "0" + days : days;
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
if (format === "hh:mm:ss") {
return `${hours}:${minutes}:${seconds}`;
} else if (format === "dd:hh:mm:ss") {
return `${days}:${hours}:${minutes}:${seconds}`;
}
}

View File

@ -1,26 +0,0 @@
module.exports = function statisticsUpdate(client, guild, radio) {
client.datastore.checkEntry(guild.id);
radio.currentGuild = client.datastore.getEntry(guild.id);
if(!radio.currentGuild.statistics[radio.station.name]){
radio.currentGuild.statistics[radio.station.name] = {};
radio.currentGuild.statistics[radio.station.name].time = 0;
radio.currentGuild.statistics[radio.station.name].used = 0;
client.datastore.updateEntry(guild, radio.currentGuild);
}
if(!radio.connection.dispatcher){
let date = new Date();
radio.currentTime = date.getTime();
radio.playTime = parseInt(radio.currentTime)-parseInt(radio.startTime);
radio.currentGuild.statistics[radio.station.name].time = parseInt(radio.currentGuild.statistics[radio.station.name].time)+parseInt(radio.playTime);
} else {
radio.currentGuild.statistics[radio.station.name].time = parseInt(radio.currentGuild.statistics[radio.station.name].time)+parseInt(radio.connection.dispatcher.streamTime.toFixed(0));
}
radio.currentGuild.statistics[radio.station.name].used = parseInt(radio.currentGuild.statistics[radio.station.name].used)+1;
client.datastore.updateEntry(guild, radio.currentGuild);
client.datastore.calculateGlobal(client);
}

View File

@ -1,2 +0,0 @@
const radioClient = require("./client/class.js");
const client = new radioClient();

6615
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,10 +1,12 @@
{
"name": "eximiabots-radiox",
"version": "0.1.0",
"version": "0.3.1",
"description": "Internet Radio to your Discord guild",
"main": "index.js",
"scripts": {
"start": "node ."
"build": "rimraf ./build && tsc",
"start": "node build/index.js",
"start:dev": "npm run build && node build/index.js"
},
"repository": {
"type": "git",
@ -16,10 +18,34 @@
"url": "https://github.com/warengroup/eximiabots-radiox/issues"
},
"dependencies": {
"@discordjs/opus": "^0.3.3",
"discord.js": "^12.5.3",
"dotenv": "^8.2.0",
"@discordjs/builders": "^0.6.0",
"@discordjs/opus": "^0.6.0",
"@discordjs/rest": "^0.1.1-canary.0",
"@discordjs/voice": "^0.6.0",
"discord-api-types": "^0.22.0",
"discord.js": "^13.1.0",
"dotenv": "^10.0.0",
"libsodium-wrappers": "^0.7.9",
"node-fetch": "^2.6.1",
"path": "^0.12.7"
},
"devDependencies": {
"@types/node": "^16.7.8",
"@types/ws": "^7.4.7",
"@typescript-eslint/eslint-plugin": "^4.29.3",
"@typescript-eslint/parser": "^4.29.3",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"nodemon": "^2.0.12",
"prettier": "^2.3.2",
"rimraf": "^3.0.2",
"ts-node": "^10.2.1",
"tsc-watch": "^4.5.0",
"typescript": "^4.4.2"
},
"engines": {
"node": ">=16.6.0",
"npm": ">=7.0.0"
}
}

92
src/Client.ts Normal file
View File

@ -0,0 +1,92 @@
import Discord, { Client, Collection } from "discord.js";
import fs from "fs";
import Datastore from "./client/datastore.js";
import { command, radio } from "./client/utils/typings.js";
import config from "./config.js";
import messages from "./client/messages.js";
import path from "path";
const events = "./client/events/";
const GatewayIntents = new Discord.Intents();
GatewayIntents.add(
1 << 0, // GUILDS
1 << 7, // GUILD_VOICE_STATES
1 << 9 // GUILD_MESSAGES
);
class RadioClient extends Client {
readonly commands: Collection<string, command>;
readonly radio: Map<string, radio>;
public funcs: any;
readonly config = config;
readonly messages = messages;
public datastore: Datastore | null;
constructor() {
super({
intents: GatewayIntents
});
this.commands = new Collection();
this.radio = new Map();
this.datastore = null;
this.funcs = {};
this.funcs.check = require("./client/funcs/check.js");
this.funcs.checkFetchStatus = require("./client/funcs/checkFetchStatus.js");
this.funcs.isDev = require("./client/funcs/isDev.js");
this.funcs.logger = require("./client/funcs/logger.js");
this.funcs.msToTime = require("./client/funcs/msToTime.js");
this.funcs.statisticsUpdate = require("./client/funcs/statisticsUpdate.js");
this.funcs.saveState = require("./client/funcs/saveState.js");
this.funcs.loadState = require("./client/funcs/loadState.js");
console.log('RadioX ' + this.config.version);
console.log('Internet Radio to your Discord guild');
console.log('(c)2020-2021 EximiaBots by Warén Group');
console.log('');
this.funcs.logger("Bot", "Starting");
const commandFiles = fs.readdirSync(path.join("./src/client/commands")).filter(f => f.endsWith(".js"));
for (const file of commandFiles) {
const command = require(`./client/commands/${file}`);
this.commands.set(command.name, command);
}
this.on("ready", () => {
require(`${events}ready`).execute(this);
});
this.on("messageCreate", msg => {
require(`${events}messageCreate`).execute(this, msg);
});
this.on("messageDelete", msg => {
require(`${events}messageDelete`).execute(this, msg);
});
this.on("interactionCreate", interaction => {
require(`${events}interactionCreate`).execute(this, interaction);
});
this.on("voiceStateUpdate", (oldState, newState) => {
require(`${events}voiceStateUpdate`).execute(this, oldState, newState);
});
process.on('SIGINT', () => {
require(`${events}SIGINT`).execute(this);
});
process.on('SIGTERM', () => {
require(`${events}SIGTERM`).execute(this);
});
this.on("error", error => {
console.error(error);
});
this.login(this.config.token).catch(err => console.log("Failed to login: " + err));
}
}
export default RadioClient

67
src/client/commands.js Normal file
View File

@ -0,0 +1,67 @@
const { SlashCommandBuilder } = require('@discordjs/builders');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { token, version } = require('../config.js');
const fs = require('fs');
const path = require ('path');
module.exports = {
async execute(client) {
const commands = [];
const commandFiles = fs.readdirSync(path.join("./src/client/commands")).filter(f => f.endsWith(".js"));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
command.data = new SlashCommandBuilder()
.setName(command.name)
.setDescription(command.description);
command.data = command.data.toJSON();
if(command.options) {
command.options.forEach(function(option) {
if(option.type == "STRING") option.type = 3;
command.data.options.push(option);
});
}
commands.push(command.data);
}
const rest = new REST({ version: '9' }).setToken(token);
(async () => {
try {
client.funcs.logger('Slash Commands', 'Started refreshing application (/) commands.');
if(version.includes("-dev")){
await rest.put(
Routes.applicationCommands(client.user.id),
{ body: [] },
);
let guilds = await client.guilds.fetch();
guilds.forEach(async guild => {
try {
await rest.put(
Routes.applicationGuildCommands(client.user.id, guild.id),
{ body: commands },
);
} catch (DiscordAPIError) {
}
});
} else {
await rest.put(
Routes.applicationCommands(client.user.id),
{ body: commands },
);
}
client.funcs.logger('Slash Commands', 'Successfully reloaded application (/) commands.' + "\n");
} catch (error) {
client.funcs.logger('Slash Commands', 'Reloading application (/) commands failed.' + "\n");
console.error(error);
}
})();
}
}

View File

@ -5,7 +5,7 @@ module.exports = {
description: 'Report a bug',
permission: 'none',
category: 'info',
async execute(msg, args, client, Discord, command) {
async execute(interaction, client, Discord, command) {
let message = {};
message.bugTitle = client.messages.bugTitle.replace("%client.user.username%", client.user.username);
@ -17,7 +17,10 @@ module.exports = {
.setColor(client.config.embedColor)
.setDescription(message.bugDescription)
.setFooter(client.messages.footerText, "https://cdn.discordapp.com/emojis/" + client.messageEmojis["eximiabots"].replace(/[^0-9]+/g, ''));
msg.channel.send(embed);
},
interaction.reply({
embeds: [embed],
ephemeral: true
});
}
};

View File

@ -0,0 +1,35 @@
module.exports = {
name: 'help',
alias: 'h',
usage: '<command(opt)>',
description: 'Get help using bot',
permission: 'none',
category: 'info',
execute(interaction, client, Discord, command) {
let message = {};
const categories = [];
for (let i = 0; i < client.commands.size; i++) {
if (!categories.includes([...client.commands.values()][i].category)) categories.push([...client.commands.values()][i].category);
}
let commands = '';
for (let i = 0; i < categories.length; i++) {
commands += `**» ${categories[i].toUpperCase()}**\n${client.commands.filter(x => x.category === categories[i] && !x.omitFromHelp).map(x => `\`${x.name}\``).join(', ')}\n`;
}
message.helpTitle = client.messages.helpTitle.replace("%client.user.username%", client.user.username);
message.helpDescription = client.messages.helpDescription.replace("%commands%", commands);
const embed = new Discord.MessageEmbed()
.setTitle(message.helpTitle)
.setThumbnail("https://cdn.discordapp.com/emojis/" + client.messageEmojis["logo"].replace(/[^0-9]+/g, ''))
.setColor(client.config.embedColor)
.setDescription(message.helpDescription)
.setFooter(client.messages.footerText, "https://cdn.discordapp.com/emojis/" + client.messageEmojis["eximiabots"].replace(/[^0-9]+/g, ''));
interaction.reply({
embeds: [embed],
ephemeral: true
});
}
};

View File

@ -5,14 +5,18 @@ module.exports = {
description: 'Invite Bot',
permission: 'none',
category: 'info',
execute(msg, args, client, Discord, command) {
execute(interaction, client, Discord, command) {
let message = {};
message.inviteTitle = client.messages.inviteTitle.replace("%client.user.username%", client.user.username);
const embed = new Discord.MessageEmbed()
.setTitle(message.inviteTitle)
.setColor(client.config.embedColor)
.setURL(client.config.invite)
.setURL("https://discord.com/api/oauth2/authorize?client_id=" + client.user.id + "&permissions=2184465408&scope=applications.commands%20bot") //View Channels, Send Messages, Embed Links, Use External Emojis, Use Slash Commands, Connect, Speak, Use Voice Activity
.setFooter(client.messages.footerText, "https://cdn.discordapp.com/emojis/" + client.messageEmojis["eximiabots"].replace(/[^0-9]+/g, ''));
return msg.channel.send(embed);
interaction.reply({
embeds: [embed],
ephemeral: true
});
}
};

View File

@ -0,0 +1,81 @@
module.exports = {
name: 'list',
alias: 'l',
usage: '',
description: 'List radio stations',
permission: 'none',
category: 'radio',
execute(interaction, client, Discord, command) {
let message = {};
if(!client.stations) {
message.errorToGetPlaylist = client.messages.errorToGetPlaylist.replace("%client.config.supportGuild%", client.config.supportGuild);
return interaction.reply(client.messageEmojis["error"] + message.errorToGetPlaylist);
}
const radio = client.radio.get(interaction.guild.id);
if(radio){
let menu = [];
let stations = new Array();
let options = new Array();
options[1] = new Array();
options[2] = new Array();
stations[1] = client.stations.slice(0,24).forEach(station => {
station = {
label: station.name,
description: station.owner,
value: station.name
};
options[1].push(station);
});
stations[2] = client.stations.slice(25).forEach(station => {
station = {
label: station.name,
description: station.owner,
value: station.name
};
options[2].push(station);
});
menu = new Discord.MessageActionRow()
.addComponents(
new Discord.MessageSelectMenu()
.setCustomId('play')
.setPlaceholder('Change station')
.addOptions(options[1])
.addOptions(options[2])
);
stations = null;
options = null;
interaction.reply({
content: '**Select station:**',
components: [menu],
ephemeral: true
});
} else {
let stations = `${client.stations.map(s => `**#** ${s.name}`).join('\n')}`
const hashs = stations.split('**#**').length;
for (let i = 0; i < hashs; i++) {
stations = stations.replace('**#**', `**${i + 1}.**`);
}
let embed = new Discord.MessageEmbed()
.setTitle(client.messages.listTitle)
.setThumbnail("https://cdn.discordapp.com/emojis/" + client.messageEmojis["list"].replace(/[^0-9]+/g, ''))
.setColor(client.config.embedColor)
.setDescription(stations)
.setFooter(client.messages.footerText, "https://cdn.discordapp.com/emojis/" + client.messageEmojis["eximiabots"].replace(/[^0-9]+/g, ''));
interaction.reply({
embeds: [embed],
ephemeral: true
});
}
}
};

View File

@ -5,14 +5,14 @@ module.exports = {
description: 'Bot Maintenance',
permission: 'none',
category: 'info',
execute(msg, args, client, Discord, command) {
execute(interaction, client, Discord, command) {
let message = {};
if(!client.funcs.isDev(client.config.devId, msg.author.id)) return msg.channel.send(client.messageEmojis["error"] + client.messages.notAllowed);
if(!client.funcs.isDev(client.config.devId, interaction.user.id)) return interaction.reply(client.messageEmojis["error"] + client.messages.notAllowed);
if(!client.stations) {
message.errorToGetPlaylist = client.messages.errorToGetPlaylist.replace("%client.config.supportGuild%", client.config.supportGuild);
return msg.channel.send(client.messageEmojis["error"] + message.errorToGetPlaylist);
return interaction.reply(client.messageEmojis["error"] + message.errorToGetPlaylist);
}
let currentRadios = client.radio.keys();
@ -26,18 +26,12 @@ module.exports = {
currentRadio.guild = client.datastore.getEntry(radio.value).guild;
if(currentRadio){
client.funcs.statisticsUpdate(client, currentRadio.currentGuild.guild, currentRadio);
currentRadio.connection.dispatcher?.destroy();
currentRadio.voiceChannel.leave();
const cembed = new Discord.MessageEmbed()
.setTitle(client.messages.maintenanceTitle)
.setThumbnail("https://cdn.discordapp.com/emojis/" + client.messageEmojis["maintenance"].replace(/[^0-9]+/g, ''))
.setColor(client.config.embedColor)
.setDescription(client.messages.sendedMaintenanceMessage)
.setFooter(client.messages.footerText, "https://cdn.discordapp.com/emojis/" + client.messageEmojis["eximiabots"].replace(/[^0-9]+/g, ''));
currentRadio.textChannel.send(cembed);
client.funcs.statisticsUpdate(client, currentRadio.guild, currentRadio);
currentRadio.connection?.destroy();
currentRadio.audioPlayer?.stop();
currentRadio.message?.delete();
client.radio.delete(radio.value);
stoppedRadios += "-" + radio.value + ": " + currentRadio.currentGuild.guild.name + "\n";
stoppedRadios += "-" + radio.value + ": " + currentRadio.guild.name + "\n";
}
radio = currentRadios.next();
}
@ -48,6 +42,10 @@ module.exports = {
.setColor(client.config.embedColor)
.setDescription("Stopped all radios" + "\n" + stoppedRadios)
.setFooter(client.messages.footerText, "https://cdn.discordapp.com/emojis/" + client.messageEmojis["eximiabots"].replace(/[^0-9]+/g, ''));
return msg.channel.send(embed);
interaction.reply({
embeds: [embed],
ephemeral: true
});
}
};

View File

@ -5,19 +5,23 @@ module.exports = {
description: 'Current Radio Station',
permission: 'none',
category: 'radio',
async execute(msg, args, client, Discord, command) {
async execute(interaction, client, Discord, command) {
let message = {};
const radio = client.radio.get(msg.guild.id);
if (!radio) return msg.channel.send('There is nothing playing.');
if(!client.stations) {
message.errorToGetPlaylist = client.messages.errorToGetPlaylist.replace("%client.config.supportGuild%", client.config.supportGuild);
return msg.channel.send(client.messageEmojis["error"] + message.errorToGetPlaylist);
}
const completed = (radio.connection.dispatcher.streamTime.toFixed(0));
const radio = client.radio.get(interaction.guild.id);
if (!radio) return interaction.reply('There is nothing playing.');
if(!client.stations) {
message.errorToGetPlaylist = client.messages.errorToGetPlaylist.replace("%client.config.supportGuild%", client.config.supportGuild);
return interaction.reply(client.messageEmojis["error"] + message.errorToGetPlaylist);
}
let date = new Date();
radio.currentTime = date.getTime();
radio.playTime = parseInt(radio.currentTime)-parseInt(radio.startTime);
const completed = (radio.playTime);
message.nowplayingDescription = client.messages.nowplayingDescription.replace("%radio.station.name%", radio.station.name);
message.nowplayingDescription = message.nowplayingDescription.replace("%radio.station.owner%", radio.station.owner);
message.nowplayingDescription = message.nowplayingDescription.replace("%client.funcs.msToTime(completed, \"hh:mm:ss\")%", client.funcs.msToTime(completed, "hh:mm:ss"));
message.nowplayingDescription = message.nowplayingDescription.replace("%client.funcs.msToTime(completed)%", client.funcs.msToTime(completed));
const embed = new Discord.MessageEmbed()
.setTitle(client.messages.nowplayingTitle)
@ -25,6 +29,10 @@ module.exports = {
.setColor(client.config.embedColor)
.setDescription(message.nowplayingDescription)
.setFooter(client.messages.footerText, "https://cdn.discordapp.com/emojis/" + client.messageEmojis["eximiabots"].replace(/[^0-9]+/g, ''));
return msg.channel.send(embed);
interaction.reply({
embeds: [embed],
ephemeral: true
});
}
};

340
src/client/commands/play.js Normal file
View File

@ -0,0 +1,340 @@
const {
createAudioPlayer,
createAudioResource,
getVoiceConnection,
joinVoiceChannel
} = require("@discordjs/voice");
module.exports = {
name: "play",
alias: "p",
usage: "<song name>",
description: "Play radio",
options: [
{ type: "STRING", name: "query", description: "Select station", required: false}
],
permission: "none",
category: "radio",
async execute(interaction, client, Discord, command) {
let message = {};
let query = interaction.options?.getString("query") ?? interaction.values?.[0];
if(!query){
if(!client.stations) {
message.errorToGetPlaylist = client.messages.errorToGetPlaylist.replace("%client.config.supportGuild%", client.config.supportGuild);
return interaction.reply(client.messageEmojis["error"] + message.errorToGetPlaylist);
}
let stations = new Array();
let options = new Array();
options[1] = new Array();
options[2] = new Array();
stations[1] = client.stations.slice(0,24).forEach(station => {
station = {
label: station.name,
description: station.owner,
value: station.name
};
options[1].push(station);
});
stations[2] = client.stations.slice(25).forEach(station => {
station = {
label: station.name,
description: station.owner,
value: station.name
};
options[2].push(station);
});
const menu = new Discord.MessageActionRow()
.addComponents(
new Discord.MessageSelectMenu()
.setCustomId('play')
.setPlaceholder('Nothing selected')
.addOptions(options[1])
.addOptions(options[2])
);
stations = null;
options = null;
return interaction.reply({
content: '**Select station:**',
components: [menu],
ephemeral: true
});
}
let url = query ? query.replace(/<(.+)>/g, "$1") : "";
const radio = client.radio.get(interaction.guild.id);
const voiceChannel = interaction.member.voice.channel;
if (!radio) {
if (!interaction.member.voice.channel)
return interaction.reply({
content: client.messageEmojis["error"] + client.messages.noVoiceChannel,
ephemeral: true
});
} else {
if (voiceChannel !== radio.voiceChannel)
return interaction.reply({
content: client.messageEmojis["error"] + client.messages.wrongVoiceChannel,
ephemeral: true
});
}
if (!client.stations) {
message.errorToGetPlaylist = client.messages.errorToGetPlaylist.replace(
"%client.config.supportGuild%",
client.config.supportGuild
);
return interaction.reply({
content: client.messageEmojis["error"] + message.errorToGetPlaylist,
ephemeral: true
});
}
if (!query) return interaction.reply(client.messages.noQuery);
const permissions = voiceChannel.permissionsFor(interaction.client.user);
if (!permissions.has("CONNECT")) {
return interaction.reply(client.messageEmojis["error"] + client.messages.noPermsConnect);
}
if (!permissions.has("SPEAK")) {
return interaction.reply(client.messageEmojis["error"] + client.messages.noPermsSpeak);
}
let station;
const number = parseInt(query - 1);
if (url.startsWith("http")) {
return interaction.reply({
content: client.messageEmojis["error"] + client.messages.errorStationURL,
ephemeral: true
});
} else if (!isNaN(number)) {
if (number > client.stations.length - 1) {
return interaction.reply({
content: client.messageEmojis["error"] + client.messages.wrongStationNumber,
ephemeral: true
});
} else {
url = client.stations[number].stream[client.stations[number].stream.default];
station = client.stations[number];
}
} else {
if (query.length < 3)
return interaction.reply({
content: client.messageEmojis["error"] + client.messages.tooShortSearch,
ephemeral: true
});
const sstation = await searchStation(query, client);
if (!sstation)
return interaction.reply({
content: client.messageEmojis["error"] + client.messages.noSearchResults,
ephemeral: true
});
url = sstation.stream[sstation.stream.default];
station = sstation;
}
if (radio) {
client.funcs.statisticsUpdate(client, interaction.guild, radio);
radio.audioPlayer.stop();
let date = new Date();
radio.station = station;
radio.textChannel = interaction.channel;
radio.startTime = date.getTime();
play(interaction, interaction.guild, client, url, Discord);
return;
}
const construct = {
textChannel: interaction.channel,
voiceChannel: voiceChannel,
connection: null,
message: null,
audioPlayer: createAudioPlayer(),
station: station
};
client.radio.set(interaction.guild.id, construct);
try {
const connection =
getVoiceConnection(voiceChannel.guild.id) ??
joinVoiceChannel({
channelId: voiceChannel.id,
guildId: voiceChannel.guild.id,
adapterCreator: voiceChannel.guild.voiceAdapterCreator
});
construct.connection = connection;
let date = new Date();
construct.startTime = date.getTime();
play(interaction, interaction.guild, client, url, Discord);
client.datastore.checkEntry(interaction.guild.id);
construct.currentGuild = client.datastore.getEntry(interaction.guild.id);
if (!construct.currentGuild.statistics[construct.station.name]) {
construct.currentGuild.statistics[construct.station.name] = {};
construct.currentGuild.statistics[construct.station.name].time = 0;
construct.currentGuild.statistics[construct.station.name].used = 0;
client.datastore.updateEntry(interaction.guild, construct.currentGuild);
}
} catch (error) {
console.log(error);
client.radio.delete(interaction.guild.id);
return interaction.reply(client.messageEmojis["error"] + `An error occured: ${error}`);
}
}
};
async function play(interaction, guild, client, url, Discord) {
let message = {};
const radio = client.radio.get(guild.id);
const resource = createAudioResource(url);
radio.connection.subscribe(radio.audioPlayer);
radio.audioPlayer.play(resource);
resource.playStream
.on("readable", () => {
client.funcs.logger('Radio', 'Stream started' + " / " + guild.id + " / " + radio.station.name);
})
.on("finish", () => {
client.funcs.logger('Radio', 'Stream finished' + " / " + guild.id);
client.funcs.statisticsUpdate(client, guild, radio);
radio.connection?.destroy();
radio.audioPlayer?.stop();
client.radio.delete(guild.id);
return;
})
.on("error", error => {
client.funcs.logger('Radio', 'Stream errored');
console.error(error);
radio.connection?.destroy();
radio.audioPlayer?.stop();
client.radio.delete(guild.id);
return interaction.reply(client.messages.errorPlaying);
});
message.nowplayingDescription = client.messages.nowplayingDescription.replace("%radio.station.name%", radio.station.name);
message.nowplayingDescription = message.nowplayingDescription.replace("%radio.station.owner%", radio.station.owner);
message.nowplayingDescription = message.nowplayingDescription.replace("%client.funcs.msToTime(completed)%", "");
message.nowplayingDescription = message.nowplayingDescription.replace("Owner: ", "");
message.nowplayingDescription = message.nowplayingDescription.replace("**", "");
message.nowplayingDescription = message.nowplayingDescription.replace("**", "");
const embed = new Discord.MessageEmbed()
.setTitle(client.user.username)
.setThumbnail("https://cdn.discordapp.com/emojis/" + client.messageEmojis["play"].replace(/[^0-9]+/g, ''))
.setColor(client.config.embedColor)
.addField(client.messages.nowplayingTitle, message.nowplayingDescription, true)
.setFooter(client.messages.footerText, "https://cdn.discordapp.com/emojis/" + client.messageEmojis["eximiabots"].replace(/[^0-9]+/g, ''));
const buttons = new Discord.MessageActionRow()
.addComponents(
new Discord.MessageButton()
.setCustomId('list')
.setEmoji(client.messageEmojis["list"])
.setStyle('SECONDARY')
)
.addComponents(
new Discord.MessageButton()
.setCustomId('prev')
.setEmoji(client.messageEmojis["prev"])
.setStyle('SECONDARY')
.setDisabled(true)
)
.addComponents(
new Discord.MessageButton()
.setCustomId('stop')
.setEmoji(client.messageEmojis["stop"])
.setStyle('SECONDARY')
)
.addComponents(
new Discord.MessageButton()
.setCustomId('next')
.setEmoji(client.messageEmojis["next"])
.setStyle('SECONDARY')
.setDisabled(true)
)
.addComponents(
new Discord.MessageButton()
.setCustomId('statistics')
.setEmoji(client.messageEmojis["statistics"])
.setStyle('SECONDARY')
);
if(!radio.message){
radio.message = await radio.textChannel.send({ embeds: [embed], components: [buttons] });
} else {
radio.message.edit({ embeds: [embed], components: [buttons] });
}
message.play = client.messages.play.replace("%radio.station.name%", radio.station.name);
interaction.reply({
content: client.messageEmojis["play"] + message.play,
ephemeral: true
});
}
function searchStation(key, client) {
if (client.stations === null) return false;
let foundStations = [];
if (!key) return false;
if (key == "radio") return false;
client.stations
.filter(
x => x.name.toUpperCase().includes(key.toUpperCase()) || x === key
)
.forEach(x =>
foundStations.push({ station: x, name: x.name, probability: 100 })
);
if (key.startsWith("radio ")) key = key.slice(6);
const probabilityIncrement = 100 / key.split(" ").length / 2;
for (let i = 0; i < key.split(" ").length; i++) {
client.stations
.filter(
x => x.name.toUpperCase().includes(key.split(" ")[i].toUpperCase()) || x === key
)
.forEach(x =>
foundStations.push({ station: x, name: x.name, probability: probabilityIncrement })
);
}
if (foundStations.length === 0) return false;
for (let i = 0; i < foundStations.length; i++) {
for (let j = 0; j < foundStations.length; j++) {
if (foundStations[i] === foundStations[j] && i !== j) foundStations.splice(i, 1);
}
}
for (let i = 0; i < foundStations.length; i++) {
if (foundStations[i].name.length > key.length) {
foundStations[i].probability -=
(foundStations[i].name.split(" ").length - key.split(" ").length) *
(probabilityIncrement * 0.5);
} else if (foundStations[i].name.length === key.length) {
foundStations[i].probability += probabilityIncrement * 0.9;
}
for (let j = 0; j < key.split(" ").length; j++) {
if (!foundStations[i].name.toUpperCase().includes(key.toUpperCase().split(" ")[j])) {
foundStations[i].probability -= probabilityIncrement * 0.5;
}
}
}
let highestProbabilityStation;
for (let i = 0; i < foundStations.length; i++) {
if (
!highestProbabilityStation ||
highestProbabilityStation.probability < foundStations[i].probability
)
highestProbabilityStation = foundStations[i];
if (
highestProbabilityStation &&
highestProbabilityStation.probability === foundStations[i].probability
) {
highestProbabilityStation = foundStations[i].station;
}
}
return highestProbabilityStation;
}

View File

@ -2,19 +2,19 @@ module.exports = {
name: 'statistics',
alias: 'stats',
usage: '',
description: 'Show usage statistics.',
description: 'Show statistics',
permission: 'none',
category: 'info',
execute(msg, args, client, Discord, command) {
execute(interaction, client, Discord, command) {
let message = {};
let stations = client.stations;
let currentGuild = client.datastore.getEntry(msg.guild.id);
let currentGuild = client.datastore.getEntry(interaction.guild.id);
let statistics = "";
if(!client.stations) {
message.errorToGetPlaylist = client.messages.errorToGetPlaylist.replace("%client.config.supportGuild%", client.config.supportGuild);
return msg.channel.send(client.messageEmojis["error"] + message.errorToGetPlaylist);
}
if(!client.stations) {
message.errorToGetPlaylist = client.messages.errorToGetPlaylist.replace("%client.config.supportGuild%", client.config.supportGuild);
return interaction.reply(client.messageEmojis["error"] + message.errorToGetPlaylist);
}
if(!currentGuild || currentGuild && !currentGuild.statistics){
statistics = "You have not listened any radio station";
@ -22,7 +22,7 @@ module.exports = {
Object.keys(stations).forEach(function(station) {
if(currentGuild.statistics[stations[station].name] && currentGuild.statistics[stations[station].name].time && parseInt(currentGuild.statistics[stations[station].name].time) > 0 && currentGuild.statistics[stations[station].name].used && parseInt(currentGuild.statistics[stations[station].name].used) > 0){
statistics += `**${parseInt(station) + 1}** ` + stations[station].name + " \n";
statistics += "Time: " + client.funcs.msToTime(currentGuild.statistics[stations[station].name].time, "dd:hh:mm:ss") + "\n";
statistics += "Time: " + client.funcs.msToTime(currentGuild.statistics[stations[station].name].time) + "\n";
statistics += "Used: " + currentGuild.statistics[stations[station].name].used + "\n";
}
});
@ -34,6 +34,10 @@ module.exports = {
.setColor(client.config.embedColor)
.setDescription(statistics)
.setFooter(client.messages.footerText, "https://cdn.discordapp.com/emojis/" + client.messageEmojis["eximiabots"].replace(/[^0-9]+/g, ''));
return msg.channel.send(embed);
interaction.reply({
embeds: [embed],
ephemeral: true
});
}
};

View File

@ -1,27 +1,31 @@
module.exports = {
name: 'status',
alias: 'none',
alias: 'st',
usage: '',
description: 'Bot Status',
permission: 'none',
category: 'info',
async execute(msg, args, client, Discord, command) {
async execute(interaction, client, Discord, command) {
let message = {};
message.statusTitle = client.messages.statusTitle.replace("%client.user.username%", client.user.username);
let uptime = client.funcs.msToTime(client.uptime, "dd:hh:mm:ss");
let uptime = client.funcs.msToTime(client.uptime);
const embed = new Discord.MessageEmbed()
.setTitle(message.statusTitle)
.setThumbnail("https://cdn.discordapp.com/emojis/" + client.messageEmojis["logo"].replace(/[^0-9]+/g, ''))
.setColor(client.config.embedColor)
.addField(client.messages.statusField1, Date.now() - msg.createdTimestamp + "ms", true)
.addField(client.messages.statusField1, Date.now() - interaction.createdTimestamp + "ms", true)
.addField(client.messages.statusField2, client.ws.ping + "ms", true)
.addField(client.messages.statusField3, uptime, true)
.addField(client.messages.statusField4, client.config.version, true)
.addField(client.messages.statusField5, client.config.hostedBy, true)
.setFooter(client.messages.footerText, "https://cdn.discordapp.com/emojis/" + client.messageEmojis["eximiabots"].replace(/[^0-9]+/g, ''));
msg.channel.send(embed);
interaction.reply({
embeds: [embed],
ephemeral: true
});
}
};

View File

@ -0,0 +1,41 @@
module.exports = {
name: 'stop',
description: 'Stop radio',
alias: 's',
usage: '',
permission: 'none',
category: 'radio',
async execute(interaction, client, Discord, command) {
const radio = client.radio.get(interaction.guild.id);
if (client.funcs.check(client, interaction, command)) {
client.funcs.statisticsUpdate(client, interaction.guild, radio);
radio.connection?.destroy();
radio.audioPlayer?.stop();
client.funcs.logger('Radio', 'Stream stopped' + " / " + interaction.guild.id);
const embed = new Discord.MessageEmbed()
.setTitle(client.user.username)
.setThumbnail("https://cdn.discordapp.com/emojis/" + client.messageEmojis["stop"].replace(/[^0-9]+/g, ''))
.setColor(client.config.embedColor)
.addField(client.messages.nowplayingTitle, "-", true)
.setFooter(client.messages.footerText, "https://cdn.discordapp.com/emojis/" + client.messageEmojis["eximiabots"].replace(/[^0-9]+/g, ''));
if(!radio.message){
radio.message = radio.textChannel.send({ embeds: [embed], components: [] });
} else {
radio.message.edit({ embeds: [embed], components: [] });
}
setTimeout(async function() {
await radio.message?.delete();
}, 5000);
client.radio.delete(interaction.guild.id);
interaction.reply({
content: client.messageEmojis["stop"] + client.messages.stop,
ephemeral: true
});
}
}
};

View File

@ -8,11 +8,15 @@ module.exports = class {
}
loadData() {
const dir = path.join(path.dirname(__dirname), '../datastore');
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
//console.log("");
const dataFiles = fs.readdirSync(path.join(path.dirname(__dirname), 'datastore')).filter(f => f.endsWith('.json'));
const dataFiles = fs.readdirSync(path.join(path.dirname(__dirname), '../datastore')).filter(f => f.endsWith('.json'));
for (const file of dataFiles) {
try {
const json = require(`../datastore/${file}`);
const json = require(`../../datastore/${file}`);
this.map.set(json.guild.id, json);
//console.log('[LOADED] ' + file + " (" + json.guild.id + ")");
//console.log(JSON.stringify(json, null, 4));
@ -76,6 +80,7 @@ module.exports = class {
newData.guild = {};
newData.guild.id = id;
newData.statistics = {};
newData.state = {};
this.map.set(id, newData);
this.saveEntry(id, newData);
}
@ -86,6 +91,10 @@ module.exports = class {
updateEntry(guild, newData) {
newData.guild.name = guild.name;
let date = new Date();
newData.updated = date.toISOString().substring(0, 10)
this.map.set(guild.id, newData);
this.saveEntry(guild.id, newData);
//this.showEntry(this.getEntry(guild.id));
@ -106,6 +115,9 @@ module.exports = class {
"time": 0,
"used": 0
}
},
"state": {
}
}
@ -115,7 +127,7 @@ module.exports = class {
saveEntry(file, data) {
data = JSON.stringify(data, null, 4);
fs.writeFile(path.join(path.dirname(__dirname), 'datastore') + "/" + file + ".json", data, 'utf8', function(err) {
fs.writeFile(path.join(path.dirname(__dirname), '../datastore') + "/" + file + ".json", data, 'utf8', function(err) {
if (err) {
//console.log(err);
}

View File

@ -9,7 +9,9 @@ module.exports = {
stop: "<:RadioXStop:688541155377414168>",
statistics: "<:RadioXStatistics:694954485507686421>",
maintenance: "<:RadioXMaintenance:695043843057254493>",
error: "<:RadioXError:688541155792781320>"
error: "<:RadioXError:688541155792781320>",
prev: "<:RadioXPrev:882153637370023957>",
next: "<:RadioXNext:882153637474893834>"
};
let fallbackEmojis = {
@ -20,14 +22,16 @@ module.exports = {
stop: "⏹️",
statistics: "📊",
maintenance: "🛠️",
error: "❌"
error: "❌",
prev: "⏪",
next: "⏩"
};
client.messageEmojis = {};
for (customEmojiName in customEmojis) {
customEmojiID = customEmojis[customEmojiName].replace(/[^0-9]+/g, '');
customEmoji = client.emojis.cache.get(customEmojiID);
for (const customEmojiName in customEmojis) {
const customEmojiID = customEmojis[customEmojiName].replace(/[^0-9]+/g, '');
const customEmoji = client.emojis.cache.get(customEmojiID);
if (customEmoji) {
client.messageEmojis[customEmojiName] = customEmojis[customEmojiName];
} else {

View File

@ -0,0 +1,43 @@
import Discord from "discord.js";
module.exports = {
name: 'SIGINT',
async execute(client) {
setTimeout(async function () {
let message = {};
if (!client.stations) return process.exit();
let currentRadios = client.radio.keys();
let radio = currentRadios.next();
while (!radio.done) {
let currentRadio = client.radio.get(radio.value);
currentRadio.guild = client.datastore.getEntry(radio.value).guild;
if (currentRadio) {
client.funcs.statisticsUpdate(client, currentRadio.guild, currentRadio);
client.funcs.saveState(client, currentRadio.guild, currentRadio);
currentRadio.connection?.destroy();
currentRadio.audioPlayer?.stop();
currentRadio.message?.delete();
client.radio.delete(radio.value);
}
radio = currentRadios.next();
}
console.log("\n");
client.funcs.logger("Bot", "Closing");
console.log("\n");
client.user.setStatus('dnd');
setInterval(() => {
if(radio.done){
process.exit();
}
}, 1000);
}, 5000);
}
}

View File

@ -0,0 +1,6 @@
module.exports = {
name: 'SIGTERM',
async execute(client) {
process.emit('SIGINT');
}
}

View File

@ -0,0 +1,40 @@
import Discord from "discord.js";
module.exports = {
name: 'interactionCreate',
async execute(client, interaction) {
const permissions = interaction.channel.permissionsFor(interaction.client.user);
if (!permissions.has('EMBED_LINKS')) return interaction.send(client.messages.noPermsEmbed);
if(interaction.isCommand()){
const commandName = interaction.commandName;
const command = client.commands.get(commandName);
if (!command) return;
try {
command.execute(interaction, client, Discord, command);
} catch (error) {
interaction.reply({
content: client.messages.runningCommandFailed,
ephemeral: true
});
console.error(error);
}
} else if (interaction.isSelectMenu() || interaction.isButton()){
const commandName = interaction.customId;
const command = client.commands.get(commandName);
if (!command) return;
try {
command.execute(interaction, client, Discord, command);
} catch (error) {
interaction.reply({
content: client.messages.runningCommandFailed,
ephemeral: true
});
console.error(error);
}
}
}
}

View File

@ -0,0 +1,54 @@
import Discord from "discord.js";
module.exports = {
name: 'messageCreate',
async execute(client, msg) {
if (msg.author.bot || !msg.guild) return;
let prefix = "rx$";
if(client.user.username == "RadioX"){
prefix = "rx>";
} else if (client.user.username == "RadioX Beta"){
prefix = "rx-";
} else if (client.user.username == "RadioX Dev"){
prefix = "rx$";
} else if(msg.mentions.members.first() && msg.mentions.members.first().user.id === client.user.id){
prefix = "<@!" + client.user.id + "> ";
} else {
return;
}
const args = msg.content.slice(prefix.length).split(' ');
if (!msg.content.startsWith(prefix)) return;
if (!args[0]) return;
const commandName = args[0].toLowerCase();
if (commandName === 'none') return;
const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName)) || client.commandAliases.get(commandName);
if (!command && msg.content !== `${prefix}`) return;
const permissions = msg.channel.permissionsFor(msg.client.user);
if (!permissions.has('EMBED_LINKS')) return msg.channel.send(client.messages.noPermsEmbed);
try {
let message = {};
message.messageCommandsDeprecatedTitle = client.messages.messageCommandsDeprecatedTitle.replace("%client.user.username%", client.user.username);
const embed = new Discord.MessageEmbed()
.setTitle(message.messageCommandsDeprecatedTitle)
.setThumbnail("https://cdn.discordapp.com/emojis/" + client.messageEmojis["logo"].replace(/[^0-9]+/g, ''))
.setColor(client.config.embedColor)
.setDescription(client.messages.messageCommandsDeprecatedDescription)
.setFooter(client.messages.footerText, "https://cdn.discordapp.com/emojis/" + client.messageEmojis["eximiabots"].replace(/[^0-9]+/g, ''));
msg.channel.send({ embeds: [embed] });
setTimeout(function() {
msg.delete();
}, 30000);
} catch (error) {
msg.reply({
content: client.messages.runningCommandFailed,
ephemeral: true
});
console.error(error);
}
}
}

View File

@ -0,0 +1,10 @@
module.exports = {
name: 'messageDelete',
async execute(client, msg) {
if (!msg.author.bot || !msg.guild) return;
const radio = client.radio.get(msg.guild.id);
if (!radio) return;
if(msg.id != radio.message.id) return;
radio.message = null;
}
}

View File

@ -0,0 +1,94 @@
import Datastore from "../datastore.js";
import fetch from "node-fetch";
module.exports = {
name: 'ready',
async execute(client) {
client.funcs.logger("Bot", "Ready");
/*DATASTORE*/
client.funcs.logger('Datastore', 'Initialize');
client.datastore = new Datastore();
/*DEVELOPERS*/
client.funcs.logger('Developers');
client.developers = "";
let user = "";
for (let i = 0; i < client.config.devId.length; i++) {
user = await client.users.fetch(client.config.devId[i]);
console.log("- " + user.tag);
if (i == client.config.devId.length - 1) {
client.developers += user.tag;
} else {
client.developers += user.tag + " & ";
}
}
console.log("\n");
/*STATIONS*/
try {
client.funcs.logger('Stations', 'Started fetching list ' + client.config.stationslistUrl);
client.stations = await fetch(client.config.stationslistUrl)
.then(client.funcs.checkFetchStatus)
.then(response => response.json());
client.funcs.logger('Stations');
client.stations.forEach(station => {
console.log("- " + station.name);
});
console.log("\n");
client.funcs.logger('Stations', 'Successfully fetched list');
} catch (error) {
client.funcs.logger('Stations', 'Fetching list failed');
console.error(error + "\n");
}
setInterval(async () => {
try {
client.funcs.logger('Stations', 'Started fetching list ' + client.config.stationslistUrl);
client.stations = await fetch(client.config.stationslistUrl)
.then(client.funcs.checkFetchStatus)
.then(response => response.json());
client.funcs.logger('Stations', 'Successfully fetched list');
} catch (error) {
client.funcs.logger('Stations', 'Fetching list failed');
//console.error(error);
}
}, 3600000);
if(!client.stations) {
client.user.setStatus('dnd');
}
/*GUILDS*/
client.funcs.logger('Guilds', 'Started fetching list');
client.funcs.logger('Guilds');
let guilds = await client.guilds.fetch();
guilds.forEach(guild => {
console.log("- " + guild.id + ": " + guild.name);
});
console.log("\n");
client.funcs.logger('Guilds', 'Successfully fetched list');
/*STATISTICS*/
client.datastore.calculateGlobal(client);
/*EMOJIS*/
require(`../emojis.js`).execute(client);
/*COMMANDS*/
require(`../commands.js`).execute(client);
setTimeout(function () {
/*RESTORE RADIO*/
require(`../restoreradio.js`).execute(client, guilds);
}, 5000);
}
}

View File

@ -1,3 +1,8 @@
const {
getVoiceConnection,
joinVoiceChannel
} = require("@discordjs/voice");
module.exports = {
name: "voiceStateUpdate",
async execute(client, oldState, newState) {
@ -7,8 +12,13 @@ module.exports = {
if (!radio) return;
if (newState.member.id === client.user.id && oldState.member.id === client.user.id) {
if (newState.channel === null) {
client.funcs.statisticsUpdate(client, newState.guild, radio);
radio.connection?.destroy();
radio.audioPlayer?.stop();
radio.message?.delete();
client.funcs.logger('Radio', 'Stream stopped' + " / " + newState.guild.id);
return client.radio.delete(newState.guild.id);
}
@ -16,13 +26,22 @@ module.exports = {
if (!newPermissions.has("CONNECT") || !newPermissions.has("SPEAK") || !newPermissions.has("VIEW_CHANNEL")) {
try {
setTimeout(
async () => (radio.connection = await oldState.channel.join()),
async () => (
radio.connection = joinVoiceChannel({
channelId: oldState.channel.id,
guildId: oldState.channel.guild.id,
adapterCreator: oldState.channel.guild.voiceAdapterCreator
})
//radio.connection = await oldState.channel.join()
),
1000
);
} catch (error) {
client.funcs.statisticsUpdate(client, newState.guild, radio);
radio.connection.dispatcher.destroy();
radio.voiceChannel.leave();
radio.connection?.destroy();
radio.audioPlayer?.stop();
radio.message?.delete();
client.funcs.logger('Radio', 'Stream stopped' + " / " + newState.guild.id);
client.radio.delete(oldState.guild.id);
}
return;
@ -30,19 +49,22 @@ module.exports = {
if (newState.channel !== radio.voiceChannel) {
change = true;
radio.voiceChannel = newState.channel;
radio.connection = await newState.channel.join();
radio.connection = getVoiceConnection(newState.channel.guild.id);
//radio.connection = await newState.channel.join();
}
}
if ((oldState.channel.members.size === 1 && oldState.channel === radio.voiceChannel) || change) {
setTimeout(() => {
if (!radio || !radio.connection.dispatcher || !radio.connection.dispatcher === null) return;
if (!radio || !radio.connection || !radio.connection === null) return;
if (radio.voiceChannel.members.size === 1) {
client.funcs.statisticsUpdate(client, newState.guild, radio);
radio.connection.dispatcher.destroy();
radio.voiceChannel.leave();
radio.connection?.destroy();
radio.audioPlayer?.stop();
radio.message?.delete();
client.funcs.logger('Radio', 'Stream stopped' + " / " + newState.guild.id);
client.radio.delete(newState.guild.id);
}
}, 120000);
}, 60000);
}
},
};

29
src/client/funcs/check.js Normal file
View File

@ -0,0 +1,29 @@
module.exports = function (client, interaction, command) {
let message = {};
const radio = client.radio.get(interaction.guild.id);
const permissions = interaction.channel.permissionsFor(interaction.user);
if (!radio) {
interaction.reply({
content: client.messageEmojis["error"] + client.messages.notPlaying,
ephemeral: true
});
return false;
}
if (interaction.member.voice.channel !== radio.voiceChannel) {
interaction.reply({
content: client.messageEmojis["error"] + client.messages.wrongVoiceChannel,
ephemeral: true
});
return false;
}
if(!command.permission == 'none'){
if (!permissions.has(command.permission)) {
message.noPerms = client.messages.noPerms.replace("%command.permission%", command.permission);
interaction.reply({
content: client.messageEmojis["error"] + message.noPerms,
ephemeral: true
});
return false;
} else return true;
} else return true;
};

View File

@ -1,7 +1,7 @@
module.exports = function (devList, authorID){
let response = false;
Object.keys(devList).forEach(function(oneDev) {
devID = devList[oneDev];
let devID = devList[oneDev];
if(authorID == devID){
response = true;
}

View File

@ -0,0 +1,10 @@
module.exports = function loadState(client, guild){
let data = client.datastore.getEntry(guild.id);
if(!data) return;
let state;
state = data.state;
data.state = {};
client.datastore.updateEntry(guild, data);
return state;
}

View File

@ -0,0 +1,5 @@
module.exports = function (area, text){
let date = new Date();
console.log('[' + area + '] ' + date.toISOString());
if(text) console.log(text + '\n');
}

View File

@ -0,0 +1,12 @@
module.exports = function msToTime(duration) {
let seconds = Math.floor((duration / 1000) % 60),
minutes = Math.floor((duration / (1000 * 60)) % 60),
hours = Math.floor((duration / (1000 * 60 * 60)) % 24),
days = Math.floor((duration / (1000 * 60 * 60 * 24)));
return +days > 0
? `${days}:${+hours < 10 ? `0${hours}` : hours}:${+minutes < 10 ? `0${minutes}` : minutes}:${+seconds < 10 ? `0${seconds}` : seconds}`
: +hours > 0
? `${+hours < 10 ? `0${hours}` : hours}:${+minutes < 10 ? `0${minutes}` : minutes}:${+seconds < 10 ? `0${seconds}` : seconds}`
: `${+minutes < 10 ? `0${minutes}` : minutes}:${+seconds < 10 ? `0${seconds}` : seconds}`;
}

View File

@ -0,0 +1,18 @@
module.exports = function saveState(client, guild, radio){
client.datastore.checkEntry(guild.id);
let date = new Date();
let data = client.datastore.getEntry(guild.id);
data.state = {};
data.state.channels = {};
data.state.channels.text = radio.textChannel.id;
data.state.channels.voice = radio.voiceChannel.id;
data.state.date = date.toISOString();
data.state.station = {};
data.state.station.name = radio.station.name;
data.state.station.owner = radio.station.owner;
client.datastore.updateEntry(guild, data);
}

View File

@ -0,0 +1,22 @@
module.exports = function statisticsUpdate(client, guild, radio) {
client.datastore.checkEntry(guild.id);
radio.datastore = client.datastore.getEntry(guild.id);
if(!radio.datastore.statistics[radio.station.name]){
radio.datastore.statistics[radio.station.name] = {};
radio.datastore.statistics[radio.station.name].time = 0;
radio.datastore.statistics[radio.station.name].used = 0;
client.datastore.updateEntry(guild, radio.datastore);
}
let date = new Date();
radio.currentTime = date.getTime();
radio.playTime = parseInt(radio.currentTime)-parseInt(radio.startTime);
radio.datastore.statistics[radio.station.name].time = parseInt(radio.datastore.statistics[radio.station.name].time)+parseInt(radio.playTime);
radio.datastore.statistics[radio.station.name].used = parseInt(radio.datastore.statistics[radio.station.name].used)+1;
client.datastore.updateEntry(guild, radio.datastore);
client.datastore.calculateGlobal(client);
}

View File

@ -7,13 +7,11 @@ module.exports = {
bugTitle: "Found a bug with %client.user.username%?",
bugDescription: "Join the support server \n %client.config.supportGuild%",
helpTitle: "%client.user.username% help:",
helpDescription: "%commands% \n %client.config.prefix%help <command> to see more information about a command.",
helpCommandTitle: "%client.config.prefix%%command.name% %command.usage%",
helpCommandDescription: "%command.description% \n Command Alias: %command.alias%",
helpDescription: "%commands%",
inviteTitle: "Invite %client.user.username% to your Discord server!",
listTitle: "Radio Stations",
nowplayingTitle: "Now Playing",
nowplayingDescription: "**%radio.station.name%** \n Owner: %radio.station.owner% \n %client.funcs.msToTime(completed, \"hh:mm:ss\")%",
nowplayingDescription: "**%radio.station.name%** \n Owner: %radio.station.owner% \n %client.funcs.msToTime(completed)%",
noVoiceChannel: "You need to be in a voice channel to play radio!",
noQuery: "You need to use a number or search for a supported station!",
noPermsConnect: "I cannot connect to your voice channel.",
@ -24,11 +22,6 @@ module.exports = {
errorPlaying: "An error has occured while playing radio!",
play: "Start playing: %radio.station.name%",
stop: "Stopped playback!",
currentVolume: "Current volume: **%radio.volume%**",
maxVolume: "The max volume is `100`!",
invalidVolume: "You need to enter a valid __number__.",
negativeVolume: "The volume needs to be a positive number!",
newVolume: "Volume is now: **%volume%**",
statisticsTitle: "Statistics",
maintenanceTitle: "Maintenance",
errorToGetPlaylist: "You can't use this bot because it has no playlist available. Check more information in our Discord support server %client.config.supportGuild% !",
@ -41,5 +34,7 @@ module.exports = {
statusField3: "Uptime",
statusField4: "Version",
statusField5: "Hosted by",
errorStationURL: "Station can't be URL"
errorStationURL: "Station can't be URL",
messageCommandsDeprecatedTitle: "%client.user.username%",
messageCommandsDeprecatedDescription: "We recommend you to reauthorize our bot by clicking the invite link down below, because Discord is planning to remove message content from verified bots [Read More](https://support-dev.discord.com/hc/en-us/articles/4404772028055) \n\n **Invite Bot** \n https://wgi.fi/radiox_invite \n\n This bot now supports slash commands, you should start using them instead. Type / into the message box and select the bot you wish to use. Remember to be careful as there are a few bugs here and there on Discord. \n\n We will remove this deprecation message in March of 2022 when RadioX 1.0.0 is released."
};

207
src/client/restoreradio.js Normal file
View File

@ -0,0 +1,207 @@
import Discord from "discord.js";
const {
createAudioPlayer,
createAudioResource,
getVoiceConnection,
joinVoiceChannel
} = require("@discordjs/voice");
module.exports = {
async execute(client, guilds) {
guilds.forEach(async guild => {
let state = client.funcs.loadState(client, guild);
if(!state) return;
if(!state.station || !state.channels.voice || !state.channels.text) return;
const sstation = await searchStation(state.station.name, client);
let url = sstation.stream[sstation.stream.default];
let station = sstation;
const construct = {
textChannel: client.channels.cache.get(state.channels.text),
voiceChannel: client.channels.cache.get(state.channels.voice),
connection: null,
message: null,
audioPlayer: createAudioPlayer(),
station: station
};
client.radio.set(guild.id, construct);
try {
let voiceChannel = client.channels.cache.get(state.channels.voice);
const connection =
getVoiceConnection(guild.id) ??
joinVoiceChannel({
channelId: voiceChannel.id,
guildId: voiceChannel.guild.id,
adapterCreator: voiceChannel.guild.voiceAdapterCreator
});
construct.connection = connection;
let date = new Date();
construct.startTime = date.getTime();
play(null, guild, client, url, Discord);
client.datastore.checkEntry(guild.id);
construct.datastore = client.datastore.getEntry(guild.id);
if (!construct.datastore.statistics[construct.station.name]) {
construct.datastore.statistics[construct.station.name] = {};
construct.datastore.statistics[construct.station.name].time = 0;
construct.datastore.statistics[construct.station.name].used = 0;
client.datastore.updateEntry(guild, construct.datastore);
}
} catch (error) {
console.log(error);
}
});
}
}
async function play(interaction, guild, client, url, Discord) {
let message = {};
const radio = client.radio.get(guild.id);
const resource = createAudioResource(url);
radio.connection.subscribe(radio.audioPlayer);
radio.audioPlayer.play(resource);
resource.playStream
.on("readable", () => {
client.funcs.logger('Radio', 'Stream started' + " / " + guild.id + " / " + radio.station.name);
})
.on("finish", () => {
client.funcs.logger('Radio', 'Stream finished' + " / " + guild.id);
client.funcs.statisticsUpdate(client, guild, radio);
radio.connection?.destroy();
radio.audioPlayer?.stop();
client.radio.delete(guild.id);
return;
})
.on("error", error => {
client.funcs.logger('Radio', 'Stream errored');
console.error(error);
radio.connection?.destroy();
radio.audioPlayer?.stop();
client.radio.delete(guild.id);
});
message.nowplayingDescription = client.messages.nowplayingDescription.replace("%radio.station.name%", radio.station.name);
message.nowplayingDescription = message.nowplayingDescription.replace("%radio.station.owner%", radio.station.owner);
message.nowplayingDescription = message.nowplayingDescription.replace("%client.funcs.msToTime(completed)%", "");
message.nowplayingDescription = message.nowplayingDescription.replace("Owner: ", "");
message.nowplayingDescription = message.nowplayingDescription.replace("**", "");
message.nowplayingDescription = message.nowplayingDescription.replace("**", "");
const embed = new Discord.MessageEmbed()
.setTitle(client.user.username)
.setThumbnail("https://cdn.discordapp.com/emojis/" + client.messageEmojis["play"].replace(/[^0-9]+/g, ''))
.setColor(client.config.embedColor)
.addField(client.messages.nowplayingTitle, message.nowplayingDescription, true)
.setFooter(client.messages.footerText, "https://cdn.discordapp.com/emojis/" + client.messageEmojis["eximiabots"].replace(/[^0-9]+/g, ''));
const buttons = new Discord.MessageActionRow()
.addComponents(
new Discord.MessageButton()
.setCustomId('list')
.setEmoji(client.messageEmojis["list"])
.setStyle('SECONDARY')
)
.addComponents(
new Discord.MessageButton()
.setCustomId('prev')
.setEmoji(client.messageEmojis["prev"])
.setStyle('SECONDARY')
.setDisabled(true)
)
.addComponents(
new Discord.MessageButton()
.setCustomId('stop')
.setEmoji(client.messageEmojis["stop"])
.setStyle('SECONDARY')
)
.addComponents(
new Discord.MessageButton()
.setCustomId('next')
.setEmoji(client.messageEmojis["next"])
.setStyle('SECONDARY')
.setDisabled(true)
)
.addComponents(
new Discord.MessageButton()
.setCustomId('statistics')
.setEmoji(client.messageEmojis["statistics"])
.setStyle('SECONDARY')
);
if(!radio.message){
radio.message = await radio.textChannel.send({ embeds: [embed], components: [buttons] });
} else {
radio.message.edit({ embeds: [embed], components: [buttons] });
}
message.play = client.messages.play.replace("%radio.station.name%", radio.station.name);
}
function searchStation(key, client) {
if (client.stations === null) return false;
let foundStations = [];
if (!key) return false;
if (key == "radio") return false;
client.stations
.filter(
x => x.name.toUpperCase().includes(key.toUpperCase()) || x === key
)
.forEach(x =>
foundStations.push({ station: x, name: x.name, probability: 100 })
);
if (key.startsWith("radio ")) key = key.slice(6);
const probabilityIncrement = 100 / key.split(" ").length / 2;
for (let i = 0; i < key.split(" ").length; i++) {
client.stations
.filter(
x => x.name.toUpperCase().includes(key.split(" ")[i].toUpperCase()) || x === key
)
.forEach(x =>
foundStations.push({ station: x, name: x.name, probability: probabilityIncrement })
);
}
if (foundStations.length === 0) return false;
for (let i = 0; i < foundStations.length; i++) {
for (let j = 0; j < foundStations.length; j++) {
if (foundStations[i] === foundStations[j] && i !== j) foundStations.splice(i, 1);
}
}
for (let i = 0; i < foundStations.length; i++) {
if (foundStations[i].name.length > key.length) {
foundStations[i].probability -=
(foundStations[i].name.split(" ").length - key.split(" ").length) *
(probabilityIncrement * 0.5);
} else if (foundStations[i].name.length === key.length) {
foundStations[i].probability += probabilityIncrement * 0.9;
}
for (let j = 0; j < key.split(" ").length; j++) {
if (!foundStations[i].name.toUpperCase().includes(key.toUpperCase().split(" ")[j])) {
foundStations[i].probability -= probabilityIncrement * 0.5;
}
}
}
let highestProbabilityStation;
for (let i = 0; i < foundStations.length; i++) {
if (
!highestProbabilityStation ||
highestProbabilityStation.probability < foundStations[i].probability
)
highestProbabilityStation = foundStations[i];
if (
highestProbabilityStation &&
highestProbabilityStation.probability === foundStations[i].probability
) {
highestProbabilityStation = foundStations[i].station;
}
}
return highestProbabilityStation;
}

View File

@ -0,0 +1,3 @@
export interface command { }
export interface radio {}

View File

@ -17,11 +17,10 @@ module.exports = {
//misc
embedColor: "#88aa00",
invite: "https://discordapp.com/api/oauth2/authorize?client_id=684109535312609409&permissions=3427328&scope=bot",
hostedBy: "[Warén Group](https://waren.io)",
//Settings
prefix: process.env.RADIOX_PREFIX || "rx-",
version: process.env.RADIOX_VERSION || process.env.npm_package_version
version: process.env.RADIOX_VERSION || process.env.npm_package_version,
debug: process.env.DEBUG_MODE || false
}

3
src/index.js Normal file
View File

@ -0,0 +1,3 @@
const { default: RadioClient } = require("./Client");
const client = new RadioClient();

16
tsconfig.json Normal file
View File

@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["esnext"],
"allowJs": true,
"outDir": "build",
"rootDir": "src",
"strict": true,
"noImplicitAny": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"skipLibCheck": true
},
"exclude": ["build", "node_modules", "datastore"]
}