Skip to content

Commit

Permalink
Major changes for rubocop complaince.
Browse files Browse the repository at this point in the history
All commands tested with a test bot on my personal server.
  • Loading branch information
ldelelis committed Dec 2, 2017
1 parent ada8ac4 commit 77bac97
Show file tree
Hide file tree
Showing 6 changed files with 115 additions and 123 deletions.
12 changes: 8 additions & 4 deletions config_example.yaml
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
---
token:
serverID: ''
sudoersRole: ''
timeoutRole: ''
figletFont: '' #a font name from the fonts folder minus the .flf
roles:
sudoersRole: ''
timeoutRole: ''
nonfsfRole: ''
botdevRole: ''
infoFile: ''
figletFont: '' # a font name from the fonts folder minus the .flf
prefix: ''
lusersList: '' #a sequence of stringos
lusersList: '' # a sequence of strings
45 changes: 21 additions & 24 deletions lib/admin.rb
Original file line number Diff line number Diff line change
@@ -1,41 +1,38 @@
# Implements administration commands that are unavailable to regular users.
module Admin
extend Discordrb::Commands::CommandContainer

command(:clear,
description: "Clears N amount of messages. If no arguments are " \
"specified, 100 messages will be cleared. " \
"Requires superuser",
help_available: false) \
do |event, *args|
unless $userType != 'sudoer'
event.channel.send_message("Invalid amount") &&
break if args[0].to_i > 100
toDelete = event.channel.history(args.empty? ? 100 : args[0].to_i+1)
event.channel.delete_messages(toDelete)
"Clearing..."
description: 'Clears N amount of messages. If no arguments are ' \
'specified, 100 messages will be cleared. ' \
'Requires superuser',
help_available: false) do |event, *args|
if $user_type == 'sudoer'
event.channel.send_message('Invalid amount') && break if args[0].to_i > 100
to_delete = event.channel.history(args.empty? ? 100 : args[0].to_i + 1)
event.channel.delete_messages(to_delete)
else
"Permission denied."
event.channel.send_message('Permission denied.')
end
end

command(:timeout,
description: "Times out a user for N seconds. Requires superuser",
description: 'Times out a user for N seconds. Requires superuser',
min_args: 2,
usage: "[user to timeout] [seconds of timeout]",
help_available: false) \
do |event, *args|
unless $userType != 'sudoer'
timeOut = fork do
usage: '[user to timeout] [seconds of timeout]',
help_available: false) do |event, *args|
if $user_type == 'sudoer'
time_out = fork do
user = event.message.mentions[0].on($config['serverID'])
user.add_role($config['timeoutRole'])
user.add_role($config['roles']['timeoutRole'])
sleep args[1].to_i
user.remove_role($config['timeoutRole'])
"#{user.name} timed out for #{args[1].to_i}"
event.channel.send_message("#{user.name} timed out for #{args[1].to_i}")
end
puts Process.detach(timeOut) #This puts is imporant so the thread ID
else #Doesn't get outputted by the bot
"Permission denied."
Process.detach(time_out)
return
else
event.channel.send_message('Permission denied.')
end

end
end
81 changes: 37 additions & 44 deletions lib/fun.rb
Original file line number Diff line number Diff line change
@@ -1,72 +1,65 @@
# Implements fluff commands that serve no real use
module Fun
extend Discordrb::Commands::CommandContainer

command(:aesthic,
description: "Makes a message A E S T H E T I C",
usage: "[text to convert]",
min_args: 1) \
do |event, *args|
args.join(' ').to_fullwidth
description: 'Makes a message A E S T H E T I C',
usage: '[text to convert]',
min_args: 1) do |event, *args|
event.channel.send_message(args.join(' ').to_fullwidth)
end

command(:step,
description: "Show your soles to someone or something",
usage: "[text]",
min_args: 1) \
do |event, *args|
description: 'Show your soles to someone or something',
usage: '[text]',
min_args: 1) do |event, *args|
args.to_a.delete_at(0) if args.include?('on')
"<@#{event.author.id.to_s}> steps on #{args.join(' ')}"
event.channel.send_message("<@#{event.author.id}> steps on #{args.join(' ')}")
end

command(:slap,
description: "Hit someone or something",
usage: "[text]") \
do |event, *args|
event.channel.send_message("<@#{event::author::id.to_s}> slaps " \
"#{args.join(' ')} around a bit with a large trout")
description: 'Hit someone or something',
usage: '[text]') do |event, *args|
event.channel.send_message("<@#{event.author.id}> slaps #{args.join(' ')} around a bit with a large trout")
end

command(:figlet,
description: "Turns a message into big ASCII art letters",
usage: "[text]",
min_args: 1) \
do |event, *args|
"```" + $figlet[args.join('')] + "```"
description: 'Turns a message into big ASCII art letters',
usage: '[text]',
min_args: 1) do |event, *args|
event.channel.send_message('```' + $figlet[args.join('')] + '```')
end

command(:cowsay,
description: "Wraps a message with an ASCII art cow",
usage: "[text]",
min_args: 1) \
do |event, *args|
inputtext = args.join(' ').gsub("```", '');
renderedtext = Cowsay.say(inputtext, 'cow')
chunkedtext = ""
until renderedtext.empty?
sliced = renderedtext.slice(0..1990)
lastindex = sliced.length - 1
lastline = sliced.lines.last
unless lastline.end_with? '\n' or renderedtext.length == sliced.length
lastindex -= lastline.length
description: 'Wraps a message with an ASCII art cow',
usage: '[text]',
min_args: 1) do |event, *args|
input_text = args.join(' ').gsub('```', '')
rendered_text = Cowsay.say(input_text, 'cow')
chunked_text = ''
until rendered_text.empty?
sliced = rendered_text.slice(0..1990)
last_index = sliced.length - 1
last_line = sliced.lines.last
unless last_line.end_with?('\n') || rendered_text.length == sliced.length
last_index -= last_line.length
end
chunkedtext << "```\n" + renderedtext.slice!(0..lastindex)+ "\n```" \
+ " " * lastline.length + "\n"
chunked_text << "```\n" + rendered_text.slice!(0..last_index) + "\n```" \
+ ' ' * last_line.length + "\n"
end
chunkedtext
event.channel.send_message(chunked_text)
end

command(:me,
description: "Executes a self action",
usage: "[text]",
min_args: 1) \
do |event, *args|
description: 'Executes a self action',
usage: '[text]',
min_args: 1) do |event, *args|
event.channel.delete_message(event.channel.history(1)[0])
"<@#{event.user.id.to_s}> *#{args.join(' ')}*"
event.channel.send_message("<@#{event.user.id}> *#{args.join(' ')}*")
end

command(:fortune,
description: "Outputs a random fortune / divination / bad joke") \
do |event|
"```" + FortuneGem.give_fortune + "```"
description: 'Outputs a random fortune / divination / bad joke') do |event|
event.channel.send_message('```' + FortuneGem.give_fortune + '```')
end
end
9 changes: 5 additions & 4 deletions lib/patches.rb
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
#allow output from commands to exceed 2000 chars
# Allow output from commands to exceed 2000 chars
module Discordrb::Commands
# Overwrite of the CommandBot to monkey patch command length
class CommandBot
def execute_chain(chain, event)
def execute_chain(chain, event)
t = Thread.new do
@event_threads << t
Thread.current[:discordrb_name] = "ct-#{@current_thread += 1}"
begin
debug("Parsing command chain #{chain}")
result = @attributes[:advanced_functionality] ? CommandChain.new(chain, self).execute(event) : simple_execute(chain, event)
result = event.drain_into(result)

if event.file
event.send_file(event.file, caption: result)
else
unless result.nil? || result.empty?
Discordrb.split_message(result).each do |chunk|
event.respond chunk
end
end
end
end
rescue => e
Expand Down
42 changes: 21 additions & 21 deletions lib/utilities.rb
Original file line number Diff line number Diff line change
@@ -1,54 +1,54 @@
# Implements utility commands for everyone's use
module Utilities
extend Discordrb::Commands::CommandContainer

command(:random,
description: "Picks a random number.",
usage: "<min> <max>",
min_args: 2) \
do |event|
description: 'Picks a random number.',
usage: '<min> <max>',
min_args: 2) do |event|
# Parse the message and keep all parts but the command
# ["::random 1 2 4 5 -5"] => ["1", "2", "4", "5", "-5"]
args = (event.message.content.split (' '))[1 .. -1]
args = event.message.content.split(' ')[1..-1]

# Args to integer
input = Array.new(args.size){ |i| args[i].to_i }
input = Array.new(args.size) { |i| args[i].to_i }

case input.size
when 0
# Integer "limits" (there's no such thing in ruby though)
min = -(2**(0.size * 8 -2))
min = -(2**(0.size * 8 - 2))
max = min.abs
when 1
min = 0
max = 0
# If one args is given, the result will be of the same sign as the arg
input[0] >= 0? max = input[0] : min = input[0]
input[0] >= 0 ? max = input[0] : min = input[0]
else
min = input.min
max = input.max
end
rand(min .. max)
rand(min..max)
end

command(:echo,
description: "Echoes text.",
usage: "[text to echo]",
min_args: 1) \
do |event, *args|
args.join(' ')
description: 'Echoes text.',
usage: '[text to echo]',
min_args: 1) do |event, *args|
event.channel.send_message(args.join(' '))
end

command(:lusers,
description: "Prints the amount of lusers currently online.",
usage: "!lusers") \
do |event|
"Amount of lusers currently #{$config['lusersList'].sample}: #{event.server.online_users(include_idle: true).length.to_s}"
description: 'Prints the amount of lusers currently online.',
usage: '!lusers') do |event|
event.channel.send_message('Amount of lusers currently ' \
"#{$config['lusersList'].sample}:" \
"#{event.server.online_users(include_idle: true).length}")
end

command(:checksudo,
description: "Prints if you're a sudoer",
usage: "!checksudo") \
do |event|
"You are a #{event.user.roles.include?($config['sudoersRole'])?'sudoer':'regular user'}."
usage: '!checksudo') do |event|
event.channel.send_message('You are a ' \
"#{event.user.roles.include?($config['roles']['sudoersRole']) ? 'sudoer' : 'regular user'}.")
end
end
49 changes: 23 additions & 26 deletions main.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,60 +13,57 @@
require_relative 'lib/admin'

$config = YAML.load_file('config.yaml')
$infofile = $config['infoFile']
$pasta = YAML.load_file('pasta.yaml')

#Figlet initialization
$font = Figlet::Font.new("fonts/#{$config['figletFont']}.flf")
$figlet = Figlet::Typesetter.new($font)
# Figlet initialization
$figlet = Figlet::Typesetter.new(Figlet::Font.new("fonts/#{$config['figletFont']}.flf"))

$bot = Discordrb::Commands::CommandBot.new(token: $config['token'],
prefix: $config['prefix'],
advanced_functionality: true,
spaces_allowed: true,
chain_delimiter: '|',
previous: '-',
ignore_bots: true,
command_doesnt_exist_message: "zsh: command not found")
prefix: $config['prefix'],
advanced_functionality: true,
spaces_allowed: true,
chain_delimiter: '|',
previous: '-',
ignore_bots: true,
command_doesnt_exist_message: 'zsh: command not found')

$bot.include! Utilities
$bot.include! Fun
$bot.include! Admin

$userType = 'normal'
$user_type = 'normal'

$bot.command :sudo \
do |event, *args|
if event.author.roles.select{|role| role.id == $config['sudoersRole']}.length > 0
runCommand = args[0]
args.slice!(0)
$userType = 'sudoer'
$bot.execute_command(runCommand.to_sym, event, args)
$userType = 'normal'
$bot.command :sudo do |event, *args|
if event.author.roles.select { |role| role.id == $config['roles']['sudoersRole'] }.empty?
event.channel.send_message("<@#{event.author.id}> is not in the sudoers file. This incident will be reported.")
else
event.channel.send_message("<@#{event.author.id.to_s}> is not in the sudoers file. This incident will be reported.")
run_command = args[0]
args.slice!(0)
$user_type = 'sudoer'
$bot.execute_command(run_command.to_sym, event, args)
$user_type = 'normal'
end
nil
break # Avoids garbage messages
end

$pasta.keys.each do |pasta| # Slightly improved
$bot.command pasta.to_sym do |event, *args|
catch :RegexError do
sed = []
args.each { |string| string.split('/').each { |subs| sed.push(subs)}}
$pasta = YAML.load_file('pasta.yaml')
args.each { |string| string.split('/').each { |subs| sed.push(subs) } }
$pasta = YAML.load_file('pasta.yaml') # Required to reload the pastas
message = $pasta[pasta]
unless sed.empty?
sed.each_slice(2) do |match, replace|
begin
message.gsub!(/#{match}/i, replace || '')
rescue RegexpError
"Error: Invalid Regex"
event.channel.send_message('Error: Invalid Regex')
throw :RegexError
end
end
end
message
event.channel.send_message(message)
end
end
end
Expand Down

0 comments on commit 77bac97

Please sign in to comment.