Class: Async::Matrix::ApplicationService::Bot

Inherits:
Object
  • Object
show all
Defined in:
lib/async/matrix/application_service/bot.rb

Overview

DSL wrapper that pairs a Client with event handlers.

A Bot produces handler objects that conform to the Dispatcher’s duck-type contract (#event_types, #call). Register a bot on a Server (or Dispatcher) the same way you would register a plain handler.

bot = Bot.new(client) do
  on "m.room.member" do |event|
    join_room(event.room_id) if event.content.membership == "invite"
  end

  on "m.room.message", msgtype: "m.text", not_from: :self do |event|
    send_notice event.room_id, "Echo: #{event.content.body}"
  end
end

server.register(bot)

Defined Under Namespace

Classes: Context, Handler

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client, &block) ⇒ Bot

Returns a new instance of Bot.



34
35
36
37
38
39
# File 'lib/async/matrix/application_service/bot.rb', line 34

def initialize(client, &block)
  @client   = client
  @handlers = []

  instance_eval(&block) if block
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



32
33
34
# File 'lib/async/matrix/application_service/bot.rb', line 32

def client
  @client
end

#handlersObject (readonly)

Returns the value of attribute handlers.



32
33
34
# File 'lib/async/matrix/application_service/bot.rb', line 32

def handlers
  @handlers
end

Instance Method Details

#on(*event_types, msgtype: nil, not_from: nil, &block) ⇒ Object

Register a handler block for one or more event types.

Filters (all optional):

msgtype:  — only dispatch when content.msgtype matches (e.g. "m.text")
not_from: — :self skips events sent by this bot's own MXID

Raises:

  • (ArgumentError)


47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/async/matrix/application_service/bot.rb', line 47

def on(*event_types, msgtype: nil, not_from: nil, &block)
  raise ArgumentError, "on requires at least one event type" if event_types.empty?
  raise ArgumentError, "on requires a block" unless block

  handler = Handler.new(
    bot:         self,
    event_types: event_types.flatten,
    msgtype:     msgtype,
    not_from:    not_from,
    block:       block
  )

  @handlers << handler
  handler
end