Class: Clacky::Channel::Adapters::Wecom::Adapter

Inherits:
Base
  • Object
show all
Defined in:
lib/clacky/server/channel/adapters/wecom/adapter.rb

Overview

WeCom (Enterprise WeChat) adapter. Receives messages via WebSocket long connection and sends via bot API.

Constant Summary collapse

MAX_IMAGE_BYTES =
Clacky::Utils::FileProcessor::MAX_IMAGE_BYTES

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#platform_id, #supports_message_updates?, #update_message

Constructor Details

#initialize(config) ⇒ Adapter

Returns a new instance of Adapter.



35
36
37
38
39
40
41
42
43
44
# File 'lib/clacky/server/channel/adapters/wecom/adapter.rb', line 35

def initialize(config)
  @config = config
  @ws_client = WSClient.new(
    bot_id: config[:bot_id],
    secret: config[:secret],
    ws_url: config[:ws_url] || WSClient::WS_URL
  )
  @running = false
  @on_message = nil
end

Class Method Details

.env_keysObject



19
20
21
# File 'lib/clacky/server/channel/adapters/wecom/adapter.rb', line 19

def self.env_keys
  %w[IM_WECOM_BOT_ID IM_WECOM_SECRET]
end

.platform_config(data) ⇒ Object



23
24
25
26
27
28
# File 'lib/clacky/server/channel/adapters/wecom/adapter.rb', line 23

def self.platform_config(data)
  {
    bot_id: data["IM_WECOM_BOT_ID"],
    secret: data["IM_WECOM_SECRET"]
  }
end

.platform_idObject



15
16
17
# File 'lib/clacky/server/channel/adapters/wecom/adapter.rb', line 15

def self.platform_id
  :wecom
end

.set_env_data(data, config) ⇒ Object



30
31
32
33
# File 'lib/clacky/server/channel/adapters/wecom/adapter.rb', line 30

def self.set_env_data(data, config)
  data["IM_WECOM_BOT_ID"] = config[:bot_id]
  data["IM_WECOM_SECRET"] = config[:secret]
end

Instance Method Details

#handle_raw_message(raw) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/clacky/server/channel/adapters/wecom/adapter.rb', line 78

def handle_raw_message(raw)
  msgtype = raw["msgtype"]
  return unless %w[text image file].include?(msgtype)

  chat_id = raw["chatid"] || raw.dig("from", "userid")
  return unless chat_id

  user_id = raw.dig("from", "userid")
  chat_type = raw["chattype"] == "group" ? :group : :direct
  text  = ""
  files = []

  case msgtype
  when "text"
    text = raw.dig("text", "content").to_s.strip
    return if text.empty?
  when "image"
    url    = raw.dig("image", "url")
    aeskey = raw.dig("image", "aeskey")
    return unless url
    result = MediaDownloader.download(url, aeskey)
    mime = MediaDownloader.detect_mime(result[:body])
    if result[:body].bytesize > MAX_IMAGE_BYTES
      @ws_client.send_message(chat_id, "Image too large (#{(result[:body].bytesize / 1024.0).round(0).to_i}KB), max #{MAX_IMAGE_BYTES / 1024}KB")
      return
    end
    require "base64"
    data_url = "data:#{mime};base64,#{Base64.strict_encode64(result[:body])}"
    files = [{ name: "image.jpg", mime_type: mime, data_url: data_url }]
  when "file"
    url      = raw.dig("file", "url")
    aeskey   = raw.dig("file", "aeskey")
    return unless url
    filename = raw.dig("file", "name") || raw.dig("file", "filename") || "attachment"
    result   = MediaDownloader.download(url, aeskey)
    filename = result[:filename] || filename
    saved = Clacky::Utils::FileProcessor.save(body: result[:body], filename: filename)
    files = [saved]
  end

  event = {
    type: :message,
    platform: :wecom,
    chat_id: chat_id,
    user_id: user_id,
    text: text,
    files: files,
    message_id: raw["msgid"],
    timestamp: raw["create_time"] ? Time.at(raw["create_time"]) : Time.now,
    chat_type: chat_type,
    raw: raw
  }

  @on_message&.call(event)
rescue => e
  Clacky::Logger.error("[WecomAdapter] handle_raw_message error: #{e.message}\n#{e.backtrace.first(3).join("\n")}")
  begin
    @ws_client.send_message(chat_id, "Error processing message: #{e.message}") if chat_id
  rescue
    nil
  end
end

#send_file(chat_id, path, name: nil) ⇒ Object



66
67
68
# File 'lib/clacky/server/channel/adapters/wecom/adapter.rb', line 66

def send_file(chat_id, path, name: nil)
  @ws_client.send_file(chat_id, path, name: name)
end

#send_text(chat_id, text, reply_to: nil) ⇒ Object



62
63
64
# File 'lib/clacky/server/channel/adapters/wecom/adapter.rb', line 62

def send_text(chat_id, text, reply_to: nil)
  @ws_client.send_message(chat_id, text)
end

#start(&on_message) ⇒ Object



46
47
48
49
50
51
52
53
54
55
# File 'lib/clacky/server/channel/adapters/wecom/adapter.rb', line 46

def start(&on_message)
  @running = true
  @on_message = on_message

  @ws_client.start do |raw|
    handle_raw_message(raw)
  end
rescue WSClient::AuthError => e
  Clacky::Logger.error("[WecomAdapter] Authentication failed, not retrying: #{e.message}")
end

#stopObject



57
58
59
60
# File 'lib/clacky/server/channel/adapters/wecom/adapter.rb', line 57

def stop
  @running = false
  @ws_client.stop
end

#validate_config(config) ⇒ Object



70
71
72
73
74
75
# File 'lib/clacky/server/channel/adapters/wecom/adapter.rb', line 70

def validate_config(config)
  errors = []
  errors << "bot_id is required" if config[:bot_id].nil? || config[:bot_id].empty?
  errors << "secret is required" if config[:secret].nil? || config[:secret].empty?
  errors
end