소스 검색

added a bit more framework, and a hello command

Kylie Jo Swistak 6 년 전
부모
커밋
240c0186e4
3개의 변경된 파일95개의 추가작업 그리고 2개의 파일을 삭제
  1. 18 0
      app/models/commands.rb
  2. 34 0
      app/models/concerns/serializable.rb
  3. 43 2
      bot.rb

+ 18 - 0
app/models/commands.rb

@@ -0,0 +1,18 @@
+require 'optparse'
+
+class Command
+  attr_reader :name, :options_parser, :operation
+
+  def initialize(name, options ={}, &block)
+    @name = name
+    @operation = block
+  end
+
+  def call(message_str, event=nil)
+    match = /pkmn-\w+\s?(.*)/.match(message_str)
+    args = match[1]
+    params = args.split(/\s?\|\s?/).reject(&:empty?)
+
+    operation.call(event, *params)
+  end
+end

+ 34 - 0
app/models/concerns/serializable.rb

@@ -0,0 +1,34 @@
+# frozen_string_literal: true
+
+module Serializable
+  extend ActiveSupport::Concern
+
+  def initialize(json)
+    unless json.blank?
+      json = JSON.parse(json) if json.is_a?(String)
+      json.to_hash.each do |k, v|
+        klass = self.class.constants.detect { |c| c.downcase == k.to_sym }
+        v = self.class.const_get(klass).new(v) if klass
+
+        public_send("#{k}=", v)
+      end
+    end
+  end
+
+  class_methods do
+    def load(json)
+      return nil if json.blank?
+
+      new(json)
+    end
+
+    def dump(obj)
+      # Make sure the type is right.
+      if obj.is_a?(self)
+        obj.to_json
+      else
+        raise "Expected #{self}, got #{obj.class}"
+      end
+    end
+  end
+end

+ 43 - 2
bot.rb

@@ -10,6 +10,9 @@ Bundler.require(:default, BOT_ENV)
 require 'active_record'
 
 # Constants: such as roles and channel ids
+
+HAP_ROTOM = "https://static.pokemonpets.com/images/monsters-images-800-800/479-Rotom.png"
+
 # ---
 
 Dotenv.load if BOT_ENV != 'production'
@@ -38,14 +41,52 @@ bot = Discordrb::Bot.new(token: token)
 # ---
 
 # Commands: structure basic bot commands here
+
+hello = Command.new(:hello) do |event|
+  user = event.author.nickname || event.author.name
+
+  greetings = [
+    "Hi there, #{user}",
+    "Greetings #{user}, you lovable bum",
+    "Alola, #{user}",
+    "Hello, #{user}! The Guildmasters have been waiting",
+    "#{user} would like to battle!"
+  ]
+
+  Embed.new(
+    description: greetings.sample,
+    color: event.author.color.combined,
+    thumbnail: {
+      url: HAP_ROTOM
+    }
+  )
+end
+
 # ---
 
+commands = [
+  hello
+]
+
 # This will trigger on every message sent in discord
 bot.message do |event|
   content = event.message.content
 
-  if content == '!hello'
-    event.respond("Hello there #{event.author.name}")
+  if (match = /^pkmn-(\w+)/.match(content))
+      command = match[1]
+
+      if cmd = commands.detect { |c| c.name == command.to_sym }
+        reply = cmd.call(content, event)
+
+        if reply.is_a? Embed
+          event.send_embed("", reply)
+        elsif reply
+          event.respond(reply)
+        else
+          event.respond("Something went wrong!")
+        end
+      end
+
   end
 end