telegram_alerts 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 27ed353f8f0cf2082df344ecf42243dc14ec87de19812ca3baf1f2d94b632d13
4
+ data.tar.gz: 1b70bdff3253101393271bf49bc5515e4e835ec6b36f51b7f9ae2f3a25a2972f
5
+ SHA512:
6
+ metadata.gz: 2583bb7e479888c8a12d028016549c0b8514f92a20c2277fe288b5408e6064ebdbb7dbaecca707c96e89307ed1f4a09ad6512fcf021398bf34e184c6df528094
7
+ data.tar.gz: defdccd1a5f5c375357ab2aa2bb286c51325351f2bf9afb4cd995cff6e3abc8a93b038a7d9c99e613d20b6cebff9c8d66c45f106832c7b65e718c977a5a282cb
data/.gitignore ADDED
@@ -0,0 +1,14 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ .idea
10
+ *.gem
11
+ .ruby-version
12
+
13
+ # rspec failure tracking
14
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in telegram_alerts.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 mikael
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,106 @@
1
+ # TelegramAlerts
2
+ TelegramAlerts is a Ruby gem that allows you to receive notifications about exceptions and alerts in your Ruby applications through Telegram. The notifications include information such as the exception class, message, backtrace, environment, and time of occurrence.
3
+
4
+ ## Installation
5
+ Install the gem and add to the application's Gemfile by executing:
6
+
7
+ $ bundle add telegram_alerts
8
+
9
+ If bundler is not being used to manage dependencies, install the gem by executing:
10
+
11
+ $ gem install telegram_alerts
12
+
13
+ ## Description
14
+ In order to use TelegramAlerts, you need to create a subclass of TelegramAlerts::ChatMixin and set the chat key.
15
+
16
+ ### _exception_ method
17
+ The `exception` function returns a message in HTML format. The message includes:
18
+
19
+ - Emoji corresponding to the severity level
20
+ - Exception class
21
+ - Exception message
22
+ - Custom message if any
23
+ - Simplified backtrace
24
+ - Environment details such as host name, ruby version, project name and path, date and time, timezone
25
+
26
+ Each piece of information is separated by newlines and formatted with either bold or italic text to distinguish different elements of the message.
27
+
28
+ ### _message_ method
29
+ The `message` function is responsible for sending an message to the specified Telegram channel. The message includes information about the severity of the issue, the date and time, and a descriptive message.
30
+
31
+ ### Available severity levels
32
+ The available severity levels in the TelegramAlert gem are:
33
+
34
+ - FATAL (🔥): represents a critical error that requires immediate attention;
35
+ - ERROR (❌): represents an error that is not critical but requires attention;
36
+ - WARN (⚠️): represents a warning that does not require immediate attention;
37
+ - INFO (ℹ️): represents an informational message;
38
+ - DEBUG (🔍): represents a message that is useful for debugging purposes.
39
+
40
+ ## Usage
41
+
42
+ Here's an example of how to use TelegramAlerts in a Ruby application:
43
+
44
+ ```ruby
45
+ require 'telegram_alerts'
46
+
47
+ TelegramAlerts.chats_settings.merge!({
48
+ monitor: {
49
+ bot_token: 'BOT_TOKEN',
50
+ chat_id: 'MONITOR_CHAT_ID',
51
+ host_name: `hostname`.strip,
52
+ project_name: 'AwesomeProject'
53
+ },
54
+ logs: {
55
+ bot_token: 'BOT_TOKEN',
56
+ chat_id: 'LOGS_CHAT_ID',
57
+ host_name: `hostname`.strip,
58
+ project_name: 'AwesomeProject'
59
+ }
60
+ })
61
+
62
+ module AwesomeProjectAlertsChats
63
+ class MonitorChat < TelegramAlerts::ChatMixin
64
+ def self.chat
65
+ :monitor
66
+ end
67
+ end
68
+
69
+ class LogsChat < TelegramAlerts::ChatMixin
70
+ def self.chat
71
+ :logs
72
+ end
73
+ end
74
+ end
75
+ ```
76
+
77
+ Then, In your application code, you can use the `log_exception` method to log an exception and receive a notification to the Telegram chat or group:
78
+
79
+ ```ruby
80
+
81
+ begin
82
+ # Some code that raises an exception
83
+ rescue => e
84
+ AwesomeProjectAlertsChats::MonitorChat.exception(e, 'FATAL', 'A fatal error has occurred.')
85
+ end
86
+ ```
87
+
88
+ You can also use the `message` method to send an notification to Telegram:
89
+
90
+ ```ruby
91
+ AwesomeProjectAlertsChats::LogsChat.message('User created', 'INFO')
92
+ ```
93
+
94
+ ## Development
95
+
96
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
97
+
98
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
99
+
100
+ ## Contributing
101
+
102
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/telegram_alerts.
103
+
104
+ ## License
105
+
106
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "telegram_alerts"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TelegramAlerts
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,128 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'telegram_alerts/version'
4
+
5
+ module TelegramAlerts
6
+
7
+ def self.chats_settings
8
+ @chats_settings ||= {}
9
+ end
10
+
11
+ def self.special_telegram_chars
12
+ @special_telegram_chars ||= {
13
+ '<' => '',
14
+ '>' => '()',
15
+ }
16
+ end
17
+
18
+ def self.severity_parser
19
+ @severity_parser ||= {
20
+ 'ALERT' => '🔔',
21
+ 'FATAL' => '🔥',
22
+ 'ERROR' => '❌',
23
+ 'WARN' => '⚠️',
24
+ 'INFO' => 'ℹ️',
25
+ 'DEBUG' => '🔍'
26
+ }
27
+ end
28
+
29
+ class ChatMixin
30
+
31
+ def self.chat
32
+ raise 'You must define a chat key'
33
+ end
34
+
35
+ def self.bot_token
36
+ token = TelegramAlerts.chats_settings[chat]['bot_token'] || TelegramAlerts.chats_settings[chat][:bot_token]
37
+ if token.nil?
38
+ raise 'You must define a bot token'
39
+ end
40
+ token
41
+ end
42
+
43
+ def self.chat_id
44
+ _id = TelegramAlerts.chats_settings[chat]['chat_id'] || TelegramAlerts.chats_settings[chat][:chat_id]
45
+ if _id.nil?
46
+ raise 'You must define a chat id'
47
+ end
48
+ _id
49
+ end
50
+
51
+ def self.host_name
52
+ name = TelegramAlerts.chats_settings[chat]['host_name'] || TelegramAlerts.chats_settings[chat][:host_name]
53
+ if name.nil?
54
+ raise 'You must define a host name'
55
+ end
56
+ name
57
+ end
58
+
59
+ def self.project_name
60
+ name = TelegramAlerts.chats_settings[chat]['project_name'] || TelegramAlerts.chats_settings[chat][:project_name]
61
+ if name.nil?
62
+ raise 'You must define a project name'
63
+ end
64
+ name
65
+ end
66
+
67
+ def self.exception(e, severity, message: nil)
68
+ message = parse_exception(e, severity, message: message)
69
+ send_message(message, bot_token, chat_id)
70
+ end
71
+
72
+ def self.send_message(message, bot_token, chat_id)
73
+ body = {
74
+ 'chat_id' => chat_id,
75
+ 'text' => message,
76
+ 'parse_mode' => 'HTML'
77
+ }
78
+ telegram_endpoint_uri = URI("https://api.telegram.org/bot#{bot_token}/sendMessage")
79
+ Net::HTTP.post_form(telegram_endpoint_uri, body)
80
+ end
81
+
82
+ def self.message(message, severity = 'INFO')
83
+ severity_emoji = TelegramAlerts.severity_parser[severity]
84
+ title = "<b>#{severity_emoji} #{severity.capitalize}</b>"
85
+ time = "<i>#{Time.now.strftime('%H:%M:%S %d-%m-%Y %z')}</i>"
86
+ send_message("#{title}\n\n#{message}\n\n#{time}", bot_token, chat_id)
87
+ end
88
+
89
+ def self.parse_exception(exception, severity, message = nil)
90
+ severity_emoji = TelegramAlerts.severity_parser[severity]
91
+ project_path = File.expand_path('../..', __FILE__)
92
+
93
+ lines = exception.backtrace.map{ |x|
94
+ x.match(/^(.+?):(\d+)(|:in `(.+)')$/);
95
+ [$1,$2,$4]
96
+ }.reject { |x| x.first&.include?('.rvm/') }
97
+
98
+ now = Time.now
99
+
100
+ formatted_message = [
101
+ "#{severity_emoji} <b>#{exception.class}</b>",
102
+ "\n<b>Message</b>",
103
+ "<i>#{exception.message}</i>",
104
+ # Custom message goes here if any
105
+ "\n<b>Backtrace</b>",
106
+ lines.map do
107
+ |file, line, method|
108
+ output = "#{file}:#{line} in `#{method}'"
109
+ TelegramAlerts.special_telegram_chars.each do |k, v|
110
+ output = output.gsub(k, v)
111
+ end
112
+ output
113
+ end,
114
+ "\n<b>Environment</b>",
115
+ " Env: #{host_name} server with ruby #{RUBY_VERSION}",
116
+ " Project: #{project_name}",
117
+ " Path: #{project_path}",
118
+ "\n<i>#{now.strftime('%H:%M:%S %d-%m-%Y')}</i>",
119
+ "\n<i>#{now.strftime('%z')} #{ENV['TZ']}</i>"
120
+ ]
121
+
122
+ formatted_message.insert(3, "<i>#{message}</i>") unless message.nil?
123
+
124
+ return formatted_message.join("\n")
125
+ end
126
+
127
+ end
128
+ end
@@ -0,0 +1,4 @@
1
+ module TelegramAlerts
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
@@ -0,0 +1,32 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+
5
+ require_relative 'lib/telegram_alerts/version'
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = 'telegram_alerts'
9
+ spec.version = TelegramAlerts::VERSION
10
+ spec.authors = ['mikael']
11
+ spec.email = ['mikael.santilio@gmail.com']
12
+
13
+ spec.summary = 'Telegram Alerts'
14
+ spec.description = 'A Ruby gem that allows you to receive notifications about exceptions and alerts in your Ruby applications through Telegram.'
15
+ spec.homepage = 'https://github.com/MikaelSantilio/telegram_alerts'
16
+ spec.required_ruby_version = Gem::Requirement.new('>= 2.5.0')
17
+
18
+ spec.metadata['allowed_push_host'] = 'https://rubygems.org'
19
+
20
+ spec.metadata['homepage_uri'] = spec.homepage
21
+ spec.metadata['source_code_uri'] = 'https://github.com/MikaelSantilio/telegram_alerts'
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
26
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
27
+ end
28
+ spec.bindir = 'exe'
29
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
30
+ spec.require_paths = ['lib']
31
+
32
+ end
metadata ADDED
@@ -0,0 +1,59 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: telegram_alerts
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - mikael
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-02-04 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: A Ruby gem that allows you to receive notifications about exceptions
14
+ and alerts in your Ruby applications through Telegram.
15
+ email:
16
+ - mikael.santilio@gmail.com
17
+ executables: []
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - ".gitignore"
22
+ - ".rspec"
23
+ - Gemfile
24
+ - LICENSE.txt
25
+ - README.md
26
+ - Rakefile
27
+ - bin/console
28
+ - bin/setup
29
+ - lib/telegram_alerts.rb
30
+ - lib/telegram_alerts/version.rb
31
+ - sig/telegram_alerts.rbs
32
+ - telegram_alerts.gemspec
33
+ homepage: https://github.com/MikaelSantilio/telegram_alerts
34
+ licenses: []
35
+ metadata:
36
+ allowed_push_host: https://rubygems.org
37
+ homepage_uri: https://github.com/MikaelSantilio/telegram_alerts
38
+ source_code_uri: https://github.com/MikaelSantilio/telegram_alerts
39
+ post_install_message:
40
+ rdoc_options: []
41
+ require_paths:
42
+ - lib
43
+ required_ruby_version: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: 2.5.0
48
+ required_rubygems_version: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - ">="
51
+ - !ruby/object:Gem::Version
52
+ version: '0'
53
+ requirements: []
54
+ rubyforge_project:
55
+ rubygems_version: 2.7.6
56
+ signing_key:
57
+ specification_version: 4
58
+ summary: Telegram Alerts
59
+ test_files: []