qbot 0.1.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 85d73bad55f14325b0a78aeaff2341de02ef5614aa2fffe440bf67a2a3b70b74
4
+ data.tar.gz: 4482b338249e3c9fa3f480768f41dde54e160220929b0d6bd58e9e2a7679ad20
5
+ SHA512:
6
+ metadata.gz: a4cc7f82c33ba57018a77b0cfadfe8c168647d0d00c53722bc894ea741dc250c1cfa042814c53673a4f12ac512a55304335be7ecf9a8917ccdd2673f084ffde4
7
+ data.tar.gz: d8a08ddb77ede43079f68587967d5e70902df0ab2a9fbcb05d8ad3ade91cd0f95482e4ae7c97d3456d20577c477ad60d985c1366904ba62337bb0ee21087d3fb
@@ -0,0 +1,8 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at haccht@users.noreply.github.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in qbot.gemspec
6
+ gemspec
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 haccht
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.
@@ -0,0 +1,72 @@
1
+ # Qbot
2
+
3
+ Qbot is a tiny bot flamework written in Ruby.
4
+ Qbot comes with the Slack adapter and the Mattermost adapter.
5
+
6
+ ## Installation
7
+
8
+ Add this line to your application's Gemfile:
9
+
10
+ ```ruby
11
+ gem 'qbot'
12
+ ```
13
+
14
+ And then execute:
15
+
16
+ $ bundle
17
+
18
+ Or install it yourself as:
19
+
20
+ $ gem install qbot
21
+
22
+ ## Usage
23
+
24
+ Write your bot in `bot.rb`.
25
+
26
+ ```
27
+ require 'qbot'
28
+ require 'qbot/adapter/slack'
29
+
30
+ on /^ping/ do
31
+ post 'pong'
32
+ end
33
+
34
+ on /^echo (.+)$/ do |msg|
35
+ post msg[1]
36
+ end
37
+
38
+ cron '*/5 * * * *' do
39
+ post 'hello?', channel_name: 'random'
40
+ end
41
+ ```
42
+
43
+ Then put your Slack API Token in `.env`.
44
+
45
+ ```
46
+ QBOT_SLACK_API_TOKEN=xoxb-############-#######################C
47
+ ```
48
+
49
+ And now start your bot with the following command.
50
+
51
+ ```
52
+ ruby bot.rb
53
+ ```
54
+
55
+
56
+ ## Development
57
+
58
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
59
+
60
+ 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 tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
61
+
62
+ ## Contributing
63
+
64
+ Bug reports and pull requests are welcome on GitHub at https://github.com/haccht/qbot. 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.
65
+
66
+ ## License
67
+
68
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
69
+
70
+ ## Code of Conduct
71
+
72
+ Everyone interacting in the Qbot project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/qbot/blob/master/CODE_OF_CONDUCT.md).
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+ task :default => :spec
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "qbot"
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(__FILE__)
@@ -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,21 @@
1
+ require 'qbot/base'
2
+ require 'qbot/autorun'
3
+
4
+ module Qbot
5
+
6
+ module Delegator
7
+
8
+ def self.delegate(*names)
9
+ names.each do |name|
10
+ define_method(name) do |*args, &block|
11
+ Qbot::Base.send(name, *args, &block)
12
+ end
13
+ end
14
+ end
15
+ delegate :on, :cron
16
+
17
+ end
18
+
19
+ end
20
+
21
+ extend Qbot::Delegator
@@ -0,0 +1,43 @@
1
+ module Qbot
2
+
3
+ Message = Struct.new(:text, :data, :matched)
4
+
5
+ module Adapter
6
+
7
+ class Driver
8
+
9
+ class << self
10
+
11
+ def inherited(subclass)
12
+ @target = subclass
13
+ end
14
+
15
+ def build
16
+ @target.new
17
+ end
18
+
19
+ end
20
+
21
+ def run(bots)
22
+ on_message do |message|
23
+ bots.each { |bot| bot.call(message.dup) }
24
+ end
25
+ end
26
+
27
+ def on_message(&block)
28
+ raise 'Not implemented'
29
+ end
30
+
31
+ def post(text, **options)
32
+ raise 'Not implemented'
33
+ end
34
+
35
+ def reply_to(message, text, **options)
36
+ raise 'Not implemented'
37
+ end
38
+
39
+ end
40
+
41
+ end
42
+
43
+ end
@@ -0,0 +1,140 @@
1
+ require 'faraday'
2
+ require 'faraday_middleware'
3
+ require 'faye/websocket'
4
+ require 'json'
5
+
6
+ module Qbot
7
+
8
+ module Adapter
9
+
10
+ class Mattermost < Qbot::Adapter::Driver
11
+
12
+ def initialize(url: nil, username: nil, password: nil)
13
+ @mm_url = url || ENV['QBOT_MATTERMOST_URL']
14
+ @server = URI.join(@mm_url, '/').to_s
15
+ @error = false
16
+
17
+ resp = api_call(:post, '/users/login', :body => {
18
+ login_id: username || ENV['QBOT_MATTERMOST_USERNAME'],
19
+ password: password || ENV['QBOT_MATTERMOST_PASSWORD'],
20
+ })
21
+
22
+ access_token(resp.headers['token'])
23
+ end
24
+
25
+ def access_token(token)
26
+ @token = token
27
+ end
28
+
29
+ def on_message(&block)
30
+ ws_url = URI.join(@server.gsub(/^http(s?):/, 'ws\1:'), endpoint('/websocket')).to_s
31
+ headers = { "Authorization" => "Bearer #{@token}" }
32
+
33
+ EM.run do
34
+ @ws = Faye::WebSocket::Client.new(ws_url, {}, { headers: headers, ping: 60})
35
+
36
+ @ws.on :open do |e|
37
+ Qbot.app.logger.info("#{self.class} - Websocket connection opened")
38
+ end
39
+
40
+ @ws.on :close do |e|
41
+ Qbot.app.logger.info("#{self.class} - Websocket connection closed")
42
+ stop if @error
43
+ on_message(&block) # restart
44
+ end
45
+
46
+ @ws.on :error do |e|
47
+ Qbot.app.logger.error("#{self.class} - #{e.message}")
48
+ @error = true
49
+ end
50
+
51
+ @ws.on :message do |e|
52
+ data = JSON.parse(e.data)
53
+ emit_event(data, block)
54
+ end
55
+ end
56
+ end
57
+
58
+ def stop
59
+ EM.stop
60
+ end
61
+
62
+ def post(text, **options)
63
+ api_call(:post, "/posts", body: options.merge(message: text))
64
+ end
65
+
66
+ def reply_to(message, text, **options)
67
+ if options[:channel_id]
68
+ channel_id = options[:channel_id]
69
+ elsif options[:channel_name]
70
+ channel = channel(options[:channel_name])
71
+ channel_id = channel['id'] if channel
72
+ end
73
+
74
+ channel_id ||= message.data['channel_id'] if message
75
+ return unless channel_id
76
+
77
+ post(text, **options.merge(channel_id: channel_id))
78
+ end
79
+
80
+ private
81
+ def endpoint(path)
82
+ URI(@mm_url).path + "/api/v4#{path}"
83
+ end
84
+
85
+ def emit_event(data, callback)
86
+ event = data['event'].to_sym
87
+ Qbot.app.logger.debug("#{self.class} - Event '#{event}' recieved")
88
+
89
+ case event
90
+ when :posted
91
+ post = JSON.parse(data['data']['post'])
92
+
93
+ message = Qbot::Message.new
94
+ message.data = post
95
+ message.text = post['message']
96
+
97
+ Qbot.app.logger.info("#{self.class} - Message was '#{message.text}'")
98
+ callback.call(message)
99
+ end
100
+ end
101
+
102
+ def api_call(method, path, **options, &block)
103
+ headers = { "Authorization" => "Bearer #{@token}", "Accept" => "application/json" }
104
+
105
+ connection = Faraday::Connection.new(url: @server, headers: headers ) do |con|
106
+ con.response :json
107
+ con.adapter :httpclient
108
+ end
109
+
110
+ connection.send(method) do |request|
111
+ request.url endpoint(path), options
112
+ request.body = options[:body].to_json if options[:body]
113
+ end
114
+ end
115
+
116
+ def me
117
+ resp = api_call(:get, "/users/me")
118
+ resp.body
119
+ end
120
+
121
+ def channel(name)
122
+ resp = api_call(:get, "/teams/#{team['id']}/channels/name/#{name}")
123
+ resp.body
124
+ end
125
+
126
+ def team
127
+ if name = ENV['QBOT_MATTERMOST_TEAM']
128
+ resp = api_call(:get, "/teams/name/#{name}")
129
+ resp.body
130
+ else
131
+ resp = api_call(:get, "/users/#{me['id']}/teams")
132
+ resp.body.first
133
+ end
134
+ end
135
+
136
+ end
137
+
138
+ end
139
+
140
+ end
@@ -0,0 +1,46 @@
1
+ require 'eventmachine'
2
+
3
+ module Qbot
4
+
5
+ module Adapter
6
+
7
+ class Shell < Qbot::Adapter::Driver
8
+
9
+ module Keyboard
10
+
11
+ include EM::Protocols::LineText2
12
+
13
+ def initialize(callback)
14
+ @callback = callback
15
+ $stdout.print ">> "
16
+ end
17
+
18
+ def receive_line(text)
19
+ exit 0 if text.strip == 'exit'
20
+
21
+ message = Qbot::Message.new
22
+ message.data = text
23
+ message.text = text
24
+
25
+ @callback.call(message)
26
+ $stdout.print ">> "
27
+ end
28
+ end
29
+
30
+ def on_message(&block)
31
+ EM.run { EM.open_keyboard(Keyboard, block) }
32
+ end
33
+
34
+ def post(text, **options)
35
+ $stdout.puts text
36
+ end
37
+
38
+ def reply_to(message, text, **options)
39
+ post(text, **options)
40
+ end
41
+
42
+ end
43
+
44
+ end
45
+
46
+ end
@@ -0,0 +1,127 @@
1
+ require 'faraday'
2
+ require 'faraday_middleware'
3
+ require 'faye/websocket'
4
+ require 'json'
5
+
6
+ module Qbot
7
+
8
+ module Adapter
9
+
10
+ class Slack < Qbot::Adapter::Driver
11
+
12
+ SLACK_API_URL = 'https://slack.com/api'
13
+
14
+ def initialize(api_token: nil)
15
+ @server = URI.join(SLACK_API_URL, '/').to_s
16
+ @error = false
17
+
18
+ access_token(api_token || ENV['QBOT_SLACK_API_TOKEN'])
19
+ end
20
+
21
+ def access_token(token)
22
+ @token = token
23
+ end
24
+
25
+ def on_message(&block)
26
+ resp = api_call(:get, '/rtm.start')
27
+ data = JSON.parse(resp.body)
28
+ ws_url = data['url']
29
+
30
+ EM.run do
31
+ @ws = Faye::WebSocket::Client.new(ws_url, {}, { ping: 60})
32
+
33
+ @ws.on :open do |e|
34
+ Qbot.app.logger.info("#{self.class} - Websocket connection opened")
35
+ end
36
+
37
+ @ws.on :close do |e|
38
+ Qbot.app.logger.info("#{self.class} - Websocket connection closed")
39
+ stop if @error
40
+ on_message(&block) # restart
41
+ end
42
+
43
+ @ws.on :error do |e|
44
+ Qbot.app.logger.error("#{self.class} - #{e.message}")
45
+ @error = true
46
+ end
47
+
48
+ @ws.on :message do |e|
49
+ data = JSON.parse(e.data)
50
+ emit_event(data, block)
51
+ end
52
+ end
53
+ end
54
+
55
+ def stop
56
+ EM.stop
57
+ end
58
+
59
+ def post(text, **options)
60
+ api_call(:post, "/chat.postMessage", options.merge(text: text))
61
+ end
62
+
63
+ def reply_to(message, text, **options)
64
+ if options[:channel_id]
65
+ channel_id = options[:channel_id]
66
+ elsif options[:channel_name]
67
+ channel = channel(options[:channel_name])
68
+ channel_id = channel['id'] if channel
69
+ end
70
+
71
+ channel_id ||= message.data['channel'] if message
72
+ return unless channel_id
73
+
74
+ post(text, **options.merge(channel: channel_id))
75
+ end
76
+
77
+ private
78
+ def endpoint(path)
79
+ URI(SLACK_API_URL).path + path
80
+ end
81
+
82
+ def emit_event(data, callback)
83
+ event = data['type'].to_sym
84
+ Qbot.app.logger.debug("#{self.class} - Event '#{event}' recieved")
85
+
86
+ case event
87
+ when :message
88
+ return if data['subtype']
89
+
90
+ message = Qbot::Message.new
91
+ message.data = data
92
+ message.text = data['text']
93
+
94
+ Qbot.app.logger.info("#{self.class} - Message was '#{message.text}'")
95
+ callback.call(message)
96
+ end
97
+ end
98
+
99
+ def api_call(method, path, **options, &block)
100
+ connection = Faraday::Connection.new(url: @server ) do |con|
101
+ con.request :url_encoded
102
+ con.adapter :httpclient
103
+ end
104
+
105
+ connection.send(
106
+ method,
107
+ endpoint(path),
108
+ { token: @token }.merge(options)
109
+ )
110
+ end
111
+
112
+ def me
113
+ resp = api_call(:get, "/auth.test")
114
+ JSON.parse(resp.body)
115
+ end
116
+
117
+ def channel(name)
118
+ resp = api_call(:get, "/channels.list")
119
+ data = JSON.parse(resp.body)
120
+ data['channels'].find { |c| c['name'] == name }
121
+ end
122
+
123
+ end
124
+
125
+ end
126
+
127
+ end
@@ -0,0 +1,67 @@
1
+ require 'logger'
2
+ require 'singleton'
3
+ require 'timers'
4
+
5
+ require 'qbot/version'
6
+
7
+ module Qbot
8
+
9
+ class << self
10
+
11
+ def app
12
+ Qbot::Application.instance
13
+ end
14
+
15
+ def run!(*args)
16
+ app.start
17
+ end
18
+
19
+ end
20
+
21
+ class Application
22
+
23
+ include Singleton
24
+ attr_reader :timers
25
+ attr_reader :logger
26
+
27
+ def initialize
28
+ @bots = []
29
+ @threads = []
30
+ @timers = Timers::Group.new
31
+ @logger = Logger.new(STDOUT)
32
+ end
33
+
34
+ def add(bot)
35
+ @bots << bot
36
+ end
37
+
38
+ def bots
39
+ @bots.map { |bot| bot.class.name }.uniq
40
+ end
41
+
42
+ def start
43
+ @logger.info("Booting #{self.class}.")
44
+ @logger.info("#{storage.class} - Storage driver loaded")
45
+ @logger.info("#{adapter.class} - Adapter driver loaded")
46
+
47
+ @threads << Thread.start { loop { @timers.wait } }
48
+ @threads << Thread.start { adapter.run(@bots) }
49
+ @threads.each { |th| th.join }
50
+ end
51
+
52
+ def stop
53
+ adapter.stop if adapter.respond_to?(:stop)
54
+ @threads.each { |th| th.kill if th }
55
+ end
56
+
57
+ def adapter
58
+ @adapter ||= Qbot::Adapter::Driver.build
59
+ end
60
+
61
+ def storage
62
+ @storage ||= Qbot::Storage::Driver.build
63
+ end
64
+
65
+ end
66
+
67
+ end
@@ -0,0 +1,19 @@
1
+ require 'qbot/embed/help'
2
+
3
+ module Qbot
4
+
5
+ def self.autorun
6
+ at_exit do
7
+ exit if $!
8
+
9
+ %i{INT TERM}.each do |signal|
10
+ Signal.trap(signal) { exit }
11
+ end
12
+
13
+ Qbot.run!(ARGV)
14
+ end
15
+ end
16
+
17
+ end
18
+
19
+ Qbot.autorun
@@ -0,0 +1,69 @@
1
+ require 'parse-cron'
2
+ require 'dotenv/load'
3
+
4
+ require 'qbot/app'
5
+ require 'qbot/adapter'
6
+ require 'qbot/adapter/shell'
7
+ require 'qbot/storage'
8
+ require 'qbot/storage/memory'
9
+
10
+ module Qbot
11
+
12
+ class Base
13
+
14
+ class << self
15
+
16
+ def on(pattern, &block)
17
+ pattern = Regexp.new(pattern.to_s) unless Regexp === pattern
18
+ Qbot.app.add(new(pattern, &block))
19
+ end
20
+
21
+ def cron(pattern, &block)
22
+ schedule(pattern, &block)
23
+ end
24
+
25
+ def usage(text)
26
+ on(/^#{prefix}help\s+#{name.downcase}\b/) { post(text) }
27
+ end
28
+
29
+ private
30
+ def prefix
31
+ "#{ENV['QBOT_PREFIX']}\s+" if ENV['QBOT_PREFIX']
32
+ end
33
+
34
+ def schedule(pattern, &block)
35
+ parser = CronParser.new(pattern)
36
+ current = Time.now
37
+ delay = parser.next(current) - current
38
+
39
+ Qbot.app.timers.after(delay) do
40
+ new(pattern).instance_eval(&block)
41
+ schedule(pattern, &block)
42
+ end
43
+ end
44
+
45
+ end
46
+
47
+ def initialize(pattern, &block)
48
+ @pattern = pattern
49
+ @callback = block
50
+ end
51
+
52
+ def call(message)
53
+ @message = message
54
+ return unless @pattern =~ @message.text.to_s.strip
55
+
56
+ instance_exec($~, &@callback)
57
+ end
58
+
59
+ def post(text, **options)
60
+ Qbot.app.adapter.reply_to(@message, text, **options)
61
+ end
62
+
63
+ def cache
64
+ Qbot.app.storage.namespace(self.class.name)
65
+ end
66
+
67
+ end
68
+
69
+ end
@@ -0,0 +1,79 @@
1
+ module Qbot
2
+
3
+ class Cron < Qbot::Base
4
+
5
+ on /^cron add (\S+ \S+ \S+ \S+ \S+) (.+)$/ do |msg|
6
+ post start(unique_id, msg[1], msg[2])
7
+ end
8
+
9
+ on /^cron del (\d+)/ do |msg|
10
+ post stop(msg[1].to_i)
11
+ end
12
+
13
+ on /^cron list\b/ do |msg|
14
+ post list_all
15
+ end
16
+
17
+ usage <<~EOL
18
+ Usage:
19
+ `cron add <pattern> <message>` - add a cron task.
20
+ `cron del <cron-id>` - remove a cron task.
21
+ `cron list` - list all cron tasks.
22
+ EOL
23
+
24
+ def self.timers
25
+ @timers ||= {}
26
+ end
27
+
28
+ def start(id, cron, text)
29
+ schedule(id, cron, text) rescue return
30
+
31
+ cache[id] = [cron, text]
32
+ "ADD " + dump_line(id, cron, text)
33
+ end
34
+
35
+ def stop(id)
36
+ Cron.timers[id].cancel if Cron.timers[id]
37
+ cron, text = cache[id]
38
+ return unless cron && text
39
+
40
+ cache[id] = nil
41
+ "DEL " + dump_line(id, cron, text)
42
+ end
43
+
44
+ def list_all
45
+ resp = StringIO.new
46
+ cache.each do |id, (cron, text)|
47
+ next unless cron && text
48
+ resp.puts dump_line(id, cron, text)
49
+ end
50
+
51
+ resp.string
52
+ end
53
+
54
+ private
55
+ def schedule(id, cron, text)
56
+ parser = CronParser.new(cron)
57
+ current = Time.now
58
+ delay = parser.next(current) - current
59
+
60
+ Cron.timers[id] = Qbot.app.timers.after(delay) do
61
+ post(text)
62
+ schedule(id, cron, text)
63
+ end
64
+ end
65
+
66
+ def dump_line(id, cron, text)
67
+ "#{id.to_s.rjust(3, '0')}: #{cron} #{text}"
68
+ end
69
+
70
+ def unique_id
71
+ loop do
72
+ id = (0..999).to_a.sample
73
+ return id unless cache[id]
74
+ end
75
+ end
76
+
77
+ end
78
+
79
+ end
@@ -0,0 +1,16 @@
1
+ module Qbot
2
+
3
+ class Echo < Qbot::Base
4
+
5
+ on /^echo( .+)$/ do |msg|
6
+ post msg[1].strip
7
+ end
8
+
9
+ usage <<~EOL
10
+ Usage:
11
+ `echo <text>` - Reflect the given <text>.
12
+ EOL
13
+
14
+ end
15
+
16
+ end
@@ -0,0 +1,22 @@
1
+ require 'stringio'
2
+
3
+ module Qbot
4
+
5
+ class Help < Qbot::Base
6
+
7
+ on /^#{prefix}help$/ do |msg|
8
+ names = Qbot.app.bots
9
+ .reject { |n| %w(Qbot::Base Qbot::Help).include?(n) }
10
+ .map { |n| n.split('::').last.downcase }
11
+
12
+ next if names.empty?
13
+ resp = StringIO.new
14
+ resp.puts 'Features:'
15
+ resp.puts names.map { |name| " #{name}" }
16
+
17
+ post resp.string
18
+ end
19
+
20
+ end
21
+
22
+ end
@@ -0,0 +1,11 @@
1
+ module Qbot
2
+
3
+ class Ping < Qbot::Base
4
+
5
+ on /^ping\b/i do |msg|
6
+ post msg[0].tr('iI', 'oO')
7
+ end
8
+
9
+ end
10
+
11
+ end
@@ -0,0 +1,27 @@
1
+ module Qbot
2
+
3
+ module Storage
4
+
5
+ class Driver
6
+
7
+ class << self
8
+
9
+ def inherited(subclass)
10
+ @target = subclass
11
+ end
12
+
13
+ def build
14
+ @target.new
15
+ end
16
+
17
+ end
18
+
19
+ def namespace(ns)
20
+ raise 'Not implemented'
21
+ end
22
+
23
+ end
24
+
25
+ end
26
+
27
+ end
@@ -0,0 +1,44 @@
1
+ require 'leveldb'
2
+
3
+ module Qbot
4
+
5
+ module Storage
6
+
7
+ class LevelDB < Qbot::Storage::Driver
8
+
9
+ QBOT_LEVELDB_DEFAULT_DATABASE = 'qbot-storage.db'
10
+ QBOT_LEVELDB_DEFAULT_BACKUP_INTERVAL = 5
11
+
12
+ def initialize
13
+ interval = ENV['QBOT_LEVELDB_BACKUP_INTERVAL'] || QBOT_LEVELDB_DEFAULT_BACKUP_INTERVAL
14
+ database = ENV['QBOT_LEVELDB_DATABASE'] || QBOT_LEVELDB_DEFAULT_DATABASE
15
+
16
+ @db = ::LevelDB::DB.new(File.join(Dir.pwd, database))
17
+ @cache = {}
18
+
19
+ restore
20
+ Qbot.app.timers.every(interval) { backup }
21
+ end
22
+
23
+ def namespace(ns)
24
+ @cache[ns] ||= {}
25
+ end
26
+
27
+ private
28
+ def backup
29
+ return if @cache.keys.empty?
30
+ @db.batch do |batch|
31
+ @cache.each { |ns, v| batch[ns] = Marshal.dump(v) }
32
+ end
33
+ end
34
+
35
+ def restore
36
+ return if @db.keys.empty?
37
+ @db.each { |ns, v| @cache[ns] = Marshal.load(v) }
38
+ end
39
+
40
+ end
41
+
42
+ end
43
+
44
+ end
@@ -0,0 +1,19 @@
1
+ module Qbot
2
+
3
+ module Storage
4
+
5
+ class Memory < Qbot::Storage::Driver
6
+
7
+ def initialize
8
+ @db = {}
9
+ end
10
+
11
+ def namespace(ns)
12
+ @db[ns]
13
+ end
14
+
15
+ end
16
+
17
+ end
18
+
19
+ end
@@ -0,0 +1,3 @@
1
+ module Qbot
2
+ VERSION = "0.1.1"
3
+ end
@@ -0,0 +1,35 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "qbot/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "qbot"
8
+ spec.version = Qbot::VERSION
9
+ spec.authors = ["haccht"]
10
+ spec.email = ["haccht@users.noreply.github.com"]
11
+
12
+ spec.summary = %q{Tiny chatbot flamework.}
13
+ spec.description = %q{Tiny chatbot flamework.}
14
+ spec.homepage = "https://github.com/haccht/qbot"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
18
+ f.match(%r{^(test|spec|features)/})
19
+ end
20
+ spec.bindir = "exe"
21
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
+ spec.require_paths = ["lib"]
23
+
24
+ spec.add_development_dependency "bundler", "~> 1.16"
25
+
26
+ spec.add_dependency "rake", "~> 10.0"
27
+ spec.add_dependency "dotenv", "~> 2.5"
28
+ spec.add_dependency "timers", "~> 4.1"
29
+ spec.add_dependency "parse-cron", "~> 0.1"
30
+ spec.add_dependency "leveldb", "~> 0.1"
31
+ spec.add_dependency "faraday", "~> 0.14"
32
+ spec.add_dependency "faraday_middleware", "~> 0.12"
33
+ spec.add_dependency "httpclient", ">= 2.2"
34
+ spec.add_dependency "faye-websocket", "~> 0.10"
35
+ end
metadata ADDED
@@ -0,0 +1,209 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: qbot
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - haccht
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2018-08-31 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.16'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.16'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: dotenv
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '2.5'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '2.5'
55
+ - !ruby/object:Gem::Dependency
56
+ name: timers
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '4.1'
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '4.1'
69
+ - !ruby/object:Gem::Dependency
70
+ name: parse-cron
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '0.1'
76
+ type: :runtime
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '0.1'
83
+ - !ruby/object:Gem::Dependency
84
+ name: leveldb
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '0.1'
90
+ type: :runtime
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '0.1'
97
+ - !ruby/object:Gem::Dependency
98
+ name: faraday
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '0.14'
104
+ type: :runtime
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '0.14'
111
+ - !ruby/object:Gem::Dependency
112
+ name: faraday_middleware
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - "~>"
116
+ - !ruby/object:Gem::Version
117
+ version: '0.12'
118
+ type: :runtime
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - "~>"
123
+ - !ruby/object:Gem::Version
124
+ version: '0.12'
125
+ - !ruby/object:Gem::Dependency
126
+ name: httpclient
127
+ requirement: !ruby/object:Gem::Requirement
128
+ requirements:
129
+ - - ">="
130
+ - !ruby/object:Gem::Version
131
+ version: '2.2'
132
+ type: :runtime
133
+ prerelease: false
134
+ version_requirements: !ruby/object:Gem::Requirement
135
+ requirements:
136
+ - - ">="
137
+ - !ruby/object:Gem::Version
138
+ version: '2.2'
139
+ - !ruby/object:Gem::Dependency
140
+ name: faye-websocket
141
+ requirement: !ruby/object:Gem::Requirement
142
+ requirements:
143
+ - - "~>"
144
+ - !ruby/object:Gem::Version
145
+ version: '0.10'
146
+ type: :runtime
147
+ prerelease: false
148
+ version_requirements: !ruby/object:Gem::Requirement
149
+ requirements:
150
+ - - "~>"
151
+ - !ruby/object:Gem::Version
152
+ version: '0.10'
153
+ description: Tiny chatbot flamework.
154
+ email:
155
+ - haccht@users.noreply.github.com
156
+ executables: []
157
+ extensions: []
158
+ extra_rdoc_files: []
159
+ files:
160
+ - ".gitignore"
161
+ - CODE_OF_CONDUCT.md
162
+ - Gemfile
163
+ - LICENSE.txt
164
+ - README.md
165
+ - Rakefile
166
+ - bin/console
167
+ - bin/setup
168
+ - lib/qbot.rb
169
+ - lib/qbot/adapter.rb
170
+ - lib/qbot/adapter/mattermost.rb
171
+ - lib/qbot/adapter/shell.rb
172
+ - lib/qbot/adapter/slack.rb
173
+ - lib/qbot/app.rb
174
+ - lib/qbot/autorun.rb
175
+ - lib/qbot/base.rb
176
+ - lib/qbot/embed/cron.rb
177
+ - lib/qbot/embed/echo.rb
178
+ - lib/qbot/embed/help.rb
179
+ - lib/qbot/embed/ping.rb
180
+ - lib/qbot/storage.rb
181
+ - lib/qbot/storage/leveldb.rb
182
+ - lib/qbot/storage/memory.rb
183
+ - lib/qbot/version.rb
184
+ - qbot.gemspec
185
+ homepage: https://github.com/haccht/qbot
186
+ licenses:
187
+ - MIT
188
+ metadata: {}
189
+ post_install_message:
190
+ rdoc_options: []
191
+ require_paths:
192
+ - lib
193
+ required_ruby_version: !ruby/object:Gem::Requirement
194
+ requirements:
195
+ - - ">="
196
+ - !ruby/object:Gem::Version
197
+ version: '0'
198
+ required_rubygems_version: !ruby/object:Gem::Requirement
199
+ requirements:
200
+ - - ">="
201
+ - !ruby/object:Gem::Version
202
+ version: '0'
203
+ requirements: []
204
+ rubyforge_project:
205
+ rubygems_version: 2.7.6
206
+ signing_key:
207
+ specification_version: 4
208
+ summary: Tiny chatbot flamework.
209
+ test_files: []