telegram-support-bot 0.1.03

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: 8d61645170c11693b5022efec80d4a7e439ab8378c377ed010d121c0429518be
4
+ data.tar.gz: 565dc25a57ed67dbd428c79b8e08bc7682a537d9ba467f918f646ff03db412a2
5
+ SHA512:
6
+ metadata.gz: d17862439a4fb473284529a3420e69e47ab114418b4b166bdb77bcef4dbc578e25b1fbe768f87c3e9c53be566145221322c04e4eee2b4c83d26d2fb5b458c8b3
7
+ data.tar.gz: 296405e4807e520564eb679086343c8b1f45e95c1148911b37a9a16157e8a6333f71e949912ac1b4568e62d6fc2f4a302212fa0b4d9b9a1268e1d56e1fa52a69
@@ -0,0 +1,151 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="AutoImportSettings">
4
+ <option name="autoReloadType" value="SELECTIVE" />
5
+ </component>
6
+ <component name="ChangeListManager">
7
+ <list default="true" id="edf498b0-8552-42f1-846d-0c79d29ff991" name="Changes" comment="">
8
+ <change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
9
+ <change beforePath="$PROJECT_DIR$/Gemfile" beforeDir="false" afterPath="$PROJECT_DIR$/Gemfile" afterDir="false" />
10
+ <change beforePath="$PROJECT_DIR$/lib/telegram_support_bot/adapters/telegram_bot_adapter.rb" beforeDir="false" afterPath="$PROJECT_DIR$/lib/telegram_support_bot/adapters/telegram_bot_adapter.rb" afterDir="false" />
11
+ <change beforePath="$PROJECT_DIR$/spec/telegram_support_bot/adapters/telegram_bot_adapter_spec.rb" beforeDir="false" afterPath="$PROJECT_DIR$/spec/telegram_support_bot/adapters/telegram_bot_adapter_spec.rb" afterDir="false" />
12
+ </list>
13
+ <option name="SHOW_DIALOG" value="false" />
14
+ <option name="HIGHLIGHT_CONFLICTS" value="true" />
15
+ <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
16
+ <option name="LAST_RESOLUTION" value="IGNORE" />
17
+ </component>
18
+ <component name="FileTemplateManagerImpl">
19
+ <option name="RECENT_TEMPLATES">
20
+ <list>
21
+ <option value="Minitest Spec" />
22
+ </list>
23
+ </option>
24
+ </component>
25
+ <component name="Git.Settings">
26
+ <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
27
+ </component>
28
+ <component name="MarkdownSettingsMigration">
29
+ <option name="stateVersion" value="1" />
30
+ </component>
31
+ <component name="ProjectColorInfo">{
32
+ &quot;associatedIndex&quot;: 4
33
+ }</component>
34
+ <component name="ProjectId" id="2ciiVgDyGIIwTjG6xCPIunFNdqZ" />
35
+ <component name="ProjectLevelVcsManager">
36
+ <ConfirmationsSetting value="2" id="Add" />
37
+ </component>
38
+ <component name="ProjectViewState">
39
+ <option name="hideEmptyMiddlePackages" value="true" />
40
+ <option name="showLibraryContents" value="true" />
41
+ </component>
42
+ <component name="PropertiesComponent"><![CDATA[{
43
+ "keyToString": {
44
+ "DefaultRubyCreateTestTemplate": "Minitest Spec",
45
+ "RSpec.Unnamed.executor": "Run",
46
+ "Ruby.scratch_61.executor": "Run",
47
+ "RunOnceActivity.OpenProjectViewOnStart": "true",
48
+ "RunOnceActivity.ShowReadmeOnStart": "true",
49
+ "git-widget-placeholder": "main",
50
+ "last_opened_file_path": "/home/max/code/gems/telegram_support_bot",
51
+ "node.js.detected.package.eslint": "true",
52
+ "node.js.detected.package.tslint": "true",
53
+ "node.js.selected.package.eslint": "(autodetect)",
54
+ "node.js.selected.package.tslint": "(autodetect)",
55
+ "nodejs_package_manager_path": "npm",
56
+ "ruby.structure.view.model.defaults.configured": "true",
57
+ "settings.editor.selected.configurable": "org.jetbrains.plugins.ruby.settings.RubyActiveModuleSdkConfigurable",
58
+ "vue.rearranger.settings.migration": "true"
59
+ },
60
+ "keyToStringList": {
61
+ "com.intellij.ide.scratch.ScratchImplUtil$2/New Scratch File": [
62
+ "ruby"
63
+ ]
64
+ }
65
+ }]]></component>
66
+ <component name="RecentsManager">
67
+ <key name="CopyFile.RECENT_KEYS">
68
+ <recent name="$PROJECT_DIR$/spec/telegram_support_bot/adapters" />
69
+ <recent name="$PROJECT_DIR$/spec/support" />
70
+ <recent name="$PROJECT_DIR$/spec" />
71
+ <recent name="$PROJECT_DIR$/lib/telegram_support_bot" />
72
+ <recent name="$PROJECT_DIR$/lib/telegram_support_bot/adapters" />
73
+ </key>
74
+ </component>
75
+ <component name="RunManager" selected="Ruby.scratch_61">
76
+ <configuration name="Unnamed" type="RSpecRunConfigurationType" factoryName="RSpec" nameIsGenerated="true">
77
+ <module name="telegram_support_bot" />
78
+ <predefined_log_file enabled="true" id="RUBY_RSPEC" />
79
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="RUBY_ARGS" VALUE="" />
80
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="WORK DIR" VALUE="" />
81
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="SHOULD_USE_SDK" VALUE="false" />
82
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="ALTERN_SDK_NAME" VALUE="" />
83
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="myPassParentEnvs" VALUE="true" />
84
+ <EXTENSION ID="BundlerRunConfigurationExtension" BUNDLE_MODE="AUTO" bundleExecEnabled="true" />
85
+ <EXTENSION ID="RubyCoverageRunConfigurationExtension" track_test_folders="true" runner="rcov" ENABLE_BRANCH_COVERAGE="true" ENABLE_FORKED_COVERAGE="true">
86
+ <COVERAGE_PATTERN ENABLED="true">
87
+ <PATTERN REGEXPS="/.rvm/" INCLUDED="false" />
88
+ </COVERAGE_PATTERN>
89
+ </EXTENSION>
90
+ <EXTENSION ID="org.jetbrains.plugins.ruby.rails.run.RailsRunConfigurationExtension" SCRATCH_USE_RAILS_RUNNER="false" />
91
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="TESTS_FOLDER_PATH" VALUE="$MODULE_DIR$/spec" />
92
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="TEST_SCRIPT_PATH" VALUE="" />
93
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="TEST_SCRIPT_PATHS" VALUE="" />
94
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="SPEC_RUNNER_PATH" VALUE="" />
95
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="TEST_FILE_MASK" VALUE="**/*_spec.rb" />
96
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="SPEC_EXAMPLE_NAME" VALUE="" />
97
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="USE_EXAMPLE_MATCHES" VALUE="false" />
98
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="LINE_NUMBER_EXAMPLE_IDS" VALUE="" />
99
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="TEST_TEST_TYPE" VALUE="ALL_IN_FOLDER" />
100
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="SPEC_ARGS" VALUE="" />
101
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="RUNNER_VERSION" VALUE="" />
102
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="USE_CUSTOM_SPEC_RUNNER" VALUE="false" />
103
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="DRB" VALUE="false" />
104
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="ZEUS" VALUE="false" />
105
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="SPRING" VALUE="false" />
106
+ <RSPEC_RUN_CONFIG_SETTINGS_ID NAME="FULL_BACKTRACE" VALUE="false" />
107
+ <method v="2" />
108
+ </configuration>
109
+ <configuration name="scratch_61" type="RubyRunConfigurationType" factoryName="Ruby" temporary="true">
110
+ <RUBY_RUN_CONFIG NAME="RUBY_ARGS" VALUE="" />
111
+ <RUBY_RUN_CONFIG NAME="WORK DIR" VALUE="$PROJECT_DIR$" />
112
+ <RUBY_RUN_CONFIG NAME="SHOULD_USE_SDK" VALUE="false" />
113
+ <RUBY_RUN_CONFIG NAME="ALTERN_SDK_NAME" VALUE="" />
114
+ <RUBY_RUN_CONFIG NAME="myPassParentEnvs" VALUE="true" />
115
+ <EXTENSION ID="BundlerRunConfigurationExtension" BUNDLE_MODE="AUTO" bundleExecEnabled="true" />
116
+ <EXTENSION ID="org.jetbrains.plugins.ruby.rails.run.RailsRunConfigurationExtension" SCRATCH_USE_RAILS_RUNNER="false" />
117
+ <RUBY_RUN_CONFIG NAME="SCRIPT_PATH" VALUE="$APPLICATION_CONFIG_DIR$/scratches/scratch_61.rb" />
118
+ <RUBY_RUN_CONFIG NAME="SCRIPT_ARGS" VALUE="" />
119
+ <method v="2" />
120
+ </configuration>
121
+ <list>
122
+ <item itemvalue="RSpec.Unnamed" />
123
+ <item itemvalue="Ruby.scratch_61" />
124
+ </list>
125
+ <recent_temporary>
126
+ <list>
127
+ <item itemvalue="Ruby.scratch_61" />
128
+ </list>
129
+ </recent_temporary>
130
+ </component>
131
+ <component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
132
+ <component name="SpringUtil" SPRING_PRE_LOADER_OPTION="true" RAKE_SPRING_PRE_LOADER_OPTION="true" RAILS_SPRING_PRE_LOADER_OPTION="true" />
133
+ <component name="TaskManager">
134
+ <task active="true" id="Default" summary="Default task">
135
+ <changelist id="edf498b0-8552-42f1-846d-0c79d29ff991" name="Changes" comment="" />
136
+ <created>1708600824931</created>
137
+ <option name="number" value="Default" />
138
+ <option name="presentableId" value="Default" />
139
+ <updated>1708600824931</updated>
140
+ <workItem from="1708600827139" duration="10157000" />
141
+ <workItem from="1708784534887" duration="682000" />
142
+ </task>
143
+ <servers />
144
+ </component>
145
+ <component name="TypeScriptGeneratedFilesManager">
146
+ <option name="version" value="3" />
147
+ </component>
148
+ <component name="com.intellij.coverage.CoverageDataManagerImpl">
149
+ <SUITE FILE_PATH="coverage/telegram_support_bot@Unnamed.rcov" NAME="Unnamed Coverage Results" MODIFIED="1708610177774" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="rcov" COVERAGE_BY_TEST_ENABLED="true" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="" MODULE_NAME="telegram_support_bot" />
150
+ </component>
151
+ </project>
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at max@buslaev.net. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in telegram-support-bot.gemspec
6
+ gemspec
7
+
8
+ group :development, :test do
9
+ gem "rake", "~> 13.0"
10
+ gem "rspec", "~> 3.0"
11
+ gem 'pry'
12
+ gem 'amazing_print'
13
+ gem 'telegram-bot'
14
+ gem 'telegram-bot-types'
15
+ # gem 'telegram-bot-ruby'
16
+ end
17
+
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Max Buslaev
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,60 @@
1
+ # TelegramSupportBot
2
+
3
+ ## Introduction
4
+ `TelegramSupportBot` is a Ruby gem designed to enhance customer support through Telegram, allowing for the management of queries directly from a designated chat while ensuring privacy and confidentiality.
5
+
6
+ ## Features
7
+ - Forward messages between users and a support chat
8
+ - Supports various message types (text, images, videos, documents, audio, stickers)
9
+ - Auto-away messages for off-hours
10
+ - Simple configuration and deployment
11
+
12
+ ## Installation
13
+ Add to your Gemfile:
14
+ ```ruby
15
+ gem 'telegram-support-bot'
16
+ ```
17
+
18
+ ## Usage
19
+ ### Webhook Integration
20
+
21
+ #### Creating and Configuring Your Bot
22
+ 1. **Create Your Bot** via BotFather on Telegram to get your bot token.
23
+ 2. **Deploy Your Application** and set up a controller action for webhook callbacks, directing them to `TelegramSupportBot.process_update`.
24
+ 3. **Set the Webhook URL** using the Telegram Bot API to your controller action.
25
+
26
+ #### Setting Up Your Telegram Bot
27
+ 1. **Add Your Bot to a Support Chat** and obtain the `support_chat_id` by sending the `/start` command to the bot inside the support chat.
28
+ 2. **Configure Your Bot** in your Ruby application with the token and `support_chat_id`, and set a welcome message.
29
+
30
+ ```ruby
31
+ TelegramSupportBot.configure do |config|
32
+ config.adapter = :telegram_bot
33
+ config.adapter_options = { token: 'YOUR_TELEGRAM_BOT_TOKEN' }
34
+ config.support_chat_id = 'YOUR_SUPPORT_CHAT_ID'
35
+ config.welcome_message = 'Hi! How can we help you?'
36
+ end
37
+ ```
38
+
39
+ 3. **Interact with Users**: Messages to your bot will be forwarded to the support chat, and replies in the chat will be sent back to the users.
40
+
41
+ ### Adapters
42
+ `TelegramSupportBot` supports integration through adapters. Currently, `telegram-bot` is supported with plans to add `telegram-bot-ruby`.
43
+
44
+ #### Custom Adapter Implementation
45
+ Implement custom adapters by inheriting from `TelegramSupportBot::Adapter::Base` and defining message sending and forwarding methods.
46
+
47
+ ## Development
48
+ - Run `bin/setup` to install dependencies.
49
+ - Use `rake spec` for tests and `bin/console` for an interactive prompt.
50
+ - To install locally, use `bundle exec rake install`.
51
+ - For releases, update `version.rb`, and run `bundle exec rake release`.
52
+
53
+ ## Contributing
54
+ Contributions are welcome via GitHub, adhering to the [code of conduct](https://github.com/austerlitz/telegram_support_bot/blob/main/CODE_OF_CONDUCT.md).
55
+
56
+ ## License
57
+ Available under the [MIT License](https://opensource.org/licenses/MIT).
58
+
59
+ ## Code of Conduct
60
+ Follow the project's [code of conduct](https://github.com/austerlitz/telegram_support_bot/blob/main/CODE_OF_CONDUCT.md).
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
@@ -0,0 +1,22 @@
1
+ # lib/telegram_support_bot/adapter_factory.rb
2
+ module TelegramSupportBot
3
+ module AdapterFactory
4
+ ADAPTERS = {
5
+ telegram_bot: 'TelegramSupportBot::Adapters::TelegramBot',
6
+ telegram_bot_ruby: 'TelegramSupportBot::Adapters::TelegramBotRuby'
7
+ # Add more predefined adapters here
8
+ }.freeze
9
+
10
+ def self.build(adapter_specification, adapter_options = {})
11
+ case adapter_specification
12
+ when Symbol
13
+ adapter_class = ADAPTERS[adapter_specification].constantize
14
+ adapter_class.new(adapter_options)
15
+ when Class
16
+ adapter_specification.new(adapter_options)
17
+ else
18
+ raise ArgumentError, "Unsupported adapter specification: #{adapter_specification}"
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TelegramSupportBot
4
+ module Adapters
5
+ class Base
6
+ attr_reader :bot
7
+
8
+ def initialize(**options)
9
+ @options = options
10
+ setup(options)
11
+ end
12
+
13
+ def setup(options)
14
+ # Setup based on options, to be overridden by child classes if necessary
15
+ end
16
+
17
+ def send_message(chat_id:, text:)
18
+ # Implementation using the telegram-bot gem
19
+ end
20
+
21
+ def send_media(chat_id:, type:, media:, **options)
22
+ # send photos, videos, documents
23
+ end
24
+
25
+ def forward_message(from_chat_id:, chat_id:, message_id:)
26
+ # forward messages to the support chat
27
+ end
28
+
29
+ def on_message(&block)
30
+ # Implementation to register a block to be called on new messages
31
+ end
32
+ end
33
+ end
34
+ end
35
+
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TelegramSupportBot
4
+ module Adapters
5
+ class TelegramBot < Base
6
+
7
+ def initialize(**options)
8
+ super
9
+ @bot = Telegram::Bot::Client.new(@options[:token], @options[:username])
10
+ end
11
+
12
+ def send_message(chat_id:, text:, **options)
13
+ @bot.send_message(chat_id: chat_id, text: text, **options)
14
+ end
15
+
16
+ def send_photo(chat_id:, photo:, **options)
17
+ @bot.send_photo(chat_id: chat_id, photo: photo, **options)
18
+ end
19
+
20
+ def send_video(chat_id:, video:, **options)
21
+ @bot.send_video(chat_id: chat_id, video: video, **options)
22
+ end
23
+
24
+ def send_document(chat_id:, document:, **options)
25
+ @bot.send_document(chat_id: chat_id, document: document, **options)
26
+ end
27
+
28
+ # Handles sending audio messages
29
+ def send_audio(chat_id:, audio:, **options)
30
+ @bot.send_audio(chat_id: chat_id, audio: audio, **options)
31
+ end
32
+ # Handles sending audio messages
33
+ def send_voice(chat_id:, voice:, **options)
34
+ @bot.send_voice(chat_id: chat_id, voice: voice, **options)
35
+ end
36
+
37
+ # Handles sending sticker messages
38
+ def send_sticker(chat_id:, sticker:, **options)
39
+ @bot.send_sticker(chat_id: chat_id, sticker: sticker, **options)
40
+ end
41
+
42
+ # New generic send_media method
43
+ def send_media(chat_id:, type:, media:, **options)
44
+ case type.to_sym
45
+ when :text
46
+ send_message(chat_id: chat_id, text: media, **options)
47
+ when :photo
48
+ send_photo(chat_id: chat_id, photo: media, **options)
49
+ when :video
50
+ send_video(chat_id: chat_id, video: media, **options)
51
+ when :video_note
52
+ send_video_note(chat_id: chat_id, video_note: media, **options)
53
+ when :document
54
+ send_document(chat_id: chat_id, document: media, **options)
55
+ when :audio
56
+ send_audio(chat_id: chat_id, audio: media, **options)
57
+ when :voice
58
+ send_voice(chat_id: chat_id, voice: media, **options)
59
+ when :sticker
60
+ send_sticker(chat_id: chat_id, sticker: media, **options)
61
+ else
62
+ raise ArgumentError, "Unsupported media type: #{type}"
63
+ end
64
+ end
65
+
66
+ def forward_message(from_chat_id:, chat_id:, message_id:)
67
+ @bot.forward_message(
68
+ chat_id: chat_id,
69
+ from_chat_id: from_chat_id,
70
+ message_id: message_id
71
+ )
72
+ end
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TelegramSupportBot
4
+ module Adapters
5
+ class TelegramBotRuby
6
+ end
7
+ end
8
+ end
@@ -0,0 +1,54 @@
1
+ module TelegramSupportBot
2
+ class AutoAwayScheduler
3
+ def initialize(adapter, configuration)
4
+ @adapter = adapter
5
+ @configuration = configuration
6
+ @scheduled_tasks = {}
7
+ end
8
+
9
+ def schedule_auto_away_message(user_message_id, chat_id)
10
+ # Cancel any existing scheduled task for this message to avoid duplicate messages
11
+ cancel_scheduled_task(user_message_id)
12
+
13
+ # Only proceed if auto-away is configured
14
+ auto_away_interval = @configuration.auto_away_interval || 60
15
+
16
+ # Immediately store the thread object in the hash to mark this message ID as scheduled
17
+ @scheduled_tasks[user_message_id] = Thread.new do
18
+ sleep(auto_away_interval) # Wait for the specified interval
19
+
20
+ # After waking up, check if the task is still relevant
21
+ if @scheduled_tasks[user_message_id]
22
+ send_auto_away_message(chat_id)
23
+ notify_support_chat
24
+
25
+ # Once the auto-away message has been sent, remove this task from the schedule
26
+ @scheduled_tasks.delete(user_message_id)
27
+ end
28
+ end
29
+ end
30
+
31
+
32
+ def cancel_scheduled_task(user_message_id)
33
+ if task = @scheduled_tasks[user_message_id]
34
+ task.kill # Terminate the scheduled thread
35
+ @scheduled_tasks.delete(user_message_id)
36
+ end
37
+ end
38
+
39
+ private
40
+
41
+ def send_auto_away_message(chat_id)
42
+ auto_away_message = @configuration.auto_away_message
43
+ @adapter.send_message(chat_id: chat_id, text: auto_away_message)
44
+ end
45
+
46
+ def notify_support_chat
47
+ @adapter.send_message(
48
+ chat_id: @configuration.support_chat_id,
49
+ text: 'Auto-away message has been sent to user: "'+@configuration.auto_away_message+'"',
50
+ )
51
+
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TelegramSupportBot
4
+ class Configuration
5
+ attr_accessor :adapter, :adapter_options, :support_chat_id, :welcome_message,
6
+ :auto_away_message, :auto_away_interval
7
+
8
+ def initialize
9
+ @adapter = :telegram_bot
10
+ @adapter_options = {}
11
+ @welcome_message = 'Welcome! How can we help you?'
12
+ @auto_away_interval = 10 # seconds
13
+ @auto_away_message = 'We are sorry, all operators are busy at the moment. Please wait'
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TelegramSupportBot
4
+ VERSION = "0.1.03"
5
+ end
@@ -0,0 +1,185 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "telegram_support_bot/version"
4
+ require_relative 'telegram_support_bot/configuration'
5
+ require_relative 'telegram_support_bot/auto_away_scheduler'
6
+ require_relative 'telegram_support_bot/adapter_factory'
7
+ require_relative 'telegram_support_bot/adapters/base'
8
+ require_relative 'telegram_support_bot/adapters/telegram_bot'
9
+ require_relative 'telegram_support_bot/adapters/telegram_bot_ruby'
10
+
11
+ module TelegramSupportBot
12
+ class << self
13
+ attr_accessor :configuration
14
+ attr_reader :message_chat_id
15
+
16
+ # Provides a method to configure the gem.
17
+ def configure
18
+ self.configuration ||= Configuration.new
19
+ yield(configuration) if block_given?
20
+ end
21
+
22
+ # Lazily builds and returns the adapter based on the current configuration.
23
+ # This method initializes the adapter when it's first called.
24
+ def adapter
25
+ @adapter ||= AdapterFactory.build(configuration.adapter, configuration.adapter_options)
26
+ end
27
+
28
+ def scheduler
29
+ @scheduler ||= AutoAwayScheduler.new(adapter, configuration)
30
+ end
31
+
32
+ def process_update(update)
33
+ # Handle different types of updates
34
+ if update['message']
35
+ # Process standard messages
36
+ process_message(update['message'])
37
+ elsif update['my_chat_member']
38
+ # Handle the bot being added to or removed from a chat
39
+ handle_my_chat_member_update(update['my_chat_member'])
40
+ # Add other update types as needed
41
+ else
42
+ # Log or handle unknown update types
43
+ puts "Received an unknown type of update: #{update}"
44
+ end
45
+ end
46
+
47
+ private
48
+
49
+ def process_message(message)
50
+ @message_chat_id = message['chat']['id']
51
+ ap message
52
+
53
+ if message_chat_id == configuration.support_chat_id
54
+ process_support_chat_message(message)
55
+ else
56
+ # Message is from an individual user, forward it to the support chat
57
+ if message['text'] == '/start'
58
+ # Send welcome message to the user
59
+ adapter.send_message(chat_id: message_chat_id, text: configuration.welcome_message)
60
+ else
61
+ forward_message_to_support_chat(message)
62
+ end
63
+ end
64
+ end
65
+
66
+ def process_support_chat_message(message)
67
+ if message.key?('reply_to_message')
68
+ # It's a reply in the support chat
69
+ process_reply_in_support_chat(message)
70
+ elsif message['text']&.start_with?('/')
71
+ process_command(message)
72
+ else
73
+ # For non-command messages, you might want to handle differently or just ignore
74
+ # For now, let's just acknowledge the message
75
+ acknowledge_non_command_message(message)
76
+ end
77
+ end
78
+
79
+ def acknowledge_non_command_message(message)
80
+ reply_message = 'I received your message, but I only respond to commands. Please use /start to get started.'
81
+ adapter.send_message(
82
+ chat_id: message_chat_id,
83
+ text: reply_message,
84
+ reply_to_message_id: message['message_id']
85
+ )
86
+ end
87
+
88
+ def process_command(message)
89
+ command = message['text'].split(/[ \@]/).first.downcase # Extract the command, normalize to lowercase
90
+
91
+ case command
92
+ when '/start'
93
+ send_welcome_message(chat_id: message_chat_id)
94
+ else
95
+ # Respond to unknown commands
96
+ unknown_command_response = "I don't know the command #{command}. Please use /start to begin or check the available commands."
97
+ adapter.send_message(chat_id: message_chat_id, text: unknown_command_response)
98
+ end
99
+ end
100
+
101
+ def process_reply_in_support_chat(message)
102
+ reply_to_message = message['reply_to_message']
103
+
104
+ if reply_to_message.key?('forward_from')
105
+ # The reply is to a forwarded message
106
+ original_user_id = reply_to_message['forward_from']['id']
107
+ caption = message['caption'] if message.key?('caption')
108
+
109
+ # Determine the type of media and prepare the content and options
110
+ type, media, options = extract_media_info(message)
111
+ options[:caption] = caption if caption
112
+
113
+ message_id = message['message_id']
114
+ if :unknown == type
115
+ # Handle other types of messages or default case
116
+ warning_message = "Warning: The message type received from the user is not supported by the bot. Please assist the user directly."
117
+ adapter.send_message(
118
+ chat_id: configuration.support_chat_id,
119
+ text: warning_message,
120
+ reply_to_message_id: message_id
121
+ )
122
+ else
123
+ adapter.send_media(chat_id: original_user_id, type: type, media: media, **options)
124
+ # scheduler.cancel_scheduled_task(message_id)
125
+ end
126
+ end
127
+ end
128
+
129
+ def extract_media_info(message)
130
+ if message.key?('text')
131
+ [:text, message['text'], { entities: message.fetch('entities', []) }]
132
+ elsif message.key?('photo')
133
+ photo = message['photo'].last # Assuming you want to send the highest quality photo
134
+ [:photo, photo['file_id'], {}]
135
+ elsif message.key?('video')
136
+ [:video, message['video']['file_id'], {}]
137
+ elsif message.key?('video_note')
138
+ [:video, message['video_note']['file_id'], {}]
139
+ elsif message.key?('document')
140
+ [:document, message['document']['file_id'], {}]
141
+ elsif message.key?('audio')
142
+ [:audio, message['audio']['file_id'], {
143
+ duration: message['audio'].fetch('duration', 0),
144
+ performer: message['audio'].fetch('performer', ''),
145
+ title: message['audio'].fetch('title', '')
146
+ }]
147
+ elsif message.key?('voice')
148
+ [:voice, message['voice']['file_id'], {}]
149
+ elsif message.key?('sticker')
150
+ [:sticker, message['sticker']['file_id'], {}]
151
+ else
152
+ [:unknown, "This type of message is not supported.", {}]
153
+ end
154
+ end
155
+
156
+ def forward_message_to_support_chat(message)
157
+ message_id = message['message_id']
158
+ adapter.forward_message(
159
+ from_chat_id: message_chat_id,
160
+ message_id: message_id,
161
+ chat_id: configuration.support_chat_id)
162
+ # scheduler.schedule_auto_away_message(message_id, message_chat_id)
163
+ end
164
+
165
+ def handle_my_chat_member_update(update)
166
+ # Check if the bot has been added to the chat
167
+ if update['new_chat_member']
168
+ chat_id = update['chat']['id']
169
+ send_welcome_message(chat_id: chat_id)
170
+ end
171
+ end
172
+
173
+ def send_welcome_message(chat_id:)
174
+ welcome_text = "Hello! Thank you for adding me to your chat. To configure your system, please use the following support chat ID: <code>#{chat_id}</code>."
175
+ adapter.send_message(chat_id: chat_id, text: welcome_text, parse_mode: 'HTML')
176
+ end
177
+
178
+ end
179
+
180
+ # Reset the adapter instance (useful for testing or reconfiguration).
181
+ def self.reset_adapter!
182
+ @adapter = nil
183
+ end
184
+ end
185
+
@@ -0,0 +1,4 @@
1
+ module TelegramSupportBot
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/telegram_support_bot/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'telegram-support-bot'
7
+ spec.version = TelegramSupportBot::VERSION
8
+ spec.authors = ['Max Buslaev']
9
+ spec.email = ['max@buslaev.net']
10
+
11
+ spec.summary = 'A Rails gem for integrating a Telegram bot into your application for seamless
12
+ support desk functionality.'
13
+ spec.description = 'The telegram_support_bot gem provides Rails applications with an
14
+ easy-to-integrate Telegram bot, designed to enhance customer support services.
15
+ By leveraging this gem, developers can swiftly add a Telegram-based support desk to their
16
+ application, enabling direct communication between users and support agents through Telegram.
17
+ Features include automatic message forwarding to a designated secret chat for support agents,
18
+ the ability to reply directly from the secret chat to users, and customizable responses
19
+ for common queries. This gem simplifies the process of setting up a robust support channel on one of
20
+ the most popular messaging platforms, making it an ideal solution for businesses looking to improve
21
+ their customer service experience.'
22
+ spec.homepage = 'https://github.com/austerlitz/telegram_support_bot'
23
+ spec.license = 'MIT'
24
+ # spec.required_ruby_version = '>= 2.6.0'
25
+
26
+ # Specify which files should be added to the gem when it is released.
27
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
28
+ spec.files = Dir.chdir(__dir__) do
29
+ `git ls-files -z`.split("\x0").reject do |f|
30
+ (File.expand_path(f) == __FILE__) || f.start_with?(*%w[bin/ test/ spec/ features/ .git .circleci appveyor])
31
+ end
32
+ end
33
+ spec.bindir = 'exe'
34
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
35
+ spec.require_paths = ['lib']
36
+
37
+ end
metadata ADDED
@@ -0,0 +1,70 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: telegram-support-bot
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.03
5
+ platform: ruby
6
+ authors:
7
+ - Max Buslaev
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-02-25 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: |-
14
+ The telegram_support_bot gem provides Rails applications with an
15
+ easy-to-integrate Telegram bot, designed to enhance customer support services.
16
+ By leveraging this gem, developers can swiftly add a Telegram-based support desk to their
17
+ application, enabling direct communication between users and support agents through Telegram.
18
+ Features include automatic message forwarding to a designated secret chat for support agents,
19
+ the ability to reply directly from the secret chat to users, and customizable responses
20
+ for common queries. This gem simplifies the process of setting up a robust support channel on one of
21
+ the most popular messaging platforms, making it an ideal solution for businesses looking to improve
22
+ their customer service experience.
23
+ email:
24
+ - max@buslaev.net
25
+ executables: []
26
+ extensions: []
27
+ extra_rdoc_files: []
28
+ files:
29
+ - ".idea/workspace.xml"
30
+ - ".rspec"
31
+ - CODE_OF_CONDUCT.md
32
+ - Gemfile
33
+ - LICENSE.txt
34
+ - README.md
35
+ - Rakefile
36
+ - lib/telegram_support_bot.rb
37
+ - lib/telegram_support_bot/adapter_factory.rb
38
+ - lib/telegram_support_bot/adapters/base.rb
39
+ - lib/telegram_support_bot/adapters/telegram_bot.rb
40
+ - lib/telegram_support_bot/adapters/telegram_bot_ruby.rb
41
+ - lib/telegram_support_bot/auto_away_scheduler.rb
42
+ - lib/telegram_support_bot/configuration.rb
43
+ - lib/telegram_support_bot/version.rb
44
+ - sig/telegram_support_bot.rbs
45
+ - telegram_support_bot.gemspec
46
+ homepage: https://github.com/austerlitz/telegram_support_bot
47
+ licenses:
48
+ - MIT
49
+ metadata: {}
50
+ post_install_message:
51
+ rdoc_options: []
52
+ require_paths:
53
+ - lib
54
+ required_ruby_version: !ruby/object:Gem::Requirement
55
+ requirements:
56
+ - - ">="
57
+ - !ruby/object:Gem::Version
58
+ version: '0'
59
+ required_rubygems_version: !ruby/object:Gem::Requirement
60
+ requirements:
61
+ - - ">="
62
+ - !ruby/object:Gem::Version
63
+ version: '0'
64
+ requirements: []
65
+ rubygems_version: 3.2.3
66
+ signing_key:
67
+ specification_version: 4
68
+ summary: A Rails gem for integrating a Telegram bot into your application for seamless
69
+ support desk functionality.
70
+ test_files: []