# -*- coding: utf-8 -*- require 'xmpp4r/message' require_relative '../module_base' module Lain module Modules class Topic < Base def on_message(muc, message) return unless /\A!topic\b/ =~ message.body if /\A!topic\s*(?:\ss(?:how)?.*)?\Z/ =~ message.body show_topic(muc, message) elsif /\A!topic\s+a(?:dd)?\s+(.+)\Z/ =~ message.body add_topic(muc, message, $~[1].strip) elsif /\A!topic\s+d(?:el(?:ete)?)?\s+([[:xdigit:]]+)\Z/ =~ message.body del_topic(muc, message, $~[1].to_i(16)) end end def commands { '!topic [s[how]]' => 'show topics (with indices)', '!topic a[dd] ' => 'add a topic', '!topic d[el[ete]] ' => 'remove topic ' } end private def current_topic(muc) topic = muc.subject return [] if topic.nil? topic.split('|').map { |s| s.strip } end def set_topic(muc, topic) muc.subject = topic.join(" | ") end def topic_list(topic) topic.each_with_index.map { |t, i| "[#{'%02x' % i}] #{t}" }.join("\n") end def show_topic(muc, message) topic = current_topic muc if topic.empty? muc.say "\nTOPIC EMPTY" return end muc.say("\nBEGIN TOPIC LIST\n" + topic_list(topic) + "\nEND TOPIC LIST") end def add_topic(muc, message, text) topic = current_topic muc if text.empty? pre = "\nERROR: No topic given." else topic.unshift text set_topic(muc, topic) pre = "\nSUCCESS" end muc.say(pre + "\n\nBEGIN TOPIC LIST\n" + topic_list(topic) + "\nEND TOPIC LIST") end def del_topic(muc, message, index) topic = current_topic muc begin deleted = topic.delete_at index rescue deleted = nil end if deleted.nil? pre = "\nERROR: Invalid index [#{'%02x' % index}]." else set_topic(muc, topic) pre = "\nSUCCESS" end muc.say(pre + "\n\nBEGIN TOPIC LIST\n" + topic_list(topic) + "\nEND TOPIC LIST") end end end end