eureka-bot-tg 2.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 15887bf0b1d071d0f3d45823f0b20ee3469e538a
4
+ data.tar.gz: 53a4fca61b46ba09d7de5789505811951b3b3208
5
+ SHA512:
6
+ metadata.gz: 81afa83566d24732de51325525c63a4f152daf557ffe88fc158541f33c4882fbf599a3b0d58426a73036155d61a3579f7dba01191230117c47a64b123fee58e6
7
+ data.tar.gz: 33370cdf42624476e524d4b976a2874ec3bae99445788cf0d6bca4060ba64f57ff0e39ad458979c03a67cddc45538dc23f77843142ef303c067a3f45d370001e
data/.gitignore ADDED
@@ -0,0 +1,33 @@
1
+ /.bundle
2
+
3
+ /.yardoc
4
+ /_yardoc/
5
+ /coverage/
6
+ /pkg/
7
+
8
+ # Ignore all logfiles and tempfiles.
9
+ /log/*
10
+ /tmp/*
11
+ !/log/.keep
12
+ !/tmp/.keep
13
+ mkmf.log
14
+
15
+ nbproject
16
+ .idea
17
+ *~
18
+
19
+ *.swp
20
+ *.swap
21
+ *.bundle
22
+ *.so
23
+ *.o
24
+ *.a
25
+
26
+ .vagrant
27
+ .ruby-env
28
+ .DS_Store
29
+ Vagrantfile
30
+ Gemfile.lock
31
+ spec/config.yml
32
+ /examples/_tg.txt
33
+ /eureka-bot-tg*.gem
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
@@ -0,0 +1,49 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, and in the interest of
4
+ fostering an open and welcoming community, we pledge to respect all people who
5
+ contribute through reporting issues, posting feature requests, updating
6
+ documentation, submitting pull requests or patches, and other activities.
7
+
8
+ We are committed to making participation in this project a harassment-free
9
+ experience for everyone, regardless of level of experience, gender, gender
10
+ identity and expression, sexual orientation, disability, personal appearance,
11
+ body size, race, ethnicity, age, religion, or nationality.
12
+
13
+ Examples of unacceptable behavior by participants include:
14
+
15
+ * The use of sexualized language or imagery
16
+ * Personal attacks
17
+ * Trolling or insulting/derogatory comments
18
+ * Public or private harassment
19
+ * Publishing other's private information, such as physical or electronic
20
+ addresses, without explicit permission
21
+ * Other unethical or unprofessional conduct
22
+
23
+ Project maintainers have the right and responsibility to remove, edit, or
24
+ reject comments, commits, code, wiki edits, issues, and other contributions
25
+ that are not aligned to this Code of Conduct, or to ban temporarily or
26
+ permanently any contributor for other behaviors that they deem inappropriate,
27
+ threatening, offensive, or harmful.
28
+
29
+ By adopting this Code of Conduct, project maintainers commit themselves to
30
+ fairly and consistently applying these principles to every aspect of managing
31
+ this project. Project maintainers who do not follow or enforce the Code of
32
+ Conduct may be permanently removed from the project team.
33
+
34
+ This code of conduct applies both within project spaces and in public spaces
35
+ when an individual is representing the project or its community.
36
+
37
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
38
+ reported by contacting a project maintainer at dizeru@gmail.com. All
39
+ complaints will be reviewed and investigated and will result in a response that
40
+ is deemed necessary and appropriate to the circumstances. Maintainers are
41
+ obligated to maintain confidentiality with regard to the reporter of an
42
+ incident.
43
+
44
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
45
+ version 1.3.0, available at
46
+ [http://contributor-covenant.org/version/1/3/0/][version]
47
+
48
+ [homepage]: http://contributor-covenant.org
49
+ [version]: http://contributor-covenant.org/version/1/3/0/
data/Gemfile ADDED
@@ -0,0 +1,2 @@
1
+ source 'https://rubygems.org'
2
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 dizer
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,69 @@
1
+ # Eureka Bot telegram adapter
2
+
3
+ ```ruby
4
+ # Telegram Echo server
5
+
6
+ require 'eureka-bot'
7
+
8
+ class TgController::CommandsController < TgController
9
+ def start
10
+ answer(
11
+ method: 'sendMessage',
12
+ params: {
13
+ text: 'Hi! Please send me _some_ message',
14
+ parse_mode: 'Markdown',
15
+ }
16
+ )
17
+ end
18
+
19
+ def help
20
+ answer(
21
+ method: 'sendMessage',
22
+ params: {
23
+ text: 'Just send message'
24
+ }
25
+ )
26
+ end
27
+ end
28
+
29
+ class TgController::TextController < TgController
30
+ def text
31
+ answer(
32
+ method: 'sendMessage',
33
+ params: {
34
+ text: message.dig('message', 'text'),
35
+ }
36
+ )
37
+ end
38
+ end
39
+ ```
40
+
41
+ ## Installation
42
+
43
+ Add this line to your application's Gemfile:
44
+
45
+ ```ruby
46
+ gem 'eureka-bot-tg'
47
+ ```
48
+
49
+ And then execute:
50
+
51
+ $ bundle
52
+
53
+ Or install it yourself as:
54
+
55
+ $ gem install eureka-bot-tg
56
+
57
+ ## Usage
58
+
59
+ Please check examples directory
60
+
61
+ ## Contributing
62
+
63
+ Bug reports and pull requests are welcome on GitHub at https://github.com/dizer/eureka-bot-tg. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
64
+
65
+
66
+ ## License
67
+
68
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
69
+
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "eureka/bot/tg"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
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,36 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'eureka_bot/tg/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "eureka-bot-tg"
8
+ spec.version = EurekaBot::Tg::VERSION
9
+ spec.authors = ["dizer"]
10
+ spec.email = ["dizeru@gmail.com"]
11
+
12
+ spec.summary = %q{Run your messenger bots}
13
+ spec.homepage = ""
14
+ spec.license = "MIT"
15
+
16
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
17
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
18
+ if spec.respond_to?(:metadata)
19
+ # spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
20
+ else
21
+ raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
22
+ end
23
+
24
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
25
+ spec.bindir = "exe"
26
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
27
+ spec.require_paths = ["lib"]
28
+
29
+ spec.add_dependency 'activesupport', '>= 5.0.0'
30
+ spec.add_dependency 'rest-client', '>= 2.0'
31
+ spec.add_dependency 'eureka-bot', '>= 1.0'
32
+
33
+ spec.add_development_dependency 'rspec', '~> 3.6.0'
34
+ spec.add_development_dependency 'factory_girl'
35
+ spec.add_development_dependency 'webmock'
36
+ end
@@ -0,0 +1,18 @@
1
+ require 'rubygems'
2
+ require 'bundler'
3
+ Bundler.setup(:default)
4
+ require 'eureka-bot'
5
+ require_relative "../lib/eureka_bot/tg"
6
+
7
+ $tg_token = nil
8
+
9
+ path = File.dirname(__FILE__) + '/_tg.txt'
10
+
11
+ if File.exists?(path)
12
+ $tg_token = File.read(path).strip
13
+ else
14
+ raise 'Please create examples/_tg.txt file with Telegram bot token.'
15
+ end
16
+
17
+ EurekaBot.logger = Logger.new(STDOUT)
18
+ EurekaBot::Tg.client = EurekaBot::Tg::Client.new(token: $tg_token)
data/examples/echo.rb ADDED
@@ -0,0 +1,31 @@
1
+ # Echo server
2
+
3
+ require_relative '_setup'
4
+
5
+ class SampleResolver < EurekaBot::Tg::Resolver
6
+ def controller_namespace
7
+ Controllers
8
+ end
9
+ end
10
+
11
+ class Controllers < EurekaBot::Tg::Controller
12
+ class TextController < Controllers
13
+ def text
14
+ answer(
15
+ method: 'sendMessage',
16
+ params: {
17
+ text: message.dig('message', 'text'),
18
+ }
19
+ )
20
+ end
21
+ end
22
+ end
23
+
24
+ offset = nil
25
+ loop do
26
+ EurekaBot::Tg.client.make_request('getUpdates', payload: {offset: offset}.compact.to_json).each do |update|
27
+ EurekaBot::Job::Input.perform_later(SampleResolver.to_s, update)
28
+ offset = offset ? [offset, update['update_id'] + 1].max : update['update_id'] + 1
29
+ end
30
+ EurekaBot.logger.info '#ping'
31
+ end
@@ -0,0 +1,13 @@
1
+ $:.unshift File.dirname(__FILE__)
2
+
3
+ class FilesBot
4
+ extend ActiveSupport::Autoload
5
+
6
+ autoload :Resolver
7
+ autoload :Controller
8
+ end
9
+
10
+ error_logger = Logger.new(STDERR)
11
+ EurekaBot.add_exception_handler do |e, klass, args|
12
+ error_logger.error(e)
13
+ end
@@ -0,0 +1,7 @@
1
+ class FilesBot::Controller < EurekaBot::Tg::Controller
2
+ extend ActiveSupport::Autoload
3
+
4
+ autoload :CommandsController
5
+ autoload :DocumentsController
6
+ autoload :TextController
7
+ end
@@ -0,0 +1,16 @@
1
+ class FilesBot::Controller::CommandsController < FilesBot::Controller
2
+
3
+ def start
4
+ answer(
5
+ method: 'sendMessage',
6
+ params: {
7
+ text: [
8
+ '*Welcome!*',
9
+ 'Please send me document'
10
+ ].join("\n"),
11
+ parse_mode: 'Markdown',
12
+ }
13
+ )
14
+ end
15
+
16
+ end
@@ -0,0 +1,15 @@
1
+ class FilesBot::Controller::DocumentsController < FilesBot::Controller
2
+
3
+ def document
4
+ caption = message.dig('message', 'caption').presence || params.dig(:document, 'file_name')
5
+ link = client.get_file_url(params.dig(:document, 'file_id'))
6
+ answer(
7
+ method: 'sendMessage',
8
+ params: {
9
+ text: "Download file: [#{caption}](#{link})",
10
+ parse_mode: 'Markdown',
11
+ }
12
+ )
13
+ end
14
+
15
+ end
@@ -0,0 +1,12 @@
1
+ class FilesBot::Controller::TextController < FilesBot::Controller
2
+
3
+ def text
4
+ answer(
5
+ method: 'sendMessage',
6
+ params: {
7
+ text: 'Please send me document'
8
+ }
9
+ )
10
+ end
11
+
12
+ end
@@ -0,0 +1,5 @@
1
+ class FilesBot::Resolver < EurekaBot::Tg::Resolver
2
+ def controller_namespace
3
+ FilesBot::Controller
4
+ end
5
+ end
@@ -0,0 +1,11 @@
1
+ require_relative '../_setup'
2
+ require_relative 'files_bot'
3
+
4
+ offset = nil
5
+ loop do
6
+ EurekaBot::Tg.client.make_request('getUpdates', payload: {offset: offset}.compact.to_json).each do |update|
7
+ EurekaBot::Job::Input.perform_later(FilesBot::Resolver.to_s, update)
8
+ offset = offset ? [offset, update['update_id'] + 1].max : update['update_id'] + 1
9
+ end
10
+ EurekaBot.logger.info '#ping'
11
+ end
@@ -0,0 +1,90 @@
1
+ # SQS requires adapter
2
+
3
+ $sqs = ::Aws::SQS::Client.new(
4
+ region: 'us-east-1',
5
+ credentials: Aws::Credentials.new(
6
+ 'access_key_id',
7
+ 'secret_access_key',
8
+ )
9
+ )
10
+
11
+ class SQSAdapter
12
+ def initialize
13
+ @monitor = Monitor.new
14
+ end
15
+
16
+ def enqueue(job)
17
+ data = {
18
+ queue_url: job.queue_name,
19
+ message_body: ActiveSupport::JSON.encode(job.serialize)
20
+ }
21
+
22
+ order_queue = job.arguments.dig(1, :order_queue).presence
23
+
24
+ # Support of FIFO queues
25
+ if order_queue
26
+ data.merge!(
27
+ message_group_id: order_queue,
28
+ message_deduplication_id: [order_queue, job.arguments.dig(1, :order)].join('-')
29
+ )
30
+ end
31
+ @monitor.synchronize do
32
+ $sqs.send_message(data)
33
+ end
34
+ end
35
+
36
+ def enqueue_at(job, timestamp) #:nodoc:
37
+ raise NotImplementedError, "This queueing backend does not support scheduling jobs. To see what features are supported go to http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters.html"
38
+ end
39
+ end
40
+
41
+ ActiveJob::QueueAdapters::SqsAdapter = SQSAdapter
42
+ EurekaBot::Job.queue_adapter = :sqs
43
+
44
+ # Rake task to listen
45
+ namespace :sqs do
46
+ desc 'run jobs'
47
+ task :run do
48
+ job_class = ENV['JOB_CLASS'].constantize
49
+ poller = Aws::SQS::QueuePoller.new(job_class.queue_name, client: sqs)
50
+ poller.poll(max_number_of_messages: 1, wait_time_seconds: 20) do |msg|
51
+ job_data = ActiveSupport::JSON.decode(msg.body)
52
+ job_class.execute job_data
53
+ end
54
+ end
55
+ end
56
+
57
+ #
58
+ # Bonus: AMQP adapter:
59
+ #
60
+
61
+ $bunny = begin
62
+ bunny = Bunny.new(config['amqp'])
63
+ bunny.start
64
+ bunny
65
+ end
66
+
67
+ $bunny_channel = begin
68
+ bunny.create_channel
69
+ end
70
+
71
+ class AMQPAdapter
72
+ def initialize
73
+ @monitor = Monitor.new
74
+ end
75
+
76
+ def enqueue(job) #:nodoc:
77
+ @monitor.synchronize do
78
+ queue_name = job.queue_name
79
+ exchange = $bunny_channel.default_exchange
80
+ data = ActiveSupport::JSON.encode(job.serialize)
81
+ queue = $bunny_channel.queue(queue_name, durable: true)
82
+ exchange.publish(data, routing_key: queue.name)
83
+ end
84
+ end
85
+
86
+ def enqueue_at(job, timestamp) #:nodoc:
87
+ raise NotImplementedError, "This queueing backend does not support scheduling jobs. To see what features are supported go to http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters.html"
88
+ end
89
+ end
90
+
@@ -0,0 +1,36 @@
1
+ # Replies example
2
+
3
+ require_relative '_setup'
4
+
5
+ class SampleResolver < EurekaBot::Tg::Resolver
6
+ def controller_namespace
7
+ Controllers
8
+ end
9
+ end
10
+
11
+ class Controllers < EurekaBot::Tg::Controller
12
+ class TextController < Controllers
13
+ def text
14
+ answer(
15
+ method: 'sendMessage',
16
+ params: {
17
+ text: message.dig('message', 'text'),
18
+ reply_markup: reply_markup(resize_keyboard: true, one_time_keyboard: true) do
19
+ [
20
+ ['A', 'B', 'C']
21
+ ]
22
+ end.to_json
23
+ }
24
+ )
25
+ end
26
+ end
27
+ end
28
+
29
+ offset = nil
30
+ loop do
31
+ EurekaBot::Tg.client.make_request('getUpdates', payload: {offset: offset}.compact.to_json).each do |update|
32
+ EurekaBot::Job::Input.perform_later(SampleResolver.to_s, update)
33
+ offset = offset ? [offset, update['update_id'] + 1].max : update['update_id'] + 1
34
+ end
35
+ EurekaBot.logger.info '#ping'
36
+ end
@@ -0,0 +1,54 @@
1
+ # Sample sinatra server
2
+
3
+ require_relative '_setup'
4
+
5
+ require 'sinatra'
6
+
7
+ class SampleResolver < EurekaBot::Tg::Resolver
8
+ def controller_namespace
9
+ Controllers
10
+ end
11
+ end
12
+
13
+ class Controllers < EurekaBot::Tg::Controller
14
+ class TextController < Controllers
15
+ def text
16
+ answer(
17
+ method: 'sendMessage',
18
+ params: {
19
+ text: message.dig('message', 'text'),
20
+ }
21
+ )
22
+ end
23
+ end
24
+ end
25
+
26
+ class SampleServer < Sinatra::Base
27
+ configure do
28
+ EurekaBot::Tg.client = EurekaBot::Tg::Client.new(token: $tg_token)
29
+
30
+ enable :logging
31
+ use Rack::CommonLogger, EurekaBot.logger
32
+ end
33
+
34
+ helpers do
35
+ def webhook
36
+ @webhook ||= EurekaBot::Tg::Webhook.new(
37
+ params: params,
38
+ resolver_class: SampleResolver
39
+ )
40
+ end
41
+ end
42
+
43
+ post '/webhook' do
44
+ webhook.check_token!('S0M∑-S∑CUR∑-T0K∑N')
45
+ webhook.process
46
+
47
+ [
48
+ 200,
49
+ {'Content-Type' => 'text/plain'},
50
+ ''
51
+ ]
52
+ end
53
+
54
+ end
@@ -0,0 +1,40 @@
1
+ # Session example (Redis)
2
+
3
+ require_relative '_setup'
4
+ require 'redis'
5
+
6
+ $redis = Redis.new(url: 'redis://localhost:6379/1')
7
+
8
+ class SampleResolver < EurekaBot::Tg::Resolver
9
+ def controller_namespace
10
+ Controllers
11
+ end
12
+ end
13
+
14
+ class Controllers < EurekaBot::Tg::Controller
15
+ class TextController < Controllers
16
+ def text
17
+ answer(
18
+ method: 'sendMessage',
19
+ params: {
20
+ text: session.data[:text],
21
+ }
22
+ )
23
+
24
+ session.update(text: message.dig('message', 'text'))
25
+ end
26
+ end
27
+
28
+ def session
29
+ @session ||= EurekaBot::Session.new(['session', chat['id'], from['id']].join('.'), redis: $redis)
30
+ end
31
+ end
32
+
33
+ offset = nil
34
+ loop do
35
+ EurekaBot::Tg.client.make_request('getUpdates', payload: {offset: offset}.compact.to_json).each do |update|
36
+ EurekaBot::Job::Input.perform_later(SampleResolver.to_s, update)
37
+ offset = offset ? [offset, update['update_id'] + 1].max : update['update_id'] + 1
38
+ end
39
+ EurekaBot.logger.info '#ping'
40
+ end
data/examples/sync.rb ADDED
@@ -0,0 +1,34 @@
1
+ # Echo server
2
+
3
+ require_relative '_setup'
4
+
5
+ class SampleResolver < EurekaBot::Tg::Resolver
6
+ def controller_namespace
7
+ Controllers
8
+ end
9
+ end
10
+
11
+ class Controllers < EurekaBot::Tg::Controller
12
+ class TextController < Controllers
13
+ def text
14
+ answer(
15
+ method: 'sendMessage',
16
+ params: {
17
+ text: message.dig('message', 'text'),
18
+ }
19
+ )
20
+ end
21
+ end
22
+ end
23
+
24
+ # EurekaBot::Job.queue_adapter = :async # default
25
+ EurekaBot::Job.queue_adapter = :inline # everything will work synchronously. Not recommended.
26
+
27
+ offset = nil
28
+ loop do
29
+ EurekaBot::Tg.client.make_request('getUpdates', payload: {offset: offset}.compact.to_json).each do |update|
30
+ EurekaBot::Job::Input.perform_later(SampleResolver.to_s, update)
31
+ offset = offset ? [offset, update['update_id'] + 1].max : update['update_id'] + 1
32
+ end
33
+ EurekaBot.logger.info '#ping'
34
+ end
@@ -0,0 +1,49 @@
1
+ namespace :eureka do
2
+ namespace :tg do
3
+ desc 'Telegram long polling'
4
+ task :listen do
5
+ token = ENV.fetch('TG_TOKEN')
6
+ resolver_class = ENV.fetch('RESOLVER').constantize
7
+ offset = ENV.fetch('OFFSET', nil)
8
+ limit = ENV.fetch('LIMIT', 100)
9
+ timeout = ENV.fetch('TIMEOUT', 10)
10
+
11
+ EurekaBot::Tg.client = EurekaBot::Tg::Client.new(token: token)
12
+
13
+ EurekaBot.logger.info "starting getting #getUpdates for #{EurekaBot::Tg.client.make_request('getMe').to_json}"
14
+
15
+ loop do
16
+ EurekaBot::Tg.client.make_request('getUpdates', payload: {offset: offset, limit: limit, timeout: timeout}.compact.to_json).each do |update|
17
+ EurekaBot::Job::Input.perform_later(resolver_class.to_s, update)
18
+ offset = offset ? [offset, update['update_id'] + 1].max : update['update_id'] + 1
19
+ end
20
+ EurekaBot.logger.info '#ping'
21
+ end
22
+ end
23
+
24
+ desc 'Get/Set webhook'
25
+ task :webhook do
26
+ token = ENV.fetch('TG_TOKEN')
27
+ url = ENV.fetch('URL', nil)
28
+ max_connections = ENV.fetch('max_connections', nil)
29
+ client = EurekaBot::Tg::Client.new(token: token)
30
+
31
+ if url.present?
32
+ EurekaBot.logger.info(
33
+ {
34
+ result: client.make_request(
35
+ 'setWebhook',
36
+ payload: {
37
+ url: url,
38
+ max_connections: max_connections
39
+ }.compact.to_json
40
+ )
41
+ }.to_json
42
+ )
43
+ end
44
+
45
+ EurekaBot.logger.info client.make_request('getWebhookInfo').to_json
46
+ end
47
+ end
48
+ end
49
+
@@ -0,0 +1,26 @@
1
+ require 'active_support'
2
+
3
+ module EurekaBot
4
+ module Tg
5
+ extend ActiveSupport::Autoload
6
+
7
+ autoload :Client
8
+ autoload :Controller
9
+ autoload :Resolver
10
+ autoload :Sender
11
+ autoload :Version
12
+ autoload :Webhook
13
+
14
+ cattr_accessor :client
15
+
16
+ def self.rake_tasks
17
+ Dir.glob(File.dirname(__FILE__) + '/tasks/*.rake')
18
+ end
19
+
20
+ def self.load_rake_tasks(rake)
21
+ rake_tasks.each do |task|
22
+ rake.send(:import, task)
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,102 @@
1
+ require 'rest-client'
2
+
3
+ class EurekaBot::Tg::Client
4
+ include EurekaBot::Instrumentation
5
+
6
+ attr_reader :token, :url
7
+
8
+ def initialize(token:, url: 'https://api.telegram.org')
9
+ @url = url
10
+ @token = token
11
+ end
12
+
13
+ def get_file_url(file_id)
14
+ file_path = make_request('getFile', payload: {file_id: file_id}.to_json)['file_path']
15
+ [url, '/file', '/bot', token, '/', file_path].join
16
+ end
17
+
18
+ def parse_response(response)
19
+ ActiveSupport::JSON.decode(response) if response.present?
20
+ end
21
+
22
+ def extract_result(response)
23
+ if response['ok']
24
+ response['result']
25
+ else
26
+ raise EurekaBot::Tg::Client::Error.new(error_code: response['error_code'], description: response['description'])
27
+ end
28
+ end
29
+
30
+ def make_request(route, method: :get, **rest)
31
+ full_route = Array.wrap(route).join('/')
32
+ instrument 'eureka-bot.tg.request', route: full_route, method: method, rest: JSON.generate(rest) do
33
+ res = resource[full_route]
34
+
35
+ options = rest.clone
36
+ payload = options.delete(:payload)
37
+ headers = (res.options[:headers] || {}).merge(options)
38
+
39
+ request = options.merge(
40
+ method: method,
41
+ url: res.url,
42
+ headers: headers
43
+ )
44
+
45
+ request[:payload] = payload if payload
46
+
47
+ if request[:payload].is_a?(Hash)
48
+ request[:headers].delete('Content-Type')
49
+ request[:multipart] = true
50
+ end
51
+
52
+ response = nil
53
+
54
+ begin
55
+ response = parse_response(
56
+ RestClient::Request.execute(request).body
57
+ )
58
+ rescue RestClient::Exception => e
59
+ EurekaBot.exception_handler(e, e.class, custom_params: {error: e, http_code: e.http_code, http_body: e.http_body}.to_json)
60
+ response = parse_response(e.http_body)
61
+ end
62
+
63
+ if response
64
+ instrument 'eureka-bot.tg.response', response: response
65
+ extract_result(response)
66
+ end
67
+ end
68
+ end
69
+
70
+ def resource
71
+ @resource ||= RestClient::Resource.new(
72
+ [
73
+ url,
74
+ ['bot', token].join
75
+ ].to_param,
76
+ headers: {
77
+ 'Content-Type' => 'application/JSON'
78
+ },
79
+ logger: EurekaBot.logger,
80
+ timeout: 30
81
+ )
82
+ end
83
+
84
+ class Error < StandardError
85
+ attr_reader :error_code, :description
86
+
87
+ def initialize(error_code:, description: '')
88
+ @error_code = error_code
89
+ @description = description
90
+ end
91
+
92
+ def to_s
93
+ to_json
94
+ end
95
+
96
+ def to_json
97
+ {error_code: error_code, description: description}.to_json
98
+ end
99
+
100
+ end
101
+
102
+ end
@@ -0,0 +1,42 @@
1
+ class EurekaBot::Tg::Controller < EurekaBot::Controller
2
+ extend ActiveSupport::Autoload
3
+
4
+ autoload :Response
5
+ autoload :SystemController
6
+
7
+ autoload :RepliesConcern, 'eureka_bot/tg/controller/concerns/replies_concern'
8
+ include EurekaBot::Tg::Controller::RepliesConcern
9
+
10
+
11
+ def answer(params={})
12
+ super({params: {chat_id: chat_id}}.deep_merge(params))
13
+ end
14
+
15
+ def reply(params={})
16
+ answer(params.deep_merge({params: {reply_to_message_id: message_id}}))
17
+ end
18
+
19
+ def chat
20
+ message.dig('message', 'chat') || message.dig('callback_query', 'message', 'chat') || raise("Cant find chat in #{message}")
21
+ end
22
+
23
+ def from
24
+ message.dig('message', 'from') || message.dig('callback_query', 'from') || raise("Cant find from in #{message}")
25
+ end
26
+
27
+ def chat_id
28
+ chat['id']
29
+ end
30
+
31
+ def message_id
32
+ message.dig('message', 'message_id') || message.dig('callback_query', 'message', 'message_id') || raise("Cant find message_id in #{message}")
33
+ end
34
+
35
+ def response_class
36
+ EurekaBot::Tg::Controller::Response
37
+ end
38
+
39
+ def client
40
+ EurekaBot::Tg.client
41
+ end
42
+ end
@@ -0,0 +1,65 @@
1
+ module EurekaBot::Tg::Controller::RepliesConcern
2
+ extend ActiveSupport::Concern
3
+
4
+ def reply_markup(type: :classic, **options, &block)
5
+ markup = case type
6
+ when :inline
7
+ InlineMarkup.new(self, options)
8
+ when :classic
9
+ ClassicMarkup.new(self, options)
10
+ else
11
+ raise
12
+ end
13
+ markup.run(&block)
14
+ markup
15
+ end
16
+
17
+ def global_reply_markup
18
+ reply_markup resize_keyboard: true, one_time_keyboard: false do
19
+ [
20
+ ['Get Tasks', 'Account', 'Help']
21
+ ]
22
+ end
23
+ end
24
+
25
+ class Markup
26
+ attr_reader :context, :items, :options
27
+
28
+ def initialize(context, options={})
29
+ @context = context
30
+ @options = options
31
+ @items = []
32
+ end
33
+
34
+ def run(&block)
35
+ @items = block.call(self)
36
+ end
37
+
38
+ def method_missing(symbol, *args)
39
+ if context.respond_to?(symbol)
40
+ context.send(symbol, *args)
41
+ else
42
+ super
43
+ end
44
+ end
45
+ end
46
+
47
+ class ClassicMarkup < Markup
48
+ def as_json(*args)
49
+ {
50
+ keyboard: items,
51
+ resize_keyboard: options[:resize_keyboard],
52
+ one_time_keyboard: options[:one_time_keyboard],
53
+ selective: options[:selective],
54
+ }.compact.as_json(*args)
55
+ end
56
+ end
57
+
58
+ class InlineMarkup < Markup
59
+ def as_json(*args)
60
+ {
61
+ inline_keyboard: items
62
+ }.as_json(*args)
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,18 @@
1
+ class EurekaBot::Tg::Controller::Response < EurekaBot::Controller::Response
2
+
3
+ set_callback :add, :after, :consume
4
+
5
+ def consume
6
+ while element = @data.shift
7
+ EurekaBot::Job::Output.perform_later(
8
+ self.class.sender_class.to_s,
9
+ element
10
+ )
11
+ end
12
+ end
13
+
14
+ def self.sender_class
15
+ @@sender_class ||= EurekaBot::Tg::Sender
16
+ end
17
+
18
+ end
@@ -0,0 +1,7 @@
1
+ class EurekaBot::Tg::Controller::SystemController < EurekaBot::Tg::Controller
2
+
3
+ def nothing
4
+
5
+ end
6
+
7
+ end
@@ -0,0 +1,65 @@
1
+ class EurekaBot::Tg::Resolver < EurekaBot::Resolver
2
+ def resolve
3
+
4
+ if callback_query.present?
5
+ version, controller, action, *data = callback_query['data'].split(':')
6
+ return {
7
+ controller: controller,
8
+ action: action.to_sym,
9
+ params: {raw: data, version: version}
10
+ }
11
+ end
12
+
13
+ if simple_message.present?
14
+ if simple_message['text'].to_s[0] == '/'
15
+ parts = simple_message['text'].split(' ')
16
+ return {
17
+ controller: 'commands',
18
+ action: parts[0].gsub('/', '').to_sym,
19
+ params: {raw: parts[1..-1], version: 'v1'}
20
+ }
21
+ end
22
+
23
+ if simple_message['photo'].present?
24
+ return {
25
+ controller: 'photos',
26
+ action: :photo,
27
+ params: {photos: simple_message['photo'], version: 'v1'}
28
+ }
29
+ end
30
+
31
+ if simple_message['document'].present?
32
+ return {
33
+ controller: 'documents',
34
+ action: :document,
35
+ params: {document: simple_message['document'], version: 'v1'}
36
+ }
37
+ end
38
+
39
+ if simple_message['text'].present?
40
+ return {
41
+ controller: 'text',
42
+ action: :text,
43
+ params: {raw: simple_message['text'], version: 'v1'}
44
+ }
45
+ end
46
+ end
47
+
48
+ {
49
+ controller: 'system',
50
+ action: :nothing
51
+ }
52
+ end
53
+
54
+ def controller_namespace
55
+ EurekaBot::Tg::Controller
56
+ end
57
+
58
+ def simple_message
59
+ message['message'].presence
60
+ end
61
+
62
+ def callback_query
63
+ message['callback_query'].presence
64
+ end
65
+ end
@@ -0,0 +1,20 @@
1
+ class EurekaBot::Tg::Sender
2
+ include EurekaBot::Instrumentation
3
+
4
+ attr_reader :logger, :client
5
+
6
+ def initialize(client: EurekaBot::Tg.client, logger: EurekaBot.logger)
7
+ @logger = logger
8
+ @client = client
9
+ end
10
+
11
+ def deliver(message)
12
+ message = message.stringify_keys
13
+ client.make_request(
14
+ message['method'],
15
+ method: :post,
16
+ payload: message['params'].to_json
17
+ )
18
+ end
19
+
20
+ end
@@ -0,0 +1,5 @@
1
+ module EurekaBot
2
+ module Tg
3
+ VERSION = '2.0.11'
4
+ end
5
+ end
@@ -0,0 +1,32 @@
1
+ class EurekaBot::Tg::Webhook
2
+ include EurekaBot::Instrumentation
3
+
4
+ class TokenVerificationFailed < StandardError;
5
+ end
6
+
7
+ attr_reader :params, :resolver_class
8
+
9
+ def initialize(params:, resolver_class:)
10
+ @params = params
11
+ @resolver_class = resolver_class
12
+ end
13
+
14
+ def process
15
+ instrument 'eureka-bot.tg.webhook', params: params do
16
+ EurekaBot::Job::Input.perform_later(resolver_class.to_s, params)
17
+ end
18
+ end
19
+
20
+ def check_token(valid_token, token_path: [:token])
21
+ token = params.dig(*token_path)
22
+ token.to_s == valid_token.to_s
23
+ end
24
+
25
+ def check_token!(valid_token, token_path: [:token])
26
+ check_token(valid_token, token_path: token_path) || (raise TokenVerificationFailed.new({
27
+ expected_token: valid_token,
28
+ token_path: token_path,
29
+ params: params
30
+ }.to_json))
31
+ end
32
+ end
data/log/.keep ADDED
File without changes
data/tmp/.keep ADDED
File without changes
metadata ADDED
@@ -0,0 +1,165 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: eureka-bot-tg
3
+ version: !ruby/object:Gem::Version
4
+ version: 2.0.11
5
+ platform: ruby
6
+ authors:
7
+ - dizer
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2018-04-08 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: 5.0.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: 5.0.0
27
+ - !ruby/object:Gem::Dependency
28
+ name: rest-client
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '2.0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '2.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: eureka-bot
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '1.0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '1.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rspec
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: 3.6.0
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: 3.6.0
69
+ - !ruby/object:Gem::Dependency
70
+ name: factory_girl
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: webmock
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ description:
98
+ email:
99
+ - dizeru@gmail.com
100
+ executables: []
101
+ extensions: []
102
+ extra_rdoc_files: []
103
+ files:
104
+ - ".gitignore"
105
+ - ".rspec"
106
+ - CODE_OF_CONDUCT.md
107
+ - Gemfile
108
+ - LICENSE.txt
109
+ - README.md
110
+ - Rakefile
111
+ - bin/console
112
+ - bin/setup
113
+ - eureka-bot-tg.gemspec
114
+ - examples/_setup.rb
115
+ - examples/echo.rb
116
+ - examples/files_bot/files_bot.rb
117
+ - examples/files_bot/files_bot/controller.rb
118
+ - examples/files_bot/files_bot/controller/commands_controller.rb
119
+ - examples/files_bot/files_bot/controller/documents_controller.rb
120
+ - examples/files_bot/files_bot/controller/text_controller.rb
121
+ - examples/files_bot/files_bot/resolver.rb
122
+ - examples/files_bot/run.rb
123
+ - examples/queues.rake
124
+ - examples/reply_keyboard.rb
125
+ - examples/server.rb
126
+ - examples/session.rb
127
+ - examples/sync.rb
128
+ - lib/eureka_bot/tasks/tg.rake
129
+ - lib/eureka_bot/tg.rb
130
+ - lib/eureka_bot/tg/client.rb
131
+ - lib/eureka_bot/tg/controller.rb
132
+ - lib/eureka_bot/tg/controller/concerns/replies_concern.rb
133
+ - lib/eureka_bot/tg/controller/response.rb
134
+ - lib/eureka_bot/tg/controller/system_controller.rb
135
+ - lib/eureka_bot/tg/resolver.rb
136
+ - lib/eureka_bot/tg/sender.rb
137
+ - lib/eureka_bot/tg/version.rb
138
+ - lib/eureka_bot/tg/webhook.rb
139
+ - log/.keep
140
+ - tmp/.keep
141
+ homepage: ''
142
+ licenses:
143
+ - MIT
144
+ metadata: {}
145
+ post_install_message:
146
+ rdoc_options: []
147
+ require_paths:
148
+ - lib
149
+ required_ruby_version: !ruby/object:Gem::Requirement
150
+ requirements:
151
+ - - ">="
152
+ - !ruby/object:Gem::Version
153
+ version: '0'
154
+ required_rubygems_version: !ruby/object:Gem::Requirement
155
+ requirements:
156
+ - - ">="
157
+ - !ruby/object:Gem::Version
158
+ version: '0'
159
+ requirements: []
160
+ rubyforge_project:
161
+ rubygems_version: 2.6.14
162
+ signing_key:
163
+ specification_version: 4
164
+ summary: Run your messenger bots
165
+ test_files: []