Class: WechatWork::Wechat

Inherits:
Object
  • Object
show all
Defined in:
lib/wechat_work.rb

Instance Method Summary collapse

Constructor Details

#initializeWechat

Returns a new instance of Wechat.



36
37
38
39
40
41
42
43
44
# File 'lib/wechat_work.rb', line 36

def initialize
  @corpid = WechatWork.config.corpid
  @agentid = WechatWork.config.agentid
  @agentsecret = WechatWork.config.agentsecret

  @token = access_token
  @token_expire = 0
  @last_get_token_time = 0
end

Instance Method Details

#access_tokenObject



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/wechat_work.rb', line 46

def access_token
  url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=#{@corpid}&corpsecret=#{@agentsecret}"
  resp = RestClient.get url
  data = JSON.parse(resp)
  unless data['errcode'] == 0
    puts data
    raise AccessTokenError.new()
  end

  @token = data["access_token"]
  @last_get_token_time = Time.now.to_i
  @token_expire = data["expires_in"]

  @token
end

#send_text_message(content, *users) ⇒ Object



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
# File 'lib/wechat_work.rb', line 68

def send_text_message(content, *users)
  return unless content
  return if content.length == 0
  return if users.length == 0
  
  # 使用缓存token
  access_token if token_invalid?

  touser = users.join('|')  

  url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=#{@token}"
  payload = {
    touser: touser,
    msgtype: 'text',
    agentid: @agentid,
    text: {
      content: content
    }
  }

  resp = RestClient.post url, payload.to_json, {content_type: :json, accept: :json}
  data = JSON.parse(resp)

  if data['errcode'] != 0
    puts "send failed errorcode: #{data['errcode']}"
  end
end

#token_invalid?Boolean

Returns:

  • (Boolean)


62
63
64
65
# File 'lib/wechat_work.rb', line 62

def token_invalid?
  return true unless @token
  Time.now().to_i - @last_get_token_time > (@token_expire - 100)
end