├── Procfile ├── settings.json ├── docker-compose.yml ├── Dockerfile ├── package.json ├── README.md ├── LICENSE ├── .dockerignore ├── CONTRIBUTING.md ├── CODE_OF_CONDUCT.md ├── .gitignore └── bot.js /Procfile: -------------------------------------------------------------------------------- 1 | worker: node bot.js 2 | -------------------------------------------------------------------------------- /settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "prefix": "!", 3 | "role": "DJ" 4 | } 5 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | 3 | services: 4 | sirgroove: 5 | build: . 6 | container_name: sirgroove 7 | restart: unless-stopped 8 | environment: 9 | - BOT_TOKEN= 10 | - YOUTUBE_API_KEY= 11 | - BOT_MASTER= 12 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:14-alpine 2 | 3 | LABEL maintainer="bananaprotocol@protonmail.com" 4 | 5 | WORKDIR /usr/share/app 6 | 7 | COPY package.json package-lock.json ./ 8 | 9 | RUN apk update 10 | RUN apk add --no-cache --virtual build-deps g++ make python 11 | RUN npm install 12 | RUN apk del build-deps 13 | RUN apk add --no-cache ffmpeg 14 | 15 | COPY . . 16 | 17 | ENV BOT_TOKEN= 18 | ENV YOUTUBE_API_KEY= 19 | ENV BOT_MASTER= 20 | 21 | CMD ["node", "bot.js"] 22 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "sirgroove", 3 | "version": "0.8.0", 4 | "description": "Music bot for Discord", 5 | "main": "bot.js", 6 | "scripts": { 7 | "start": "node bot.js" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/bananaprotocol/sirgroove.git" 12 | }, 13 | "keywords": [ 14 | "discord", 15 | "bot", 16 | "music" 17 | ], 18 | "author": "bananaprotocol", 19 | "license": "MIT", 20 | "dependencies": { 21 | "@discordjs/opus": "^0.3.2", 22 | "discord.js": "^12.4.0", 23 | "dotenv": "^8.2.0", 24 | "request": "^2.88.2", 25 | "ytdl-core": "^4.5.0" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `Sir Groove` - A simple music bot written in Discord.js 2 | 3 | ## Install 4 | 5 | ### Hosted by me 6 | 7 | [Discord Invite Link](https://discordapp.com/oauth2/authorize?client_id=380083023225421825&scope=bot) 8 | 9 | ### Self hosted 10 | Make sure to have `git`, `node` and `ffmpeg` installed. 11 | 12 | Clone the repo using 13 | 14 | git clone https://github.com/bananaprotocol/sirgroove 15 | 16 | Install all dependencies using 17 | 18 | npm install 19 | 20 | Make sure to have your bot token and YouTube API key set in .env 21 | 22 | ``` 23 | BOT_TOKEN=mytoken 24 | YOUTUBE_API_KEY=myapikey 25 | ``` 26 | Start the bot using 27 | 28 | npm start 29 | 30 | You can keep the bot up to date by using 31 | 32 | git pull && npm install 33 | 34 | ## Contributing 35 | Contributions are welcome! Please read the [contributing guidelines](CONTRIBUTING.md) before getting started. 36 | 37 | ## License 38 | [MIT](LICENSE) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018-2021 bananaprotocol 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | .env.test 60 | 61 | # parcel-bundler cache (https://parceljs.org/) 62 | .cache 63 | 64 | # next.js build output 65 | .next 66 | 67 | # nuxt.js build output 68 | .nuxt 69 | 70 | # vuepress build output 71 | .vuepress/dist 72 | 73 | # Serverless directories 74 | .serverless/ 75 | 76 | # FuseBox cache 77 | .fusebox/ 78 | 79 | # DynamoDB Local files 80 | .dynamodb/ 81 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | ## Code of Conduct 4 | 5 | This project is intended to be a safe, welcoming space for collaboration. All contributors are expected to adhere to the [Contributor Covenant](CODE_OF_CONDUCT.md) code of conduct. Thank you for being kind to each other! 6 | 7 | ## Contributions welcome! 8 | 9 | **Before spending lots of time on something, ask for feedback on your idea first!** 10 | 11 | Please search [issues](../../issues/) and [pull requests](../../pulls/) before adding something new! This helps avoid duplicating efforts and conversations. 12 | 13 | This project welcomes any kind of contribution! Here are a few suggestions: 14 | 15 | - **Ideas**: participate in an issue thread or start your own to have your voice heard. 16 | - **Writing**: contribute your expertise in an area by helping expand the included content. 17 | - **Copy editing**: fix typos, clarify language, and generally improve the quality of the content. 18 | - **Formatting**: help keep content easy to read with consistent formatting. 19 | - **Code**: help maintain and improve the project codebase. 20 | 21 | ## Project Governance 22 | 23 | **This is an [OPEN Open Source Project](http://openopensource.org/).** 24 | 25 | Individuals making significant and valuable contributions are given commit access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project. 26 | 27 | ### Rules 28 | 29 | There are a few basic ground rules for collaborators: 30 | 31 | 1. **No `--force` pushes** or modifying the Git history in any way. 32 | 1. **Non-master branches** ought to be used for ongoing work. 33 | 1. **External API changes and significant modifications** ought to be subject to an **internal pull request** to solicit feedback from other contributors. 34 | 1. Internal pull requests to solicit feedback are *encouraged* for any other non-trivial contribution but left to the discretion of the contributor. 35 | 1. Contributors should attempt to adhere to the prevailing code style. 36 | 37 | ### Releases 38 | 39 | Declaring formal releases remains the prerogative of the project maintainer. 40 | 41 | ### Changes to this arrangement 42 | 43 | This is an experiment and feedback is welcome! This document may also be subject to pull requests or changes by contributors where you believe you have something valuable to add or change. -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at thebananaprotocol@gmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: http://contributor-covenant.org 74 | [version]: http://contributor-covenant.org/version/1/4/ -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ### ArchLinuxPackages ### 2 | *.tar 3 | *.tar.* 4 | *.jar 5 | *.exe 6 | *.msi 7 | *.zip 8 | *.tgz 9 | *.log 10 | *.log.* 11 | *.sig 12 | 13 | pkg/ 14 | src/ 15 | 16 | ### Intellij ### 17 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 18 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 19 | 20 | # User-specific stuff: 21 | .idea/**/workspace.xml 22 | .idea/**/tasks.xml 23 | .idea/dictionaries 24 | 25 | # Sensitive or high-churn files: 26 | .idea/**/dataSources/ 27 | .idea/**/dataSources.ids 28 | .idea/**/dataSources.xml 29 | .idea/**/dataSources.local.xml 30 | .idea/**/sqlDataSources.xml 31 | .idea/**/dynamic.xml 32 | .idea/**/uiDesigner.xml 33 | 34 | # Gradle: 35 | .idea/**/gradle.xml 36 | .idea/**/libraries 37 | 38 | # CMake 39 | cmake-build-debug/ 40 | 41 | # Mongo Explorer plugin: 42 | .idea/**/mongoSettings.xml 43 | 44 | ## File-based project format: 45 | *.iws 46 | 47 | ## Plugin-specific files: 48 | 49 | # IntelliJ 50 | /out/ 51 | 52 | # mpeltonen/sbt-idea plugin 53 | .idea_modules/ 54 | 55 | # JIRA plugin 56 | atlassian-ide-plugin.xml 57 | 58 | # Cursive Clojure plugin 59 | .idea/replstate.xml 60 | 61 | # Ruby plugin and RubyMine 62 | /.rakeTasks 63 | 64 | # Crashlytics plugin (for Android Studio and IntelliJ) 65 | com_crashlytics_export_strings.xml 66 | crashlytics.properties 67 | crashlytics-build.properties 68 | fabric.properties 69 | 70 | ### Intellij Patch ### 71 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 72 | 73 | # *.iml 74 | # modules.xml 75 | # .idea/misc.xml 76 | # *.ipr 77 | 78 | # Sonarlint plugin 79 | .idea/sonarlint 80 | 81 | ### Linux ### 82 | *~ 83 | 84 | # temporary files which can be created if a process still has a handle open of a deleted file 85 | .fuse_hidden* 86 | 87 | # KDE directory preferences 88 | .directory 89 | 90 | # Linux trash folder which might appear on any partition or disk 91 | .Trash-* 92 | 93 | # .nfs files are created when an open file is removed but is still being accessed 94 | .nfs* 95 | 96 | ### macOS ### 97 | *.DS_Store 98 | .AppleDouble 99 | .LSOverride 100 | 101 | # Icon must end with two \r 102 | Icon 103 | 104 | # Thumbnails 105 | ._* 106 | 107 | # Files that might appear in the root of a volume 108 | .DocumentRevisions-V100 109 | .fseventsd 110 | .Spotlight-V100 111 | .TemporaryItems 112 | .Trashes 113 | .VolumeIcon.icns 114 | .com.apple.timemachine.donotpresent 115 | 116 | # Directories potentially created on remote AFP share 117 | .AppleDB 118 | .AppleDesktop 119 | Network Trash Folder 120 | Temporary Items 121 | .apdisk 122 | 123 | ### Node ### 124 | # Logs 125 | logs 126 | npm-debug.log* 127 | yarn-debug.log* 128 | yarn-error.log* 129 | 130 | # Runtime data 131 | pids 132 | *.pid 133 | *.seed 134 | *.pid.lock 135 | 136 | # Directory for instrumented libs generated by jscoverage/JSCover 137 | lib-cov 138 | 139 | # Coverage directory used by tools like istanbul 140 | coverage 141 | 142 | # nyc test coverage 143 | .nyc_output 144 | 145 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 146 | .grunt 147 | 148 | # Bower dependency directory (https://bower.io/) 149 | bower_components 150 | 151 | # node-waf configuration 152 | .lock-wscript 153 | 154 | # Compiled binary addons (http://nodejs.org/api/addons.html) 155 | build/Release 156 | 157 | # Dependency directories 158 | node_modules/ 159 | jspm_packages/ 160 | 161 | # Typescript v1 declaration files 162 | typings/ 163 | 164 | # Optional npm cache directory 165 | .npm 166 | 167 | # Optional eslint cache 168 | .eslintcache 169 | 170 | # Optional REPL history 171 | .node_repl_history 172 | 173 | # Output of 'npm pack' 174 | 175 | # Yarn Integrity file 176 | .yarn-integrity 177 | 178 | # dotenv environment variables file 179 | .env 180 | 181 | 182 | ### SublimeText ### 183 | # cache files for sublime text 184 | *.tmlanguage.cache 185 | *.tmPreferences.cache 186 | *.stTheme.cache 187 | 188 | # workspace files are user-specific 189 | *.sublime-workspace 190 | 191 | # project files should be checked into the repository, unless a significant 192 | # proportion of contributors will probably not be using SublimeText 193 | # *.sublime-project 194 | 195 | # sftp configuration file 196 | sftp-config.json 197 | 198 | # Package control specific files 199 | Package Control.last-run 200 | Package Control.ca-list 201 | Package Control.ca-bundle 202 | Package Control.system-ca-bundle 203 | Package Control.cache/ 204 | Package Control.ca-certs/ 205 | Package Control.merged-ca-bundle 206 | Package Control.user-ca-bundle 207 | oscrypto-ca-bundle.crt 208 | bh_unicode_properties.cache 209 | 210 | # Sublime-github package stores a github token in this file 211 | # https://packagecontrol.io/packages/sublime-github 212 | GitHub.sublime-settings 213 | 214 | ### VisualStudioCode ### 215 | .vscode/* 216 | !.vscode/settings.json 217 | !.vscode/tasks.json 218 | !.vscode/launch.json 219 | !.vscode/extensions.json 220 | .history 221 | 222 | ### WebStorm ### 223 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 224 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 225 | 226 | # User-specific stuff: 227 | 228 | # Sensitive or high-churn files: 229 | 230 | # Gradle: 231 | 232 | # CMake 233 | 234 | # Mongo Explorer plugin: 235 | 236 | ## File-based project format: 237 | 238 | ## Plugin-specific files: 239 | 240 | # IntelliJ 241 | 242 | # mpeltonen/sbt-idea plugin 243 | 244 | # JIRA plugin 245 | 246 | # Cursive Clojure plugin 247 | 248 | # Ruby plugin and RubyMine 249 | 250 | # Crashlytics plugin (for Android Studio and IntelliJ) 251 | 252 | ### WebStorm Patch ### 253 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 254 | 255 | # *.iml 256 | # modules.xml 257 | # .idea/misc.xml 258 | # *.ipr 259 | 260 | # Sonarlint plugin 261 | 262 | ### Windows ### 263 | # Windows thumbnail cache files 264 | Thumbs.db 265 | ehthumbs.db 266 | ehthumbs_vista.db 267 | 268 | # Folder config file 269 | Desktop.ini 270 | 271 | # Recycle Bin used on file shares 272 | $RECYCLE.BIN/ 273 | 274 | # Windows Installer files 275 | *.cab 276 | *.msm 277 | *.msp 278 | 279 | # Windows shortcuts 280 | *.lnk 281 | -------------------------------------------------------------------------------- /bot.js: -------------------------------------------------------------------------------- 1 | const Discord = require('discord.js'); 2 | const client = new Discord.Client(); 3 | const ytdl = require('ytdl-core'); 4 | const request = require('request'); 5 | const fs = require('fs'); 6 | require('dotenv').config(); 7 | 8 | let config = require('./settings.json'); 9 | 10 | const botToken = process.env.BOT_TOKEN; 11 | const youtubeAPIKey = process.env.YOUTUBE_API_KEY; 12 | const botMaster = process.env.BOT_MASTER; 13 | const prefix = config.prefix; 14 | const role = config.role; 15 | 16 | let guilds = {}; 17 | client.on('ready', function () { 18 | console.log(`Logged in as ${client.user.username}#${client.user.discriminator}`); 19 | clientUser = client.user; 20 | clientUser.setActivity('some sick Tunes!', { type: 'PLAYING' }); 21 | }); 22 | 23 | client.on('message', function (message) { 24 | const member = message.member; 25 | const msg = message.content.toLowerCase(); 26 | const args = message.content.split(' ').slice(1).join(' '); 27 | 28 | if (!guilds[message.guild.id]) { 29 | guilds[message.guild.id] = { 30 | queue: [], 31 | queueNames: [], 32 | isPlaying: false, 33 | dispatcher: null, 34 | voiceChannel: null, 35 | skipReq: 0, 36 | skippers: [], 37 | playedTracks: [] 38 | }; 39 | } 40 | 41 | if (message.author.equals(client.user) || message.author.bot) return; 42 | 43 | if (msg.startsWith(prefix + 'play')) { 44 | if (member.voice.channel || guilds[message.guild.id].voiceChannel != null) { 45 | if (guilds[message.guild.id].queue.length > 0 || guilds[message.guild.id].isPlaying) { 46 | getID(args, function (id) { 47 | addToQueue(id, message); 48 | getVideoInfo(id, function (videoInfo) { 49 | guilds[message.guild.id].queueNames.push(videoInfo.videoDetails.title); 50 | addToPlayedTracks(message, videoInfo, message.author); 51 | message.reply('the song: **' + videoInfo.videoDetails.title + '** has been added to the queue.'); 52 | }); 53 | }); 54 | } else { 55 | guilds[message.guild.id].isPlaying = true; 56 | getID(args, function (id) { 57 | guilds[message.guild.id].queue.push(id); 58 | playMusic(id, message); 59 | getVideoInfo(id, function (videoInfo) { 60 | guilds[message.guild.id].queueNames.push(videoInfo.videoDetails.title); 61 | addToPlayedTracks(message, videoInfo, message.author); 62 | message.reply('the song: **' + videoInfo.videoDetails.title + '** is now playing!'); 63 | }); 64 | }); 65 | } 66 | } else if (member.voice.channel === false) { 67 | message.reply('you have to be in a voice channel to play music!'); 68 | } else { 69 | message.reply('you have to be in a voice channel to play music!'); 70 | } 71 | } else if (msg.startsWith(prefix + 'skip')) { 72 | if (guilds[message.guild.id].skippers.indexOf(message.author.id) === -1) { 73 | guilds[message.guild.id].skippers.push(message.author.id); 74 | guilds[message.guild.id].skipReq++; 75 | if (guilds[message.guild.id].skipReq >= 76 | Math.ceil((guilds[message.guild.id].voiceChannel.members.size - 1) / 2) || message.guild.member(message.author.id).roles.cache.find(roles => roles.name === role)) { 77 | skipMusic(message); 78 | message.reply('your skip request has been accepted. The current song will be skipped!'); 79 | } else { 80 | message.reply('your skip request has been accepted. You need **' + 81 | (Math.ceil((guilds[message.guild.id].voiceChannel.members.size - 1) / 2) - 82 | guilds[message.guild.id].skipReq) + '** more skip request(s)!'); 83 | } 84 | } else { 85 | message.reply('you already submitted a skip request.'); 86 | } 87 | } else if (msg.startsWith(prefix + 'queue')) { 88 | var codeblock = '```'; 89 | for (let i = 0; i < guilds[message.guild.id].queueNames.length; i++) { 90 | let temp = (i + 1) + '. ' + guilds[message.guild.id].queueNames[i] + 91 | (i === 0 ? ' **(Current Song)**' : '') + '\n'; 92 | if ((codeblock + temp).length <= 2000 - 3) { 93 | codeblock += temp; 94 | } else { 95 | codeblock += '```'; 96 | message.channel.send(codeblock); 97 | codeblock = '```'; 98 | } 99 | } 100 | 101 | codeblock += '```'; 102 | message.channel.send(codeblock); 103 | } else if (msg.startsWith(prefix + 'stop')) { 104 | if (guilds[message.guild.id].isPlaying === false) { 105 | message.reply('no music is playing!'); 106 | return; 107 | } 108 | 109 | if (message.guild.member(message.author.id).roles.cache.find(roles => roles.name === role)) { 110 | message.reply('stopping the music...'); 111 | 112 | guilds[message.guild.id].queue = []; 113 | guilds[message.guild.id].queueNames = []; 114 | guilds[message.guild.id].isPlaying = false; 115 | guilds[message.guild.id].dispatcher.end(); 116 | guilds[message.guild.id].voiceChannel.leave(); 117 | } else { 118 | message.reply("nice try, but only " + role + "s can stop me!"); 119 | } 120 | 121 | } else if (msg.startsWith(prefix + 'history')){ 122 | let defaultTrackCount = 30; 123 | argArr = args.split(' '); 124 | let includeUsers = argArr.some(val => val != null && val.toLowerCase().indexOf('user') >= 0); 125 | let includeTimes = argArr.some(val => val != null && val.toLowerCase().indexOf('time') >= 0); 126 | let historyTxt = getPlayedTracksText(message, tryParseInt(args, defaultTrackCount), includeUsers, includeTimes); 127 | let historyMsgs = splitTextByLines(historyTxt); 128 | for (let i = 0; i < historyMsgs.length; i++){ 129 | message.reply(historyMsgs[i]); 130 | } 131 | } 132 | }); 133 | 134 | function isYoutube(str) { 135 | return str.toLowerCase().indexOf('youtube.com') > -1; 136 | } 137 | 138 | function searchVideo(query, callback) { 139 | request('https://www.googleapis.com/youtube/v3/search?part=id&type=video&q=' + 140 | encodeURIComponent(query) + '&key=' + youtubeAPIKey, 141 | function (error, response, body) { 142 | var json = JSON.parse(body); 143 | if (!json.items[0]) { 144 | callback('5FjWe31S_0g'); 145 | } else { 146 | callback(json.items[0].id.videoId); 147 | } 148 | }); 149 | } 150 | 151 | function getID(str, callback) { 152 | if (isYoutube(str)) { 153 | callback(ytdl.getURLVideoID(str)); 154 | } else { 155 | searchVideo(str, function (id) { 156 | callback(id); 157 | }); 158 | } 159 | } 160 | 161 | async function getVideoInfo(id, callback) { 162 | callback(await ytdl.getInfo(id)); 163 | } 164 | 165 | function addToQueue(strID, message) { 166 | if (isYoutube(strID)) { 167 | guilds[message.guild.id].queue.push(ytdl.getURLVideoID(strID)); 168 | } else { 169 | guilds[message.guild.id].queue.push(strID); 170 | } 171 | } 172 | 173 | function playMusic(id, message) { 174 | guilds[message.guild.id].voiceChannel = message.member.voice.channel; 175 | 176 | guilds[message.guild.id].voiceChannel.join().then(function (connection) { 177 | stream = ytdl('https://www.youtube.com/watch?v=' + id, { 178 | filter: 'audioonly', 179 | dlChunkSize: 0 180 | }); 181 | guilds[message.guild.id].skipReq = 0; 182 | guilds[message.guild.id].skippers = []; 183 | 184 | guilds[message.guild.id].dispatcher = connection.play(stream); 185 | guilds[message.guild.id].dispatcher.on('end', function () { 186 | guilds[message.guild.id].skipReq = 0; 187 | guilds[message.guild.id].skippers = []; 188 | guilds[message.guild.id].queue.shift(); 189 | guilds[message.guild.id].queueNames.shift(); 190 | if (guilds[message.guild.id].queue.length === 0) { 191 | guilds[message.guild.id].queue = []; 192 | guilds[message.guild.id].queueNames = []; 193 | guilds[message.guild.id].isPlaying = false; 194 | } else { 195 | setTimeout(function () { 196 | playMusic(guilds[message.guild.id].queue[0], message); 197 | }, 500); 198 | } 199 | }); 200 | }); 201 | } 202 | 203 | function skipMusic(message) { 204 | guilds[message.guild.id].dispatcher.end(); 205 | } 206 | 207 | function addToPlayedTracks(message, videoInfo, user){ 208 | let trackInfo = { 209 | title: videoInfo.videoDetails.title, 210 | url: videoInfo.videoDetails.video_url, 211 | dateVal: Date.now(), 212 | username: user.username 213 | }; 214 | guilds[message.guild.id].playedTracks.push(trackInfo); 215 | if (guilds[message.guild.id].playedTracks.length > 100){ 216 | guilds[message.guild.id].playedTracks.shift(); 217 | } 218 | } 219 | 220 | function getPlayedTracksText(message, trackCount, includeUsers, includeTimes){ 221 | const playedTracks = guilds[message.guild.id].playedTracks; 222 | if (trackCount == undefined){ 223 | trackCount = playedTracks.length; 224 | } 225 | const startIndex = trackCount >= playedTracks.length ? 0 : playedTracks.length - trackCount; 226 | let tracksText = ''; 227 | for (let i = startIndex; i < playedTracks.length; i++){ 228 | const trackNum = i - startIndex + 1; 229 | tracksText += `${trackNum}: ${playedTracks[i].title} (<${playedTracks[i].url}>)${(includeUsers ? ' by ' + playedTracks[i].username : '')}${(includeTimes ? ' at ' + formatDate(playedTracks[i].dateVal) : '')}\n`; 230 | } 231 | return tracksText.trim(); 232 | } 233 | 234 | function splitTextByLines(text, maxCharsPerText){ 235 | if (text == undefined || text.length == 0){ 236 | return []; 237 | } 238 | if (maxCharsPerText == undefined){ 239 | maxCharsPerText = 2000; 240 | } 241 | const lines = text.split('\n'); 242 | let messages = ['']; 243 | let charCount = 0; 244 | let messageIndex = 0; 245 | for (let i = 0; i < lines.length; i++){ 246 | const line = lines[i] + '\n'; 247 | charCount += line.length; 248 | if (charCount <= maxCharsPerText){ 249 | messages[messageIndex] += line; 250 | } else { 251 | let lineTextRemaining = line; 252 | while (charCount > maxCharsPerText){ 253 | let currentLineText = lineTextRemaining.substr(0, maxCharsPerText); 254 | messages.push(currentLineText); 255 | messageIndex++; 256 | charCount -= maxCharsPerText; 257 | if (charCount > 0){ 258 | let startSplitIndex = maxCharsPerText <= lineTextRemaining.length ? maxCharsPerText : lineTextRemaining.length - 1; 259 | lineTextRemaining = lineTextRemaining.substring(startSplitIndex, lineTextRemaining.length); 260 | } else { 261 | charCount = 0 262 | } 263 | } 264 | } 265 | } 266 | for (let i = 0; i < messages.length; i++){ 267 | messages[i] = messages[i].trim(); 268 | } 269 | return messages; 270 | } 271 | 272 | function tryParseInt(arg, defaultVal){ 273 | if (defaultVal == undefined){ 274 | defaultVal = 0; 275 | } 276 | try { 277 | let argNum = parseInt(arg); 278 | if (!isNaN(argNum)){ 279 | return argNum; 280 | } 281 | return defaultVal; 282 | } catch (parseException){ 283 | return defaultVal; 284 | } 285 | } 286 | 287 | //YYYY-MM-DD hh:mm:ss UTC 288 | function formatDate(dateValue){ 289 | const date = new Date(dateValue); 290 | return `${date.getUTCFullYear()}-${padTo2DigitInt(date.getUTCMonth() + 1)}-${padTo2DigitInt(date.getUTCDate())} ${padTo2DigitInt(date.getUTCHours())}:${padTo2DigitInt(date.getUTCMinutes())}:${padTo2DigitInt(date.getUTCSeconds())} UTC`; 291 | } 292 | 293 | function padTo2DigitInt(intValue){ 294 | return intValue > 9 ? '' + intValue: '0' + intValue; 295 | } 296 | 297 | client.login(botToken); 298 | --------------------------------------------------------------------------------