Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Initial commit

  • Loading branch information...
commit 1c296ef8f00853f043af347c94d05ab318a5c0df 0 parents
@wjessop authored
2  .gitignore
@@ -0,0 +1,2 @@
+.rvmrc
+pkg/
2  Gemfile
@@ -0,0 +1,2 @@
+source :rubygems
+gemspec
135 README.md
@@ -0,0 +1,135 @@
+# Scamp
+
+A framework for writing [Campfire](http://campfirenow.com/) bots. Scamp is in early development so use it at your own risk, pull requests welcome.
+
+## Requirements
+
+Ruby >= 1.9.2 (At least for the named captures)
+
+## Installation
+
+`gem install Scamp` or put `gem 'Scamp'` in your Gemfile.
+
+## Usage and Examples
+
+Matchers are tested in order and all that satisfy the match and conditions will be run. Careful, Scamp listens to itself, you could easily create an infinite loop. Look in the examples dir for more.
+
+ require 'Scamp'
+
+ scamp = Scamp.new(:api_key => "YOUR API KEY")
+
+ Scamp.behaviour do
+ #
+ # Simple matching based on regex or string:
+ #
+ match /^repeat (\w+), (\w+)$/ do
+ say "You said #{matches[0]} and #{matches[1]}"
+ end
+
+ #
+ # A special user and channel method is available in match blocks.
+ #
+ match "a user said" do
+ say "#{user} said something in channel #{channel}"
+ end
+
+ match "Hello!" do
+ say "Hi there"
+ end
+
+ #
+ # Limit the match to certain channels, users or both.
+ #
+ match /^Lets match (.+)$/, :conditions => {:channel => /someregex/} do
+ say "Only said if channel name mathces /someregex/"
+ end
+
+ match "some text", :conditions => {:user => /someregex/} do
+ say "Only said if user name mathces /someregex/"
+ end
+
+ match /some other text/, :conditions => {:user => /someregex/, :channel => /some other regex/} do
+ say "You can mix conditions"
+ end
+
+ #
+ # Named caputres become avaiable in your match block
+ #
+ match /^say (?<yousaid>.+)$/ do
+ say "You said #{yousaid}"
+ end
+
+ #
+ # You can say multiple times, and you can specify an alternate channel.
+ # Default behaviour is to 'say' in the channel that caused the match.
+ #
+ match "something" do
+ say "#{user} said something in channel #{channel}"
+ say "#{user} said something in channel #{channel}", 237872
+ say "#{user} said something in channel #{channel}", "System Administration"
+ end
+
+ # Connect and join some channels
+ scamp.connect!([293788, "Monitoring"])
+
+In the channel/user conditions you can use the name, regex or ID of a user or channel, in say you can ise a string or ID, eg:
+
+ :conditions => {:channel => /someregex/}
+ :conditions => {:channel => "some string"}
+ :conditions => {:channel => 123456}
+
+ :conditions => {:user => /someregex/}
+ :conditions => {:user => "some string"}
+ :conditions => {:user => 123456}
+
+ say "#{user} said something in channel #{channel}", 237872
+ say "#{user} said something in channel #{channel}", "System Administration"
+
+## TODO
+
+* Write the tests
+* Allow multiple values for conditions, eg: :conditions => {:channel => [/someregex/, "Some channel"]}
+* Remove debugging output
+* Add support for a logger
+
+## Known issues
+
+* Bot doesn't detect that it's been kicked out of a channel and recommect
+* Bot tends to crash when it encounters an error.
+
+## How to contribute
+
+Here's the most direct way to get your work merged into the project:
+
+1. Fork the project
+2. Clone down your fork
+3. Create a feature branch
+4. Add your feature + tests
+5. Make sure everything still passes by running the tests
+6. If necessary, rebase your commits into logical chunks, without errors
+7. Push the branch up
+8. Send a pull request for your branch
+
+Take a look at the TODO list or known issues for some inspiration if you need it.
+
+## License
+
+Copyright (C) 2011 by Will Jessop
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
1  Rakefile
@@ -0,0 +1 @@
+require 'bundler/gem_tasks'
76 examples/bot.rb
@@ -0,0 +1,76 @@
+#!/usr/bin/env ruby
+
+$:.unshift File.join(File.dirname(__FILE__), '../lib')
+
+require 'Scamp'
+
+scamp = Scamp.new(:api_key => "YOUR API KEY")
+
+Scamp.behaviour do
+ # Match some regex limited to a channel condition based on a channel id
+ match /^channel id (.+)$/, :conditions => {:channel => 401839} do
+ # Reply in the current channel
+ say "Match some regex limited to a channel condition based on a channel id"
+ end
+
+ # Limit a match to a channel condition based on a string
+ match "channel name check", :conditions => {:channel => "Monitoring"} do
+ say "Limit a match to a channel condition based on a string"
+ end
+
+ # Limit a match to a channel condition based on a regex
+ match /^channel regex (.+)$/, :conditions => {:channel => /someregex/} do
+ say "Limit a match to a channel condition based on a regex"
+ end
+
+ # Limit a match to a user condition based on a regex
+ match /^user regex (.+)$/, :conditions => {:user => /someregex/} do
+ say "Limit a match to a user condition based on a regex"
+ end
+
+ # Limit a match to a user condition based on a string
+ match /^user name (.+)$/, :conditions => {:user => "Will Jessop"} do
+ say "Limit a match to a user condition based on a string"
+ end
+
+ # Limit a match to a user condition based on a string
+ match "user id check", :conditions => {:user => 774016} do
+ say "Limit a match to a user condition based on an ID"
+ end
+
+ # Limit a match to a channel & user condition combined
+ match /^something (.+)$/, :conditions => {:channel => "Monitoring", :user => "Will Jessop"} do
+ # Reply in the current channel
+ say "Limit a match to a channel & user condition combined"
+ end
+
+ # Match text with a regex, access the captures from the match object
+ match /^repeat (\w+), (\w+)$/ do
+ say "You said #{matches[0]} and #{matches[1]}"
+ end
+
+ # Match text with a regex, access the named captures as a method
+ match /^say (?<yousaid>.+)$/ do
+ say "You said #{yousaid}"
+ end
+
+ # Simple string match, interpolating the channel and user in response.
+ match "something" do |data|
+ # Send the response to a different channel
+ say "#{user} said something in channel #{channel}", "Robot Army"
+
+ # Send the response to a different channel, using the channel ID
+ say "#{user} said something in channel #{channel}", 293788
+
+ # Send the response to the originating channel
+ say "#{user} said something in channel #{channel}"
+ end
+
+ match "multi-condition match", :conditions => {:channel => [401839, "Monitoring"], :nick => ["Will Jessop", "Noah Lorang"]} do
+ # Reply in the current channel
+ say "multi-condition match"
+ end
+end
+
+# FIXME: this does if the channel doesn't exist. Need a better error.
+scamp.connect!([293788, "Monitoring"])
51 lib/scamp.rb
@@ -0,0 +1,51 @@
+require 'eventmachine'
+require 'em-http-request'
+require 'yajl'
+
+require "scamp/version"
+require 'scamp/connection'
+require 'scamp/channels'
+require 'scamp/users'
+require 'scamp/matcher'
+require 'scamp/action'
+
+class Scamp
+ include Connection
+ include Channels
+ include Users
+
+ attr_accessor :channels, :user_cache, :channel_cache
+ attr :matchers, :api_key
+
+ def initialize(options = {})
+ options ||= {}
+ raise ArgumentError, "You must pass an API key" unless options[:api_key]
+
+ @api_key = options[:api_key]
+ @channels = {}
+ @user_cache = {}
+ @channel_cache = {}
+ @matchers ||= []
+ end
+
+ def behaviour &block
+ instance_eval &block
+ end
+
+ def connect!(channel_list)
+ connect(api_key, channel_list)
+ end
+
+ private
+
+ def match trigger, params={}, &block
+ params ||= {}
+ matchers << Matcher.new(self, {:trigger => trigger, :action => block, :conditions => params[:conditions]})
+ end
+
+ def process_message(msg)
+ matchers.each do |matcher|
+ matcher.attempt(msg)
+ end
+ end
+end
57 lib/scamp/action.rb
@@ -0,0 +1,57 @@
+#
+# Actions are run in the context of a Scamp::Action.
+# This allows us to make channel, nick etc. methods
+# available on a per-message basis
+#
+
+# {:room_id=>401839, :created_at=>"2011/09/10 00:23:19 +0000", :body=>"something", :id=>408089344, :user_id=>774016, :type=>"TextMessage"}
+
+class Scamp
+ class Action
+
+ attr :matches, :bot
+
+ def initialize(bot, action, message)
+ @bot = bot
+ @action = action
+ @message = message
+ end
+
+ def matches=(match)
+ @matches = match[1..-1]
+ match.names.each do |name|
+ name_s = name.to_sym
+ self.class.send :define_method, name_s do
+ match[name_s]
+ end
+ end
+ end
+
+ def channel
+ puts "Need the real channel name at #{__FILE__}:#{__LINE__}"
+ @message[:room_id]
+ end
+
+ def user
+ bot.username_for(@message[:user_id])
+ end
+
+ def user_id
+ @message[:user_id]
+ end
+
+ def message
+ @message[:body]
+ end
+
+ def run
+ self.instance_eval &@action
+ end
+
+ private
+
+ def say(msg, channel_id_or_name = channel)
+ bot.say(msg, channel_id_or_name)
+ end
+ end
+end
101 lib/scamp/channels.rb
@@ -0,0 +1,101 @@
+class Scamp
+ module Channels
+ # TextMessage (regular chat message),
+ # PasteMessage (pre-formatted message, rendered in a fixed-width font),
+ # SoundMessage (plays a sound as determined by the message, which can be either “rimshot”, “crickets”, or “trombone”),
+ # TweetMessage (a Twitter status URL to be fetched and inserted into the chat)
+
+ # curl -vvv -H 'Content-Type: application/json' -d '{"message":{"body":"Yeeeeeaaaaaahh", "type":"Textmessage"}}' -u API_KEY:X https://37s.campfirenow.com/room/293788/speak.json
+ def say(message, channel)
+ url = "https://37s.campfirenow.com/room/#{channel_id(channel)}/speak.json"
+ http = EventMachine::HttpRequest.new(url).post :head => {'Content-Type' => 'application/json', 'authorization' => [api_key, 'X']}, :body => Yajl::Encoder.encode({:message => {:body => message, :type => "Textmessage"}})
+
+ http.errback { STDERR.puts "Error speaking: '#{message}' to #{channel_id(channel)}" }
+ end
+
+ def paste(text, channel)
+ end
+
+ def upload
+ end
+
+ def join(channel_id)
+ url = "https://37s.campfirenow.com/room/#{channel_id}/join.json"
+ http = EventMachine::HttpRequest.new(url).post :head => {'Content-Type' => 'application/json', 'authorization' => [api_key, 'X']}
+
+ http.errback { STDERR.puts "Error joining channel: #{channel_id}" }
+ http.callback {
+ yield if block_given?
+ }
+ end
+
+ def channel_id(channel_id_or_name)
+ if channel_id_or_name.is_a? Integer
+ return channel_id_or_name
+ else
+ return channel_id_from_channel_name(channel_id_or_name)
+ end
+ end
+
+ def channel_name_for(channel_id)
+ data = channel_cache_data(channel_id)
+ return data["name"] if data
+ channel_id.to_s
+ end
+
+ private
+
+ def channel_cache_data(channel_id)
+ return channel_cache[channel_id] if channel_cache.has_key? channel_id
+ fetch_channel_data(channel_id)
+ return false
+ end
+
+ def populate_channel_list
+ url = "https://37s.campfirenow.com/rooms.json"
+ http = EventMachine::HttpRequest.new(url).get :head => {'authorization' => [api_key, 'X']}
+ http.errback { puts http.status }
+ http.callback {
+ new_channels = {}
+ Yajl::Parser.parse(http.response)['rooms'].each do |c|
+ new_channels[c["name"]] = c
+ end
+ # No idea why using the "channels" accessor here doesn't
+ # work but accessing the ivar directly does. There's
+ # Probably a bug.
+ @channels = new_channels # replace existing channel list
+ yield if block_given?
+ }
+ end
+
+ def fetch_channel_data(channel_id)
+ STDERR.puts "Fetching channel data for #{channel_id}"
+ url = "https://37s.campfirenow.com/room/#{channel_id}.json"
+ http = EventMachine::HttpRequest.new(url).get :head => {'authorization' => [api_key, 'X']}
+ http.errback { STDERR.puts "Couldn't get data for channel #{channel_id} at url #{url}" }
+ http.callback {
+ puts "Fetched channel data for #{channel_id}"
+ room = Yajl::Parser.parse(http.response)['room']
+ channel_cache[room["id"]] = room
+ room['users'].each do |u|
+ update_user_cache_with(u["id"], u)
+ end
+ }
+ end
+
+ def stream(channel_id)
+ json_parser = Yajl::Parser.new :symbolize_keys => true
+ json_parser.on_parse_complete = method(:process_message)
+
+ url = "https://streaming.campfirenow.com/room/#{channel_id}/live.json"
+ http = EventMachine::HttpRequest.new(url).get :head => {'authorization' => [api_key, 'X']}
+ http.errback { STDERR.puts "Couldn't stream channel #{channel_id} at url #{url}" }
+ http.stream {|chunk| json_parser << chunk }
+ end
+
+ def channel_id_from_channel_name(channel_name)
+ puts "Looking for channel id for #{channel_name}"
+ channels[channel_name]["id"]
+ end
+ end
+end #class
21 lib/scamp/connection.rb
@@ -0,0 +1,21 @@
+class Scamp
+ module Connection
+ private
+
+ def connect(api_key, channels_to_join)
+ EventMachine.run do
+ # Ideally populate_channel_list would block, but I can't see an easy way to do this, so a hacky callback it is.
+ populate_channel_list do
+ channels_to_join.map{|c| channel_id(c) }.each do |id|
+ puts "Joining channel #{id}"
+ join(id) do
+ fetch_channel_data(id)
+ stream(id)
+ end
+ end
+ end
+ end
+ end
+
+ end #module
+end #class
79 lib/scamp/matcher.rb
@@ -0,0 +1,79 @@
+class Scamp
+ class Matcher
+ attr_accessor :conditions, :trigger, :action, :bot
+
+ def initialize(bot, params = {})
+ params ||= {}
+ params[:conditions] ||= {}
+ params.each { |k,v| send("#{k}=", v) }
+ @bot = bot
+ end
+
+ def attempt(msg)
+ return false unless conditions_satisfied_by(msg)
+ match = triggered_by(msg[:body])
+ if match
+ if match.is_a? MatchData
+ run(msg, match)
+ else
+ run(msg)
+ end
+ return true
+ end
+ false
+ end
+
+ private
+
+ def triggered_by(message_text)
+ if trigger.is_a? String
+ return true if trigger == message_text
+ elsif trigger.is_a? Regexp
+ return trigger.match message_text
+ else
+ STDERR.puts "Don't know what to do with #{trigger.inspect} at #{__FILE__}:#{__LINE__}"
+ end
+ false
+ end
+
+ def run(msg, match = nil)
+ action_run = Action.new(bot, action, msg)
+ action_run.matches = match if match
+ action_run.run
+ end
+
+ def conditions_satisfied_by(msg)
+ # STDERR.puts "Need to take into account nick, channel and regexps at #{__FILE__}:#{__LINE__}"
+
+ # nick
+ # channel name
+ # nick regex
+ # channel regex
+
+ #{"room_id":1,"created_at":"2009-12-01 23:44:40","body":"hello","id":1,"user_id":1,"type":"TextMessage"}
+
+ # item will be :nick or :channel
+ # cond is the regex, int or string value.
+ conditions.each do |item, cond|
+ STDERR.puts "Checking #{item} against #{cond}"
+ puts "msg is #{msg.inspect}"
+ if cond.is_a? Integer
+ # puts "item is #{msg[{:channel => :room_id, :user => :user_id}[item]]}"
+ return false unless msg[{:channel => :room_id, :user => :user_id}[item]] == cond
+ elsif cond.is_a? String
+ case item
+ when :channel
+ return false unless bot.channel_name_for(msg[:room_id]) == cond
+ when :user
+ return false unless bot.username_for(msg[:user_id]) == cond
+ end
+ STDERR.puts "Don't know how to deal with a match item of #{item}, cond #{cond}"
+ elsif cond.is_a? Regexp
+ return false
+ return false unless msg[item].match(cond)
+ end
+ end
+ true
+ end
+ end
+end
45 lib/scamp/users.rb
@@ -0,0 +1,45 @@
+class Scamp
+ module Users
+
+ # <user>
+ # <id type="integer">1</id>
+ # <name>Jason Fried</name>
+ # <email-address>jason@37signals.com</email-address>
+ # <admin type="boolean">true</admin>
+ # <created-at type="datetime">2009-11-20T16:41:39Z</created-at>
+ # <type>Member</type>
+ # <avatar-url>http://asset0.37img.com/global/.../avatar.png</avatar-url>
+ # </user>
+
+ # Return the user_id if we haven't got the real name and
+ # kick off a user data fetch
+ def username_for(user_id)
+ return user_cache[user_id]["name"] if user_cache[user_id]
+ fetch_data_for(user_id)
+ return user_id.to_s
+ end
+
+ private
+
+ def fetch_data_for(user_id)
+ url = "https://37s.campfirenow.com/users/#{user_id}.json"
+ http = EventMachine::HttpRequest.new(url).get(:head => {'authorization' => [api_key, 'X'], "Content-Type" => "application/json"})
+ puts http.inspect
+ http.callback do
+ STDERR.puts "Got the data for #{user_id}"
+ update_user_cache_with(user_id, Yajl::Parser.parse(http.response)['user'])
+ end
+ http.errback do
+ STDERR.puts "Couldn't fetch user data for #{user_id} with url #{url}"
+ STDERR.puts http.response_header.status
+ STDERR.puts http.response_header.inspect
+ STDERR.puts http.response.inspect
+ end
+ end
+
+ def update_user_cache_with(user_id, data)
+ STDERR.puts "Updated user cache for #{data['name']}"
+ user_cache[user_id] = data
+ end
+ end
+end
3  lib/scamp/version.rb
@@ -0,0 +1,3 @@
+module Scamp
+ VERSION = "0.0.1"
+end
22 scamp.gemspec
@@ -0,0 +1,22 @@
+# -*- encoding: utf-8 -*-
+$:.push File.expand_path("../lib", __FILE__)
+require "Scamp/version"
+
+Gem::Specification.new do |s|
+ s.name = "Scamp"
+ s.version = Scamp::VERSION
+ s.authors = ["Will Jessop"]
+ s.email = ["will@willj.net"]
+ s.homepage = ""
+ s.summary = %q{Eventmachine based Campfire bot framework}
+ s.description = %q{Eventmachine based Campfire bot framework}
+
+ s.files = `git ls-files`.split("\n")
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
+ s.require_paths = ["lib"]
+
+ s.add_dependency('eventmachine', '~> 0.12.10')
+ s.add_dependency('yajl-ruby', '~> 0.8.3')
+ s.add_dependency('em-http-request', '~> 0.3.0')
+end
Please sign in to comment.
Something went wrong with that request. Please try again.