跳转到主要内容

聊天集成

discourse-chat-integration 抽象了 Discourse 与外部聊天室系统集成所需的样板代码。提供商实现可以支持三种功能:通知、斜杠命令和聊天记录。

添加提供商有两种方式:在你自己的插件中添加,或者向 discourse-chat-integration 提交拉取请求。本文将详细介绍后者,但其中大部分信息在两种情况下都适用。

本文对整体工作方式做了一般性概述,但理解它的最佳方式是阅读现有提供商的代码。我已尽量用注释说明不常见的部分,并很乐意在此话题中回答问题 :slight_smile:

添加通知支持 :bell:

  1. 在 Provider 文件夹中,以你的聊天室系统名称创建一个新文件夹:例如 hipchat
  2. 按照格式 hipchat_provider.rb 创建一个新的 ruby 文件
  3. 在其中,于 DiscourseChat::Provider 内定义一个新模块。模块名称必须以 Provider 结尾才能被正确加载。你的模块必须定义三个常量:
    • PROVIDER_NAME:用于在内部引用你的提供商的字符串。不应包含任何空白字符。它可能与文件夹名称相同
    • PROVIDER_ENABLED_SETTING:一个符号,引用用于启用/禁用此提供商的站点设置。确保你在插件的 settings.yml 文件中定义它。
    • CHANNEL_PARAMETERS:一个哈希数组,定义你的提供商需要的每个频道的有关数据。这可能是 URL、用户名,或某种“频道 ID"。每个哈希应指定参数
      • key:你之后用来引用该数据的键
      • regex:用于验证用户提供值的正则表达式。客户端和服务器都会进行检查。例如,要只允许非空白字符,你可以使用 ^\S+$
      • unique:(可选)将此项设置为 true,以阻止用户使用相同的参数值创建多个频道
      • hidden:(可选)将此项设置为 true,以在频道列表中隐藏此参数。它在“编辑频道”弹窗中始终会显示。

[quote] :information_source: 如果你的频道参数不易被人读懂,你可能需要添加一个"Name"参数,让用户输入一个更有用的频道标识符以便参考。示例参见 hipchat 提供商。 [/quote]

  1. 你的模块还必须定义函数 self.trigger_notification(post, channel)。在此函数内,你应编写实际向聊天系统发送通知的代码。具体实现因提供商而异,但通常包括向其 API 发送 RESTful 请求。可以参考现有提供商的实现来帮助你。
  2. 确保处理提供商 API 返回的错误。你应抛出一个 DiscourseChat::ProviderError,并可选地指定一个(客户端)翻译键来提供有关错误的信息。该信息将显示在管理界面中当前频道的对应位置。你可以在 info 哈希中指定其他对象,这些对象会包含在站点的日志中。
  3. 为确保 Discourse 加载你的 ruby 文件,你应在 provider.rb 底部添加一行 require_relative。

最终你应该得到类似这样的内容:

module DiscourseChat::Provider::HipchatProvider

  # This should be unique, and without whitespace
  PROVIDER_NAME = "hipchat".freeze

  # Make sure the referenced setting has been added to settings.yml as a boolean
  PROVIDER_ENABLED_SETTING = :chat_integration_hipchat_enabled

  CHANNEL_PARAMETERS = [
                        { key: "name", regex: '^\S+' }, # Must not start with a space
                        { key: "webhook_url", regex: 'hipchat\.com', unique: true, hidden: true }, # Must contain hipchat.com
                        { key: "color", regex: '^(yellow|green|red|purple|gray|random)$' } # Must be one of these colors
                       ]

  def self.trigger_notification(post, channel)

    # Access the user-defined channel parameters like this
    webhook_url = channel.data['webhook_url']
    color = channel.data['color']

    # The "post" object can be used to get the information to send
    title = post.topic.title
    link_url = post.full_url

    # Post.excerpt has a number of options you can use to format nicely before sending to your chat system
    # Most of the time, you'll want remap_emojis to convert discourse emojis to unicode
    excerpt = post.excerpt(400, text_entities: true, strip_links: true, remap_emoji: true)

    # Make an API request to your API provider
    # This might be useful: http://www.rubyinside.com/nethttp-cheat-sheet-2940.html

    # Parse the response to your API request, and raise any errors using the DiscourseChat::ProviderError
    error_key = 'chat_integration.provider.hipchat.invalid_color'
    raise ::DiscourseChat::ProviderError.new info: {error_key: error_key}

  end
end

翻译键

在 client.en.yml 中,你应该为你的提供商指定一个标题,为任意参数指定标题和帮助信息,并在抛出 DiscourseChat::ProviderError 时指定你所使用的错误键。例如:

en:
  js:
    chat_integration:
      provider:
        hipchat:
          title: "HipChat"
          param:
            name:
              title: "Name"
              help: "A name to describe the channel. It is not used for the connection to HipChat."
            webhook_url:
              title: "Webhook URL"
              help: "The webhook URL created in your HipChat integration"
            color:
              title: "Color"
              help: "The color of the message in HipChat. Must be one of yellow,green,red,purple,gray,random"
          errors:
            invalid_color: "The API rejected the color you selected"

你应该确保同时为你创建的所有站点设置提供翻译。除非你在 self.trigger_notification 实现中使用它们,否则无需定义任何服务器端翻译

添加斜杠命令支持 :speech_balloon:

那么,你的通知已经正常运行了,但你希望能够在聊天系统内部控制规则。常见的做法是使用“斜杠命令”。不同的聊天系统实现方式略有不同,但总体思路是你拥有表示“操作”的关键词,之后可以提供参数。例如,在 Slack 中我们有

/discourse watch support tag:help

为此,你需要了解你的聊天系统提供了什么方法来使用斜杠命令进行通信。大多数提供商都能够“注册”斜杠命令,然后输入一个 URL,每当你的斜杠命令被调用时,该 URL 都会收到一个 POST 请求。

discourse-chat-integration 提供了一些系统来帮助你完成这项工作。要在论坛上 /chat-integration/ 下注册一个新的 URL,你应该在提供商的文件夹中创建一个新文件,名称类似于 telegram_command_controller.rb。

module DiscourseChat::Provider::TelegramProvider
  class TelegramCommandController < DiscourseChat::Provider::HookController
    requires_provider ::DiscourseChat::Provider::TelegramProvider::PROVIDER_NAME

    before_filter :telegram_token_valid?, only: :command

    skip_before_filter :check_xhr,
                       :preload_json,
                       :verify_authenticity_token,
                       :redirect_to_login_if_required,
                       only: :command

    def command
      # Work out which channel the commands are coming from
      chat_id = params['message']['chat']['id']

      provider = DiscourseChat::Provider::TelegramProvider::PROVIDER_NAME

      channel = DiscourseChat::Channel.with_provider(provider).with_data_value('chat_id', chat_id).first

      if channel.exists?

        # This is something like "watch support tag:hello"
        text = params['message']['text']

        # Split each parameter into its own item
        tokens = message['text'].split(" ")

        # Use the helper method to process the command
        response = ::DiscourseChat::Helper.process_command(channel, tokens)

        # You can call methods from your provider module to send
        # a response back
        DiscourseChat::Provider::TelegramProvider.sendMessage(message)
     end

      # Always give telegram a success message, otherwise we'll stop receiving webhooks
      data = {
        success: true
      }
      render json: data
    end

    def telegram_token_valid?
      params.require(:token)

      if SiteSetting.chat_integration_telegram_secret.blank? ||
         SiteSetting.chat_integration_telegram_secret != params[:token]
        raise Discourse::InvalidAccess.new
      end
    end
  end

  class TelegramEngine < ::Rails::Engine
    engine_name DiscourseChat::PLUGIN_NAME + "-telegram"
    isolate_namespace DiscourseChat::Provider::TelegramProvider
  end

  TelegramEngine.routes.draw do
    post "command/:token" => "telegram_command#command"
  end
end

一些值得注意的事项:

  • 你的控制器应该继承自 DiscourseChat::Provider::HookController。这可以确保在插件被禁用时它也被禁用
  • 你需要以某种方式验证请求的真实性。这因提供商而异,但 before_filter 通常效果不错。
  • skip_before_filter 项是必选项,这样你的端点在被提供商调用时才能正常工作。
  • 你应该在提供商的模块内部定义一个 Rails::Engine。它应该以 Engine 结尾,并且会被自动加载到 URL /chat-integration/<provider name> 下
  • 有一个辅助方法 DiscourseChat::Helper.process_command(channel, tokens),它处理创建/编辑规则的实际逻辑。你只需将频道对象和一个字符串数组传递给它

语言字符串 要使用 Helper.process_command 方法,你需要在 server.en.yml 中为你的提供商定义这些语言字符串:

mattermost:
  status:
    header: |
      *Rules for this channel*
      (if multiple rules match a post, the topmost rule is executed)
    no_rules: "There are no rules set up for this channel. Run `/discourse help` for instructions."
    rule_string: "*%{index})* *%{filter}* posts in *%{category}*"
    rule_string_tags_suffix: " with tags: *%{tags}*"
  parse_error: "Sorry, I didn't understand that. Run `/discourse help` for instructions."
  create:
    created: "Rule created successfully"
    updated: "Rule updated successfully"
    error: "Sorry, an error occured while creating that rule."
  delete:
    success: "Rule deleted successfully"
    error: "Sorry, an error occured while deleting that rule. Run `/discourse status` for a list of rules."
  not_found:
    tag: "The *%{name}* tag cannot be found."
    category: "The *%{name}* category cannot be found. Available categories: *%{list}*"
  help: |
    *New rule:* `/discourse [watch|follow|mute] [category] [tag:name]`
    (you must specify a rule type and at least one category or tag)
    - *watch* – notify this channel for new topics and new replies
    - *follow* – notify this channel for new topics
    - *mute* – block notifications to this channel

    *Remove rule:* `/discourse remove [rule number]`
    (`[rule number]` can be found by running `/discourse status`)

    *List rules:* `/discourse status`

    *Help:* `/discourse help`

添加聊天记录发布支持 :scroll:

发布聊天记录是为 discourse-chat-integration 实现提供商最难的部分。由于各提供商的 API 差异巨大,几乎没有可供提供商之间共享的逻辑。

随着越来越多的提供商被实现,或许可以抽象行为以便共享。欢迎在为更多提供商提供聊天记录支持的同时,提交此类抽象的 PR。

有一个辅助方法,负责将聊天记录存储在服务器上,以便用户撰写草稿。DiscourseChat::Helper.save_transcript(text) 方法接受一个字符串(包含帖子的正文),并返回一个密钥字符串。聊天记录将在服务器上存储 1 小时。

https://github.com/discourse/discourse-chat-integration/blob/4f9ad4efefa0270e00a24e711dd65ff1928b82cf/app/helpers/helper.rb#L192-L198

要让用户访问聊天记录,你应该给他们一个如下格式的链接

为新提供商实现聊天记录支持的最佳方法是查看 Slack 的实现:

https://github.com/discourse/discourse/blob/main/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/slack/slack_transcript.rb