From 688e37145b4af7dd8f3a87393f319c817eddddfd Mon Sep 17 00:00:00 2001 From: Spotlight Date: Sun, 19 Jan 2020 16:27:37 -0600 Subject: [PATCH 01/42] Apply Rubocop automatic suggestions --- .gitignore | 1 + .rubocop.yml | 28 +++ Gemfile | 3 +- config/custom/custom.sample.rb | 40 ++-- maintenance.rb | 48 ++--- modules/custom.rb | 58 +++--- modules/extra/joke.rb | 93 +++++----- modules/extra/json_cmds.rb | 321 ++++++++++++++++----------------- modules/extra/love.rb | 106 +++++------ modules/helper/avatar.rb | 11 +- modules/helper/db.rb | 10 +- modules/helper/download.rb | 9 +- modules/helper/embeds.rb | 28 ++- modules/helper/misc.rb | 21 ++- modules/helper/parse.rb | 119 ++++++------ modules/logging/stats.rb | 178 +++++++++--------- modules/misc/donators.rb | 198 +++++++++++--------- modules/misc/helpabout.rb | 21 ++- modules/misc/textgen.rb | 9 +- modules/mod/clear.rb | 189 ++++++++++--------- modules/mod/kickban.rb | 127 +++++++------ modules/mod/unban.rb | 37 ++-- modules/owner/dm.rb | 54 +++--- modules/owner/eval.rb | 111 ++++++------ modules/owner/ignore.rb | 94 +++++----- modules/owner/owners.rb | 84 ++++----- modules/owner/profile.rb | 145 ++++++++------- modules/owner/prune.rb | 127 ++++++------- modules/owner/shutdown.rb | 40 ++-- modules/owner/upload.rb | 36 ++-- modules/setup.rb | 75 ++++---- modules/utility/info.rb | 236 ++++++++++++------------ modules/utility/qr.rb | 65 +++---- modules/utility/say.rb | 34 ++-- modules/utility/servers.rb | 11 +- modules/utility/stubs.rb | 15 +- run.rb | 32 ++-- 37 files changed, 1431 insertions(+), 1383 deletions(-) create mode 100644 .rubocop.yml diff --git a/.gitignore b/.gitignore index 260ba0b..854f91e 100644 --- a/.gitignore +++ b/.gitignore @@ -137,3 +137,4 @@ log/* logs/* log* .vscode/* +!.rubocop.yml \ No newline at end of file diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..2ba0c8e --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,28 @@ +Metrics/BlockLength: + Enabled: false + +Metrics/MethodLength: + Enabled: false + +Style/Documentation: + Enabled: false + +Security/Eval: + Exclude: + - "exts/core/eval.rb" + +Lint/Debugger: + Exclude: + - "run.rb" + +Layout/LineLength: + Exclude: + - "config/custom/custom.sample.rb" + +Style/GlobalVars: + Exclude: + - "run.rb" + +Security/Open: + Exclude: + - "helpers/download.rb" diff --git a/Gemfile b/Gemfile index aa659e6..91143a4 100644 --- a/Gemfile +++ b/Gemfile @@ -1,3 +1,5 @@ +# frozen_string_literal: true + source 'http://rubygems.org' gem 'commandrb', git: 'https://github.com/Yuuki-Discord/commandrb.git' gem 'discordrb', git: 'https://github.com/discordrb/discordrb.git' @@ -10,4 +12,3 @@ gem 'redis' gem 'redis-namespace' gem 'rqrcode' gem 'rumoji' - diff --git a/config/custom/custom.sample.rb b/config/custom/custom.sample.rb index c1448f3..0fa385c 100644 --- a/config/custom/custom.sample.rb +++ b/config/custom/custom.sample.rb @@ -1,34 +1,35 @@ -# Three different ways to add custom commands easy. +# frozen_string_literal: true +# Three different ways to add custom commands easy. #### NOTE #### # The below examples that use {user} and {userid} do not currently function. # This feature is planned for later. -CUSTOM = {} +CUSTOM = {}.freeze # 1. Make your own hashes! CUSTOM[:pong] = { - :type => 'text', - :response => 'Ping!' + type: 'text', + response: 'Ping!' } CUSTOM[:hi] = { - :type => 'text', - :response => 'Hello, {user}!' + type: 'text', + response: 'Hello, {user}!' } CUSTOM[:mentionme] = { - :type => 'text', - :response => 'Hello, <@{userid}>!' + type: 'text', + response: 'Hello, <@{userid}>!' } # 2. All in one hash! CUSTOM_TEXT = { - :pong => 'Ping!', - :hi => 'Hello, {user}!', - :mentionme => 'Hello, <@{userid}>!' -} + pong: 'Ping!', + hi: 'Hello, {user}!', + mentionme: 'Hello, <@{userid}>!' +}.freeze # 3. Change one variable(!) CUSTOM_TEXT[:pong] = 'Ping' @@ -36,15 +37,14 @@ CUSTOM_TEXT[:mentionme] = 'Hello, <@{userid}>!' # Don't forget images! -CUSTOM_IMAGE = {} +CUSTOM_IMAGE = {}.freeze CUSTOM_IMAGE[:dab] = 'custom/dab.jpg' - CUSTOM_TEXT = { - lenny: '( ͡° ͜ʖ ͡°)', - shrug: '¯\_(ツ)_/¯', - support: "⚙ **Need help?**\nYou can join the support server here:\n**https://discord.gg/PrTMrv4 **", - facedesk: 'https://giphy.com/gifs/XLOsdacfjL5cI', - smea: 'https://giphy.com/gifs/Sb2NkTl1oV6eI', -} + lenny: '( ͡° ͜ʖ ͡°)', + shrug: '¯\_(ツ)_/¯', + support: "⚙ **Need help?**\nYou can join the support server here:\n**https://discord.gg/PrTMrv4 **", + facedesk: 'https://giphy.com/gifs/XLOsdacfjL5cI', + smea: 'https://giphy.com/gifs/Sb2NkTl1oV6eI' +}.freeze diff --git a/maintenance.rb b/maintenance.rb index e8070ee..0fa0aa6 100644 --- a/maintenance.rb +++ b/maintenance.rb @@ -1,37 +1,39 @@ +# frozen_string_literal: true + require 'yaml' require 'discordrb' # Load Config from YAML -if File.exists?('config/maintenance.yml') - @config = YAML.load_file('config/maintenance.yml') -else - @config = YAML.load_file('config/config.yml') -end +@config = if File.exist?('config/maintenance.yml') + YAML.load_file('config/maintenance.yml') + else + YAML.load_file('config/config.yml') + end @config.each do |key, value| - if value.nil? - puts "config.yml: #{key} is nil!" - puts 'Corrupt or incorrect Yaml.' - exit - else - puts("config.yml: Found #{key}: #{value}") if @config['verbose'] - end + if value.nil? + puts "config.yml: #{key} is nil!" + puts 'Corrupt or incorrect Yaml.' + exit + else + puts("config.yml: Found #{key}: #{value}") if @config['verbose'] + end end - + bot = Discordrb::Bot.new token: @config['token'] bot.ready do |event| - event.bot.dnd - event.bot.game = "Down for maintenance... :(" + event.bot.dnd + event.bot.game = 'Down for maintenance... :(' end bot.message do |event| - if event.message.content.split(' ').length > 1 - @config['prefixes'].each { |x| - if event.message.content.start_with? x - event.respond("Hi, if you're seeing this message, it means that Yuuki-Bot is currently unavailable (Deliberately, unlike downtime) or is in maintenance due to a major bug that needs to be dealt with.\nPlease try again later, and contact `#{event.bot.user(@config['master_owner']).distinct}` if problems persist.\nSorry for any inconvenience caused!") - break - end - } + if event.message.content.split(' ').length > 1 + @config['prefixes'].each do |x| + if event.message.content.start_with? x + event.respond("Hi, if you're seeing this message, it means that Yuuki-Bot is currently unavailable (Deliberately, unlike downtime) or is in maintenance due to a major bug that needs to be dealt with.\nPlease try again later, and contact `#{event.bot.user(@config['master_owner']).distinct}` if problems persist.\nSorry for any inconvenience caused!") + break + end end + end end -bot.run \ No newline at end of file +bot.run diff --git a/modules/custom.rb b/modules/custom.rb index c5c1eaf..e94a912 100644 --- a/modules/custom.rb +++ b/modules/custom.rb @@ -1,54 +1,52 @@ +# frozen_string_literal: true + module YuukiBot module Custom - - if File.exists?('config/custom/custom.rb') + if File.exist?('config/custom/custom.rb') require './config/custom/custom.rb' unless CUSTOM_TEXT.nil? || CUSTOM_TEXT == {} - CUSTOM_TEXT.each {|name, response| + CUSTOM_TEXT.each do |name, response| $cbot.add_command(name.to_sym, - code: proc {|event| - event.respond(response) - } - ) + code: proc { |event| + event.respond(response) + }) puts "Added custom command: #{name}" - } + end end unless CUSTOM_IMAGE.nil? || CUSTOM_IMAGE == {} - CUSTOM_IMAGE.each {|name, image| + CUSTOM_IMAGE.each do |name, image| $cbot.add_command(name.to_sym, - code: proc {|event| - event.channel.send_file(File.new("./config/custom/#{image}")) - } - ) + code: proc { |event| + event.channel.send_file(File.new("./config/custom/#{image}")) + }) puts "Added custom command: #{name}" - } + end end end - yml_commands = YAML.load_file('./config/custom/custom.yml') if File.exists?('config/custom/custom.yml') + if File.exist?('config/custom/custom.yml') + yml_commands = YAML.load_file('./config/custom/custom.yml') + end unless yml_commands.nil? || yml_commands[:text].nil? || yml_commands[:text] == {} - yml_commands[:text].each {|name, response| + yml_commands[:text].each do |name, response| $cbot.add_command(name.to_sym, - code: proc {|event| - event.respond(response) - } - ) + code: proc { |event| + event.respond(response) + }) puts "Added custom command: #{name}" - } + end end unless yml_commands.nil? || yml_commands[:image].nil? || yml_commands[:image] == {} - yml_commands[:image].each {|name, image| + yml_commands[:image].each do |name, image| $cbot.add_command(name.to_sym, - code: proc {|event| - event.channel.send_file(File.new("./config/custom/#{image}")) - } - ) + code: proc { |event| + event.channel.send_file(File.new("./config/custom/#{image}")) + }) puts "Added custom command: #{name}" - } + end end - require './config/custom/code.rb' if File.exists? 'config/custom/code.rb' - + require './config/custom/code.rb' if File.exist? 'config/custom/code.rb' end -end \ No newline at end of file +end diff --git a/modules/extra/joke.rb b/modules/extra/joke.rb index ed88543..eb19bb0 100644 --- a/modules/extra/joke.rb +++ b/modules/extra/joke.rb @@ -1,60 +1,57 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe), spotlight_is_ok, Larsenv 2017-2020 module YuukiBot module Extra - text_joke_commands = %w(doit pun wisdom lawyerjoke) - text_joke_commands.each { |x| + text_joke_commands = %w[doit pun wisdom lawyerjoke] + text_joke_commands.each do |x| $cbot.add_command(x.to_sym, - code: proc { |event| - result = File.readlines("text/Jokes/#{x}.txt").sample.chomp - event.respond("\\*#{result}*") - } - ) - } + code: proc { |event| + result = File.readlines("text/Jokes/#{x}.txt").sample.chomp + event.respond("\\*#{result}*") + }) + end - text_other_commands = %w(vote topicchange fortunes factdiscord randomssmash4item) - text_other_commands.each { |x| + text_other_commands = %w[vote topicchange fortunes factdiscord randomssmash4item] + text_other_commands.each do |x| $cbot.add_command(x.to_sym, - code: proc { |event| - result = File.readlines("text/Other/Text/#{x}.txt").sample.chomp - event.respond("#{result}") - }, - min_args: 1 - ) - } + code: proc { |event| + result = File.readlines("text/Other/Text/#{x}.txt").sample.chomp + event.respond(result.to_s) + }, + min_args: 1) + end $cbot.add_command(:confucius, - code: proc { |event, _| - event.respond("Confucious say #{File.readlines('text/Jokes/confucious.txt').sample.chomp}") - }, - min_args: 1 - ) - - $cbot.add_command(:dance, - code: proc { |event, args| - letters = YAML.load_file('config/dancingletters.yml') - event.respond(args.join(' ').downcase.gsub(/[a-zA-Z0-9@?!&$-]/, letters).to_s ) - }, - min_args: 1 - ) + code: proc { |event, _| + event.respond("Confucious say #{File.readlines('text/Jokes/confucious.txt').sample.chomp}") + }, + min_args: 1) + + $cbot.add_command(:dance, + code: proc { |event, args| + letters = YAML.load_file('config/dancingletters.yml') + event.respond(args.join(' ').downcase.gsub(/[a-zA-Z0-9@?!&$-]/, letters).to_s) + }, + min_args: 1) $cbot.add_command(:notice, - code: proc { |event, args| - target_guess = event.bot.parse_mention(args.join(' ')) - if args.nil? or args == [] or args[0] == 'me' - target = event.user.name - elsif target_guess.nil? - target = args.join(' ') - else - target = target_guess.name - end - - if args.length >= 2 && args[1] == 'senpai' - event.respond("\\*Senpai notices #{whom}*") - else - event.respond("\\*notices #{whom}*") - end - }, - min_args: 1 - ) + code: proc { |event, args| + target_guess = event.bot.parse_mention(args.join(' ')) + target = if args.nil? || (args == []) || (args[0] == 'me') + event.user.name + elsif target_guess.nil? + args.join(' ') + else + target_guess.name + end + + if args.length >= 2 && args[1] == 'senpai' + event.respond("\\*Senpai notices #{whom}*") + else + event.respond("\\*notices #{whom}*") + end + }, + min_args: 1) end end diff --git a/modules/extra/json_cmds.rb b/modules/extra/json_cmds.rb index cc3b867..7b548b3 100644 --- a/modules/extra/json_cmds.rb +++ b/modules/extra/json_cmds.rb @@ -1,231 +1,218 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe), spotlight_is_ok, Larsenv 2017-2020 module YuukiBot module Extra if YuukiBot.config['extra_commands'] - json_food_commands = %w(beer biscuit brekkie burger cake cereal cheese chicken chocolate coffee cookie donut doobie drinks halal icecream kebab keto kosher milkshake muffin noodles nugget oreo pancake pasta pie pizza potato rice sandwich scone snack soup steak sushi taco tea wine) + json_food_commands = %w[beer biscuit brekkie burger cake cereal cheese chicken chocolate coffee cookie donut doobie drinks halal icecream kebab keto kosher milkshake muffin noodles nugget oreo pancake pasta pie pizza potato rice sandwich scone snack soup steak sushi taco tea wine] - json_food_commands.each { |x| + json_food_commands.each do |x| $cbot.add_command(x.to_sym, - code: proc { |event,args| - target_guess = event.bot.parse_mention(args.join(' ')) - if args.nil? or args == [] - target = event.user.name - elsif target_guess.nil? - target = args.join(' ') - else - target = target_guess.name - end - - json = JSON.parse(File.read("text/Food/#{x}.json")) - - variables = {} - variables['user'] = target - event.respond("\\*#{Textgen.generate_string(json['templates'], json['parts'], variables)}*") - }, - triggers: [x, "give #{x} to ", "give a #{x} to "] - ) + code: proc { |event, args| + target_guess = event.bot.parse_mention(args.join(' ')) + target = if args.nil? || (args == []) + event.user.name + elsif target_guess.nil? + args.join(' ') + else + target_guess.name + end + + json = JSON.parse(File.read("text/Food/#{x}.json")) + + variables = {} + variables['user'] = target + event.respond("\\*#{Textgen.generate_string(json['templates'], json['parts'], variables)}*") + }, + triggers: [x, "give #{x} to ", "give a #{x} to "]) puts "Added food command for #{x}!" if YuukiBot.config['verbose'] - } + end $cbot.commands[:brekkie][:triggers].push('breakfast', 'brekky', 'give breakfast to ', 'give a breakfast to', 'give brekky to ', 'give a brekky to') - json_attack_commands = %w(slap compliment strax present) - json_attack_commands.each { |x| + json_attack_commands = %w[slap compliment strax present] + json_attack_commands.each do |x| $cbot.add_command(x.to_sym, - code: proc { |event,args| - target_guess = event.bot.parse_mention(args.join(' ')) - if args.nil? or args == [] - target = event.user.name - elsif target_guess.nil? - target = args.join(' ') - else - target = target_guess.name - end - - json = JSON.parse(File.read("text/Attack/JSON/#{x}.json")) - - variables = {} - variables['user'] = target - event.respond("\\*#{Textgen.generate_string(json['templates'], json['parts'], variables)}*") - } - ) + code: proc { |event, args| + target_guess = event.bot.parse_mention(args.join(' ')) + target = if args.nil? || (args == []) + event.user.name + elsif target_guess.nil? + args.join(' ') + else + target_guess.name + end + + json = JSON.parse(File.read("text/Attack/JSON/#{x}.json")) + + variables = {} + variables['user'] = target + event.respond("\\*#{Textgen.generate_string(json['templates'], json['parts'], variables)}*") + }) puts "Added attack command for #{x}!" if YuukiBot.config['verbose'] - } + end - text_attack_commands = %w(lart insult) - text_attack_commands.each { |x| + text_attack_commands = %w[lart insult] + text_attack_commands.each do |x| $cbot.add_command(x.to_sym, - code: proc { |event,args| - target_guess = event.bot.parse_mention(args.join(' ')) - if args.nil? or args == [] - target = event.user.name - elsif target_guess.nil? - target = args.join(' ') - else - target = target_guess.name - end - - result = File.readlines("text/Attacks/Text/#{x}.txt").sample.chomp - result = result.gsub('{user}', target) if /{user}/ =~ result - - event.respond("\\*#{result}*") - } - ) + code: proc { |event, args| + target_guess = event.bot.parse_mention(args.join(' ')) + target = if args.nil? || (args == []) + event.user.name + elsif target_guess.nil? + args.join(' ') + else + target_guess.name + end + + result = File.readlines("text/Attacks/Text/#{x}.txt").sample.chomp + if /{user}/ =~ result + result = result.gsub('{user}', target) + end + + event.respond("\\*#{result}*") + }) puts "Added attack command for #{x}!" if YuukiBot.config['verbose'] - } + end - text_attack_commands = %w(nk) - text_attack_commands.each { |x| + text_attack_commands = %w[nk] + text_attack_commands.each do |x| $cbot.add_command(x.to_sym, - code: proc { |event| - result = File.readlines("text/Attacks/Text/#{x}.txt").sample.chomp + code: proc { |event| + result = File.readlines("text/Attacks/Text/#{x}.txt").sample.chomp - event.respond("\\*#{result}*") - } - ) + event.respond("\\*#{result}*") + }) puts "Added attack command for #{x}!" if YuukiBot.config['verbose'] - } + end - text_joke_commands = %w(doit pun wisdom lawyerjoke) - text_joke_commands.each { |x| + text_joke_commands = %w[doit pun wisdom lawyerjoke] + text_joke_commands.each do |x| $cbot.add_command(x.to_sym, - code: proc { |event| - result = File.readlines("text/Jokes/#{x}.txt").sample.chomp + code: proc { |event| + result = File.readlines("text/Jokes/#{x}.txt").sample.chomp - event.respond("\\*#{result}*") - } - ) + event.respond("\\*#{result}*") + }) puts "Added jokes command for #{x}!" if YuukiBot.config['verbose'] - } + end - text_other_commands = %w(vote topicchange fortunes factdiscord randomssmash4item) - text_other_commands.each { |x| + text_other_commands = %w[vote topicchange fortunes factdiscord randomssmash4item] + text_other_commands.each do |x| $cbot.add_command(x.to_sym, - code: proc { |event| - result = File.readlines("text/Other/Text/#{x}.txt").sample.chomp + code: proc { |event| + result = File.readlines("text/Other/Text/#{x}.txt").sample.chomp - event.respond("\\*#{result}*") - } - ) + event.respond("\\*#{result}*") + }) puts "Added jokes command for #{x}!" if YuukiBot.config['verbose'] - } + end $cbot.add_command(:randomquestion, - code: proc { |event| - json = JSON.parse(File.read('text/Other/JSON/randomquestion.json')) - - # prng = Random.new - variables = {} - response = Textgen.generate_string(json['templates'], json['parts'], variables) + code: proc { |event| + json = JSON.parse(File.read('text/Other/JSON/randomquestion.json')) - event.respond(response) - } - ) - puts 'Added fun command for random question!' if YuukiBot.config['verbose'] + # prng = Random.new + variables = {} + response = Textgen.generate_string(json['templates'], json['parts'], variables) + event.respond(response) + }) + if YuukiBot.config['verbose'] + puts 'Added fun command for random question!' + end $cbot.add_command(:nextzeldagame, - code: proc { |event| - json = JSON.parse(File.read('text/Other/JSON/nextzeldagame.json')) + code: proc { |event| + json = JSON.parse(File.read('text/Other/JSON/nextzeldagame.json')) - prng = Random.new - variables = {} - variables['random_number'] = prng.rand(1..10) - response = Textgen.generate_string(json['templates'], json['parts'], variables) + prng = Random.new + variables = {} + variables['random_number'] = prng.rand(1..10) + response = Textgen.generate_string(json['templates'], json['parts'], variables) - event.respond(response) - } - ) + event.respond(response) + }) puts 'Added fun command for nextzeldagame!' if YuukiBot.config['verbose'] $cbot.add_command(:confucious, - code: proc { |event, _| - event.respond("Confucious say #{File.readlines('text/Jokes/confucious.txt').sample.chomp}") - } - ) + code: proc { |event, _| + event.respond("Confucious say #{File.readlines('text/Jokes/confucious.txt').sample.chomp}") + }) puts 'Added jokes command for confucious!' if YuukiBot.config['verbose'] $cbot.add_command(:bookpun, - code: proc { |event, _| - title, author = File.readlines('text/Jokes/bookpun.txt').sample.chomp.split ': ', 2 - event.respond("#{title} by #{author}") - } - ) + code: proc { |event, _| + title, author = File.readlines('text/Jokes/bookpun.txt').sample.chomp.split ': ', 2 + event.respond("#{title} by #{author}") + }) puts 'Added jokes command for bookpun!' if YuukiBot.config['verbose'] $cbot.add_command(:wouldyourather, - code: proc { |event, _| - json_string = open('http://rrrather.com/botapi').read - array = JSON.parse(json_string, symbolize_names: true) - event.respond("#{array[:title]}: #{array[:choicea].rstrip} OR #{array[:choiceb].rstrip}") - } - ) + code: proc { |event, _| + json_string = open('http://rrrather.com/botapi').read + array = JSON.parse(json_string, symbolize_names: true) + event.respond("#{array[:title]}: #{array[:choicea].rstrip} OR #{array[:choiceb].rstrip}") + }) puts 'Added fun command for wouldyourather!' if YuukiBot.config['verbose'] $cbot.add_command(:fact, - code: proc { |_, _| - types = %w(trivia math date year) - type = types.sample - open("http://numbersapi.com/random/#{type}").read - } - ) + code: proc { |_, _| + types = %w[trivia math date year] + type = types.sample + open("http://numbersapi.com/random/#{type}").read + }) puts 'Added fun command for fact!' if YuukiBot.config['verbose'] $cbot.add_command(:eightball, - code: proc { |event, _| - event.respond("shakes the magic 8 ball... **#{File.readlines('text/Other/8ball_responses.txt').sample.chomp}**") - } - ) + code: proc { |event, _| + event.respond("shakes the magic 8 ball... **#{File.readlines('text/Other/8ball_responses.txt').sample.chomp}**") + }) puts 'Added fun command for eightball!' if YuukiBot.config['verbose'] $cbot.add_command(:cats, - code: proc { |event, _| - json_string = open('https://catfacts-api.appspot.com/api/facts').read - array = JSON.parse(json_string, symbolize_names: true) - event.respond(array[:facts][0].to_s) - } - ) + code: proc { |event, _| + json_string = open('https://catfacts-api.appspot.com/api/facts').read + array = JSON.parse(json_string, symbolize_names: true) + event.respond(array[:facts][0].to_s) + }) puts 'Added fun command for cats!' if YuukiBot.config['verbose'] $cbot.add_command(:catgifs, - code: proc { |event, _| - gif_url = nil - open('http://marume.herokuapp.com/random.gif') do |resp| - gif_url = resp.base_uri.to_s - end - event.respond("OMG A CAT GIF: #{gif_url}") - } - ) + code: proc { |event, _| + gif_url = nil + open('http://marume.herokuapp.com/random.gif') do |resp| + gif_url = resp.base_uri.to_s + end + event.respond("OMG A CAT GIF: #{gif_url}") + }) puts 'Added fun command for catgifs!' if YuukiBot.config['verbose'] $cbot.add_command(:fight, - code: proc { |event,args| - target_guess = event.bot.parse_mention(args.join(' ')) - if args.nil? or args == [] - target = event.user.name - elsif target_guess.nil? - target = args.join(' ') - else - target = target_guess.name - end - - json = JSON.parse(File.read('text/Attack/JSON/fight.json')) - - variables = {} - variables['user'] = event.user.name - variables['target'] = target - response = Textgen.generate_string(json['templates'], json['parts'], variables) - - event.respond(response) - } - ) + code: proc { |event, args| + target_guess = event.bot.parse_mention(args.join(' ')) + target = if args.nil? || (args == []) + event.user.name + elsif target_guess.nil? + args.join(' ') + else + target_guess.name + end + + json = JSON.parse(File.read('text/Attack/JSON/fight.json')) + + variables = {} + variables['user'] = event.user.name + variables['target'] = target + response = Textgen.generate_string(json['templates'], json['parts'], variables) + + event.respond(response) + }) puts 'Added fun command for fight!' if YuukiBot.config['verbose'] end $cbot.add_command(:choose, - code: proc { |event,args| - event.respond("I choose #{args.sample}!") - } - ) - + code: proc { |event, args| + event.respond("I choose #{args.sample}!") + }) end end diff --git a/modules/extra/love.rb b/modules/extra/love.rb index 9461e57..5660742 100644 --- a/modules/extra/love.rb +++ b/modules/extra/love.rb @@ -1,62 +1,62 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe), spotlight_is_ok, Larsenv 2017-2020 module YuukiBot module Extra $cbot.add_command(:love, - code: proc { |event,args| - first = '' - second = '' - if args.length == 1 - first = event.user.name - begin - second = event.bot.parse_mention(args).name - rescue - second = args[0] - end - else - first = args[0] - second = args[1] - end + code: proc { |event, args| + first = '' + second = '' + if args.length == 1 + first = event.user.name + begin + second = event.bot.parse_mention(args).name + rescue StandardError + second = args[0] + end + else + first = args[0] + second = args[1] + end - prng = Random.new - percentage = prng.rand(1..100) + prng = Random.new + percentage = prng.rand(1..100) - case - when percentage < 10 - result = 'Awful 😭' - when percentage < 20 - result = 'Bad 😢' - when percentage < 30 - result = 'Pretty Low 😦' - when percentage < 40 - result = 'Not Too Great 😕' - when percentage < 50 - result = 'Worse Than Average 😐' - when percentage < 60 - result = 'Barely 😶' - when percentage == 69 - result = '( ͡° ͜ʖ ͡°)' - when percentage < 70 - result = 'Not Bad 🙂' - when percentage < 80 - result = 'Pretty Good 😃' - when percentage < 90 - result = 'Great 😄' - when percentage < 100 - result = 'Amazing 😍' - else - result = 'PERFECT! ❣️' - end + result = if percentage < 10 + 'Awful 😭' + elsif percentage < 20 + 'Bad 😢' + elsif percentage < 30 + 'Pretty Low 😦' + elsif percentage < 40 + 'Not Too Great 😕' + elsif percentage < 50 + 'Worse Than Average 😐' + elsif percentage < 60 + 'Barely 😶' + elsif percentage == 69 + '( ͡° ͜ʖ ͡°)' + elsif percentage < 70 + 'Not Bad 🙂' + elsif percentage < 80 + 'Pretty Good 😃' + elsif percentage < 90 + 'Great 😄' + elsif percentage < 100 + 'Amazing 😍' + else + 'PERFECT! ❣️' + end - response = "💗 **MATCHMAKING** 💗\n" + - "First - #{first}\n" + - "Second - #{second}\n" + - "**-=-=-=-=-=-=-=-=-=-=-=-**\n" + - "Result ~ #{percentage}% - #{result}\n" + response = "💗 **MATCHMAKING** 💗\n" \ + "First - #{first}\n" \ + "Second - #{second}\n" \ + "**-=-=-=-=-=-=-=-=-=-=-=-**\n" \ + "Result ~ #{percentage}% - #{result}\n" - event.respond(response) - }, - triggers: ['love', 'ship '], - min_args: 1 - ) + event.respond(response) + }, + triggers: ['love', 'ship '], + min_args: 1) end -end \ No newline at end of file +end diff --git a/modules/helper/avatar.rb b/modules/helper/avatar.rb index f21e1e1..1076ad6 100644 --- a/modules/helper/avatar.rb +++ b/modules/helper/avatar.rb @@ -1,12 +1,13 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe) 2016-2020 module YuukiBot module Helper - # Downloads an avatar when given a user object. # Returns the path of the downloaded file. def self.download_avatar(user, folder) - return download_file(avatar_url(user), folder) + download_file(avatar_url(user), folder) end def self.avatar_url(user) @@ -14,9 +15,9 @@ def self.avatar_url(user) uri = URI.parse(url) filename = File.basename(uri.path) changed_filename = if filename.start_with?('a_') - filename.gsub('.jpg', '.gif') - else - filename.gsub('.jpg', '.png') + filename.gsub('.jpg', '.gif') + else + filename.gsub('.jpg', '.png') end url = "https://cdn.discordapp.com/avatars/#{user.id}/#{changed_filename}?size=4096" url diff --git a/modules/helper/db.rb b/modules/helper/db.rb index 23b8644..a6dd5a3 100644 --- a/modules/helper/db.rb +++ b/modules/helper/db.rb @@ -1,11 +1,13 @@ +# frozen_string_literal: true + # Copyright Erisa A 2019-2020 module YuukiBot module Helper - # Relatively simple, but repeated in a lot of places. def self.owners - JSON.parse(REDIS.get('owners')) rescue [] + JSON.parse(REDIS.get('owners')) + rescue StandardError + [] end - end -end \ No newline at end of file +end diff --git a/modules/helper/download.rb b/modules/helper/download.rb index 922c243..71531f2 100644 --- a/modules/helper/download.rb +++ b/modules/helper/download.rb @@ -1,8 +1,9 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe) 2016-2020 module YuukiBot module Helper - # Download a file from a url to a specified folder. # If no name is given, it will be taken from the url. # Returns the full path of the downloaded file. @@ -17,12 +18,14 @@ def self.download_file(url, folder, name = nil) FileUtils.rm(path) if File.exist?(path) IO.copy_stream(open(url), path) - return path + path end def self.upload_file(channel, filename) channel.send_file File.new([filename].sample) - puts "Uploaded `#{filename} to \##{channel.name}!" if YuukiBot.config['debug'] + if YuukiBot.config['debug'] + puts "Uploaded `#{filename} to \##{channel.name}!" + end end end end diff --git a/modules/helper/embeds.rb b/modules/helper/embeds.rb index 165cc43..5903cb1 100644 --- a/modules/helper/embeds.rb +++ b/modules/helper/embeds.rb @@ -1,18 +1,17 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe) 2020 module YuukiBot module Helper - def self.error_embed(error: nil, footer: nil, colour: nil, color: nil, code_error: true) - if error.nil? or footer.nil? + if error.nil? || footer.nil? raise 'Invalid arguments for Helper.error_embed!' else - if color.nil? and colour.nil? - colour = 0x22ef1f - end + colour = 0x22ef1f if color.nil? && colour.nil? Discordrb::Webhooks::Embed.new( - title: "#{YuukiBot.config[:emoji_error]} An error has occured!", - description: code_error ? "```ruby\n#{error}```" : error, + title: "#{YuukiBot.config[:emoji_error]} An error has occured!", + description: code_error ? "```ruby\n#{error}```" : error, colour: colour || color, footer: Discordrb::Webhooks::EmbedFooter.new(text: footer) ) @@ -23,18 +22,15 @@ def self.avatar_embed(color: nil, colour: nil, url: nil, username: nil, time: Ti if url.nil? raise 'Invalid arguments for Helper.avatar_embed!' else - if color.nil? and colour.nil? - colour = 0x22ef1f - end + colour = 0x22ef1f if color.nil? && colour.nil? username = username.nil? ? 'Unknown User' : username Discordrb::Webhooks::Embed.new( - colour: colour || color, - image: Discordrb::Webhooks::EmbedImage.new(url: url), - author: Discordrb::Webhooks::EmbedAuthor.new(name: "Avatar for #{username}", url: url), - footer: Discordrb::Webhooks::EmbedFooter.new(text: "Avatar correct as of #{time}") + colour: colour || color, + image: Discordrb::Webhooks::EmbedImage.new(url: url), + author: Discordrb::Webhooks::EmbedAuthor.new(name: "Avatar for #{username}", url: url), + footer: Discordrb::Webhooks::EmbedFooter.new(text: "Avatar correct as of #{time}") ) end end - end -end \ No newline at end of file +end diff --git a/modules/helper/misc.rb b/modules/helper/misc.rb index 744d599..38bbd30 100644 --- a/modules/helper/misc.rb +++ b/modules/helper/misc.rb @@ -1,8 +1,9 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe) 2016-2020 module YuukiBot module Helper - def self.isadmin?(member) Commandrb.owners.include?(member) end @@ -11,7 +12,7 @@ def self.quit(status = 0) puts 'Exiting...' begin $cbot.bot.stop - rescue + rescue StandardError $cbot.bot.invisible end exit(status) @@ -26,22 +27,28 @@ def self.ctrl_c(type) trap('SIGTERM') { ctrl_c('SIGTERM') } def self.role_from_name(server, rolename) - return server.roles.select { |r| r.name == rolename }.first + server.roles.select { |r| r.name == rolename }.first end # Get the user's color def self.colour_from_user(member, default = 0) colour = default unless member.nil? - member.roles.sort_by(&:position).reverse.each do | role | + member.roles.sort_by(&:position).reverse.each do |role| next if role.color.combined == 0 - puts 'Using ' + role.name + '\'s color ' + role.color.combined.to_s if YuukiBot.config['debug'] rescue nil + + begin + if YuukiBot.config['debug'] + puts 'Using ' + role.name + '\'s color ' + role.color.combined.to_s + end + rescue StandardError + nil + end colour = role.colour.combined break end end - return colour + colour end - end end diff --git a/modules/helper/parse.rb b/modules/helper/parse.rb index 6bf4d18..751abc6 100644 --- a/modules/helper/parse.rb +++ b/modules/helper/parse.rb @@ -1,99 +1,92 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe), Spotlight 2016-2020 module YuukiBot module Helper - # Accepts a message, and returns the message content, with all mentions + channels replaced with @user#1234 or #channel-name - def self.parse_mentions(content) + def self.parse_mentions(content) # Replace user IDs with names loop do - match = /<@\d+>/.match(content) - break if match.nil? - # Get user - id = match[0] - # We have to sub to just get the numerical ID. - num_id = /\d+/.match(id)[0] - content = content.sub(id, get_user_name(num_id)) + match = /<@\d+>/.match(content) + break if match.nil? + + # Get user + id = match[0] + # We have to sub to just get the numerical ID. + num_id = /\d+/.match(id)[0] + content = content.sub(id, get_user_name(num_id)) end loop do - match = /<@!\d+>/.match(content) - break if match.nil? - # Get user - id = match[0] - # We have to sub to just get the numerical ID. - num_id = /\d+/.match(id)[0] - content = content.sub(id, get_user_name(num_id)) + match = /<@!\d+>/.match(content) + break if match.nil? + + # Get user + id = match[0] + # We have to sub to just get the numerical ID. + num_id = /\d+/.match(id)[0] + content = content.sub(id, get_user_name(num_id)) end # Replace channel IDs with names loop do - match = /<#\d+>/.match(content) - break if match.nil? - # Get channel - id = match[0] - # We have to gsub to just get the numerical ID. - num_id = /\d+/.match(id)[0] - content = content.sub(id, get_channel_name(num_id)) + match = /<#\d+>/.match(content) + break if match.nil? + + # Get channel + id = match[0] + # We have to gsub to just get the numerical ID. + num_id = /\d+/.match(id)[0] + content = content.sub(id, get_channel_name(num_id)) end content - end + end # Returns a user-readable username for the specified ID. def self.get_user_name(user_id) - return begin - '@' + $cbot.bot.user(user_id).distinct - rescue NoMethodError - '@invalid-user' - end + '@' + $cbot.bot.user(user_id).distinct + rescue NoMethodError + '@invalid-user' end # Returns a user-readable channel name for the specified ID. def self.get_channel_name(channel_id) - return begin - '#' + $cbot.bot.channel(channel_id).name - rescue NoMethodError - '#deleted-channel' - end + '#' + $cbot.bot.channel(channel_id).name + rescue NoMethodError + '#deleted-channel' end def self.filter_everyone(text) # Place a null into @everyone and @here, to prevent accidental tagging. Returns the parsed text. - return text.gsub('@everyone', "@\x00everyone").gsub('@here', "@\x00here") + text.gsub('@everyone', "@\x00everyone").gsub('@here', "@\x00here") end - # Detects which user you are talking about from a word. - def self.userparse(word) - # Trial and error, ho! + # Detects which user you are talking about from a word. + def self.userparse(word) + # Trial and error, ho! - # Can't do anything if there's nothing to begin with. - if word.nil? - return nil - end + # Can't do anything if there's nothing to begin with. + return nil if word.nil? - # If its an ID. - unless $cbot.bot.user(word).nil? - return $cbot.bot.user(word) - end + # If its an ID. + return $cbot.bot.user(word) unless $cbot.bot.user(word).nil? - # If its a mention! - begin - unless /\d+/.match(/<@!?\d+>/.match(word).to_s)[0].nil? - return $cbot.bot.user(/\d+/.match(/<@!?\d+>/.match(word).to_s)[0]) + # If its a mention! + begin + unless /\d+/.match(/<@!?\d+>/.match(word).to_s)[0].nil? + return $cbot.bot.user(/\d+/.match(/<@!?\d+>/.match(word).to_s)[0]) + end + rescue StandardError + # ignored end - rescue - # ignored - end - # Might be a username... - unless $cbot.bot.find_user(word).nil? - return $cbot.bot.find_user(word)[0] - end - - return nil - end + # Might be a username... + return $cbot.bot.find_user(word)[0] unless $cbot.bot.find_user(word).nil? - def self.userid_to_string(id) - $cbot.bot.user(id).nil? ? "Unknown User (ID: #{id})" : "#{$cbot.bot.user(id).distinct}" - end + nil + end + def self.userid_to_string(id) + $cbot.bot.user(id).nil? ? "Unknown User (ID: #{id})" : $cbot.bot.user(id).distinct.to_s + end end end diff --git a/modules/logging/stats.rb b/modules/logging/stats.rb index 3545ac9..136318c 100644 --- a/modules/logging/stats.rb +++ b/modules/logging/stats.rb @@ -1,93 +1,93 @@ +# frozen_string_literal: true + # Copyright Erisa Komuro (Seriel) 2016-2017 module YuukiBot module Logging -=begin - class << self - attr_accessor :stats - end - @stats = { - totalmessages: 0, - totalmessageedits: 0, - totalmessagedeletes: 0, - totaljoinevents: 0, - totalleaveevents: 0, - server: { - DM: {} - } - } - @stats[:server] = {} - @stats[:server][:DM] = {} - # Helper.load_stats(true) - extend Discordrb::EventContainer - - @stats = { - totalmessages: 0, - totalmessageedits: 0, - totalmessagedeletes: 0, - totaljoinevents: 0, - totalleaveevents: 0, - server: { - DM: { - messages: 0, - }, - 1234567890123456 => { - messages: 0, - message_edits: 0, - message_deletes: 0, - joinevents: 0, - leaveevents: 0 - } - } - } - - def init_stats(server_id) - @stats[:server][server_id] = { - messages: 0, - message_edits: 0, - message_deletes: 0, - joinevents: 0, - leaveevents: 0 - } - end - - message do |event| - if event.channel.private? - @stats[:server][:dm][:messages] += 1 - else - init_stats(event.server.id) if @stats[:server][server_id].nil? - @stats[:server][event.server.id][:messages] += 1 - end - @stats[:totalmessages] += 1 - Helper.save_stats - end - - message_edit do |event| - if event.channel.private? - @stats[:server][:dm][:message_edits] += 1 - else - init_stats(event.server.id) if @stats[:server][server_id].nil? - @stats[:server][event.server.id][:message_edits] += 1 - end - @stats[:totalmessageedits] += 1 - end - - message_delete do |event| - if event.channel.private? - @stats[:server][:dm][:message_edits] += 1 - else - init_stats(event.server.id) if @stats[:server][server_id].nil? - @stats[:server][event.server.id][:message_deletes] += 1 - end - @stats[:totalmessagedeletes] += 1 - end - - $cbot.add_command(:stats, - code: proc { - raise NotImplementedError - }, - triggers: %w(stats statistics stat), - cath_errors: true - ) -=end + # class << self + # attr_accessor :stats + # end + # @stats = { + # totalmessages: 0, + # totalmessageedits: 0, + # totalmessagedeletes: 0, + # totaljoinevents: 0, + # totalleaveevents: 0, + # server: { + # DM: {} + # } + # } + # @stats[:server] = {} + # @stats[:server][:DM] = {} + # # Helper.load_stats(true) + # extend Discordrb::EventContainer + # + # @stats = { + # totalmessages: 0, + # totalmessageedits: 0, + # totalmessagedeletes: 0, + # totaljoinevents: 0, + # totalleaveevents: 0, + # server: { + # DM: { + # messages: 0, + # }, + # 1234567890123456 => { + # messages: 0, + # message_edits: 0, + # message_deletes: 0, + # joinevents: 0, + # leaveevents: 0 + # } + # } + # } + # + # def init_stats(server_id) + # @stats[:server][server_id] = { + # messages: 0, + # message_edits: 0, + # message_deletes: 0, + # joinevents: 0, + # leaveevents: 0 + # } + # end + # + # message do |event| + # if event.channel.private? + # @stats[:server][:dm][:messages] += 1 + # else + # init_stats(event.server.id) if @stats[:server][server_id].nil? + # @stats[:server][event.server.id][:messages] += 1 + # end + # @stats[:totalmessages] += 1 + # Helper.save_stats + # end + # + # message_edit do |event| + # if event.channel.private? + # @stats[:server][:dm][:message_edits] += 1 + # else + # init_stats(event.server.id) if @stats[:server][server_id].nil? + # @stats[:server][event.server.id][:message_edits] += 1 + # end + # @stats[:totalmessageedits] += 1 + # end + # + # message_delete do |event| + # if event.channel.private? + # @stats[:server][:dm][:message_edits] += 1 + # else + # init_stats(event.server.id) if @stats[:server][server_id].nil? + # @stats[:server][event.server.id][:message_deletes] += 1 + # end + # @stats[:totalmessagedeletes] += 1 + # end + # + # $cbot.add_command(:stats, + # code: proc { + # raise NotImplementedError + # }, + # triggers: %w(stats statistics stat), + # cath_errors: true + # ) end -end \ No newline at end of file +end diff --git a/modules/misc/donators.rb b/modules/misc/donators.rb index 2ae04b5..7361a99 100644 --- a/modules/misc/donators.rb +++ b/modules/misc/donators.rb @@ -1,96 +1,118 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe) 2016-2020 module YuukiBot module Misc - $cbot.add_command(:donators, - code: proc { |event, args| - user = Helper.userparse(args[1]) - id = user.id rescue nil - if args[0] == 'add' - if user.nil? - event.respond("#{YuukiBot.config['emoji_error']} Not a valid user!") - next - end - donators = JSON.parse(REDIS.get('donators')) rescue [] - if donators.include?(id) - event.respond("#{YuukiBot.config['emoji_error']} User is already a donator!") - next - end - REDIS.set('donators', donators.push(id).to_json) - event.respond("#{YuukiBot.config['emoji_tickbox']} added `#{event.bot.user(id).nil? ? "Unknown User (ID: #{id})" : "#{event.bot.user(id).distinct}"}` to donators!") - elsif args[0] == 'remove' - if user.nil? - event.respond("#{YuukiBot.config['emoji_error']} Not a valid user!") - next - end - donators = JSON.parse(REDIS.get('donators')) rescue [] - unless donators.include?(id) - event.respond("#{YuukiBot.config['emoji_error']} User is not a donator!") - next - end - REDIS.set('donators', donators.delete(id).to_json) - event.respond("#{YuukiBot.config['emoji_tickbox']} removed `#{event.bot.user(id).nil? ? "Unknown User (ID: #{id})" : "#{event.bot.user(id).distinct}"}` from donators!") - else - if YuukiBot.config['show_donate_urls'] - event << "💰 Hey, making bots and hosting them isn't free. If you want this bot to stay alive, consider giving some 💵 to the devs: " - YuukiBot.config['donate_urls'].each {|url| event << "- #{url}" } - event << '__**Donators ❤️**__ (aka the best people ever)' - donators = JSON.parse(REDIS.get('donators')) rescue [] - if donators.length > 0 - donators.each {|x| - event.bot.user(x).nil? ? event << "- Unknown User (ID: `#{x}`)" : event << "- **#{event.bot.user(x).distinct}**" - } - else - event << 'None! You can be the first! :)' - end - else - event << 'Sorry, donation information has been disabled for this bot instance!' - event << 'Please contact the bot owner for more information.' - end - end - }, - owners_only: true, - failcode: proc { |event, _| - if YuukiBot.config['show_donate_urls'] - event << "💰 Hey, making bots and hosting them isn't free. If you want this bot to stay alive, consider giving some 💵 to the devs: " - YuukiBot.config['donate_urls'].each {|url| event << "- #{url}" } - event << '__**Donators ❤️*__ (aka the best people ever)' - donators = JSON.parse(REDIS.get('donators')) rescue [] - if donators.length > 0 - donators.each {|x| - event.bot.user(x).nil? ? event << "- Unknown User (ID: `#{x}`)" : event << "- **#{event.bot.user(x).distinct}**" - } - else - event << 'None! You can be the first! :)' - end - else - event << 'Sorry, donation information has been disabled for this bot instance!' - event << 'Please contact the bot owner for more information.' - end - } - ) + code: proc { |event, args| + user = Helper.userparse(args[1]) + id = begin + user.id + rescue StandardError + nil + end + if args[0] == 'add' + if user.nil? + event.respond("#{YuukiBot.config['emoji_error']} Not a valid user!") + next + end + donators = begin + JSON.parse(REDIS.get('donators')) + rescue StandardError + [] + end + if donators.include?(id) + event.respond("#{YuukiBot.config['emoji_error']} User is already a donator!") + next + end + REDIS.set('donators', donators.push(id).to_json) + event.respond("#{YuukiBot.config['emoji_tickbox']} added `#{event.bot.user(id).nil? ? "Unknown User (ID: #{id})" : event.bot.user(id).distinct.to_s}` to donators!") + elsif args[0] == 'remove' + if user.nil? + event.respond("#{YuukiBot.config['emoji_error']} Not a valid user!") + next + end + donators = begin + JSON.parse(REDIS.get('donators')) + rescue StandardError + [] + end + unless donators.include?(id) + event.respond("#{YuukiBot.config['emoji_error']} User is not a donator!") + next + end + REDIS.set('donators', donators.delete(id).to_json) + event.respond("#{YuukiBot.config['emoji_tickbox']} removed `#{event.bot.user(id).nil? ? "Unknown User (ID: #{id})" : event.bot.user(id).distinct.to_s}` from donators!") + else + if YuukiBot.config['show_donate_urls'] + event << "💰 Hey, making bots and hosting them isn't free. If you want this bot to stay alive, consider giving some 💵 to the devs: " + YuukiBot.config['donate_urls'].each { |url| event << "- #{url}" } + event << '__**Donators ❤️**__ (aka the best people ever)' + donators = begin + JSON.parse(REDIS.get('donators')) + rescue StandardError + [] + end + if !donators.empty? + donators.each do |x| + event.bot.user(x).nil? ? event << "- Unknown User (ID: `#{x}`)" : event << "- **#{event.bot.user(x).distinct}**" + end + else + event << 'None! You can be the first! :)' + end + else + event << 'Sorry, donation information has been disabled for this bot instance!' + event << 'Please contact the bot owner for more information.' + end + end + }, + owners_only: true, + failcode: proc { |event, _| + if YuukiBot.config['show_donate_urls'] + event << "💰 Hey, making bots and hosting them isn't free. If you want this bot to stay alive, consider giving some 💵 to the devs: " + YuukiBot.config['donate_urls'].each { |url| event << "- #{url}" } + event << '__**Donators ❤️*__ (aka the best people ever)' + donators = begin + JSON.parse(REDIS.get('donators')) + rescue StandardError + [] + end + if !donators.empty? + donators.each do |x| + event.bot.user(x).nil? ? event << "- Unknown User (ID: `#{x}`)" : event << "- **#{event.bot.user(x).distinct}**" + end + else + event << 'None! You can be the first! :)' + end + else + event << 'Sorry, donation information has been disabled for this bot instance!' + event << 'Please contact the bot owner for more information.' + end + }) $cbot.add_command(:donate, - code: proc {|event,args| - if YuukiBot.config['show_donate_urls'] - event << "💰 Hey, making bots and hosting them isn't free. If you want this bot to stay alive, consider giving some 💵 to the devs: " - YuukiBot.config['donate_urls'].each {|url| event << "- #{url}" } - event << '__**Donators :heart:**__ (aka the best people ever)' - donators = JSON.parse(REDIS.get('donators')) rescue [] - if donators.length > 0 - donators.each {|x| - event.bot.user(x).nil? ? event << "- Unknown User (ID: `#{x}`)" : event << "- **#{event.bot.user(x).distinct}**" - } - else - event << 'None! You can be the first! :)' - end - else - event << 'Sorry, donation information has been disabled for this bot instance!' - event << 'Please contact the bot owner for more information.' - end - }, - triggers: ['donate', 'donateinfo', 'how do i donate', 'how do i donate?', 'how do I donate', 'how do I donate?', 'doante', 'donut'] - ) - + code: proc { |event, _args| + if YuukiBot.config['show_donate_urls'] + event << "💰 Hey, making bots and hosting them isn't free. If you want this bot to stay alive, consider giving some 💵 to the devs: " + YuukiBot.config['donate_urls'].each { |url| event << "- #{url}" } + event << '__**Donators :heart:**__ (aka the best people ever)' + donators = begin + JSON.parse(REDIS.get('donators')) + rescue StandardError + [] + end + if !donators.empty? + donators.each do |x| + event.bot.user(x).nil? ? event << "- Unknown User (ID: `#{x}`)" : event << "- **#{event.bot.user(x).distinct}**" + end + else + event << 'None! You can be the first! :)' + end + else + event << 'Sorry, donation information has been disabled for this bot instance!' + event << 'Please contact the bot owner for more information.' + end + }, + triggers: ['donate', 'donateinfo', 'how do i donate', 'how do i donate?', 'how do I donate', 'how do I donate?', 'doante', 'donut']) end end diff --git a/modules/misc/helpabout.rb b/modules/misc/helpabout.rb index 008b0d5..ccd6dea 100644 --- a/modules/misc/helpabout.rb +++ b/modules/misc/helpabout.rb @@ -1,15 +1,18 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe) 2016-2020 module YuukiBot module Misc - $cbot.add_command(:help, - code: proc {|event, _| - event << (YuukiBot.config['show_help'] ? "Follow this link for basic help: ** 🔗 #{YuukiBot.config['help_url']}**" : 'Unfortunately, no command help can be shown. Please contact the bot owner.') - event << "\n You can also join our support server for realtime help: ** 🔗 <#{YuukiBot.config['support_server']}>**" if YuukiBot.config['show_support'] - event << "\n Or if you're looking to invite me to your server, you can do it here: ** 🔗 #{YuukiBot.config['invite_url'] == "nil" ? event.bot.invite_url : "<" + YuukiBot.config['invite_url'] + ">"}**" if YuukiBot.config['show_invite'] - }, - triggers: %w(help support commands invite) - ) - + code: proc { |event, _| + event << (YuukiBot.config['show_help'] ? "Follow this link for basic help: ** 🔗 #{YuukiBot.config['help_url']}**" : 'Unfortunately, no command help can be shown. Please contact the bot owner.') + if YuukiBot.config['show_support'] + event << "\n You can also join our support server for realtime help: ** 🔗 <#{YuukiBot.config['support_server']}>**" + end + if YuukiBot.config['show_invite'] + event << "\n Or if you're looking to invite me to your server, you can do it here: ** 🔗 #{YuukiBot.config['invite_url'] == 'nil' ? event.bot.invite_url : '<' + YuukiBot.config['invite_url'] + '>'}**" + end + }, + triggers: %w[help support commands invite]) end end diff --git a/modules/misc/textgen.rb b/modules/misc/textgen.rb index 4e68921..33bf594 100644 --- a/modules/misc/textgen.rb +++ b/modules/misc/textgen.rb @@ -1,13 +1,13 @@ +# frozen_string_literal: true + module YuukiBot module Textgen def self.generate_string(template, parts, variables = nil) # Choose random template template_base = template.sample # Parse variables - unless variables.nil? - variables.each do |variable| - template_base = template_base.gsub("{#{variable[0]}}", (variable[1]).to_s) - end + variables&.each do |variable| + template_base = template_base.gsub("{#{variable[0]}}", (variable[1]).to_s) end # Parse parts parts.each do |part| @@ -17,6 +17,7 @@ def self.generate_string(template, parts, variables = nil) match = Regexp.new(dynamic_regex).match(template_base) # Check for match break if match.nil? + # Okay, we can continue. Let's get a random part. part_to_replace = part[1].sample template_base = template_base.sub(dynamic_regex, part_to_replace.to_s) diff --git a/modules/mod/clear.rb b/modules/mod/clear.rb index f33336a..c0a07bd 100644 --- a/modules/mod/clear.rb +++ b/modules/mod/clear.rb @@ -1,110 +1,109 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe) 2016-2020 module YuukiBot module Mod - $cbot.add_command(:clear, - code: proc { |event, args| - unless /\A\d+\z/ =~ args[0] - event.respond("`#{args[0]}` is not a valid number!") - break - end - original_num = args[0].to_i - clearnum = original_num + 1 + code: proc { |event, args| + unless /\A\d+\z/ =~ args[0] + event.respond("`#{args[0]}` is not a valid number!") + break + end + original_num = args[0].to_i + clearnum = original_num + 1 - if clearnum >= 100 - message = "#{YuukiBot.config['emoji_warning']} You are attempting to clear more than 100 messages.\n" - message << "To avoid rate limiting, the clearing will be done 99 messages at a time, so it might take a while.\n" - message << 'This message will vanish in 5 seconds and the clearing will begin, please wait..' - event.respond(message) - sleep(5) - elsif clearnum > 1000 - message = "The maximum number of messages I can clear is 1000!" - event.respond(message) - break - end + if clearnum >= 100 + message = "#{YuukiBot.config['emoji_warning']} You are attempting to clear more than 100 messages.\n" + message << "To avoid rate limiting, the clearing will be done 99 messages at a time, so it might take a while.\n" + message << 'This message will vanish in 5 seconds and the clearing will begin, please wait..' + event.respond(message) + sleep(5) + elsif clearnum > 1000 + message = 'The maximum number of messages I can clear is 1000!' + event.respond(message) + break + end - begin - while clearnum > 0 - if clearnum >= 99 - ids = Array.new - event.channel.history(99).each { |x| ids.push(x.id) } - Discordrb::API::Channel.bulk_delete_messages(event.bot.token, event.channel.id, ids) - clearnum -= 99 - sleep(4) - else - ids = Array.new - event.channel.history(clearnum).each { |x| ids.push(x.id) } - Discordrb::API::Channel.bulk_delete_messages(event.bot.token, event.channel.id, ids) - clearnum = 0 - end - end - event.respond("#{YuukiBot.config['emoji_clear']} Cleared #{original_num} messages!\nResponsible Moderator: #{event.user.mention}\n(Messages older than 2 weeks will not have been deleted. Please use `forceclear` in those cases.)") - rescue Discordrb::Errors::NoPermission - event.respond("#{YuukiBot.config['emoji_success']} Message delete failed!\nCheck the permissions?") - break - end - nil - }, - triggers: ['clear', 'clean'], - server_only: true, - required_permissions: [:manage_messages], - owner_override: false, - max_args: 1 - ) + begin + while clearnum > 0 + if clearnum >= 99 + ids = [] + event.channel.history(99).each { |x| ids.push(x.id) } + Discordrb::API::Channel.bulk_delete_messages(event.bot.token, event.channel.id, ids) + clearnum -= 99 + sleep(4) + else + ids = [] + event.channel.history(clearnum).each { |x| ids.push(x.id) } + Discordrb::API::Channel.bulk_delete_messages(event.bot.token, event.channel.id, ids) + clearnum = 0 + end + end + event.respond("#{YuukiBot.config['emoji_clear']} Cleared #{original_num} messages!\nResponsible Moderator: #{event.user.mention}\n(Messages older than 2 weeks will not have been deleted. Please use `forceclear` in those cases.)") + rescue Discordrb::Errors::NoPermission + event.respond("#{YuukiBot.config['emoji_success']} Message delete failed!\nCheck the permissions?") + break + end + nil + }, + triggers: %w[clear clean], + server_only: true, + required_permissions: [:manage_messages], + owner_override: false, + max_args: 1) $cbot.add_command(:forceclear, - code: proc { |event, args| - unless /\A\d+\z/ =~ args[0] - event.respond("`#{args[0]}` is not a valid number!") - break - end - original_num = args[0].to_i - clearnum = original_num + 1 + code: proc { |event, args| + unless /\A\d+\z/ =~ args[0] + event.respond("`#{args[0]}` is not a valid number!") + break + end + original_num = args[0].to_i + clearnum = original_num + 1 - if clearnum > 20 - message = "#{YuukiBot.config['emoji_warning']} You are attempting a force clear on a large number of messages.\n" - message << 'Force clears are much slower than ordinary clears, but can delete messages older than 2 weeks.' - message << 'This message will vanish in 5 seconds and the clearing will begin, please wait..' - event.respond(message) - sleep(5) - elsif clearnum > 1000 - message = "I can only clear a maximum of 1000 messages!" - event.respond(message) - break - end + if clearnum > 20 + message = "#{YuukiBot.config['emoji_warning']} You are attempting a force clear on a large number of messages.\n" + message << 'Force clears are much slower than ordinary clears, but can delete messages older than 2 weeks.' + message << 'This message will vanish in 5 seconds and the clearing will begin, please wait..' + event.respond(message) + sleep(5) + elsif clearnum > 1000 + message = 'I can only clear a maximum of 1000 messages!' + event.respond(message) + break + end - begin - while clearnum > 0 - if clearnum >= 99 - ids = Array.new - event.channel.history(99).each { |x| x.delete } - clearnum -= 99 - sleep(4) - else - ids = Array.new - event.channel.history(clearnum).each { |x| x.delete } - clearnum = 0 - end - end - # Emoji below is a trash can icon thingy. - event.respond("#{YuukiBot.config['emoji_clear']} Cleared #{original_num} messages!") + begin + while clearnum > 0 + if clearnum >= 99 + ids = [] + event.channel.history(99).each(&:delete) + clearnum -= 99 + sleep(4) + else + ids = [] + event.channel.history(clearnum).each(&:delete) + clearnum = 0 + end + end + # Emoji below is a trash can icon thingy. + event.respond("#{YuukiBot.config['emoji_clear']} Cleared #{original_num} messages!") - # On second thought, that's annoying. + # On second thought, that's annoying. - #~ sleep(3) - #~ message.delete - rescue Discordrb::Errors::NoPermission - event.respond("#{YuukiBot.config['emoji_success']} Message delete failed!\nCheck the permissions?") - break - end - nil - }, - triggers: ['clear', 'clean'], - server_only: true, - required_permissions: [:manage_messages], - owner_override: false, - max_args: 1 - ) + # ~ sleep(3) + # ~ message.delete + rescue Discordrb::Errors::NoPermission + event.respond("#{YuukiBot.config['emoji_success']} Message delete failed!\nCheck the permissions?") + break + end + nil + }, + triggers: %w[clear clean], + server_only: true, + required_permissions: [:manage_messages], + owner_override: false, + max_args: 1) end end diff --git a/modules/mod/kickban.rb b/modules/mod/kickban.rb index c5062c6..e87a1c4 100644 --- a/modules/mod/kickban.rb +++ b/modules/mod/kickban.rb @@ -1,73 +1,72 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe) 2016-2020 module YuukiBot module Mod - $cbot.add_command(:kick, - code: proc { |event, args| - if !args.empty? - begin - member = event.bot.parse_mention(args[0]) - rescue - event << "#{YuukiBot.config['emoji_error']} Failed to parse user \"#{args[0]}\"\nDid you mention a user?" - break - end - message = "You have been kicked from the server **#{event.server.name}** " - message << "by #{event.message.author.mention} | **#{event.message.author.display_name}**\n" - message << "They gave the following reason: ``#{args.drop(1).join(' ')}``" - begin - member.pm(message) - rescue Discordrb::Errors::NoPermission - event << "#{YuukiBot.config['emoji_warning']} Failed to DM user about kick reason. Kicking anyway..." - end - begin - event.server.kick(member) - rescue Discordrb::Errors::NoPermission - event << "#{YuukiBot.config['emoji_error']} I don't have permission to kick that user!\nCancelling Kick..." - next - end - event << " #{YuukiBot.config['emoji_success']} #{member.name} has been ejected." - else - event << "#{YuukiBot.config['emoji_error']} Invalid argument. Please mention a valid user." - end - }, - required_permissions: [:kick_members], - owner_override: false, - server_only: true - ) + code: proc { |event, args| + if !args.empty? + begin + member = event.bot.parse_mention(args[0]) + rescue StandardError + event << "#{YuukiBot.config['emoji_error']} Failed to parse user \"#{args[0]}\"\nDid you mention a user?" + break + end + message = "You have been kicked from the server **#{event.server.name}** " + message << "by #{event.message.author.mention} | **#{event.message.author.display_name}**\n" + message << "They gave the following reason: ``#{args.drop(1).join(' ')}``" + begin + member.pm(message) + rescue Discordrb::Errors::NoPermission + event << "#{YuukiBot.config['emoji_warning']} Failed to DM user about kick reason. Kicking anyway..." + end + begin + event.server.kick(member) + rescue Discordrb::Errors::NoPermission + event << "#{YuukiBot.config['emoji_error']} I don't have permission to kick that user!\nCancelling Kick..." + next + end + event << " #{YuukiBot.config['emoji_success']} #{member.name} has been ejected." + else + event << "#{YuukiBot.config['emoji_error']} Invalid argument. Please mention a valid user." + end + }, + required_permissions: [:kick_members], + owner_override: false, + server_only: true) $cbot.add_command(:ban, - code: proc { |event, args| - if !args.empty? - member = event.bot.parse_mention(args[0]) - if member.nil? - event << "#{YuukiBot.config['emoji_error']} Failed to parse user \"#{args[0]}\"\nDid you mention a user?" - break - end - message = "You have been **permanently banned** from the server `#{event.server.name}` " - message << "by #{event.message.author.mention} | **#{event.message.author.display_name}**\n" - message << "They gave the following reason: ``#{args.drop(1).join(' ')}``\n\n" - message << "If you wish to appeal for your ban's removal, please contact this person, or the server owner." - begin - member.pm(message) - rescue Discordrb::Errors::NoPermission - event << "#{YuukiBot.config['emoji_warning']} Failed to DM user about ban reason. Banning anyway..." - end - begin - event.server.ban(member) - rescue Discordrb::Errors::NoPermission - event << "#{YuukiBot.config['emoji_error']} I don't have permission to ban that user!\nCancelling Ban..." - next - end - event << "#{YuukiBot.config['emoji_success']} The banhammer was hit on #{member.name}!" - else - event << "#{YuukiBot.config['emoji_error']} Invalid argument. Please mention a valid user." - end - }, - triggers: %w(ban), - required_permissions: [:ban_members], - owner_override: false, - server_only: true - ) + code: proc { |event, args| + if !args.empty? + member = event.bot.parse_mention(args[0]) + if member.nil? + event << "#{YuukiBot.config['emoji_error']} Failed to parse user \"#{args[0]}\"\nDid you mention a user?" + break + end + message = "You have been **permanently banned** from the server `#{event.server.name}` " + message << "by #{event.message.author.mention} | **#{event.message.author.display_name}**\n" + message << "They gave the following reason: ``#{args.drop(1).join(' ')}``\n\n" + message << "If you wish to appeal for your ban's removal, please contact this person, or the server owner." + begin + member.pm(message) + rescue Discordrb::Errors::NoPermission + event << "#{YuukiBot.config['emoji_warning']} Failed to DM user about ban reason. Banning anyway..." + end + begin + event.server.ban(member) + rescue Discordrb::Errors::NoPermission + event << "#{YuukiBot.config['emoji_error']} I don't have permission to ban that user!\nCancelling Ban..." + next + end + event << "#{YuukiBot.config['emoji_success']} The banhammer was hit on #{member.name}!" + else + event << "#{YuukiBot.config['emoji_error']} Invalid argument. Please mention a valid user." + end + }, + triggers: %w[ban], + required_permissions: [:ban_members], + owner_override: false, + server_only: true) end end diff --git a/modules/mod/unban.rb b/modules/mod/unban.rb index d47fac7..85a6194 100644 --- a/modules/mod/unban.rb +++ b/modules/mod/unban.rb @@ -1,26 +1,25 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe) 2016-2020 module YuukiBot module Mod - $cbot.add_command(:unban, - code: proc { |event, args| - target_id = args[0] - target = event.server.bans.select { |x| x.id == target_id } - if target == [] or target.nil? - event.respond("#{YuukiBot.config['emoji_error']} Failed to find user with ID `#{target_id}!`") - break - end - begin - event.server.unban(target) - rescue Discordrb::Errors::NoPermission - event.respond("#{YuukiBot.config['emoji_error']} I don't have permission to unban #{target.name}!") - end - }, - max_args: 1, - server_only: true, - required_permissions: [:ban_members] - ) - + code: proc { |event, args| + target_id = args[0] + target = event.server.bans.select { |x| x.id == target_id } + if (target == []) || target.nil? + event.respond("#{YuukiBot.config['emoji_error']} Failed to find user with ID `#{target_id}!`") + break + end + begin + event.server.unban(target) + rescue Discordrb::Errors::NoPermission + event.respond("#{YuukiBot.config['emoji_error']} I don't have permission to unban #{target.name}!") + end + }, + max_args: 1, + server_only: true, + required_permissions: [:ban_members]) end end diff --git a/modules/owner/dm.rb b/modules/owner/dm.rb index 3282768..2de6fdd 100644 --- a/modules/owner/dm.rb +++ b/modules/owner/dm.rb @@ -1,14 +1,16 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe) 2019-2020 module YuukiBot module Owner - $cbot.bot.message do |event| next unless event.channel.private? next if event.user.bot_account next if $cbot.is_owner?(event.user) + target_id = YuukiBot.config['dm_channel'].nil? ? event.bot.user(YuukiBot.config['master_owner']).pm.id : YuukiBot.config['dm_channel'] event.bot.channel(target_id).send_embed do |embed| - embed.url = "https://discordapp.com" + embed.url = 'https://discordapp.com' embed.description = event.message.content embed.timestamp = Time.now embed.author = Discordrb::Webhooks::EmbedAuthor.new(name: "DM from: #{event.user.distinct}", icon_url: Helper.avatar_url(event.user)) @@ -17,31 +19,29 @@ module Owner end $cbot.add_command(:reply, - code: proc { |event, args| - channel = event.bot.channel(args[0]) - reply = args.drop(1).join(' ') - - if channel.nil? - event.respond("#{YuukiBot.config['emoji_error']} Not a valid channel! Has the user started a conversation? ") - next - end - unless channel.private? - event.respond("#{YuukiBot.config['emoji_error']} Channel is not a DM! ") - next - end + code: proc { |event, args| + channel = event.bot.channel(args[0]) + reply = args.drop(1).join(' ') - channel.send_embed do |embed| - # embed.colour = 0xd9ea6e - embed.url = "https://discordapp.com" - embed.description = reply - embed.timestamp = Time.now - embed.author = Discordrb::Webhooks::EmbedAuthor.new(name: "Developer response from: #{event.user.distinct}", icon_url: Helper.avatar_url(event.user)) - embed.footer = Discordrb::Webhooks::EmbedFooter.new(text: "Replies to this DM will be sent to developers.") - end - event.respond "#{YuukiBot.config['emoji_success']} Your message has been sent!" - }, - owners_only: true - ) + if channel.nil? + event.respond("#{YuukiBot.config['emoji_error']} Not a valid channel! Has the user started a conversation? ") + next + end + unless channel.private? + event.respond("#{YuukiBot.config['emoji_error']} Channel is not a DM! ") + next + end + channel.send_embed do |embed| + # embed.colour = 0xd9ea6e + embed.url = 'https://discordapp.com' + embed.description = reply + embed.timestamp = Time.now + embed.author = Discordrb::Webhooks::EmbedAuthor.new(name: "Developer response from: #{event.user.distinct}", icon_url: Helper.avatar_url(event.user)) + embed.footer = Discordrb::Webhooks::EmbedFooter.new(text: 'Replies to this DM will be sent to developers.') + end + event.respond "#{YuukiBot.config['emoji_success']} Your message has been sent!" + }, + owners_only: true) end -end \ No newline at end of file +end diff --git a/modules/owner/eval.rb b/modules/owner/eval.rb index 74bbb7e..bb1f828 100644 --- a/modules/owner/eval.rb +++ b/modules/owner/eval.rb @@ -1,68 +1,65 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe) 2016-2020 module YuukiBot module Owner - $cbot.add_command(:oldeval, - code: proc { |event, args| - event.respond(eval args.join(' ')) - }, - triggers: ['raweval ', 'oldeval'], - owners_only: true - ) + code: proc { |event, args| + event.respond(eval(args.join(' '))) + }, + triggers: ['raweval ', 'oldeval'], + owners_only: true) $cbot.add_command(:eval, - code: proc { |event, args| - begin - msg = event.respond "#{YuukiBot.config['emoji_loading']} Evaluating..." - init_time = Time.now - result = eval args.join(' ') - result = result.to_s - if result.nil? || result == '' || result == ' ' || result == "\n" - msg.edit "#{YuukiBot.config['emoji_tickbox']} Done! (No output)\nCommand took #{(Time.now - init_time)} seconds to execute!" - next - end - str = '' - if result.length >= 1984 - str << "#{YuukiBot.config['emoji_warning']} Your output exceeded the character limit! (`#{result.length - 1984}`/`1984`)" - str << "You can view the result here: https://paste.erisa.moe/raw/#{$uploader.upload_raw(result)}\nCommand took #{(Time.now - init_time)} seconds to execute!" - else - str << "Output: ```\n#{result}```Command took #{(Time.now - init_time)} seconds to execute!" - end - msg.edit(str) - rescue Exception => e - msg.edit("#{YuukiBot.config['emoji_error']} An error has occured!! ```ruby\n#{e}```\nCommand took #{(Time.now - init_time)} seconds to execute!") - end - }, - triggers: ['eval2 ', 'eval'], - owners_only: true, - description: 'Evaluate a Ruby command. Owner only.', - ) + code: proc { |event, args| + begin + msg = event.respond "#{YuukiBot.config['emoji_loading']} Evaluating..." + init_time = Time.now + result = eval args.join(' ') + result = result.to_s + if result.nil? || result == '' || result == ' ' || result == "\n" + msg.edit "#{YuukiBot.config['emoji_tickbox']} Done! (No output)\nCommand took #{(Time.now - init_time)} seconds to execute!" + next + end + str = '' + if result.length >= 1984 + str << "#{YuukiBot.config['emoji_warning']} Your output exceeded the character limit! (`#{result.length - 1984}`/`1984`)" + str << "You can view the result here: https://paste.erisa.moe/raw/#{$uploader.upload_raw(result)}\nCommand took #{(Time.now - init_time)} seconds to execute!" + else + str << "Output: ```\n#{result}```Command took #{(Time.now - init_time)} seconds to execute!" + end + msg.edit(str) + rescue Exception => e + msg.edit("#{YuukiBot.config['emoji_error']} An error has occured!! ```ruby\n#{e}```\nCommand took #{(Time.now - init_time)} seconds to execute!") + end + }, + triggers: ['eval2 ', 'eval'], + owners_only: true, + description: 'Evaluate a Ruby command. Owner only.') $cbot.add_command(:bash, - code: proc { |event, args| - init_time = Time.now - msg = event.respond "#{YuukiBot.config['emoji_loading']} Evaluating..." - # Capture all output, including STDERR. - result = `#{"#{args.join(' ')} 2>&1"} ` - result = result.to_s - if result.nil? || result == '' || result == ' ' || result == "\n" - msg.edit "#{YuukiBot.config['emoji_tickbox']} Done! (No output)\nCommand took #{(Time.now - init_time)} seconds to execute!" - next - end - str = '' - if result.length >= 1984 - str << "#{YuukiBot.config['emoji_warning']} Your output exceeded the character limit! (`#{result.length - 1984}`/`1984`)" - str << "You can view the result here: https://paste.erisa.moe/raw/#{$uploader.upload_raw(result)}\nCommand took #{(Time.now - init_time)} seconds to execute!" - else - str << "Output: ```\n#{result}```Command took #{(Time.now - init_time)} seconds to execute!" - end - msg.edit(str) - }, - triggers: ['bash ', 'sh ', 'shell ', 'run '], - owners_only: true, - description: 'Evaluate a Bash command. Owner only. Use with care.' - ) - + code: proc { |event, args| + init_time = Time.now + msg = event.respond "#{YuukiBot.config['emoji_loading']} Evaluating..." + # Capture all output, including STDERR. + result = `#{"#{args.join(' ')} 2>&1"} ` + result = result.to_s + if result.nil? || result == '' || result == ' ' || result == "\n" + msg.edit "#{YuukiBot.config['emoji_tickbox']} Done! (No output)\nCommand took #{(Time.now - init_time)} seconds to execute!" + next + end + str = '' + if result.length >= 1984 + str << "#{YuukiBot.config['emoji_warning']} Your output exceeded the character limit! (`#{result.length - 1984}`/`1984`)" + str << "You can view the result here: https://paste.erisa.moe/raw/#{$uploader.upload_raw(result)}\nCommand took #{(Time.now - init_time)} seconds to execute!" + else + str << "Output: ```\n#{result}```Command took #{(Time.now - init_time)} seconds to execute!" + end + msg.edit(str) + }, + triggers: ['bash ', 'sh ', 'shell ', 'run '], + owners_only: true, + description: 'Evaluate a Bash command. Owner only. Use with care.') end end diff --git a/modules/owner/ignore.rb b/modules/owner/ignore.rb index e1d101a..f0f9570 100644 --- a/modules/owner/ignore.rb +++ b/modules/owner/ignore.rb @@ -1,54 +1,60 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe) 2016-2020 module YuukiBot module Owner - $cbot.add_command(:ignore, - code: proc { |event, args| - if args == [] - event.respond("#{YuukiBot.config['emoji_error']} Mention a valid user!") - next - end - mention = args[0] - user = Helper.userparse(args[0]) + code: proc { |event, args| + if args == [] + event.respond("#{YuukiBot.config['emoji_error']} Mention a valid user!") + next + end + mention = args[0] + user = Helper.userparse(args[0]) - ignores = JSON.parse(REDIS.get('ignores')) rescue [] - if user.nil? - event.respond("#{YuukiBot.config['emoji_error']} Not a valid user!") - elsif $cbot.is_owner?(user) - event.respond("#{YuukiBot.config['emoji_error']} You can't ignore owners!") - elsif ignores.include?(user.id) - event.respond("#{YuukiBot.config['emoji_error']} User is already ignored!") - else - REDIS.set('ignores', ignores.push(user.id).to_json) - event.bot.ignore_user(user) - event.respond("#{YuukiBot.config['emoji_tickbox']} `#{user.distinct}` is now being ignored!") - end - }, - triggers: %w(ignore), - owners_only: true - ) + ignores = begin + JSON.parse(REDIS.get('ignores')) + rescue StandardError + [] + end + if user.nil? + event.respond("#{YuukiBot.config['emoji_error']} Not a valid user!") + elsif $cbot.is_owner?(user) + event.respond("#{YuukiBot.config['emoji_error']} You can't ignore owners!") + elsif ignores.include?(user.id) + event.respond("#{YuukiBot.config['emoji_error']} User is already ignored!") + else + REDIS.set('ignores', ignores.push(user.id).to_json) + event.bot.ignore_user(user) + event.respond("#{YuukiBot.config['emoji_tickbox']} `#{user.distinct}` is now being ignored!") + end + }, + triggers: %w[ignore], + owners_only: true) $cbot.add_command(:unignore, - code: proc { |event, args| - if args == [] - event.respond("#{YuukiBot.config['emoji_error']} Mention a valid user!") - next - end - user = Helper.userparse(args[0]) - ignores = JSON.parse(REDIS.get('ignores')) rescue [] - - if user.nil? - event.respond("#{YuukiBot.config['emoji_error']} Not a valid user!") - elsif !ignores.include?(user.id) - event.respond("#{YuukiBot.config['emoji_error']} User isn't ignored!") - else - event.bot.unignore_user(user) - REDIS.set('ignores', (ignores - [user.id]).to_json) - event.respond("#{YuukiBot.config['emoji_tickbox']} `#{user.distinct}` has been removed from the ignore list!") - end - }, - owners_only: true - ) + code: proc { |event, args| + if args == [] + event.respond("#{YuukiBot.config['emoji_error']} Mention a valid user!") + next + end + user = Helper.userparse(args[0]) + ignores = begin + JSON.parse(REDIS.get('ignores')) + rescue StandardError + [] + end + if user.nil? + event.respond("#{YuukiBot.config['emoji_error']} Not a valid user!") + elsif !ignores.include?(user.id) + event.respond("#{YuukiBot.config['emoji_error']} User isn't ignored!") + else + event.bot.unignore_user(user) + REDIS.set('ignores', (ignores - [user.id]).to_json) + event.respond("#{YuukiBot.config['emoji_tickbox']} `#{user.distinct}` has been removed from the ignore list!") + end + }, + owners_only: true) end end diff --git a/modules/owner/owners.rb b/modules/owner/owners.rb index 67a7ab8..b6bc8e1 100644 --- a/modules/owner/owners.rb +++ b/modules/owner/owners.rb @@ -1,46 +1,46 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe) 2016-2020 module YuukiBot - module Owner - - $cbot.add_command(:owners, - code: proc { |event, _| - event << 'This bot instance is managed/owned by the following users. Please contact them for any issues.' - event << "- **#{event.bot.user(YuukiBot.config['master_owner']).distinct}** [**MAIN**]" unless YuukiBot.config['master_owner'].nil? - Helper.owners.each {|x| - event.bot.user(x).nil? ? event << "- Unknown User (ID: `#{x}`)" : event << "- **#{event.bot.user(x).distinct}**" - } - }, - triggers: ['owners'] - ) - - $cbot.add_command(:botowners, - code: proc { |event, args| - user = Helper.userparse(args[1]) - if user.nil? - event.respond("#{YuukiBot.config['emoji_error']} Not a valid user!") - else - case args[0] - when 'add' - if $cbot.is_owner?(user.id) - event.respond("#{YuukiBot.config['emoji_error']} User is already an owner!") - else - REDIS.set('owners', Helper.owners.push(user.id).to_json) - event.respond("#{YuukiBot.config['emoji_tickbox']} added `#{Helper.userid_to_string(user.id)}` to bot owners!") - end - when 'remove' - if YuukiBot.config['master_owner'] == user.id - event.respond("#{YuukiBot.config['emoji_error']} You can't remove the main owner!") - elsif owners.include?(user.id) - REDIS.set('owners', Helper.owners.delete(user.id).to_json) - event.respond("#{YuukiBot.config['emoji_tickbox']} removed `#{Helper.userid_to_string(user.id)}` from bot owners!") - else - event.respond("#{YuukiBot.config['emoji_error']} User is not an owner!") - end - end - end - }, - owners_only: true - ) + module Owner + $cbot.add_command(:owners, + code: proc { |event, _| + event << 'This bot instance is managed/owned by the following users. Please contact them for any issues.' + unless YuukiBot.config['master_owner'].nil? + event << "- **#{event.bot.user(YuukiBot.config['master_owner']).distinct}** [**MAIN**]" + end + Helper.owners.each do |x| + event.bot.user(x).nil? ? event << "- Unknown User (ID: `#{x}`)" : event << "- **#{event.bot.user(x).distinct}**" + end + }, + triggers: ['owners']) - end + $cbot.add_command(:botowners, + code: proc { |event, args| + user = Helper.userparse(args[1]) + if user.nil? + event.respond("#{YuukiBot.config['emoji_error']} Not a valid user!") + else + case args[0] + when 'add' + if $cbot.is_owner?(user.id) + event.respond("#{YuukiBot.config['emoji_error']} User is already an owner!") + else + REDIS.set('owners', Helper.owners.push(user.id).to_json) + event.respond("#{YuukiBot.config['emoji_tickbox']} added `#{Helper.userid_to_string(user.id)}` to bot owners!") + end + when 'remove' + if YuukiBot.config['master_owner'] == user.id + event.respond("#{YuukiBot.config['emoji_error']} You can't remove the main owner!") + elsif owners.include?(user.id) + REDIS.set('owners', Helper.owners.delete(user.id).to_json) + event.respond("#{YuukiBot.config['emoji_tickbox']} removed `#{Helper.userid_to_string(user.id)}` from bot owners!") + else + event.respond("#{YuukiBot.config['emoji_error']} User is not an owner!") + end + end + end + }, + owners_only: true) + end end diff --git a/modules/owner/profile.rb b/modules/owner/profile.rb index a74a89d..f7c9766 100644 --- a/modules/owner/profile.rb +++ b/modules/owner/profile.rb @@ -1,80 +1,79 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe) 2016-2020 module YuukiBot module Owner - $cbot.add_command(:set, - code: proc {|event,args| - if args.length.zero? - event.respond("#{YuukiBot.config['emoji_error']} Enter a valid subcommand!\nValid commands: `avatar`, `game`, `username`, `status`, `nickname`.") - else - case args[0].downcase - when 'nick', 'nickname' - begin - event.bot.profile.on(event.server).nickname = args.drop(1).join(' ') - event.respond("#{YuukiBot.config['emoji_tickbox']} Nickname changed to `#{args.drop(1).join(' ')}`") - rescue Discordrb::Errors::NoPermission - event.respond("#{YuukiBot.config['emoji_error']} I don't have permission to change my nickname!") - end - when 'avatar', 'avy' - url = args.drop(1).join(' ') - event.bot.profile.avatar = File.open(Helper.download_file(url, 'tmp')) - when 'game', 'playing' - event.bot.game = args.drop(1).join(' ') - event.respond("#{YuukiBot.config['emoji_tickbox']} Game set to `#{args.drop(1).join(' ')}`!") - when 'username', 'name' - username = args.drop(1).join(' ') - event.bot.profile.name = begin - username - rescue Error => e - event.respond("#{YuukiBot.config['emoji_error']} An error has occured!\n```ruby\n#{e}```") - end - event.respond("#{YuukiBot.config['emoji_tickbox']} Username _should_ be updated!") - when 'status', 'indicator', 'state' - state = args[1] - case state.downcase - when 'idle', 'away', 'afk' then event.bot.idle - when 'dnd' - state = 'Do Not Disturb' - when 'online' then event.bot.online - when 'invisible', 'offline' then event.bot.invisible - else - event.respond('Enter a valid argument!') - next - end - event.respond("#{YuukiBot.config['emoji_tickbox']} Status set to **#{state == 'Do Not Disturb' ? state : state.capitalize }**!") - else - event.respond("#{YuukiBot.config['emoji_error']} Enter a valid subcommand!\nValid commands: `avatar`, `game`, `username`, `status`, `nickname`.") - next - end - end - }, - triggers: %w(set config), - owners_only: true - ) - + code: proc { |event, args| + if args.length.zero? + event.respond("#{YuukiBot.config['emoji_error']} Enter a valid subcommand!\nValid commands: `avatar`, `game`, `username`, `status`, `nickname`.") + else + case args[0].downcase + when 'nick', 'nickname' + begin + event.bot.profile.on(event.server).nickname = args.drop(1).join(' ') + event.respond("#{YuukiBot.config['emoji_tickbox']} Nickname changed to `#{args.drop(1).join(' ')}`") + rescue Discordrb::Errors::NoPermission + event.respond("#{YuukiBot.config['emoji_error']} I don't have permission to change my nickname!") + end + when 'avatar', 'avy' + url = args.drop(1).join(' ') + event.bot.profile.avatar = File.open(Helper.download_file(url, 'tmp')) + when 'game', 'playing' + event.bot.game = args.drop(1).join(' ') + event.respond("#{YuukiBot.config['emoji_tickbox']} Game set to `#{args.drop(1).join(' ')}`!") + when 'username', 'name' + username = args.drop(1).join(' ') + event.bot.profile.name = begin + username + rescue Error => e + event.respond("#{YuukiBot.config['emoji_error']} An error has occured!\n```ruby\n#{e}```") + end + event.respond("#{YuukiBot.config['emoji_tickbox']} Username _should_ be updated!") + when 'status', 'indicator', 'state' + state = args[1] + case state.downcase + when 'idle', 'away', 'afk' then event.bot.idle + when 'dnd' + state = 'Do Not Disturb' + when 'online' then event.bot.online + when 'invisible', 'offline' then event.bot.invisible + else + event.respond('Enter a valid argument!') + next + end + event.respond("#{YuukiBot.config['emoji_tickbox']} Status set to **#{state == 'Do Not Disturb' ? state : state.capitalize}**!") + else + event.respond("#{YuukiBot.config['emoji_error']} Enter a valid subcommand!\nValid commands: `avatar`, `game`, `username`, `status`, `nickname`.") + next + end + end + }, + triggers: %w[set config], + owners_only: true) + $cbot.add_command(:reset, - code: proc {|event,args| - case args[0].downcase - when 'nick' || 'nickname' - begin - event.bot.profile.on(event.server).nickname = nil - event.respond("#{YuukiBot.config['emoji_tickbox']} Reset nickname!") - rescue Discordrb::Errors::NoPermission - event.respond("#{YuukiBot.config['emoji_error']} I don't have permission to change my nickname!") - end - when 'avatar' || 'avy' - event.bot.avatar = nil - event.respond "#{YuukiBot.config['emoji_success']} Reset avatar!" - when 'game' || 'playing' - event.bot.game = nil - event.respond("#{YuukiBot.config['emoji_tickbox']} Reset game!") - else - event.respond("#{YuukiBot.config['emoji_error']} Enter a valid subcommand!\nValid commands: `avatar`, `game`, `nickname`.") - next - end - }, - triggers: %w(reset), - owners_only: true - ) + code: proc { |event, args| + case args[0].downcase + when 'nick' || 'nickname' + begin + event.bot.profile.on(event.server).nickname = nil + event.respond("#{YuukiBot.config['emoji_tickbox']} Reset nickname!") + rescue Discordrb::Errors::NoPermission + event.respond("#{YuukiBot.config['emoji_error']} I don't have permission to change my nickname!") + end + when 'avatar' || 'avy' + event.bot.avatar = nil + event.respond "#{YuukiBot.config['emoji_success']} Reset avatar!" + when 'game' || 'playing' + event.bot.game = nil + event.respond("#{YuukiBot.config['emoji_tickbox']} Reset game!") + else + event.respond("#{YuukiBot.config['emoji_error']} Enter a valid subcommand!\nValid commands: `avatar`, `game`, `nickname`.") + next + end + }, + triggers: %w[reset], + owners_only: true) end end diff --git a/modules/owner/prune.rb b/modules/owner/prune.rb index 198ace2..a9877bf 100644 --- a/modules/owner/prune.rb +++ b/modules/owner/prune.rb @@ -1,73 +1,74 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe) 2016-2020 module YuukiBot module Owner - $cbot.add_command(:prune, - code: proc { |event, args| - num = 75 - count = 0 - msgs = [] - msg = event.channel.send("#{YuukiBot.config['emoji_loading']} Deleting, please wait...") - if event.bot.profile.on(event.server).permission?(:manage_messages,event.channel) - event.channel.history(num).each do |x| - if x.author.id == event.bot.profile.id && x.id != msg.id - msgs.push(x.id) - count += 1 - end + code: proc { |event, args| + num = 75 + count = 0 + msgs = [] + msg = event.channel.send("#{YuukiBot.config['emoji_loading']} Deleting, please wait...") + if event.bot.profile.on(event.server).permission?(:manage_messages, event.channel) + event.channel.history(num).each do |x| + if x.author.id == event.bot.profile.id && x.id != msg.id + msgs.push(x.id) + count += 1 + end + end + unless @count.zero? + Discordrb::API::Channel.bulk_delete_messages(event.bot.token, event.channel.id, msgs) end - Discordrb::API::Channel.bulk_delete_messages(event.bot.token, event.channel.id, msgs) unless @count.zero? - else - event.channel.history(num).each do |x| - if x.author.id == event.bot.profile.id && x.id != msg.id - x.delete - count += 1 - end - end - end - count.zero? ? msg.edit("#{YuukiBot.config['emoji_warning']} No messages found!") : msg.edit("#{YuukiBot.config['emoji_tickbox']} Pruned #{count} bot messages!") + else + event.channel.history(num).each do |x| + if x.author.id == event.bot.profile.id && x.id != msg.id + x.delete + count += 1 + end + end + end + count.zero? ? msg.edit("#{YuukiBot.config['emoji_warning']} No messages found!") : msg.edit("#{YuukiBot.config['emoji_tickbox']} Pruned #{count} bot messages!") - if args[0] == '-f' - sleep 2 - msg.delete - end - }, - triggers: %w(prune cleanup purge stfu ), - required_permissions: [:manage_messages], - owner_override: true, - max_args: 1 - ) + if args[0] == '-f' + sleep 2 + msg.delete + end + }, + triggers: %w[prune cleanup purge stfu], + required_permissions: [:manage_messages], + owner_override: true, + max_args: 1) $cbot.add_command(:pruneuser, - code: proc { |event, args| - begin - user = event.bot.parse_mention(args[0]) - num = args[1] - num = 75 if num.nil? - count = 0 - msgs = {} - event.channel.history(num).each do |x| - if x.author.id == user.id - msgs.push(x.id) - count += 1 - end - end - Discordrb::API::Channel.bulk_delete_messages(event.bot.token, event.channel.id, msgs) - event.respond("#{YuukiBot.config['emoji_tickbox']} Pruned #{count} messages by **#{user.distinct}** !") - rescue Discordrb::Errors::NoPermission - event.respond("#{YuukiBot.config['emoji_error']} I don't have permission to delete messages!") - puts 'The bot does not have the delete message permission!' - end - }, - triggers: [ - 'pruneuser', - 'cleanupuser', - 'purgeuser', - 'cleanup user', - 'purge user', - ], - required_permissions: [:manage_messages], - owner_override: true, - max_args: 1 - ) + code: proc { |event, args| + begin + user = event.bot.parse_mention(args[0]) + num = args[1] + num = 75 if num.nil? + count = 0 + msgs = {} + event.channel.history(num).each do |x| + if x.author.id == user.id + msgs.push(x.id) + count += 1 + end + end + Discordrb::API::Channel.bulk_delete_messages(event.bot.token, event.channel.id, msgs) + event.respond("#{YuukiBot.config['emoji_tickbox']} Pruned #{count} messages by **#{user.distinct}** !") + rescue Discordrb::Errors::NoPermission + event.respond("#{YuukiBot.config['emoji_error']} I don't have permission to delete messages!") + puts 'The bot does not have the delete message permission!' + end + }, + triggers: [ + 'pruneuser', + 'cleanupuser', + 'purgeuser', + 'cleanup user', + 'purge user' + ], + required_permissions: [:manage_messages], + owner_override: true, + max_args: 1) end end diff --git a/modules/owner/shutdown.rb b/modules/owner/shutdown.rb index a868c0d..93b78f2 100644 --- a/modules/owner/shutdown.rb +++ b/modules/owner/shutdown.rb @@ -1,29 +1,27 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe) 2016-2020 module YuukiBot module Owner - $cbot.add_command(:shutdown, - code: proc { |event, _| - event.bot.invisible - event.respond('Goodbye!') - Helper.quit(0) - }, - triggers: ['shutdown', 'bye', 'fuck off', 'die', 'kys', 'go away'], - owners_only: true, - description: 'Shuts down the bot. Owner only.', - catch_errors: false - ) + code: proc { |event, _| + event.bot.invisible + event.respond('Goodbye!') + Helper.quit(0) + }, + triggers: ['shutdown', 'bye', 'fuck off', 'die', 'kys', 'go away'], + owners_only: true, + description: 'Shuts down the bot. Owner only.', + catch_errors: false) $cbot.add_command(:reboot, - code: proc { |event, _| - event.respond 'Rebooting...!' - Helper.quit(1) - }, - triggers: ['reboot', 'restart', 'reload', 'gtfo', 'machine 🅱roke', '🅱achine 🅱roke'], - owners_only: true, - description: 'Shuts down the bot. Owner only.', - catch_errors: false - ) - + code: proc { |event, _| + event.respond 'Rebooting...!' + Helper.quit(1) + }, + triggers: ['reboot', 'restart', 'reload', 'gtfo', 'machine 🅱roke', '🅱achine 🅱roke'], + owners_only: true, + description: 'Shuts down the bot. Owner only.', + catch_errors: false) end end diff --git a/modules/owner/upload.rb b/modules/owner/upload.rb index 18351c4..233ab7b 100644 --- a/modules/owner/upload.rb +++ b/modules/owner/upload.rb @@ -1,27 +1,25 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe) 2016-2020 module YuukiBot module Owner - $cbot.add_command(:upload, - code: proc { |event, args| - filename = args.join(' ') - event.channel.send_file File.new([filename].sample) - }, - triggers: %w(upload sendfile), - owners_only: true - ) + code: proc { |event, args| + filename = args.join(' ') + event.channel.send_file File.new([filename].sample) + }, + triggers: %w[upload sendfile], + owners_only: true) $cbot.add_command(:rehost, - code: proc { |event, args| - event.channel.start_typing - url = args.join(' ') - file = Helper.download_file(url, 'tmp') - Helper.upload_file(event.channel, file) - event.message.delete - }, - triggers: %w(rehost sendurl), - owners_only: true - ) - + code: proc { |event, args| + event.channel.start_typing + url = args.join(' ') + file = Helper.download_file(url, 'tmp') + Helper.upload_file(event.channel, file) + event.message.delete + }, + triggers: %w[rehost sendurl], + owners_only: true) end end diff --git a/modules/setup.rb b/modules/setup.rb index d9654aa..7a396f3 100644 --- a/modules/setup.rb +++ b/modules/setup.rb @@ -1,13 +1,14 @@ -module YuukiBot +# frozen_string_literal: true +module YuukiBot class << self - attr_accessor :config + attr_accessor :config end require 'yaml' # Load Config from YAML - unless File.exists?('config/config.yml') + unless File.exist?('config/config.yml') puts 'You don\'t have a valid config file!' puts 'If you want to create a config file manually, please stop this program with Ctrl+C and follow the instructions in config/README.md.' puts 'Waiting 3 seconds...' @@ -23,21 +24,21 @@ class << self print 'Please paste that string here: ' token = gets.chomp - puts "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-" + puts '-=-=-=-=-=-=-=-=-=-=-=-=-=-=-' puts 'Awesome! Now you\'ll need to head to the top of the page and fetch the Client ID, which should be a long number.' print 'And paste that here: ' appid = gets.chomp - puts "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-" + puts '-=-=-=-=-=-=-=-=-=-=-=-=-=-=-' puts 'Wew, thats the hard part out of the way. Now you get to decide some needed options for your bot!' puts 'Your bot will need at least one prefix to be used. For example if you use the prefix s!, your help command will be s!help' puts 'If your prefix is a word, please add a space after it! (For example enter \'tomoe\' for \'tomoe ping\' instead of \'tomoeping\'' print 'Enter your first prefix here: ' - prefix = gets.chomp() + prefix = gets.chomp puts "Nice prefix! Your bots help command will be: '#{prefix}help'" - puts "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-" + puts '=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-' puts 'Thats enough information to get the bot launching, but theres one more thing we need.' puts 'If you haven\'t already, go to User Settings -> Appearance, and enable Developer Mode.' puts 'Then, right click your own name and select Copy ID.' @@ -59,7 +60,7 @@ class << self puts 'All done! The bot will launch in 1 second..' sleep(1) # So the user knows what the hecc just happened. - # Lets go! + # Lets go! end @config = YAML.load_file('config/config.yml') @@ -70,7 +71,7 @@ class << self exit else if key == 'token' - puts "config.yml: Found: token: [REDACTED]" + puts 'config.yml: Found: token: [REDACTED]' else puts("config.yml: Found #{key}: #{value}") if @config['verbose'] end @@ -85,15 +86,13 @@ class << self raise 'Invalid status' end - if @config['token'].nil? - raise 'No valid token entered!' - end - - if @config['master_owner'].nil? - @config['owners'] = [@config['owners'][0]] - else - @config['owners'] = [@config['master_owner']] - end + raise 'No valid token entered!' if @config['token'].nil? + + @config['owners'] = if @config['master_owner'].nil? + [@config['owners'][0]] + else + [@config['master_owner']] + end def self.build_init # Transfer it into an init hash. @@ -110,33 +109,45 @@ def self.build_init owners: @config['owners'], typing_default: @config['typing_default'], - ready: proc {|event| + ready: proc { |event| case @config['status'] - when 'idle' || 'away' || 'afk' then event.bot.idle - when 'dnd' then event.bot.dnd - when 'online' then event.bot.online - when 'invisible' || 'offline' then event.bot.invisible - when 'stream' || 'streaming' then event.bot.stream(@config['game'], @config['twitch_url']) - else - raise 'No valid status found.' + when 'idle' || 'away' || 'afk' then event.bot.idle + when 'dnd' then event.bot.dnd + when 'online' then event.bot.online + when 'invisible' || 'offline' then event.bot.invisible + when 'stream' || 'streaming' then event.bot.stream(@config['game'], @config['twitch_url']) + else + raise 'No valid status found.' end - ignored = JSON.parse(REDIS.get('ignores')) rescue [] - ignored.each {|id| + ignored = begin + JSON.parse(REDIS.get('ignores')) + rescue StandardError + [] + end + ignored.each do |id| begin $cbot.bot.ignore_user($cbot.bot.user(id)) rescue Exception => e p e end - } + end - event.bot.game = YuukiBot.config['game'] rescue nil + event.bot.game = begin + YuukiBot.config['game'] + rescue StandardError + nil + end puts "[READY] Logged in as #{event.bot.profile.distinct} (#{event.bot.profile.id})!" puts "[READY] Connected to #{event.bot.servers.count} servers!" puts "[READY] Raw Invite URL: #{event.bot.invite_url}" puts "[READY] Redis ping: #{REDIS.ping}" - puts "[READY] Vanity Invite URL: #{@config['invite_url'] rescue event.bot.invite_url}" + puts "[READY] Vanity Invite URL: #{begin + @config['invite_url'] + rescue StandardError + event.bot.invite_url + end}" } } - return init_hash + init_hash end end diff --git a/modules/utility/info.rb b/modules/utility/info.rb index 127f95b..ad10cf0 100644 --- a/modules/utility/info.rb +++ b/modules/utility/info.rb @@ -1,131 +1,125 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe) 2016-2020 module YuukiBot module Utility - $cbot.add_command(:avatar, - code: proc { |event, args| - if args.length == 0 - user = event.user - else - begin - if args[0] == "byid" - user = event.bot.user(args[1]).on(event.server) - else - user = event.bot.parse_mention(args.join(' ')).on(event.server) - end - rescue - event.channel.send_message('', false, - Helper.error_embed( - error: "Not a valid user!", - footer: "Command: `#{event.message.content}`", - colour: 0xFA0E30, - code_error: false - ) - ) - raise 'Not a valid user' - end - end - - if user.nil? - event.channel.send_message('', false, - Helper.error_embed( - error: "Error unknown. Details:\n`User is nil or not found.`", - footer: "Command: `#{event.message.content}`", - colour: 0xFA0E30, - code_error: false - ) - ) - next - end - - avy_embed = Discordrb::Webhooks::Embed.new( - image: Discordrb::Webhooks::EmbedImage.new(url: Helper.avatar_url(user)), - author: Discordrb::Webhooks::EmbedAuthor.new(name: "Avatar for #{user.name} (Click to open in browser)", url: Helper.avatar_url(user)), - footer: Discordrb::Webhooks::EmbedFooter.new(text: "Called by #{event.user.distinct} (#{event.user.id})", icon_url: Helper.avatar_url(event.user)), - timestamp: Time.now - ) - - color = Helper.colour_from_user(user, -1) - # We don't want black (0x000000) if the user has no role colors. - # Let's leave that to Discord. - avy_embed.color = color unless color == -1 - event.channel.send_message('', false, avy_embed) - }, - triggers: %w(avatar avy), - :server_only => true, - ) + code: proc { |event, args| + if args.empty? + user = event.user + else + begin + user = if args[0] == 'byid' + event.bot.user(args[1]).on(event.server) + else + event.bot.parse_mention(args.join(' ')).on(event.server) + end + rescue StandardError + event.channel.send_message('', false, + Helper.error_embed( + error: 'Not a valid user!', + footer: "Command: `#{event.message.content}`", + colour: 0xFA0E30, + code_error: false + )) + raise 'Not a valid user' + end + end + + if user.nil? + event.channel.send_message('', false, + Helper.error_embed( + error: "Error unknown. Details:\n`User is nil or not found.`", + footer: "Command: `#{event.message.content}`", + colour: 0xFA0E30, + code_error: false + )) + next + end + + avy_embed = Discordrb::Webhooks::Embed.new( + image: Discordrb::Webhooks::EmbedImage.new(url: Helper.avatar_url(user)), + author: Discordrb::Webhooks::EmbedAuthor.new(name: "Avatar for #{user.name} (Click to open in browser)", url: Helper.avatar_url(user)), + footer: Discordrb::Webhooks::EmbedFooter.new(text: "Called by #{event.user.distinct} (#{event.user.id})", icon_url: Helper.avatar_url(event.user)), + timestamp: Time.now + ) + + color = Helper.colour_from_user(user, -1) + # We don't want black (0x000000) if the user has no role colors. + # Let's leave that to Discord. + avy_embed.color = color unless color == -1 + event.channel.send_message('', false, avy_embed) + }, + triggers: %w[avatar avy], + server_only: true) $cbot.add_command(:info, - code: proc { |event, args| - if args.length == 0 or args[0].nil? or args[0] == '' - user = event.user - else - begin - if args[0] == "byid" - user = event.bot.user(args[1]) - else - user = event.bot.parse_mention(args.join(' ')) - end - rescue - user = event.user - end - end - - if user.nil? - event.channel.send_message('', false, - Helper.error_embed( - error: "Error unknown. Details:\n`User is nil or not found.`", - footer: "Command: `#{event.message.content}`", - colour: 0xFA0E30, - code_error: false - ) - ) - next - end - - # Beter than the alternative :) - begin - member = user.on(event.server) - rescue - ignoreserver = true - end - - donator = JSON.parse(REDIS.get('donators')).include?(user.id) - event.channel.send_embed("__Information about **#{user.distinct}**__") do |embed| - embed.colour = event.channel.private? ? 0xe06b2 : Helper.colour_from_user(member) - embed.thumbnail = Discordrb::Webhooks::EmbedThumbnail.new(url: Helper.avatar_url(user)) - embed.author = Discordrb::Webhooks::EmbedAuthor.new(name: "#{donator ? ' 👑' : ' 👥' } #{ignoreserver ? user.name : member.display_name}", url: Helper.avatar_url(user)) - embed.footer = Discordrb::Webhooks::EmbedFooter.new(text: "All information correct as of: #{Time.now.getutc.asctime}") - embed.add_field(name: 'User ID:', value: user.id, inline: true) - embed.add_field(name: 'Playing:', value: user.game.nil? ? '[N/A]' : user.game, inline: true) - embed.add_field(name: 'Account Created:', value: "#{user.creation_time.getutc.asctime} UTC", inline: true) - embed.add_field(name: 'Joined Server:', value: ignoreserver ? '[N/A]' : "#{member.joined_at.getutc.asctime} UTC", inline: true) - embed.add_field(name: 'Status', value: user.status.capitalize) - end - }, - triggers: %w(info profile), - ) + code: proc { |event, args| + if args.empty? || args[0].nil? || (args[0] == '') + user = event.user + else + begin + user = if args[0] == 'byid' + event.bot.user(args[1]) + else + event.bot.parse_mention(args.join(' ')) + end + rescue StandardError + user = event.user + end + end + + if user.nil? + event.channel.send_message('', false, + Helper.error_embed( + error: "Error unknown. Details:\n`User is nil or not found.`", + footer: "Command: `#{event.message.content}`", + colour: 0xFA0E30, + code_error: false + )) + next + end + + # Beter than the alternative :) + begin + member = user.on(event.server) + rescue StandardError + ignoreserver = true + end + + donator = JSON.parse(REDIS.get('donators')).include?(user.id) + event.channel.send_embed("__Information about **#{user.distinct}**__") do |embed| + embed.colour = event.channel.private? ? 0xe06b2 : Helper.colour_from_user(member) + embed.thumbnail = Discordrb::Webhooks::EmbedThumbnail.new(url: Helper.avatar_url(user)) + embed.author = Discordrb::Webhooks::EmbedAuthor.new(name: "#{donator ? ' 👑' : ' 👥'} #{ignoreserver ? user.name : member.display_name}", url: Helper.avatar_url(user)) + embed.footer = Discordrb::Webhooks::EmbedFooter.new(text: "All information correct as of: #{Time.now.getutc.asctime}") + embed.add_field(name: 'User ID:', value: user.id, inline: true) + embed.add_field(name: 'Playing:', value: user.game.nil? ? '[N/A]' : user.game, inline: true) + embed.add_field(name: 'Account Created:', value: "#{user.creation_time.getutc.asctime} UTC", inline: true) + embed.add_field(name: 'Joined Server:', value: ignoreserver ? '[N/A]' : "#{member.joined_at.getutc.asctime} UTC", inline: true) + embed.add_field(name: 'Status', value: user.status.capitalize) + end + }, + triggers: %w[info profile]) $cbot.add_command(:ping, - code: proc {|event, _| - return_message = event.respond('Pinging..!') - ping = (return_message.id - event.message.id) >> 22 - choose = %w(i o e u y a) - return_message.edit("P#{choose.sample}ng! (`#{ping}ms`)") - }, - triggers: %w(ping pong peng pung pyng pang 🅱ing) - ) - + code: proc { |event, _| + return_message = event.respond('Pinging..!') + ping = (return_message.id - event.message.id) >> 22 + choose = %w[i o e u y a] + return_message.edit("P#{choose.sample}ng! (`#{ping}ms`)") + }, + triggers: %w[ping pong peng pung pyng pang 🅱ing]) def self.ms_to_time(ms) time = ms / 1000 seconds = time % 60 - time = time / 60 + time /= 60 minutes = time % 60 - time = time / 60 + time /= 60 hours = time % 24 - time = time / 24 + time /= 24 days = time seconds = seconds.floor @@ -133,20 +127,18 @@ def self.ms_to_time(ms) hours = hours.floor days = days.floor - seconds = (seconds.to_s.length == 1) ? "0" + seconds.to_s : seconds.to_s - minutes = (minutes.to_s.length == 1) ? "0" + minutes.to_s : minutes.to_s - hours = (hours.to_s.length == 1) ? "0" + hours.to_s : hours.to_s + seconds = seconds.to_s.length == 1 ? '0' + seconds.to_s : seconds.to_s + minutes = minutes.to_s.length == 1 ? '0' + minutes.to_s : minutes.to_s + hours = hours.to_s.length == 1 ? '0' + hours.to_s : hours.to_s "#{days} day#{'s' unless days == 1}, #{hours}:#{minutes}:#{seconds}" end $cbot.add_command(:uptime, - code: proc do |event, _| - uptimems = (Time.now - $launch_time) * 1000 - - event.respond("I was launched on `#{$launch_time.asctime} UTC`\nThis means I have been online for `#{self.ms_to_time(uptimems)}` (`#{uptimems.floor}ms`)") - end - ) + code: proc do |event, _| + uptimems = (Time.now - $launch_time) * 1000 + event.respond("I was launched on `#{$launch_time.asctime} UTC`\nThis means I have been online for `#{ms_to_time(uptimems)}` (`#{uptimems.floor}ms`)") + end) end end diff --git a/modules/utility/qr.rb b/modules/utility/qr.rb index 1ce62f3..968314f 100644 --- a/modules/utility/qr.rb +++ b/modules/utility/qr.rb @@ -1,42 +1,43 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe), Spotlight 2016-2020 module YuukiBot module Utility - require 'rqrcode' require 'pomf.rb' $cbot.add_command(:qr, - code: proc { |event, args| - tmp_path = "#{Dir.pwd}/tmp/qr.png" - content = args.join(' ') - # "Sanitize" qr code content - if content.length > 1000 - event.respond("#{YuukiBot.config['emoji_error']} QR codes have a limit of 1000 characters. You went over by #{content.length - 1000}!") - next - end - qrcode = RQRCode::QRCode.new(content) - FileUtils.mkdir("#{Dir.pwd}/tmp/") unless File.exist?("#{Dir.pwd}/tmp/") - FileUtils.rm(tmp_path) if File.exist?(tmp_path) - png = qrcode.as_png( - file: tmp_path # path to write - ) - url = Pomf.upload_file(tmp_path) - event.channel.send_embed do |embed| - embed.colour = 0x74f167 - embed.url = "https://a.pomf.cat/#{url}" - - embed.image = Discordrb::Webhooks::EmbedImage.new(url: "https://a.pomf.cat/#{url}") - embed.author = Discordrb::Webhooks::EmbedAuthor.new(name: "QR Code Generated by #{event.user.distinct}:", icon_url: Helper.avatar_url(event.user)) - embed.footer = Discordrb::Webhooks::EmbedFooter.new(text: "Disclaimer: This QR Code is user-generated content.") - - embed.add_field(name: "QR Content:", value: "```#{content}```") - embed.add_field(name: "QR Code:", value: "** **") - end - }, - min_args: 1, - catch_errors: true - ) + code: proc { |event, args| + tmp_path = "#{Dir.pwd}/tmp/qr.png" + content = args.join(' ') + # "Sanitize" qr code content + if content.length > 1000 + event.respond("#{YuukiBot.config['emoji_error']} QR codes have a limit of 1000 characters. You went over by #{content.length - 1000}!") + next + end + qrcode = RQRCode::QRCode.new(content) + unless File.exist?("#{Dir.pwd}/tmp/") + FileUtils.mkdir("#{Dir.pwd}/tmp/") + end + FileUtils.rm(tmp_path) if File.exist?(tmp_path) + png = qrcode.as_png( + file: tmp_path # path to write + ) + url = Pomf.upload_file(tmp_path) + event.channel.send_embed do |embed| + embed.colour = 0x74f167 + embed.url = "https://a.pomf.cat/#{url}" + + embed.image = Discordrb::Webhooks::EmbedImage.new(url: "https://a.pomf.cat/#{url}") + embed.author = Discordrb::Webhooks::EmbedAuthor.new(name: "QR Code Generated by #{event.user.distinct}:", icon_url: Helper.avatar_url(event.user)) + embed.footer = Discordrb::Webhooks::EmbedFooter.new(text: 'Disclaimer: This QR Code is user-generated content.') + embed.add_field(name: 'QR Content:', value: "```#{content}```") + embed.add_field(name: 'QR Code:', value: '** **') + end + }, + min_args: 1, + catch_errors: true) end -end \ No newline at end of file +end diff --git a/modules/utility/say.rb b/modules/utility/say.rb index f8e0206..580742f 100644 --- a/modules/utility/say.rb +++ b/modules/utility/say.rb @@ -1,26 +1,24 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe) 2016-2020 module YuukiBot module Utility - $cbot.add_command(:say, - code: proc { |event, args| - message = args.join(' ') - new_msg = event.respond(Helper.filter_everyone(message)) - # Helper.map_say(event.channel.id, event.message.id, new_msg.id) - }, - triggers: %w(say echo talk repeat), - min_args: 1 - ) + code: proc { |event, args| + message = args.join(' ') + new_msg = event.respond(Helper.filter_everyone(message)) + # Helper.map_say(event.channel.id, event.message.id, new_msg.id) + }, + triggers: %w[say echo talk repeat], + min_args: 1) $cbot.add_command(:speak, - code: proc { |event, args| - event.message.delete - event.respond(args.join(' ')) - }, - owners_only: true, - min_args: 1, - triggers: %w(speak hide) - ) - + code: proc { |event, args| + event.message.delete + event.respond(args.join(' ')) + }, + owners_only: true, + min_args: 1, + triggers: %w[speak hide]) end end diff --git a/modules/utility/servers.rb b/modules/utility/servers.rb index ba49197..0385f5e 100644 --- a/modules/utility/servers.rb +++ b/modules/utility/servers.rb @@ -1,12 +1,11 @@ +# frozen_string_literal: true + # Copyright Erisa A. (erisa.moe) 2019-2020 module YuukiBot module Utility - $cbot.add_command(:servers, - code: proc { |event, args| - event.respond "🏠 | I am in **#{event.bot.servers.count}** servers!" - }, - ) - + code: proc { |event, _args| + event.respond "🏠 | I am in **#{event.bot.servers.count}** servers!" + }) end end diff --git a/modules/utility/stubs.rb b/modules/utility/stubs.rb index f789df0..c2620f4 100644 --- a/modules/utility/stubs.rb +++ b/modules/utility/stubs.rb @@ -1,13 +1,14 @@ +# frozen_string_literal: true + # Copyright Erisa Arrowsmith 2017 module YuukiBot module Utility - $cbot.add_command(:stubs, - code: proc { |event, _| - event.respond('This command has been removed!') - }, - triggers: %w(zalgo command angry space tell randommovie owner dump translate) - ) + code: proc { |event, _| + event.respond('This command has been removed!') + }, + triggers: %w[zalgo command angry space + tell randommovie owner dump translate]) end -end \ No newline at end of file +end diff --git a/run.rb b/run.rb index df01055..af51f21 100644 --- a/run.rb +++ b/run.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + $launch_time = Time.now module YuukiBot @@ -6,7 +8,7 @@ module YuukiBot require 'redis' require 'redis-namespace' require 'json' - + if ENV['COMMANDRB_PATH'].nil? require 'commandrb' else @@ -28,7 +30,7 @@ def is_owner?(id) if YuukiBot.config['master_owner'].to_i == id true else - Helper.owners.include?(id) + Helper.owners.include?(id) end end end @@ -37,13 +39,13 @@ def is_owner?(id) $cbot = CommandrbBot.new(init_hash) - module_dirs = %w(owner helper logging misc mod utility) - module_dirs.each {|dir| - Dir["modules/#{dir}/*.rb"].each { |r| - require_relative r - puts "Loaded: #{r}" if @config['verbose'] - } - } + module_dirs = %w[owner helper logging misc mod utility] + module_dirs.each do |dir| + Dir["modules/#{dir}/*.rb"].each do |r| + require_relative r + puts "Loaded: #{r}" if @config['verbose'] + end + end require_relative 'modules/custom' puts 'Loaded custom commands!' @@ -51,7 +53,10 @@ def is_owner?(id) # Load Extra Commands if enabled. if YuukiBot.config['extra_commands'] puts 'Loading: Extra commands...' if @config['verbose'] - Dir['modules/extra/*.rb'].each { |r| require_relative r; puts "Loaded: #{r}" if @config['verbose'] } + Dir['modules/extra/*.rb'].each do |r| + require_relative r + puts "Loaded: #{r}" if @config['verbose'] + end end # I cant think of a better way to this and honestly all this code is going to be abandoned soon. @@ -62,10 +67,13 @@ def is_owner?(id) orig_redis = Redis.new(host: YuukiBot.config['redis_host'], port: YuukiBot.config['redis_port'], password: YuukiBot.config['redis_password']) end - REDIS = Redis::Namespace.new(YuukiBot.config['redis_namespace'], :redis => orig_redis ) + REDIS = Redis::Namespace.new( + YuukiBot.config['redis_namespace'], + redis: orig_redis + ) puts '>> Initial loading succesful!! <<' - $uploader = Haste::Uploader.new("https://paste.erisa.moe" ) + $uploader = Haste::Uploader.new('https://paste.erisa.moe') if YuukiBot.config['use_pry'] $cbot.bot.run(true) require 'pry' From 91824a5f776eff83a4a3d86ba8a382144b3189b5 Mon Sep 17 00:00:00 2001 From: Spotlight Date: Sun, 19 Jan 2020 16:28:05 -0600 Subject: [PATCH 02/42] Reformat redis logic --- run.rb | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/run.rb b/run.rb index af51f21..09d7e2e 100644 --- a/run.rb +++ b/run.rb @@ -59,13 +59,21 @@ def is_owner?(id) end end - # I cant think of a better way to this and honestly all this code is going to be abandoned soon. - # forgive me, for i have sinned - if YuukiBot.config['redis_password'].nil? or YuukiBot.config['redis_password'] == 'nil' - orig_redis = Redis.new(host: YuukiBot.config['redis_host'], port: YuukiBot.config['redis_port']) - else - orig_redis = Redis.new(host: YuukiBot.config['redis_host'], port: YuukiBot.config['redis_port'], password: YuukiBot.config['redis_password']) - end + # Check if the key redis_password exists or is string literal 'nil' + # If so, set it! + redis_password = YuukiBot.config['redis_password'] + orig_redis = if redis_password.nil? || (redis_password == 'nil') + Redis.new( + host: YuukiBot.config['redis_host'], + port: YuukiBot.config['redis_port'] + ) + else + Redis.new( + host: YuukiBot.config['redis_host'], + port: YuukiBot.config['redis_port'], + password: redis_password + ) + end REDIS = Redis::Namespace.new( YuukiBot.config['redis_namespace'], From 02e412268ade1b3c3557f6fd2b8638f619eb0773 Mon Sep 17 00:00:00 2001 From: Spotlight Date: Sun, 19 Jan 2020 17:22:59 -0600 Subject: [PATCH 03/42] Make version an attribute instead of global variable --- modules/version.rb | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/modules/version.rb b/modules/version.rb index 018c807..1b0e5e8 100644 --- a/modules/version.rb +++ b/modules/version.rb @@ -1 +1,8 @@ -$version = 4.3 +# frozen_string_literal: true + +module YuukiBot + class << self + attr_reader :version + end + @version = 4.3 +end From 8631ef922caf942bc86273afab535204e2f9d679 Mon Sep 17 00:00:00 2001 From: Spotlight Date: Sun, 19 Jan 2020 18:56:51 -0600 Subject: [PATCH 04/42] Concatenate eval handling logic This allows shared logic between bash and the new eval command, specifically. --- modules/owner/eval.rb | 63 ++++++++++++++++++++++++------------------- 1 file changed, 35 insertions(+), 28 deletions(-) diff --git a/modules/owner/eval.rb b/modules/owner/eval.rb index bb1f828..9f496d9 100644 --- a/modules/owner/eval.rb +++ b/modules/owner/eval.rb @@ -8,7 +8,7 @@ module Owner code: proc { |event, args| event.respond(eval(args.join(' '))) }, - triggers: ['raweval ', 'oldeval'], + triggers: ['raweval ', 'oldeval '], owners_only: true) $cbot.add_command(:eval, @@ -17,21 +17,12 @@ module Owner msg = event.respond "#{YuukiBot.config['emoji_loading']} Evaluating..." init_time = Time.now result = eval args.join(' ') - result = result.to_s - if result.nil? || result == '' || result == ' ' || result == "\n" - msg.edit "#{YuukiBot.config['emoji_tickbox']} Done! (No output)\nCommand took #{(Time.now - init_time)} seconds to execute!" - next - end - str = '' - if result.length >= 1984 - str << "#{YuukiBot.config['emoji_warning']} Your output exceeded the character limit! (`#{result.length - 1984}`/`1984`)" - str << "You can view the result here: https://paste.erisa.moe/raw/#{$uploader.upload_raw(result)}\nCommand took #{(Time.now - init_time)} seconds to execute!" - else - str << "Output: ```\n#{result}```Command took #{(Time.now - init_time)} seconds to execute!" - end - msg.edit(str) + result_output = handle_result(result, init_time) + msg.edit(result_output) rescue Exception => e - msg.edit("#{YuukiBot.config['emoji_error']} An error has occured!! ```ruby\n#{e}```\nCommand took #{(Time.now - init_time)} seconds to execute!") + msg.edit("#{YuukiBot.config['emoji_error']} An error has occurred!"\ + "```ruby\n#{e}```" \ + "Command took #{(Time.now - init_time)} seconds to execute!") end }, triggers: ['eval2 ', 'eval'], @@ -44,22 +35,38 @@ module Owner msg = event.respond "#{YuukiBot.config['emoji_loading']} Evaluating..." # Capture all output, including STDERR. result = `#{"#{args.join(' ')} 2>&1"} ` - result = result.to_s - if result.nil? || result == '' || result == ' ' || result == "\n" - msg.edit "#{YuukiBot.config['emoji_tickbox']} Done! (No output)\nCommand took #{(Time.now - init_time)} seconds to execute!" - next - end - str = '' - if result.length >= 1984 - str << "#{YuukiBot.config['emoji_warning']} Your output exceeded the character limit! (`#{result.length - 1984}`/`1984`)" - str << "You can view the result here: https://paste.erisa.moe/raw/#{$uploader.upload_raw(result)}\nCommand took #{(Time.now - init_time)} seconds to execute!" - else - str << "Output: ```\n#{result}```Command took #{(Time.now - init_time)} seconds to execute!" - end - msg.edit(str) + result_output = handle_result(result, init_time) + msg.edit(result_output) }, triggers: ['bash ', 'sh ', 'shell ', 'run '], owners_only: true, description: 'Evaluate a Bash command. Owner only. Use with care.') + + # Formulates results to an external source or character-specific message. + # @param [Object] result_output Returned result of an operation. + # @param [Class