├── other ├── downloads │ └── .gitignore ├── readme │ └── logo.png └── settings.example.json ├── modules ├── invite.js ├── log.js ├── commands │ ├── color.js │ ├── progress.js │ ├── settings.js │ ├── tiktok.js │ ├── autodownload.js │ ├── help.js │ ├── disable.js │ └── details.js ├── mongo.js ├── messageGenerator.js └── tiktok.js ├── .eslintrc.json ├── README.md ├── package.json ├── .gitignore ├── bot.js └── LICENSE /other/downloads/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | 3 | !.gitignore -------------------------------------------------------------------------------- /other/readme/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/addyire/tiktok-download/HEAD/other/readme/logo.png -------------------------------------------------------------------------------- /modules/invite.js: -------------------------------------------------------------------------------- 1 | module.exports = `https://discord.com/api/oauth2/authorize?client_id=${require('../other/settings.json').bot.id}&permissions=59392&scope=applications.commands%20bot` 2 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": false, 4 | "commonjs": true, 5 | "es2021": true 6 | }, 7 | "extends": [ 8 | "standard" 9 | ], 10 | "parserOptions": { 11 | "ecmaVersion": 12 12 | }, 13 | "rules": { 14 | "no-useless-escape": "off" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /modules/log.js: -------------------------------------------------------------------------------- 1 | const { createLogger, format, transports } = require('winston') 2 | const { combine, timestamp, errors, splat, printf } = format 3 | const path = require('path') 4 | 5 | const logPath = path.join(__dirname, '..', 'other', 'logs', 'tiktok.log') 6 | 7 | const myFormat = printf((info, guild) => { 8 | const { level, message, timestamp } = info 9 | return `[${timestamp}] [${level}]${info.serverID ? ' [' + info.serverID + ']' : ''}: ${message}` 10 | }) 11 | 12 | const logger = createLogger({ 13 | transports: [ 14 | new transports.Console({ 15 | level: 'info', 16 | format: combine( 17 | errors({ stack: true }), 18 | format.colorize(), 19 | splat(), 20 | timestamp(), 21 | myFormat 22 | ) 23 | }), 24 | new transports.File({ 25 | filename: logPath, 26 | level: 'debug' 27 | }) 28 | ] 29 | }) 30 | 31 | module.exports = logger 32 | -------------------------------------------------------------------------------- /other/settings.example.json: -------------------------------------------------------------------------------- 1 | { 2 | "bot": { 3 | "id": "bot id", 4 | "token": "bot token", 5 | "publicKey": "bot public key" 6 | }, 7 | "owner": { 8 | "tag": "user#numbers", 9 | "id": "user id", 10 | "server": "owners server id" 11 | }, 12 | "compression": { 13 | "max_size": 8388119, 14 | "audio_bitrate": 64, 15 | "restrict": false, 16 | "servers": ["Put server ID's in here for servers WITH compression. This is ignored unless restrict is enabled."] 17 | }, 18 | "tiktok": { 19 | "proxies": ["you can put proxies here. delete this if you don't have any or aren't going to use them"], 20 | "sessions": ["this is a list of sessions. visit https://github.com/drawrowfly/tiktok-scraper to learn more. leave the last item in this list to use no session", ""] 21 | }, 22 | "emojis": { 23 | "tiktok": "859225749281308702", 24 | "github": "860239859972440064", 25 | "discord": "869007508755341392" 26 | }, 27 | "status": "/help", 28 | "mongo": "mongodb://mongo server address:mongo server port/mongo database name", 29 | "relativeDownloadPath": "other/downloads" 30 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 |
3 | Discord bot that automatically downloads TikToks
4 | Discord 5 | 6 | 7 | 8 | 9 |
10 | 11 | ## Usage 12 | 13 | To use this bot simply add it to your server and do / to see all available commands. 14 | ## Features 15 | 16 | - Compression 17 | - Configurable 18 | - Easy to use 19 | 20 | ## Invite 21 | 22 | If you don't want to host the bot yourself you can get add it to your server [here](https://discord.com/api/oauth2/authorize?client_id=819836629250080779&permissions=59392&scope=applications.commands%20bot) 23 | 24 | ## Commands 25 | 26 | There are a few commands that allow you to configure the bot. 27 | 28 | - /autodownload 29 | - /details 30 | - /help 31 | - /progress 32 | - /setcolor 33 | - /settings 34 | ## Running 35 | 36 | 1. Run the following commands 37 | ``` 38 | git clone https://github.com/addyire/tiktok-download 39 | cd tiktok-download 40 | npm install 41 | ``` 42 | 2. Have a mongoDB instance running 43 | 3. Create a `other/settings.json` file using the `settings.example.json` as reference. 44 | 4. Run with `npm start` -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tiktok-download", 3 | "version": "2.2.0", 4 | "main": "bot.js", 5 | "license": "MIT", 6 | "dependencies": { 7 | "discord.js": "^13.1.0", 8 | "ffmpeg-static": "^4.3.0", 9 | "fluent-ffmpeg": "^2.1.2", 10 | "mongoose": "^5.12.10", 11 | "slash-create": "^4.0.1", 12 | "tiktok-scraper": "^1.4.36", 13 | "winston": "^3.3.3" 14 | }, 15 | "devDependencies": { 16 | "eslint": "^7.27.0", 17 | "eslint-config-standard": "^16.0.2", 18 | "eslint-plugin-import": "^2.23.3", 19 | "eslint-plugin-node": "^11.1.0", 20 | "eslint-plugin-promise": "^4.3.1" 21 | }, 22 | "scripts": { 23 | "start": "node bot.js" 24 | }, 25 | "description": "
\r
\r Discord bot that automatically downloads TikToks
\r \"Discord\"\r ", 26 | "repository": { 27 | "type": "git", 28 | "url": "git+https://github.com/addyire/tiktok-download.git" 29 | }, 30 | "keywords": [ 31 | "tiktok", 32 | "discord", 33 | "bot", 34 | "download" 35 | ], 36 | "author": "Addy Ire", 37 | "bugs": { 38 | "url": "https://github.com/addyire/tiktok-download/issues" 39 | }, 40 | "homepage": "https://github.com/addyire/tiktok-download#readme" 41 | } 42 | -------------------------------------------------------------------------------- /modules/commands/color.js: -------------------------------------------------------------------------------- 1 | const { SlashCommand } = require('slash-create') 2 | 3 | const { ServerOptions } = require('../mongo') 4 | const botInviteURL = require('../invite') 5 | const log = require('../log') 6 | const { settingsChange } = require('../messageGenerator') 7 | 8 | module.exports = class SetColor extends SlashCommand { 9 | constructor (client, creator) { 10 | super(creator, { 11 | name: 'color', 12 | description: 'Change the sidebar color', 13 | options: [ 14 | { 15 | type: 3, 16 | name: 'color', 17 | description: 'The color itself. (Must be a hexcode like this: #ff0000)', 18 | required: true 19 | } 20 | ] 21 | }) 22 | this.client = client 23 | } 24 | 25 | onError () {} 26 | 27 | async run (interaction) { 28 | let hasPerms 29 | 30 | try { 31 | hasPerms = (await (await this.client.guilds.fetch(interaction.guildID)).members.fetch(interaction.user.id)).permissions.has('ADMINISTRATOR') 32 | } catch (err) { 33 | throw new Error(`I am not in this server as a bot. Please have an administrator click [this](${botInviteURL}) link to invite me.`) 34 | } 35 | 36 | if (!hasPerms) { 37 | throw new Error('You must have the ADMINISTRATOR permission to change settings.') 38 | } 39 | 40 | const serverOptions = await ServerOptions.findOneAndUpdate({ serverID: interaction.guildID }, {}, { upsert: true, new: true, setDefaultsOnInsert: true, useFindAndModify: false }) 41 | const args = interaction.data.data.options.reduce((a, b) => { 42 | a[b.name] = b.value 43 | return a 44 | }, {}) 45 | 46 | log.info(`Set color to: ${args.color}`, { serverID: interaction.guildID }) 47 | 48 | serverOptions.color = args.color 49 | 50 | await serverOptions.validate() 51 | await serverOptions.save() 52 | 53 | interaction.send({ 54 | embeds: [ 55 | settingsChange(`I have changed the color to \`${args.color}\``) 56 | ] 57 | }) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /modules/commands/progress.js: -------------------------------------------------------------------------------- 1 | const { SlashCommand } = require('slash-create') 2 | 3 | const { ServerOptions } = require('../mongo') 4 | const botInviteURL = require('../invite') 5 | const { settingsChange } = require('../messageGenerator') 6 | const log = require('../log') 7 | 8 | module.exports = class Progress extends SlashCommand { 9 | constructor (client, creator) { 10 | super(creator, { 11 | name: 'progress', 12 | description: 'Change video download progress settings.', 13 | options: [ 14 | { 15 | type: 5, 16 | name: 'enabled', 17 | description: 'Whether this is enabled or not.', 18 | required: true 19 | } 20 | ] 21 | }) 22 | this.client = client 23 | } 24 | 25 | onError () {} 26 | 27 | async run (interaction) { 28 | let hasPerms 29 | 30 | try { 31 | hasPerms = (await (await this.client.guilds.fetch(interaction.guildID)).members.fetch(interaction.user.id)).permissions.has('ADMINISTRATOR') 32 | } catch (err) { 33 | throw new Error(`I am not in this server as a bot. Please have an administrator click [this](${botInviteURL}) link to invite me.`) 34 | } 35 | 36 | if (!hasPerms) { 37 | throw new Error('You must have the ADMINISTRATOR permission to change settings.') 38 | } 39 | 40 | const serverOptions = await ServerOptions.findOneAndUpdate({ serverID: interaction.guildID }, {}, { upsert: true, new: true, setDefaultsOnInsert: true, useFindAndModify: false }) 41 | const args = interaction.data.data.options.reduce((a, b) => { 42 | a[b.name] = b.value 43 | return a 44 | }, {}) 45 | 46 | serverOptions.progress.enabled = args.enabled 47 | 48 | await serverOptions.validate() 49 | await serverOptions.save() 50 | 51 | log.info(`${args.enabled ? 'Enabled' : 'Disabled'} progress message`, { serverID: interaction.guildID }) 52 | 53 | interaction.send({ 54 | embeds: [ 55 | settingsChange(`I have ${args.enabled ? 'enabled' : 'disabled'} the progress message`) 56 | ] 57 | }) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | *.log 3 | npm-debug.log* 4 | yarn-debug.log* 5 | yarn-error.log* 6 | lerna-debug.log* 7 | 8 | # Diagnostic reports (https://nodejs.org/api/report.html) 9 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 10 | 11 | # Runtime data 12 | pids 13 | *.pid 14 | *.seed 15 | *.pid.lock 16 | 17 | # Directory for instrumented libs generated by jscoverage/JSCover 18 | lib-cov 19 | 20 | # Coverage directory used by tools like istanbul 21 | coverage 22 | *.lcov 23 | 24 | # nyc test coverage 25 | .nyc_output 26 | 27 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 28 | .grunt 29 | 30 | # Bower dependency directory (https://bower.io/) 31 | bower_components 32 | 33 | # node-waf configuration 34 | .lock-wscript 35 | 36 | # Compiled binary addons (https://nodejs.org/api/addons.html) 37 | build/Release 38 | 39 | # Dependency directories 40 | node_modules/ 41 | jspm_packages/ 42 | 43 | # TypeScript v1 declaration files 44 | typings/ 45 | 46 | # TypeScript cache 47 | *.tsbuildinfo 48 | 49 | # Optional npm cache directory 50 | .npm 51 | 52 | # Optional eslint cache 53 | .eslintcache 54 | 55 | # Microbundle cache 56 | .rpt2_cache/ 57 | .rts2_cache_cjs/ 58 | .rts2_cache_es/ 59 | .rts2_cache_umd/ 60 | 61 | # Optional REPL history 62 | .node_repl_history 63 | 64 | # Output of 'npm pack' 65 | *.tgz 66 | 67 | # Yarn Integrity file 68 | .yarn-integrity 69 | 70 | # dotenv environment variables file 71 | .env 72 | .env.test 73 | 74 | # parcel-bundler cache (https://parceljs.org/) 75 | .cache 76 | 77 | # Next.js build output 78 | .next 79 | 80 | # Nuxt.js build / generate output 81 | .nuxt 82 | dist 83 | 84 | # Gatsby files 85 | .cache/ 86 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 87 | # https://nextjs.org/blog/next-9-1#public-directory-support 88 | # public 89 | 90 | # vuepress build output 91 | .vuepress/dist 92 | 93 | # Serverless directories 94 | .serverless/ 95 | 96 | # FuseBox cache 97 | .fusebox/ 98 | 99 | # DynamoDB Local files 100 | .dynamodb/ 101 | 102 | # TernJS port file 103 | .tern-port 104 | 105 | #Settings 106 | settings.json 107 | -------------------------------------------------------------------------------- /modules/commands/settings.js: -------------------------------------------------------------------------------- 1 | const { SlashCommand } = require('slash-create') 2 | const Discord = require('discord.js') 3 | 4 | const { ServerOptions } = require('../mongo') 5 | const botInviteURL = require('../invite') 6 | const log = require('../log') 7 | module.exports = class Settings extends SlashCommand { 8 | constructor (client, creator) { 9 | super(creator, { 10 | name: 'settings', 11 | description: 'Displays the current server settings.' 12 | }) 13 | this.client = client 14 | } 15 | 16 | onError () {} 17 | 18 | async run (interaction) { 19 | let hasPerms 20 | 21 | try { 22 | hasPerms = (await (await this.client.guilds.fetch(interaction.guildID)).members.fetch(interaction.user.id)).permissions.has('ADMINISTRATOR') 23 | } catch (err) { 24 | throw new Error(`I am not in this server as a bot. Please have an administrator click [this](${botInviteURL}) link to invite me.`) 25 | } 26 | 27 | if (!hasPerms) { 28 | throw new Error('You must have the ADMINISTRATOR permission to view settings.') 29 | } 30 | 31 | const serverOptions = await ServerOptions.findOneAndUpdate({ serverID: interaction.guildID }, {}, { upsert: true, new: true, setDefaultsOnInsert: true, useFindAndModify: false }).exec() 32 | 33 | // Create embed 34 | const e = new Discord.MessageEmbed() 35 | .setTitle('Server Settings') 36 | .setColor(serverOptions.color) 37 | .setDescription('Here are the settings for this server') 38 | 39 | const data = serverOptions.toObject() 40 | 41 | // Delete db stuff 42 | delete data._id 43 | delete data.serverID 44 | delete data.__v 45 | 46 | for (const key of Object.keys(data)) { 47 | const cat = data[key] 48 | let str = '' 49 | 50 | if (key === 'banned' || key === 'limiter') continue 51 | 52 | if (typeof cat === 'object') { 53 | for (const item of Object.keys(cat)) { 54 | if (typeof cat[item] === 'object') continue 55 | str += `\`${item}\`: \`${cat[item]}\`\n` 56 | } 57 | } else { 58 | str = `\`${cat}\`` 59 | } 60 | 61 | e.addField(key, str) 62 | } 63 | 64 | interaction.send({ embeds: [e.toJSON()] }) 65 | 66 | log.info('Displaying settings', { serverID: interaction.guildID }) 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /modules/mongo.js: -------------------------------------------------------------------------------- 1 | // Require stuff 2 | const mongoose = require('mongoose') 3 | const { mongo } = require('../other/settings.json') 4 | const log = require('./log') 5 | 6 | mongoose.connect(mongo, { useNewUrlParser: true, useUnifiedTopology: true }) 7 | 8 | // Define a function that checks if a string is a color code 9 | const colorValidator = (v) => (/^#([0-9a-f]{3}){1,2}$/i).test(v) 10 | 11 | // Create link style type 12 | class LinkStyle extends mongoose.SchemaType { 13 | constructor (key, options) { 14 | super(key, options, 'LinkStyle') 15 | } 16 | 17 | cast (val) { 18 | if (['disabled', 'embed', 'button', 'both'].indexOf(val) === -1) { 19 | throw new Error('Not a valid type') 20 | } 21 | return val 22 | } 23 | } 24 | 25 | mongoose.Schema.Types.LinkStyle = LinkStyle 26 | 27 | // Create the schema 28 | const serverSchema = new mongoose.Schema({ 29 | details: { 30 | enabled: { 31 | type: Boolean, 32 | default: true 33 | }, 34 | description: { 35 | type: Boolean, 36 | default: true 37 | }, 38 | author: { 39 | type: Boolean, 40 | default: true 41 | }, 42 | requester: { 43 | type: Boolean, 44 | default: true 45 | }, 46 | analytics: { 47 | type: Boolean, 48 | default: true 49 | }, 50 | link: { 51 | type: LinkStyle, 52 | default: 'button' 53 | } 54 | }, 55 | progress: { 56 | enabled: { 57 | type: Boolean, 58 | default: true 59 | } 60 | }, 61 | autodownload: { 62 | enabled: { 63 | type: Boolean, 64 | default: true 65 | }, 66 | deletemessage: { 67 | type: Boolean, 68 | default: true 69 | }, 70 | smart: { 71 | type: Boolean, 72 | default: true 73 | }, 74 | displayErrors: { 75 | type: Boolean, 76 | default: true 77 | } 78 | }, 79 | color: { 80 | type: String, 81 | validate: { 82 | validator: colorValidator, 83 | message: p => `${p.value} is not a valid color.` 84 | }, 85 | default: '#FF00FF' 86 | }, 87 | banned: { 88 | users: { 89 | type: [String], 90 | default: [] 91 | }, 92 | channels: { 93 | type: [String], 94 | default: [] 95 | } 96 | }, 97 | serverID: String 98 | }) 99 | 100 | // Load schema 101 | const ServerOptions = mongoose.model('server', serverSchema) 102 | 103 | // Export schema 104 | module.exports = { ServerOptions } 105 | 106 | // Log database events 107 | mongoose.connection.on('connected', () => { 108 | log.info('Successfully connected to database!') 109 | }) 110 | mongoose.connection.on('error', (err) => { 111 | log.error(`Mongo Error \n${err}`) 112 | console.error(err) 113 | }) 114 | mongoose.connection.on('disconnected', () => { 115 | log.error('Disconnected from database!') 116 | }) 117 | -------------------------------------------------------------------------------- /modules/commands/tiktok.js: -------------------------------------------------------------------------------- 1 | const { SlashCommand } = require('slash-create') 2 | const fs = require('fs') 3 | 4 | const { ServerOptions } = require('../mongo') 5 | const TikTokParser = require('../tiktok') 6 | const { owner } = require('../../other/settings.json') 7 | const log = require('../log') 8 | const { tikTokMessage } = require('../messageGenerator') 9 | 10 | module.exports = class TikTok extends SlashCommand { 11 | constructor (client, creator) { 12 | super(creator, { 13 | name: 'tiktok', 14 | description: 'Downloads a TikTok', 15 | options: [ 16 | { 17 | type: 3, 18 | name: 'url', 19 | description: 'The URL of the TikTok', 20 | required: true 21 | } 22 | ] 23 | }) 24 | } 25 | 26 | onError () {} 27 | 28 | async run (interaction) { 29 | await interaction.defer() 30 | 31 | const serverOptions = await ServerOptions.findOneAndUpdate({ serverID: interaction.guildID }, {}, { upsert: true, new: true, setDefaultsOnInsert: true, useFindAndModify: false }) 32 | 33 | const args = interaction.data.data.options === undefined 34 | ? {} 35 | : interaction.data.data.options.reduce((a, b) => { 36 | a[b.name] = b.value 37 | return a 38 | }, {}) 39 | 40 | if (serverOptions.banned.users.indexOf(interaction.user.id) !== -1) throw new Error('You have been banned from using me.') 41 | if (!testURL(args.url)) throw new Error('Not a valid URL') 42 | 43 | log.info(`📩 - Processing Video: ${args.url}`, { serverID: interaction.guildID }) 44 | 45 | TikTokParser(args.url, interaction.guildID, () => {}).then(videoData => { 46 | const requester = { 47 | avatarURL: interaction.user.avatarURL, 48 | name: `${interaction.user.username}#${interaction.user.discriminator}` 49 | } 50 | 51 | const response = tikTokMessage(videoData, serverOptions, requester, true) 52 | response.file = { 53 | name: 'tiktok.mp4', 54 | file: fs.readFileSync(videoData.videoPath) 55 | } 56 | 57 | interaction.send(response).then(() => { 58 | videoData.purge() 59 | }) 60 | }).catch(err => { 61 | log.warn('Encountered this error while downloading video with interaction' + err, { serverID: interaction.guildID }) 62 | 63 | const e = { 64 | title: ':rotating_light: Error', 65 | description: "I couldn't download that video for some reason. Check to make sure the video is not private.", 66 | color: parseInt('FF0000', 16), 67 | footer: { 68 | text: `Please contact ${owner.tag} if you believe this is an error` 69 | } 70 | } 71 | 72 | interaction.send({ embeds: [e] }) 73 | }) 74 | } 75 | } 76 | 77 | function testURL (url) { 78 | return /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w\-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/.test(url) 79 | } 80 | -------------------------------------------------------------------------------- /modules/commands/autodownload.js: -------------------------------------------------------------------------------- 1 | const { SlashCommand } = require('slash-create') 2 | 3 | const { ServerOptions } = require('../mongo') 4 | const botInviteURL = require('../invite') 5 | const log = require('../log') 6 | const { settingsChange } = require('../messageGenerator') 7 | 8 | module.exports = class Progress extends SlashCommand { 9 | constructor (client, creator) { 10 | super(creator, { 11 | name: 'autodownload', 12 | description: 'Set whether to automatically download TikToks. No command necessary.', 13 | options: [ 14 | { 15 | type: 5, 16 | name: 'enabled', 17 | description: 'Whether this is enabled or not.', 18 | required: true 19 | }, 20 | { 21 | type: 5, 22 | name: 'deletemessage', 23 | description: 'Delete the message with the URL in it.', 24 | required: false 25 | }, 26 | { 27 | type: 5, 28 | name: 'smartdelete', 29 | description: 'When enabled, the message will not be deleted if there is more than just the URL in it.', 30 | required: false 31 | }, 32 | { 33 | type: 5, 34 | name: 'errors', 35 | description: 'When disabled, no error message will be sent when a tiktok cannot be downloaded for whatever reason.', 36 | required: false 37 | } 38 | ] 39 | }) 40 | this.client = client 41 | } 42 | 43 | onError () {} 44 | 45 | async run (interaction) { 46 | let hasPerms 47 | 48 | try { 49 | hasPerms = (await (await this.client.guilds.fetch(interaction.guildID)).members.fetch(interaction.user.id)).permissions.has('ADMINISTRATOR') 50 | } catch (err) { 51 | throw new Error(`I am not in this server as a bot. Please have an administrator click [this](${botInviteURL}) link to invite me.`) 52 | } 53 | 54 | if (!hasPerms) { 55 | throw new Error('You must have the ADMINISTRATOR permission to change settings.') 56 | } 57 | 58 | const serverOptions = await ServerOptions.findOneAndUpdate({ serverID: interaction.guildID }, {}, { upsert: true, new: true, setDefaultsOnInsert: true, useFindAndModify: false }) 59 | const args = interaction.data.data.options.reduce((a, b) => { 60 | a[b.name] = b.value 61 | return a 62 | }, {}) 63 | 64 | serverOptions.autodownload.enabled = args.enabled !== undefined ? args.enabled : serverOptions.autodownload.enabled 65 | serverOptions.autodownload.deletemessage = args.deletemessage !== undefined ? args.deletemessage : serverOptions.autodownload.deletemessage 66 | serverOptions.autodownload.smartdelete = args.smartdelete !== undefined ? args.smartdelete : serverOptions.autodownload.smartdelete 67 | serverOptions.autodownload.displayErrors = args.errors !== undefined ? args.errors : serverOptions.autodownload.displayErrors 68 | 69 | log.info('Changed auto download settings', { serverID: interaction.guildID }) 70 | 71 | await serverOptions.validate() 72 | await serverOptions.save() 73 | 74 | interaction.send({ 75 | embeds: [ 76 | settingsChange(`I have successfully ${args.enabled ? 'updated' : 'disabled'} auto download!`) 77 | ] 78 | }) 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /modules/commands/help.js: -------------------------------------------------------------------------------- 1 | const { MessageEmbed, MessageActionRow, MessageButton } = require('discord.js') 2 | const { SlashCommand } = require('slash-create') 3 | 4 | const { ServerOptions } = require('../mongo') 5 | const { version } = require('../../package.json') 6 | const { owner, emojis, helplink, voteURL } = require('../../other/settings.json') 7 | const { tiktok, github, discord } = emojis 8 | const botInviteURL = require('../invite') 9 | const log = require('../log') 10 | 11 | module.exports = class Help extends SlashCommand { 12 | constructor (client, creator) { 13 | super(creator, { 14 | name: 'help', 15 | description: 'Displays helpful information' 16 | }) 17 | this.client = client 18 | } 19 | 20 | onError () {} 21 | 22 | async run (interaction) { 23 | const serverOptions = await ServerOptions.findOneAndUpdate({ serverID: interaction.guildID }, {}, { upsert: true, new: true, setDefaultsOnInsert: true, useFindAndModify: false }) 24 | 25 | const response = {} 26 | 27 | response.embeds = [new MessageEmbed() 28 | .setTitle('TokTik Downloader') 29 | .setURL(botInviteURL) 30 | .setDescription("This bot automagically replaces TikTok URL's with a MP4 file so you don't have to leave discord to watch it. \n*If you are being DM'd responses to commands make sure the bot has sufficient permissions to send messages in ALL channels.*") 31 | .addFields({ 32 | name: 'Usage', 33 | value: 'If autodownload is enabled, you can just send a TikTok and the bot will download it. To enabled/disable this use the /autodownload command.' 34 | }, { 35 | name: 'Commands', 36 | value: 'Type / and click on the TokTik icon to see all the available commands!' 37 | }, { 38 | name: 'Open Source', 39 | value: 'You can view the code [here](https://github.com/addyire/tiktok-download) on GitHub!' 40 | }, { 41 | name: 'Help', 42 | value: `For any additional help you can join the [official help discord]${helplink ? '(' + helplink + ')' : 'not linked'}. You can also create an issue on GitHub!` 43 | }) 44 | .setColor(serverOptions.color) 45 | .setFooter(`Contact ${owner.tag} for any questions or help with this bot. | Version: ${version}`) 46 | .toJSON() 47 | ] 48 | 49 | const buttons = [ 50 | new MessageButton({ 51 | style: 'LINK', 52 | label: 'GitHub', 53 | url: 'https://github.com/addyire/tiktok-download', 54 | emoji: github 55 | }), 56 | new MessageButton({ 57 | style: 'LINK', 58 | label: 'Invite', 59 | url: botInviteURL, 60 | emoji: tiktok 61 | }) 62 | ] 63 | 64 | helplink && buttons.push(new MessageButton({ 65 | style: 'LINK', 66 | label: 'Help', 67 | url: helplink, 68 | emoji: discord 69 | })) 70 | 71 | voteURL && buttons.push(new MessageButton({ 72 | style: 'LINK', 73 | label: 'Vote', 74 | emoji: '🗳️', 75 | url: voteURL 76 | })) 77 | response.components = [ 78 | new MessageActionRow() 79 | .addComponents(buttons) 80 | .toJSON() 81 | ] 82 | 83 | interaction.send(response) 84 | 85 | log.info('Sent help information', { serverID: interaction.guildID }) 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /modules/commands/disable.js: -------------------------------------------------------------------------------- 1 | const { SlashCommand } = require('slash-create') 2 | 3 | const { ServerOptions } = require('../mongo') 4 | const botInviteURL = require('../invite') 5 | const { listBanned } = require('../messageGenerator') 6 | 7 | module.exports = class SetColor extends SlashCommand { 8 | constructor (client, creator) { 9 | super(creator, { 10 | name: 'disable', 11 | description: 'Disable for a specific user or channel', 12 | guildIDS: ['855275193022021653'], 13 | options: [ 14 | { 15 | type: 6, 16 | name: 'user', 17 | description: 'The user to disable' 18 | }, 19 | { 20 | type: 7, 21 | name: 'channel', 22 | description: 'The channel to disable' 23 | } 24 | ] 25 | }) 26 | this.client = client 27 | } 28 | 29 | onError () {} 30 | 31 | async run (interaction) { 32 | let hasPerms 33 | 34 | try { 35 | hasPerms = (await (await this.client.guilds.fetch(interaction.guildID)).members.fetch(interaction.user.id)).permissions.has('ADMINISTRATOR') 36 | } catch (err) { 37 | throw new Error(`I am not in this server as a bot. Please have an administrator click [this](${botInviteURL}) link to invite me.`) 38 | } 39 | 40 | if (!hasPerms) throw new Error('You must have the ADMINISTRATOR permission to change settings.') 41 | 42 | const serverOptions = await ServerOptions.findOneAndUpdate({ serverID: interaction.guildID }, {}, { upsert: true, new: true, setDefaultsOnInsert: true, useFindAndModify: false }) 43 | const args = interaction.data.data.options === undefined 44 | ? {} 45 | : interaction.data.data.options.reduce((a, b) => { 46 | a[b.name] = b.value 47 | return a 48 | }, {}) 49 | 50 | if (args.user && args.channel) throw new Error('You must specifiy either a user or channel to disable toktik download for.') 51 | 52 | if (args.channel) { 53 | const channelObj = await this.client.channels.fetch(args.channel) 54 | 55 | if (channelObj.type !== 'GUILD_TEXT') throw new Error('The channel you provided is not a text channel!') 56 | 57 | if (serverOptions.banned.channels.indexOf(args.channel) !== -1) { 58 | serverOptions.banned.channels = serverOptions.banned.channels.filter(i => i !== args.channel) 59 | } else { 60 | serverOptions.banned.channels.push(args.channel) 61 | } 62 | } else if (args.user) { 63 | if (serverOptions.banned.users.indexOf(args.user) !== -1) { 64 | serverOptions.banned.users = serverOptions.banned.users.filter(i => i !== args.user) 65 | } else { 66 | serverOptions.banned.users.push(args.user) 67 | } 68 | } 69 | 70 | const embed = await listBanned(serverOptions, this.client) 71 | 72 | await serverOptions.validate() 73 | await serverOptions.save() 74 | 75 | interaction.send({ 76 | embeds: [embed] //, 77 | // components: [{ 78 | // type: ComponentType.ACTION_ROW, 79 | // components: [{ 80 | // type: ComponentType.BUTTON, 81 | // style: ButtonStyle.PRIMARY, 82 | // label: 'butt', 83 | // custom_id: 'my_butt', 84 | // emoji: { name: '👌' } 85 | // }] 86 | // }] 87 | }) 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /modules/messageGenerator.js: -------------------------------------------------------------------------------- 1 | const { MessageEmbed, MessageActionRow, MessageButton } = require('discord.js') 2 | const { emojis } = require('../other/settings.json') 3 | 4 | function tikTokMessage (videoData, guildSettings, requester, interaction = false) { 5 | // Create response 6 | const tiktok = videoData.videoURL 7 | const response = {} 8 | 9 | // Define the server details for easier access 10 | const serverDetails = guildSettings.details 11 | // If they have video details enabled.... 12 | if (serverDetails.enabled && (serverDetails.description || serverDetails.requester || serverDetails.author || serverDetails.analytics)) { 13 | // Set the response embed to be the information they want 14 | const [title, url] = serverDetails.link === 'embed' || serverDetails.link === 'both' ? ['View On TikTok', tiktok] : [undefined, undefined] 15 | 16 | response.embeds = [{ 17 | title, 18 | url, 19 | description: serverDetails.description ? videoData.text : undefined, 20 | timestamp: serverDetails.requester ? new Date().toISOString() : undefined, 21 | color: parseInt(guildSettings.color.substring(1), 16), 22 | author: serverDetails.author 23 | ? { 24 | name: `${videoData.authorMeta.nickName} (${videoData.authorMeta.name})`, 25 | icon_url: videoData.authorMeta.avatar 26 | } 27 | : undefined, 28 | footer: serverDetails.requester 29 | ? { 30 | text: `Requested by ${requester.name}`, 31 | icon_url: requester.avatarURL 32 | } 33 | : undefined, 34 | fields: serverDetails.analytics 35 | ? [ 36 | { name: ':arrow_forward: Plays', value: videoData.playCount, inline: true }, 37 | { name: ':heart: Likes', value: videoData.diggCount, inline: true }, 38 | { name: ':mailbox_with_mail: Shares', value: videoData.shareCount, inline: true } 39 | ] 40 | : undefined 41 | }] 42 | } else if (interaction) { 43 | response.embeds = [{ 44 | description: 'Here\'s your video', 45 | color: parseInt(guildSettings.color.substring(1), 16) 46 | }] 47 | } 48 | 49 | // Add buttons if needed 50 | response.components = (serverDetails.link === 'button' || serverDetails.link === 'both') && serverDetails.enabled 51 | ? [new MessageActionRow() 52 | .addComponents( 53 | new MessageButton({ 54 | style: 'LINK', 55 | emoji: emojis.tiktok, 56 | url: tiktok, 57 | label: 'View On TikTok' 58 | }) 59 | ) 60 | ] 61 | : undefined 62 | 63 | return response 64 | } 65 | 66 | async function listBanned (serverOptions, client) { 67 | const embed = new MessageEmbed() 68 | .setTitle('Disabled Users/Channels') 69 | .setDescription('Autodownload will not work for the following users or channels') 70 | .setColor(serverOptions.color) 71 | 72 | const { channels, users } = serverOptions.banned 73 | 74 | const userStr = users.length === 0 ? 'None' : await users.reduce(async (str, usr) => str + `${(await client.users.fetch(usr)).tag}\n`, '') 75 | const channelStr = channels.length === 0 ? 'None' : channels.reduce((str, id) => str + `<#${id}>\n`, '') 76 | 77 | embed.addFields({ 78 | name: 'Channels', 79 | value: channelStr 80 | }, { 81 | name: 'Users', 82 | value: userStr 83 | }) 84 | 85 | return embed.toJSON() 86 | } 87 | 88 | function settingsChange (message) { 89 | // Generate message embed 90 | const res = new MessageEmbed() 91 | 92 | // Set the title and description 93 | res.setTitle(':tools: Settings Changed') 94 | res.setDescription(message) 95 | 96 | // Turn the embed into json and return 97 | return res.toJSON() 98 | } 99 | 100 | module.exports = { settingsChange, tikTokMessage, listBanned } 101 | -------------------------------------------------------------------------------- /modules/commands/details.js: -------------------------------------------------------------------------------- 1 | const { SlashCommand } = require('slash-create') 2 | 3 | const { ServerOptions } = require('../mongo') 4 | const botInviteURL = require('../invite') 5 | const { settingsChange, tikTokMessage } = require('../messageGenerator') 6 | const log = require('../log') 7 | 8 | module.exports = class Details extends SlashCommand { 9 | constructor (client, creator) { 10 | super(creator, { 11 | name: 'details', 12 | description: 'Change what video details to show after sending a TikTok.', 13 | options: [ 14 | { 15 | type: 5, 16 | name: 'enabled', 17 | description: 'Whether this is enabled or not.', 18 | required: true 19 | }, 20 | { 21 | type: 5, 22 | name: 'description', 23 | description: 'Show the description of the video. (Default: True)', 24 | required: false 25 | }, 26 | { 27 | type: 5, 28 | name: 'author', 29 | description: 'Show the author of the TikTok.', 30 | required: false 31 | }, 32 | { 33 | type: 5, 34 | name: 'requester', 35 | description: 'Show who requested the video and when.', 36 | required: false 37 | }, 38 | { 39 | type: 5, 40 | name: 'analytics', 41 | description: 'Show things like video plays, comments, and shares.', 42 | required: false 43 | }, 44 | { 45 | type: 3, 46 | name: 'link', 47 | description: 'Show the link of the TikTok.', 48 | required: false, 49 | choices: [ 50 | { 51 | name: 'disabled', 52 | value: 'disabled' 53 | }, 54 | { 55 | name: 'embed', 56 | value: 'embed' 57 | }, 58 | { 59 | name: 'button', 60 | value: 'button' 61 | }, 62 | { 63 | name: 'both', 64 | value: 'both' 65 | } 66 | ] 67 | } 68 | ] 69 | }) 70 | this.client = client 71 | } 72 | 73 | onError () {} 74 | 75 | async run (interaction) { 76 | let hasPerms 77 | 78 | try { 79 | hasPerms = (await (await this.client.guilds.fetch(interaction.guildID)).members.fetch(interaction.user.id)).permissions.has('ADMINISTRATOR') 80 | } catch (err) { 81 | throw new Error(`I am not in this server as a bot. Please have an administrator click [this](${botInviteURL}) link to invite me.`) 82 | } 83 | 84 | if (!hasPerms) { 85 | throw new Error('You must have the ADMINISTRATOR permission to change settings.') 86 | } 87 | 88 | const serverOptions = await ServerOptions.findOneAndUpdate({ serverID: interaction.guildID }, {}, { upsert: true, new: true, setDefaultsOnInsert: true, useFindAndModify: false }) 89 | const args = interaction.data.data.options.reduce((a, b) => { 90 | a[b.name] = b.value 91 | return a 92 | }, {}) 93 | 94 | serverOptions.details.enabled = args.enabled 95 | serverOptions.details.analytics = args.analytics === undefined ? serverOptions.details.analytics : args.analytics 96 | serverOptions.details.author = args.author === undefined ? serverOptions.details.author : args.author 97 | serverOptions.details.description = args.description === undefined ? serverOptions.details.description : args.description 98 | serverOptions.details.requester = args.requester === undefined ? serverOptions.details.requester : args.requester 99 | serverOptions.details.link = args.link === undefined ? serverOptions.details.link : args.link 100 | 101 | if (!serverOptions.details.analytics && !serverOptions.details.author && !serverOptions.details.description && !serverOptions.details.requester && serverOptions.details.link === 'disabled') { 102 | serverOptions.details.enabled = false 103 | } 104 | 105 | await serverOptions.validate() 106 | await serverOptions.save() 107 | 108 | log.info('Changed details', { serverID: interaction.guildID }) 109 | 110 | // Create a tiktok message using dummy data 111 | const preview = tikTokMessage({ 112 | videoURL: botInviteURL, 113 | text: 'The video description will go here!', 114 | authorMeta: { 115 | name: 'Author Username', 116 | nickName: 'Author Nick Name', 117 | avatar: 'https://static.thenounproject.com/png/82455-200.png' 118 | }, 119 | playCount: '5M', 120 | diggCount: '600K', 121 | shareCount: '100' 122 | }, serverOptions, { 123 | name: `${interaction.user.username}#${interaction.user.discriminator}`, 124 | icon_url: interaction.user.avatarURL 125 | }, true) 126 | 127 | preview.embeds.splice(0, 0, settingsChange(args.enabled ? 'Here is a preview of what the details will look like next time I send a TikTok:' : 'Next time you request a TikTok, only the video will be sent.')) 128 | 129 | interaction.send(preview) 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /modules/tiktok.js: -------------------------------------------------------------------------------- 1 | const TikTokScraper = require('tiktok-scraper') 2 | const ffmpeg = require('fluent-ffmpeg') 3 | 4 | ffmpeg.setFfmpegPath(require('ffmpeg-static')) 5 | 6 | const STATUS = { 7 | SKIPPED: [ 8 | { name: ':white_check_mark: Downloaded', value: 'Complete!', inline: true }, 9 | { name: ':fast_forward: Compressed', value: 'Skipped!', inline: true } 10 | ], 11 | COMPRESSING: [ 12 | { name: ':white_check_mark: Downloaded', value: 'Complete!', inline: true }, 13 | { name: ':thought_balloon: Compressing', value: 'Thinking...', inline: true } 14 | ], 15 | COMPLETE: [ 16 | { name: ':white_check_mark: Downloaded', value: 'Complete!', inline: true }, 17 | { name: ':white_check_mark: Compressed', value: 'Complete!', inline: true } 18 | ], 19 | NOT_PERMITTED: [ 20 | { name: ':white_check_mark: Downloaded', value: 'Complete!', inline: true }, 21 | { name: ':white_check_mark: Compressed', value: ':x: Not Permitted :x:', inline: true } 22 | ] 23 | } 24 | 25 | const https = require('https') 26 | const http = require('http') 27 | const fs = require('fs') 28 | const path = require('path') 29 | 30 | const { compression, relativeDownloadPath, tiktok } = require('../other/settings.json') 31 | const { proxies, sessions } = tiktok 32 | const log = require('./log') 33 | 34 | // Set constants 35 | const basePath = path.join(__dirname, '..', relativeDownloadPath) 36 | const DISCORD_MAX_SIZE = compression.max_size 37 | const AUDIO_BITRATE = compression.audio_bitrate 38 | const SETTINGS = { 39 | proxy: !Array.isArray(proxies) || proxies.length === 0 ? '' : proxies, 40 | sessionList: !Array.isArray(sessions) || sessions.length === 0 ? [''] : sessions 41 | } 42 | 43 | function processTikTok (videoURL, guildID, statusChange) { 44 | // Create random videoID 45 | const videoID = Math.random().toString(36).substr(7) 46 | let returnInfo = { videoURL } 47 | 48 | // Return a promise 49 | return new Promise((resolve, reject) => { 50 | // Get video metaData then... 51 | TikTokScraper.getVideoMeta(videoURL, SETTINGS).then((videoMeta) => { 52 | // Store the headers for downloading the video 53 | const headers = videoMeta.headers 54 | 55 | // Store data about the video 56 | returnInfo = { ...returnInfo, ...videoMeta.collector[0] } 57 | returnInfo.videoPath = path.join(basePath, `${videoID}.mp4`) 58 | 59 | // Shorten the numbers 60 | returnInfo.playCount = shortNum(returnInfo.playCount) 61 | returnInfo.diggCount = shortNum(returnInfo.diggCount) 62 | returnInfo.shareCount = shortNum(returnInfo.shareCount) 63 | returnInfo.commentCount = shortNum(returnInfo.commentCount) 64 | 65 | return download(returnInfo.videoUrl, { headers }, returnInfo.videoPath) 66 | }).then(() => { 67 | const videoSize = fs.statSync(returnInfo.videoPath).size 68 | 69 | // If the video is too big to upload to discord 70 | if (videoSize > DISCORD_MAX_SIZE) { 71 | // If the servers does not have compression enabled... 72 | if (!hasCompression(guildID)) { 73 | // Update status message 74 | statusChange(STATUS.NOT_PERMITTED) 75 | // Throw an error 76 | reject(new Error('Video file too large and compression is not enabled on this server.')) 77 | } 78 | 79 | // Update the status message 80 | statusChange(STATUS.COMPRESSING) 81 | 82 | // Calculate stuff for the video 83 | const oldPath = returnInfo.videoPath 84 | const newVideoPath = path.join(basePath, `${videoID}c.mp4`) 85 | const videoLength = returnInfo.videoMeta.duration 86 | const wantedSize = DISCORD_MAX_SIZE * 0.8 // Sometimes the compression is more than expected so this is done to mitigate that. 87 | const videoBitRate = ((wantedSize / 128) / videoLength) - AUDIO_BITRATE // Calculate the bitrate 88 | 89 | // Open video in ffmpeg 90 | ffmpeg(returnInfo.videoPath) 91 | .videoBitrate(videoBitRate) // Set the bitrate to the calculated bitrate 92 | .audioBitrate(AUDIO_BITRATE) // Set the audio bitrate. (this probably isn't made) 93 | .save(newVideoPath) // Save to the compressed video path 94 | .on('error', e => { // If an error occurs... 95 | log.error(`❌ - FAILED TO COMPRESS VIDEO\n${e}`, { serverID: guildID }) 96 | reject(new Error('Failed to compress the video.')) // Throw a error which will be handled later 97 | }) 98 | .on('end', () => { // Once compression is complete 99 | // Update the status message 100 | statusChange(STATUS.COMPLETE) 101 | 102 | // Define the videos purge function 103 | returnInfo.purge = () => { 104 | fs.unlinkSync(oldPath) 105 | fs.unlinkSync(newVideoPath) 106 | } 107 | returnInfo.videoPath = newVideoPath 108 | returnInfo.videoName = `${videoID}c.mp4` 109 | 110 | // Return all the data once everything is complete 111 | resolve(returnInfo) 112 | }) 113 | } else { // Otherwise... 114 | // Update the status message to say compression isn't required 115 | statusChange(STATUS.SKIPPED) 116 | 117 | // Set variables in the returnInfo 118 | returnInfo.videoName = `${videoID}.mp4` 119 | returnInfo.purge = () => { 120 | fs.unlinkSync(returnInfo.videoPath) 121 | } 122 | 123 | // Resolve the promise with the information 124 | resolve(returnInfo) 125 | } 126 | }).catch(err => { 127 | // Reject with the error that was encountered 128 | reject(err) 129 | }) 130 | }) 131 | } 132 | 133 | // Some download function I found on stack overflow that lets me use request headers 134 | function download (url, options, filePath) { 135 | const proto = !url.charAt(4).localeCompare('s') ? https : http 136 | 137 | return new Promise((resolve, reject) => { 138 | const file = fs.createWriteStream(filePath) 139 | let fileInfo = null 140 | 141 | const request = proto.get(url, options, response => { 142 | if (response.statusCode !== 200) { 143 | reject(new Error(`Failed to get '${url}' (${response.statusCode})`)) 144 | return 145 | } 146 | 147 | fileInfo = { 148 | mime: response.headers['content-type'], 149 | size: parseInt(response.headers['content-length'], 10) 150 | } 151 | 152 | response.pipe(file) 153 | }) 154 | 155 | // The destination stream is ended by the time it's called 156 | file.on('finish', () => resolve(fileInfo)) 157 | 158 | request.on('error', err => { 159 | fs.unlink(filePath, () => reject(err)) 160 | }) 161 | 162 | file.on('error', err => { 163 | fs.unlink(filePath, () => reject(err)) 164 | }) 165 | 166 | request.end() 167 | }) 168 | } 169 | 170 | // Function to check if a server has compression or not 171 | function hasCompression (guildID) { 172 | // If restrict is not enabled then return true 173 | if (!compression.restrict) return true 174 | // If serverID is in list of allowed servers, return true 175 | if (compression.servers.indexOf(guildID) !== -1) return true 176 | // Otherwise return false 177 | return false 178 | } 179 | 180 | // Function to shorten numbers 181 | function shortNum (num) { 182 | if (num >= 1000000) { 183 | return num / 1000000 + 'M' 184 | } else if (num >= 1000) { 185 | return num / 1000 + 'K' 186 | } else return String(num) 187 | } 188 | 189 | module.exports = processTikTok 190 | -------------------------------------------------------------------------------- /bot.js: -------------------------------------------------------------------------------- 1 | const { SlashCreator, GatewayServer } = require('slash-create') 2 | const path = require('path') 3 | const Discord = require('discord.js') 4 | const { FLAGS } = Discord.Intents 5 | const mongoose = require('mongoose') 6 | const fs = require('fs') 7 | 8 | const TikTokParser = require('./modules/tiktok') 9 | const { ServerOptions } = require('./modules/mongo') 10 | const { bot, status, owner } = require('./other/settings.json') 11 | const log = require('./modules/log') 12 | const botInviteURL = require('./modules/invite') 13 | const { tikTokMessage } = require('./modules/messageGenerator') 14 | 15 | const STARTERS = ['https://vm.tiktok.com/', 'http://vm.tiktok.com/', 'https://www.tiktok.com/', 'http://www.tiktok.com/', 'https://m.tiktok.com/v/', 'http://m.tiktok.com/v/', 'https://vt.tiktok.com/', 'http://vt.tiktok.com/'] 16 | 17 | // Initialize the bot and slash commands 18 | const client = new Discord.Client({ intents: [FLAGS.GUILDS, FLAGS.GUILD_MESSAGES, FLAGS.DIRECT_MESSAGES] }) 19 | const creator = new SlashCreator({ 20 | applicationID: bot.id, 21 | publicKey: bot.publicKey, 22 | token: bot.token 23 | }) 24 | 25 | // Setup slash-create 26 | creator 27 | .withServer(new GatewayServer(handler => client.ws.on('INTERACTION_CREATE', handler))) 28 | .registerCommands(fs.readdirSync(path.join(__dirname, 'modules', 'commands')).map(file => { 29 | return new (require(`./modules/commands/${file}`))(client, creator) 30 | })) 31 | .syncCommands() 32 | 33 | // Whenever this is a slash-command error run this function... 34 | creator.on('commandError', async (command, error, interaction) => { 35 | // TODO Replace entire function. This is dumb 36 | if (error) { 37 | log.error(`${error.message}`, { serverID: interaction.guildID }) 38 | } 39 | 40 | let e 41 | 42 | try { 43 | // Create a empty reason string 44 | let reason = '' 45 | 46 | // If the error type is a validation error 47 | if (error instanceof mongoose.Error.ValidationError) { 48 | // For each of validation errors 49 | for (const field in error.errors) { 50 | // Add the reason to the message with a new line. 51 | const thisE = error.errors[field] 52 | reason += `${thisE.path}: ${thisE.message}\n` 53 | } 54 | } else { 55 | // Otherwise set the reason to the error message. 56 | reason = error.message 57 | } 58 | 59 | // Create error message 60 | e = new Discord.MessageEmbed() 61 | .setTitle(':rotating_light: Error') 62 | .setColor('#ff0000') 63 | .setDescription(reason) 64 | .setFooter(`If you believe this is a bug please contact ${owner.tag}`) 65 | .toJSON() 66 | } catch (err) { 67 | log.error(`Fatal crash trying to generate error message: ${err}`) 68 | 69 | e = new Discord.MessageEmbed() 70 | .setTitle(':rotating_light: Fatal Error') 71 | .setDescription(`A fatal error has occurred. Please contact ${owner.tag} to report this bug.`) 72 | .setColor('#ff0000') 73 | .toJSON() 74 | } finally { 75 | // Respond with error 76 | interaction.send({ embeds: [e] }) 77 | } 78 | }) 79 | 80 | // On bot ready... 81 | client.on('ready', () => { 82 | // Log that the bot is ready. 83 | log.info('Bot ready!') 84 | log.info(`Invite Link: ${botInviteURL}`) 85 | 86 | const [serverCount, memberCount] = getMemberServerCount() 87 | 88 | // Log server and member count 89 | log.info(`I am in ${serverCount} servers, serving ${memberCount} users.`) 90 | 91 | // Define function to update teh status 92 | const setStatus = () => { 93 | client.user.setPresence({ 94 | activity: { 95 | name: status 96 | }, 97 | status: 'dnd' 98 | }) 99 | } 100 | 101 | // Run Now 102 | setStatus() 103 | // Every 15 minutes... 104 | setInterval(setStatus, 15 * 60 * 1000) 105 | }) 106 | 107 | // Whenever the bot joins a server... 108 | client.on('guildCreate', member => { 109 | // Get server and member count 110 | const [serverCount, memberCount] = getMemberServerCount() 111 | 112 | // Log that joined a server 113 | log.info(`Joined a new server! Now I am in ${serverCount} servers`) 114 | 115 | // Send the bot owner a message 116 | messageOwner(`I just joined the server: "${member.name}". It has ${member.memberCount} users!\nServer Count: ${serverCount} | Member Count: ${memberCount}`) 117 | }) 118 | 119 | // Whenever the bot gets removed from a server... 120 | client.on('guildDelete', server => { 121 | // Get server and member count 122 | const [serverCount, memberCount] = getMemberServerCount() 123 | 124 | // Generate the message 125 | const message = typeof server === 'undefined' ? 'A server I was in was just deleted.' : `I was just removed from: "${server.name}" which had ${server.memberCount} users.` 126 | 127 | // Log and send message to the owner 128 | log.info(`Got removed from a server! Now I am in ${serverCount} servers`) 129 | messageOwner(message + `\nServer Count: ${serverCount} | Member Count: ${memberCount}`) 130 | }) 131 | 132 | // On every message... 133 | client.on('message', async message => { 134 | // Return if user is a bot 135 | if (message.author.bot) return 136 | 137 | // Find if there is a tiktok link in the message, if there is see if there is anything else 138 | const tiktok = getTikTokFromStr(message.content) 139 | const onlyTikTok = message.content.split(' ').length === 1 140 | 141 | // If no tiktok return 142 | if (tiktok === undefined) return 143 | 144 | // Figure out weather bot has permission to speak in the channel with the tiktok. 145 | // If not set the channel to the dm channel of the user who sent the tiktok 146 | const channel = message.channel.permissionsFor(client.user).has('SEND_MESSAGES') ? message.channel : message.author 147 | 148 | // Get options for this server 149 | const guildOptions = await ServerOptions.findOneAndUpdate({ serverID: message.guild.id }, {}, { upsert: true, new: true, setDefaultsOnInsert: true, useFindAndModify: false }) 150 | 151 | // Check if this user or channel is banned 152 | if (guildOptions.banned.channels.indexOf(message.channel.id) + guildOptions.banned.users.indexOf(message.author.id) !== -2) return 153 | 154 | // If they don't have autodownload enabled then return 155 | if (!guildOptions.autodownload.enabled) return 156 | 157 | // Define some variables 158 | let videoStatus, statusMessage 159 | let statusUpdater = () => {} 160 | 161 | // If they have progress messages enabled, create the message and send it 162 | if (guildOptions.progress.enabled) { 163 | // Creating the message 164 | videoStatus = { 165 | title: 'Video Status', 166 | description: 'Downloading the video and checking if compression is required...', 167 | color: guildOptions.color, 168 | fields: [ 169 | { name: ':x: Downloaded', value: 'Waiting...', inline: true }, 170 | { name: ':x: Compressed', value: 'Waiting...', inline: true } 171 | ] 172 | } 173 | 174 | // Sending it 175 | statusMessage = await channel.send({ embeds: [videoStatus] }) 176 | 177 | // Define status updater 178 | statusUpdater = (status) => { 179 | videoStatus.fields = status 180 | statusMessage.edit({ embeds: [videoStatus] }) 181 | } 182 | } 183 | 184 | // Log that the bot got a request for a video 185 | log.info(`📩 - Processing Video: ${tiktok}`, { serverID: message.guild.id }) 186 | 187 | // Get the video data 188 | TikTokParser(tiktok, message.guild.id, statusUpdater).then(async videoData => { 189 | // With the video data... 190 | const requester = { 191 | avatarURL: message.author.avatarURL(), 192 | name: message.author.tag 193 | } 194 | // Start making the message its going to send 195 | const response = tikTokMessage(videoData, guildOptions, requester) 196 | response.files = [videoData.videoPath] 197 | 198 | // Wait for message to send... 199 | await channel.send(response).catch(err => { 200 | log.error(`⚠️ - ERROR SENDING VIDEO\n${err}`, { serverID: message.guild.id }) 201 | }) 202 | 203 | // If the message is deletable, and they have autodelete enabled, then... 204 | if (message.deletable && ((guildOptions.autodownload.deletemessage && guildOptions.autodownload.smartdelete && onlyTikTok) || (guildOptions.autodownload.deletemessage && !guildOptions.autodownload.smartdelete))) { 205 | // Delete the video 206 | message.delete() 207 | } 208 | 209 | // If there was a status message... 210 | if (statusMessage && statusMessage.deletable) { 211 | // Delete the status messsage. 212 | statusMessage.delete() 213 | } 214 | 215 | // Delete the local video file(s) 216 | videoData.purge() 217 | }).catch(err => { 218 | // If theres an error... 219 | // Log error 220 | log.error(`⚠️ - ERROR PROCESSING VIDEO\n${err}`, { serverID: message.guild.id }) 221 | 222 | // If there is a status message and it is deletable... 223 | if (statusMessage && statusMessage.deletable) { 224 | // Delete the status message if there is one 225 | statusMessage.delete() 226 | } 227 | 228 | // Check if they want errors to be displayed 229 | if (guildOptions.autodownload.displayErrors) { 230 | // Send user the error message 231 | channel.send({ 232 | embeds: [new Discord.MessageEmbed() 233 | .setTitle(':rotating_light: Error') 234 | .setColor('#ff0000') 235 | .setDescription('I couldn\'t download that video for some reason. Check to make sure the video is not private.') 236 | .setFooter(`Please contact ${owner.tag} if you believe this is an error`) 237 | ] 238 | }) 239 | } 240 | }) 241 | }) 242 | 243 | // Function to get a tiktok url from a string 244 | // The url could be anywhere in the string. 245 | function getTikTokFromStr (msg) { 246 | // Split the string and for each element... 247 | for (const element of msg.split(' ')) { 248 | // Loop through all the possible tiktok video starters... 249 | for (const starter of STARTERS) { 250 | // If there is a match then return the item of the first array 251 | if (element.startsWith(starter)) return element 252 | } 253 | } 254 | 255 | // Otherwise return undefined because nothing was found 256 | return undefined 257 | } 258 | 259 | // Function that messages the owner 260 | function messageOwner (msg) { 261 | // Get the owner by their ID 262 | client.users.fetch(owner.id).then(usr => { 263 | // Send them a message 264 | usr.send(msg) 265 | }).catch(err => log.error(`👤 - Couldn't Find Owner\nError: ${err}\nMessage: ${msg}`)) 266 | } 267 | 268 | // Function to calculate member and server count 269 | function getMemberServerCount () { 270 | return client.guilds.cache.reduce((acc, item) => { 271 | acc[0] += 1 272 | acc[1] += item.memberCount 273 | return acc 274 | }, [0, 0]) 275 | } 276 | 277 | // Dumb workaround for slash-create 278 | module.exports = client 279 | 280 | // Login with bot 281 | client.login(bot.token) 282 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------