Skip to content

Instantly share code, notes, and snippets.

@bendangelo
Created January 3, 2024 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bendangelo/dddb8135229979b47cbceec0025c1bb7 to your computer and use it in GitHub Desktop.
Save bendangelo/dddb8135229979b47cbceec0025c1bb7 to your computer and use it in GitHub Desktop.
Telegram notifier for exception notifier gem
# inside initializers/exception_notifier.rb
# Webhook notifier sends notifications over HTTP protocol. Requires 'httparty' gem.
# config.add_notifier :telegram, {
# api_key: Rails.application.credentials.telegram_api,
# chat_id: Rails.application.credentials.telegram_chat,
# backtrace_length: 10,
# body: {
# disable_notification: true,
# parse_mode: "HTML"
# }
# }
# Example of manual calling:
# ExceptionNotifier.notify_exception(
# e,
# data: {your: "data"}
# )
require 'action_dispatch'
require 'active_support/core_ext/time'
module ExceptionNotifier
class TelegramNotifier < BaseNotifier
def initialize(options)
super
@default_options = options
end
def call(exception, options = {})
env = options[:env]
options = options.reverse_merge(@default_options)
# TELEGRAM stuff
api_key = options.delete(:api_key)
chat_id = options.delete(:chat_id)
url = "https://api.telegram.org/bot#{api_key}/sendMessage?chat_id=#{chat_id}"
http_method = options.delete(:http_method) || :post
body = {}
body[:error_class] = exception.class.to_s
body[:message] = exception.message.inspect
body[:backtrace] = exception.backtrace.first(options.delete(:backtrace_length) || 5)
body[:data] = (env && env['exception_notifier.exception_data'] || {}).merge(options[:data] || {})
unless env.nil?
request = ActionDispatch::Request.new(env)
request_items = {
url: request.original_url,
http_method: request.method,
ip_address: request.remote_ip,
parameters: request.filtered_parameters,
timestamp: Time.current
}
body[:request] = request_items
body[:session] = request.session
# body[:environment] = request.filtered_env
end
body[:server] = Socket.gethostname
# body[:process] = $PROCESS_ID
# body[:rails_root] = Rails.root if defined?(Rails) && Rails.respond_to?(:root)
options[:body] ||= {}
# max message length
options[:body][:text] = format_hash_for_text(body)[0, 4096]
send_notice(exception, options, nil, @default_options) do |_, _|
resp = HTTParty.send(http_method, url, options)
if resp["ok"] == false
Rails.logger.error resp
end
end
end
def format_hash_for_text(hash)
formatted_string = ""
hash.each do |key, value|
formatted_string += "<b>#{key}</b>: "
formatted_string += "#{value}\n"
end
formatted_string.chomp # Remove trailing newline
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment