File: messagebot.nb

package info (click to toggle)
nadoka 0.10.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 492 kB
  • sloc: ruby: 3,154; makefile: 8; sh: 1
file content (96 lines) | stat: -rw-r--r-- 2,387 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# -*-ruby; coding: utf-8 -*- vim:set ft=ruby:
#
# Copyright (C) 2004 Kazuhiro NISHIYAMA
#     All rights reserved.
#     This is free software with ABSOLUTELY NO WARRANTY.
#
# You can redistribute it and/or modify it under the terms of
# the Ruby's licence.
#
=begin
BotConfig = [
{
  :name         => :MessageBot,
  :message_file => 'message.yaml',
  :root_key     => Setting_name,
  :channels     => %w[#nadoka #Ruby:*.jp],
  :nkf => "-Ww",
},
]
=end


require 'nkf'
require 'time'
require 'yaml/store'

class MessageBot < Nadoka::NDK_Bot
  
  def bot_initialize
    @store = YAML::Store.new(@bot_config[:message_file])
    @root_key = @bot_config[:root_key]
    @channels = @bot_config[:channels].collect{|ch| ch.downcase }
    @nkf = @bot_config[:nkf] || "-WjXm0"
    load_message
  end

  def load_message
    @store.transaction do |db|
      if db.root?(@root_key)
        h = db[@root_key]
        @list = h['list'] || Hash.new
        @message = h['message'] || Hash.new
      else
        @list = Hash.new
        @message = Hash.new
      end
    end
  end

  def save_message
    @store.transaction do |db|
      db[@root_key] = {
        'list' => @list,
        'message' => @message,
      }
    end
  end

  def on_privmsg prefix, ch, msg
    user = prefix.nick
    c = NKF.nkf('-w', ch.to_s).downcase
    return unless @channels.include?(c)
    u = user.downcase
    now = Time.now
    key = "#{c} #{u}"
    message_id = "<#{now.strftime('%Y%m%d%H%M%S')}.#{now.usec}.#{u}@#{c}>"
    if @list.key?(key)
      message_id_list = @list[key]
      message_id_list.each do |message_id|
        h = @message[message_id]
        next if h.key?('delivered')
        message = "#{h['from']}さんから#{h['to']}さんへ伝言「#{h['body']}」"
        send_notice(ch, NKF.nkf(@nkf, message))
        @message[message_id]['delivered'] = now
      end
      @list.delete(key)
      save_message
    end
    if /^伝言 (\S+) (.+)$/ =~ NKF.nkf('-w', msg.to_s)
      to_nick, body = $1, $2
      @message[message_id] = {
        'from' => user,
        'to' => to_nick,
        'date' => now,
        'channel' => ch,
        'body' => body,
      }
      key = "#{c} #{to_nick.downcase}"
      @list[key] ||= []
      @list[key].push(message_id)
      save_message
      send_notice(ch, NKF.nkf(@nkf, "#{$1}さんへの伝言を承りました > #{u}さん"))
    end
  end
  
end