Gem ActiveNotifier 帮助你的应用更简单的发送钉钉消息

pinewong · 2018年08月02日 · 最后由 pinewong 回复于 2018年10月18日 · 4436 次阅读

警告:项目已更换,请使用 Dingtalk Client 代替

以下是旧帖内容...


通过 webhook 发送消息,例如 钉钉机器人

安装

$ gem install active_notifier

基本使用

直接通过命令形式发送消息。必须参数:token(第三方 webhook token,默认第三方适配器是钉钉),message

在 IRB 环境中执行:

ActiveNotifier.exec(token: "your-webhook-token", message: "your-message")

每次都指定 token 太麻烦,另外字符串的消息形式也不好用,如果能像 Rails 的模版渲染一样就好了。这些我们都能实现。

在任何你想配置 ActiveNotifier 的文件中:

ActiveNotifier.configure do |config|
  config.channel_tokens = { my_channel: "xxx" }
  config.template_home = SOME_DIR
end

修改上述对应频道 my_channel 的模板:

$ echo "## #{data[:title]\n> #{data[:body]}}" > SOME_DIR/my_channel.markdown.erb

然后就可以改用下面的方法发送消息(其中 data 里的数据会被传到模板中进行预编译):

ActiveNotifier.exec(token_channel: :my_channel, template: :my_channel, data: { title: "Message Title", body: "Message Body" })

另外当我们 token_channeltemplate 名字一致时,我们可以使用 ActiveNotifier::exec 的可选参数 channel 简化:

ActiveNotifier.exec(:my_channel, data: { title: "Message Title", body: "Message Body" })

Rails 应用

对于 Rails 应用,这里还有一些生成器,可以简化上面一些复制粘贴的工作:

$ rails generate active_notifier:install

其他知识

关键方法

通过上述使用,我们可以知道 ActiveNotifer 功能主要就围绕一个 ::exec 方法,该方法还支持一些参数选项,使得更符合你的需求,具体可以看这里:RDoc exec

动态判断消息类型

消息类型选项 type 一般来说我们不用指定,他会根据我们模板类型自动判断。但是如果你有两个以上的模板类型,这时候你可以通过这个选项手动指定:

ActiveNotifier.exec(:order, data: { title: "Message Title", body: "Message Body" }, type: :text)

另外我们还有一个全局配置项 priority_type,该选项可以指定优先的类型,假设对于一个消息模版有三种实现:order.text.erb, order.markdown.erb, order.flow.erb,这时候 ActiveNotifier 会优先选择 priority_type 配置值:

ActiveNotifier.configure do |config|
  # default is :markdown
  config.priority_type = :text
end

下面命令发送的消息类型,会是 text:

ActiveNotifier.exec(:book, data: { title: "Message Title", body: "Message Body" }) # 如果是 type(同 priority_type) 类型,可以不显示指定

设置简短常量

ActiveNotifer.config.const_name = :Notifier
Notifer.exec(...)

文档和帮助

最后

希望对大家有用。项目链接:https://github.com/pinewong/active_notifier

@pinewong 老哥,能写个自动签到的脚本吗?

puma 回复

没这个需求。(要打卡可以找虚拟定位)

需要 登录 后方可回复, 如果你还没有账号请 注册新账号