Skip to content

Instantly share code, notes, and snippets.

@localhostdotdev
Created March 17, 2019 00:29
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save localhostdotdev/775740c119af1cd031aa32fcf62dc08c to your computer and use it in GitHub Desktop.
Handle errors in all Discord commands with discordrb (also formats those errors while only keeping the path in the stacktrace relative to the project's root) (only Rails.root is Rails-specific, rest is pure ruby)
module Discord
module Commands
extend Discordrb::Commands::CommandContainer
def self.handle_errors(e)
if e.is_a?(Discordrb::Errors::MessageTooLong)
"Message too long"
else
str = "#{Format.inline(e.message}\n"
str += Format.code(e.backtrace.grep(/#{Rails.root.to_s}/).map { |s| s.gsub(Rails.root.to_s, "") }.join("\n"))
str
end
end
old_command = method(:command)
def self.command(*args, &block)
old_command(*args, &block)
rescue => e
handle_errors(e)
rescue SyntaxError => e
handle_errors(e)
end
end
end
class Format
ZERO_WIDTH = "​"
def self.i(str)
"_#{str}_"
end
def self.b(str)
"**#{str}**"
end
def self.bi(str)
"***#{str}***"
end
def self.u(str)
"__#{str}__"
end
def self.ui(str)
"__*#{str}*__"
end
def self.ub(str)
"__**#{str}**__"
end
def self.ubi(str)
"__***#{str}***__"
end
def self.strike(str)
"~~#{str}~~"
end
def self.inline(str)
"`#{str.gsub("`", "'")}`"
end
def self.code(str, language: nil)
str = str.gsub("`") { ZERO_WIDTH * 2 + "`" }
"```#{language}\n#{str}\n```"
end
def self.margin(str, margin: 2)
"\n" + str.lines.map { |l| " " * margin + l }.join + "\n" * 2
end
def self.escape(str)
str = str.gsub('\\') { "\\\\" }.gsub("_") { '\\_' }
str = str.gsub("*") { "\\*" }.gsub("`") { ZERO_WIDTH * 2 + "`" }
str.gsub("~") { "\\~" }
end
def self.number(n)
n = n.to_i if n.to_i == n
ActiveSupport::NumberHelper.number_to_delimited(n)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment