Created
March 17, 2019 00:29
Star
You must be signed in to star a gist
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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