├── .gitignore
├── LICENSE
├── Package.swift
├── README.md
├── README.zh_CN.md
├── Sources
├── config.swift
└── main.swift
├── bot.png
├── botuser.png
├── channels.png
├── config.json.sample
├── config.service.sample
├── events.png
├── install.png
├── install.sh.sample
├── perm.png
├── url.png
└── userlist.png
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | /.build
3 | /Packages
4 | /*.xcodeproj
5 | /*.xcworkspace
6 | /*.playground
7 | /*.pins
8 |
9 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/Package.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Package.swift
3 | // PerfectTemplate
4 | //
5 | // Created by Kyle Jessup on 4/20/16.
6 | // Copyright (C) 2016 PerfectlySoft, Inc.
7 | //
8 | //===----------------------------------------------------------------------===//
9 | //
10 | // This source file is part of the Perfect.org open source project
11 | //
12 | // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
13 | // Licensed under Apache License v2.0
14 | //
15 | // See http://perfect.org/licensing.html for license information
16 | //
17 | //===----------------------------------------------------------------------===//
18 | //
19 |
20 | import PackageDescription
21 |
22 | let package = Package(
23 | name: "PerfectTemplate",
24 | targets: [],
25 | dependencies: [
26 | .Package(url: "https://github.com/PerfectlySoft/Perfect-HTTPServer.git", majorVersion: 2),
27 | .Package(url: "https://github.com/PerfectlySoft/Perfect-CURL.git", majorVersion: 2),
28 | .Package(url: "https://github.com/PerfectlySoft/Perfect-SQLite.git", majorVersion: 2),
29 | .Package(url: "https://github.com/PerfectSideRepos/Perfect-RegEx.git", majorVersion: 1)
30 | ]
31 | )
32 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Perfect Slack Bot [简体中文](README.zh_CN.md)
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 | This is a starter template project for Slack Bot Servers.
43 | In this template, a slack bot will join Slack channels, record all "cookies" sent by users, and reply user's query about cookies automatically.
44 |
45 | ## Prerequisites
46 |
47 | Before building / testing or deploying your own Perfect Slack Bot into production, these steps *MUST* be well prepared:
48 |
49 | - [Perfect Basics](http://www.perfect.org/docs/gettingStartedFromScratch.html)
50 | - [Slack API Development](https://api.slack.com)
51 | - An actual server with a FQDN (full qualified domain name) and an authorized certificate
52 | - [Perfect Assistant](http://www.perfect.org/en/assistant/) will be used for building & deploying. It is optional, however, a Ubuntu 16.04 (virtual machine or docker image) with preinstalled Swift 3 would be required if not using Perfect Assistant.
53 |
54 | ## Quick Start
55 |
56 | ### Step 1. Clone This Project
57 |
58 | Please clone this project by command:
59 |
60 | ```
61 | $ git clone https://github.com/PerfectServers/SlackBot.git
62 | ```
63 |
64 | There is a `config.json.sample` file in the project folder with content below. All blanks should be fulfilled before running.
65 |
66 | ``` json
67 | {
68 | "token": "xoxb-YOURAPP-TOKENXXXXXXXXXXXXXXXXX",
69 | "bot" : "yourBotName",
70 | "bot_id": "YOUR_BOT_ID",
71 | "client_id": "XXXXXXXX.YYYYYYYYYY",
72 | "client_secret": "your-client-secret",
73 | "verify_token": "token-to-verify-by-your-app",
74 | "oauth_uri": "/v1/oauth",
75 | "message_uri": "/v1/message",
76 | "confirm_uri": "/v1/confirm",
77 | "serverName": "yourhost.yourcompany.domain",
78 | "cerPath": "/opt/certificates/yourcertificate.crt",
79 | "keyPath": "/opt/certificates/yourcertificate.key",
80 | "dbPath": "/var/opt/yoursqlite.db",
81 | "runAs": "yourUserName",
82 | "port": 443,
83 | "channels": {
84 | "channel1_id": "channel1_name",
85 | "channel2_id": "channel2_name"
86 | }
87 | }
88 | ```
89 |
90 | Details of this configuration json file will be discussed later in this article.
91 |
92 | ### Step 2. Register An Application for Your Slack Team
93 |
94 | - On the [Slack API](https://api.slack.com), choose "Your Apps" to start a brand new app
95 | - Bot Users: make a valid name for your bot user, and it will apply to the configuration
96 |
97 | - Adding Permissions: in this example, permissions like "bot user", "channels:history", "channels.read" / "channels.write" and "chart:write:bot" for sending messages as bot are essentially required.
98 |
99 | - Event Subscription: this demo requires at least four Slack events to subscribe: (1) `message.channels`; (2) `message.im`; (3) `reaction_added`; (4) `reaction_removed`.
100 |
101 | - Enable Events by Setting Request URL. Given your server name is `myhost.com` and your configuration `message_uri` with `/v1/msg`, then please input this requrest url with `https://myhost.com/v1/msg`. *NOTE* Slack will not identify protocols other than HTTPS and the port to server can only be 443.
102 |
103 | - Install your app to your team.
104 |
105 | If success, copy all essential configurations to your own `config.json` file, which `token` means the *`Bot User OAuth Access Token`*
106 |
107 | ### Step 3. Tricky Part: Get Your Bot's Slack ID
108 |
109 | Slack Bot needs its id (not the display name) to work with, so it is a bit tricky to get such a name. Please read this section carefully to get the correct id:
110 |
111 | - Open a web browser and navigate to [`users.list` Slack API page](https://api.slack.com/methods/users.list/test)
112 |
113 | - Choose the right team token of your app and click `Test Method`
114 | - If success, click the link `(open raw response)` and a raw but pretty JSON text shall present.
115 | - Search the bot's display name from the JSON text.
116 | - Copy the bot's Slack ID to your configuration file.
117 |
118 |
119 | ### Step 4. Tricky Part II: Choose The Channels to Spy (Optional but Should Check for Avoiding Spam)
120 |
121 | Although many bot distributors are happy to allow their bots to join as many channels or groups as possible, you may want to restrict the bot behaviour in a few specific channels.
122 |
123 | To archive this objective, follow the instructions below:
124 |
125 | - Open a web browser and navigate to [`channels.list` Slack API page](https://api.slack.com/methods/channels.list/test)
126 | - Choose the right team token of your app and click `Test Method`
127 |
128 | - If success, click the link `(open raw response)` and a raw but pretty JSON text shall present.
129 | - Choose the channels for spying, and copy each `id` and `name` pair into your `config.json` file.
130 |
131 | *NOTE* If you prefer to allow the bot app accessing all channels, please add a snippet below after the configuration loading code:
132 |
133 | ``` swift
134 | Curl("https://slack.com/api/channels.list?token=\(token)") { ret in
135 | do {
136 | guard let b = ret,
137 | let info = try b.jsonDecode() as? [String:Any],
138 | let ok = info["ok"] as? Bool,
139 | let channels = info["channels"] as? [Any] else {
140 | Print("channel parse::ok(fault)")
141 | return nil
142 | }//end guard
143 | guard ok, channels.count > 0 else {
144 | Print("channel parse::ok(\(ok))")
145 | return nil
146 | }//end
147 | channels.forEach { channel in
148 | let ch = channel as? [String: Any] ?? [:]
149 | guard let id = ch["id"] as? String,
150 | let name = ch["name"] as? String else {
151 | return
152 | }//end guard
153 |
154 | // CAUTION: Append all channels into the cache
155 | global.channels[id] = name
156 | }//next
157 | }catch(let err) {
158 | Print("parseChannels::\(err)")
159 | return nil
160 | }// end do
161 | }//end curl
162 | ```
163 |
164 | ### Step 5. Build & Deploy The Bot Server
165 |
166 | It is strongly recommended to use [Perfect Assistant](http://www.perfect.org/en/assistant/) to automate all building / deployment jobs as required essentially for such a Slack Bot Server.
167 |
168 | However, if other cloud services than AWS / Google Cloud were considered, a install script `install.sh.sample` listed the project folder might be helpful at this point as steps below:
169 |
170 | - (1) Build on you local Ubuntu 16.04, i.e., VM or Docker. Run `$ swift build -c release` to create a release
171 | - (2) Shipped the binaries to your production server (might company with Swift runtime library if need)
172 | - (3) Copy the `config.service` and `config.json` to the server. Sample of `config.service` can be found in the same project folder.
173 | - (4) Place all your certificates file in proper folder on server with sufficient but secured permissions.
174 | - (5) Modify the `config.json` on your server to match all variables required, especially the certificates path, the database path.
175 | - (6) Modify the `config.service` on your server to match all paths required.
176 | - (7) Using `$ sudo systemctl enable config.service` to register your server app into services, then it can start up automatically by system account.
177 | - (8) Start the server. You can reset the server or run `$ sudo systemctl restart slackbot` if the service name is `slackbot`.
178 |
179 | Without Perfect Assistant, the all above steps will be also very tricky. So read check out the files content below before the building & deployment:
180 |
181 | #### Config.service Example
182 |
183 | ```
184 | [Unit]
185 | Description=Your Slack Bot Server
186 |
187 | [Service]
188 | Type=simple
189 | WorkingDirectory=/var/opt
190 | ExecStart=/path/to/yourApp/PerfectTemplate
191 | Restart=always
192 | PIDFile=/var/run/yourSlackBotApp.pid
193 | Environment="LD_LIBRARY_PATH=/usr/lib:/usr/local/lib:/usr/local/lib/swift"
194 |
195 | [Install]
196 | WantedBy=multi-user.target
197 | ```
198 |
199 | #### Installation Script Example
200 |
201 | ```
202 | # Installation Script Example
203 | # Suppose your server app is named as `slackbot`
204 | # Please make sure your server installed Swift runtime binaries,
205 | # i.e., LD_LIBRARY_PATH="/usr/lib/yourSwiftInstalationPath"
206 | # define the variables
207 | RPO=slackbot
208 | TGZ=/tmp/$RPO.tgz
209 | SVC=$RPO.service
210 | CFG=$RPO.json
211 | APP=/tmp/app.tgz
212 | SERVER=yoursshLoginUserName@yourhost.yourdomain
213 | LOCALVM=your.local.ubuntu.virtual.machine
214 |
215 | # pack source code to local vm
216 | tar czvf $TGZ Package.swift Sources
217 | scp $TGZ $LOCALVM:/tmp
218 |
219 | # build the binary on local VM
220 | ssh $LOCALVM "cd /tmp;rm -rf $RPO;mkdir $RPO; cd $RPO; tar xzvf $TGZ;swift build -c release;cd .build/release;tar czvf $APP PerfectTemplate *.so"
221 |
222 | # ship the binaries back to your production server
223 | scp $LOCALVM:$APP $APP
224 | scp $APP $SERVER:$APP
225 | scp $SVC $SERVER:/tmp/$SVC
226 | scp $CFG $SERVER:/tmp/$CFG
227 |
228 | # perform installation & register your new app as a service .
229 | ssh $SERVER "cd /opt;sudo -S rm -rf $RPO;sudo -S mkdir $RPO;cd $RPO;sudo -S tar xzvf $APP;sudo -S cp /tmp/$SVC .;sudo -S cp /tmp/$CFG .;sudo -S systemctl disable $RPO;sudo -S systemctl enable /opt/$RPO/$SVC;sudo -S systemctl start $RPO;sudo -S systemctl status $RPO"
230 | ```
231 |
232 | ### Step 6. Back To Slack API App Settings
233 |
234 | Once booting your server, then please go back to your slack api page to confirm all the settings, especially the oauth authentication page:
235 |
236 | - Verify the Event Subscription `Request URL`
237 | - Goto your slack channel, invite the bot. *NOTE* add a testing channel for testing may be helpful
238 | - Test the bot by sending it cookies and directly message it.
239 |
240 | ## Issues
241 |
242 | We are transitioning to using JIRA for all bugs and support related issues, therefore the GitHub issues has been disabled.
243 |
244 | If you find a mistake, bug, or any other helpful suggestion you'd like to make on the docs please head over to [http://jira.perfect.org:8080/servicedesk/customer/portal/1](http://jira.perfect.org:8080/servicedesk/customer/portal/1) and raise it.
245 |
246 | A comprehensive list of open issues can be found at [http://jira.perfect.org:8080/projects/ISS/issues](http://jira.perfect.org:8080/projects/ISS/issues)
247 |
248 | ## Further Information
249 | For more information on the Perfect project, please visit [perfect.org](http://perfect.org).
250 |
251 | ## Now WeChat Subscription is Available (Chinese)
252 | 
253 |
--------------------------------------------------------------------------------
/README.zh_CN.md:
--------------------------------------------------------------------------------
1 | # Perfect Slack 聊天机器人 [English](README.md)
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 | 本项目是专门为Slack聊天机器人定制的模板服务器。
43 | 在本项目模板中,一个聊天机器人可以加入授权频道,读取频道内所有用户发送的“曲奇🍪”并记录在案,而且可以直接答复用户的有关曲奇🍪饼干的问题。
44 |
45 | ## 预备知识
46 |
47 | 在您决定编译、测试或者部署您自己的基于Perfect软件框架体系的聊天机器人之前,以下基础知识⚠️不可或缺⚠️:
48 |
49 | - [Perfect 基础](http://www.perfect.org/docs/gettingStartedFromScratch_zh_CN.html)
50 | - [Slack API 在线函数接口参考](https://api.slack.com)
51 | - 提前准备好具有有效域名(FQDN)并由认证机构颁发证书的服务器
52 | - [Perfect 软件助手](http://www.perfect.org/en/assistant/) 可以用来编译和测试。这是可选的,但是如果您没有安装助手,则建议您自行在本地计算机上准备一个Ubuntu 16.04 LTS 虚拟服务器或者Docker镜像并自行安装好Swift 3.0以上版本。
53 |
54 | ## 快速上手
55 |
56 | ### 第一步:复制本项目
57 |
58 | 请使用下列命令复制本项目:
59 |
60 | ```
61 | $ git clone https://github.com/PerfectServers/SlackBot.git
62 | ```
63 |
64 | 本工程根目录之下有一个 `config.json.sample` 文件,所有内容都是必须填写的配置项:
65 |
66 | ``` json
67 | {
68 | "token": "xoxb-您的Slack应用程序通行证-TOKENXXXXXXXXXXXXXXXXX",
69 | "bot" : "聊天机器人名称",
70 | "bot_id": "聊天机器人编号",
71 | "client_id": "XXXXXXXX.YYYYYYYYYY您的应用程序编号",
72 | "client_secret": "应用程序密码",
73 | "verify_token": "反向验证通行证,即Slack在访问您的服务器是验证一下究竟是不是Slack发来的请求",
74 | "oauth_uri": "/v1/oauth接口函数地址",
75 | "message_uri": "/v1/msg接口函数地址",
76 | "confirm_uri": "/v1/confirm接口函数地址",
77 | "serverName": "yourhost.yourcompany.domain您的服务器完整域名",
78 | "cerPath": "/opt/certificates/yourcertificate.crt您的自签证书和第三方认证证书的合并文件",
79 | "keyPath": "/opt/certificates/yourcertificate.key您的证书私有钥匙文件",
80 | "dbPath": "/var/opt/yoursqlite.db数据库文件",
81 | "runAs": "yourUserName您的服务器普通用户名",
82 | "port": 443,
83 | "channels": {
84 | "channel1_id": "channel1_name需要监听的频道",
85 | "channel2_id": "channel2_name需要监听的频道"
86 | }
87 | }
88 | ```
89 |
90 | 上述文件的所有详细编写说明请参考本文后续内容。
91 |
92 | ### 第二步:到您的Slack团队上自行注册一个应用程序
93 |
94 | - 在您的 [Slack API 网页](https://api.slack.com)上,选择 "Your Apps"创建新的应用程序
95 | - 聊天机器人用户:为您的机器人起名字并应用到配置:
96 |
97 | - 增加权限。在本案例中,权限至少包括"bot user"(聊天机器人)、"channels:history"(公共频道历史)、"channels.read"(公共频道可读)、"channels.write"(公共频道可写)和 "chart:write:bot" (机器人可以发送聊天信息)。
98 |
99 | - 订阅事件:本案例需要至少以下事件在Slack应用程序控制台中进行订阅操作:(1) `message.channels`(监听频道消息); (2) `message.im`(实现即时通信); (3) `reaction_added`(增加表情); (4) `reaction_removed`(删除表情)。
100 |
101 | - 通过设置请求URL激活上述事件订阅。比如您的聊天机器人所在主机域名为`myhost.com`,而且接口程序入口点 `message_uri` 配置为 `/v1/msg`,那么请将该url设置为`https://myhost.com/v1/msg`。⚠️注意⚠️目前Slack仅支持HTTPS即443端口。
102 |
103 | - 将您的应用程序安装到您的团队中去。
104 |
105 | 如果所有工作完成,请将上述配置信息逐一输入到您的`config.json`文件,其中 `token`指的是 *`Bot User OAuth Access Token`*(聊天机器人授权访问通行证)
106 |
107 | ### 第三步:获取聊天机器人编号(概念有难度,操作须谨慎)
108 |
109 | Slack 聊天机器人需要在编程时使用自己的编号(不是屏幕上显示的名称)。要获得该编号需要一定技巧,请仔细阅读以下说明:
110 |
111 | - 打开浏览器导航至 [`users.list` Slack API page](https://api.slack.com/methods/users.list/test)
112 |
113 | - 为您的应用程序选择适合的通行证并点击在线测试 `Test Method`
114 | - 如果成功,则点击打开原始响应链接`(open raw response)`,可以看到一个JSON数据结构
115 | - 在JSON字符串中搜索您的聊天机器人名称
116 | - 将找到的聊天机器人编号拷贝到前文配置中
117 |
118 |
119 | ### 第三步:选择待监控频道(概念有难度,操作须谨慎)
120 |
121 | 该操作时可选项,但是出于安全角度来说,还是推荐完成的。
122 |
123 | 虽然相信许多聊天机器人开发商都希望其机器人产品能够加入的频道或者私聊群越多越好,但是您可能希望将聊天机器人县治在某几个特定的频道或者群聊中。
124 |
125 | 为了实现这个目标,请采用下列操作:
126 |
127 | - 打开浏览器并导航至 [`channels.list` Slack API page](https://api.slack.com/methods/channels.list/test)
128 | - 选择团队开发通行证并点击测试方法 `Test Method`
129 |
130 | - 如果查询成功,请点击原始响应数据 `(open raw response)` 查看返回的JSON数据。
131 | - 选择需要监控的频道并记录待监控频道的名称和代码(`id` / `name`),并将其填写到您的`config.json` 文件中。
132 |
133 | *注意* 如果您希望您的聊天机器人能够访问所有频道,则直接将下列代码粘贴到您的源程序内即可:
134 |
135 | ``` swift
136 | Curl("https://slack.com/api/channels.list?token=\(token)") { ret in
137 | do {
138 | guard let b = ret,
139 | let info = try b.jsonDecode() as? [String:Any],
140 | let ok = info["ok"] as? Bool,
141 | let channels = info["channels"] as? [Any] else {
142 | Print("channel parse::ok(fault)")
143 | return nil
144 | }//end guard
145 | guard ok, channels.count > 0 else {
146 | Print("channel parse::ok(\(ok))")
147 | return nil
148 | }//end
149 | channels.forEach { channel in
150 | let ch = channel as? [String: Any] ?? [:]
151 | guard let id = ch["id"] as? String,
152 | let name = ch["name"] as? String else {
153 | return
154 | }//end guard
155 |
156 | // CAUTION: Append all channels into the cache
157 | global.channels[id] = name
158 | }//next
159 | }catch(let err) {
160 | Print("parseChannels::\(err)")
161 | return nil
162 | }// end do
163 | }//end curl
164 | ```
165 |
166 | ### 第五步:编译和部署聊天机器人服务器
167 |
168 | 在此推荐使用 [Perfect Assistant 软件助手](http://www.perfect.org/en/assistant/)完成所有编译和部署的自动化操作。
169 |
170 | 但是,如果您使用的不是亚马逊AWS弹性计算EC2或者谷歌云,那么您需要详细了解整个安装部署的详细步骤。工程根目录下有一个安装脚本可供参考`install.sh.sample`:
171 |
172 | - (1) 在您本地的 Ubuntu 16.04,比如虚拟机或者Docker上,编译服务器,命令行为`$ swift build -c release` 编译为正式发行版本
173 | - (2) 用scp命令将二进制可执行的发行文件上传到服务器(可以和Swift运行函数库一起打包上传)
174 | - (3) 将配置好的 `config.service` 和 `config.json` 文件上传到服务器。其中 `config.service`模板文件可参考本工程根目录下的范例。
175 | - (4) 将您所有的证书文件放置到服务器安全、合理的路径下,并为运行提供足够但安全的权限。
176 | - (5) 在服务器上修改`config.json`文件并保证其中所有的变量,特别时各个路径,比如证书路径和数据库都完全符合实际部署。
177 | - (6) 同样如有必要,在服务器上也修改 `config.service`以匹配所有路径。
178 | - (7) 使用命令 `$ sudo systemctl enable config.service` 将您的新应用程序注册为Linux系统服务,这样服务器在重启后就能自动以管理员方式启动。
179 | - (8) 启动服务器,您可以选择重启整个服务器,或者运行 `$ sudo systemctl restart slackbot`命令行单独启动目标服务程序(假设编译后的服务命令行为 `slackbot`)
180 |
181 | 如果没有Perfect软件助手,则上述所有步骤一样是有一些难度的,因此操作时需要特别小心。请仔细阅读下列样本文件范例:
182 |
183 | #### Config.service 服务注册文件参考范例
184 |
185 | ```
186 | [Unit]
187 | Description=您的聊天机器人
188 |
189 | [Service]
190 | Type=simple
191 | WorkingDirectory=/var/opt
192 | ExecStart=/path/to/yourApp/PerfectTemplate
193 | Restart=always
194 | PIDFile=/var/run/yourSlackBotApp.pid
195 | Environment="LD_LIBRARY_PATH=/usr/lib:/usr/local/lib:/usr/local/lib/swift"
196 |
197 | [Install]
198 | WantedBy=multi-user.target
199 | ```
200 |
201 | #### 安装脚本范例
202 |
203 | ```
204 | # 安装部署脚本范例
205 | # 假设您的服务器应用程序名为`slackbot`
206 | # 请保证您的服务器上已经提前安装了Swift运行环境,比如
207 | # LD_LIBRARY_PATH="/usr/lib/yourSwiftInstalationPath"
208 | # 变量定义如下:
209 | RPO=slackbot
210 | TGZ=/tmp/$RPO.tgz
211 | SVC=$RPO.service
212 | CFG=$RPO.json
213 | APP=/tmp/app.tgz
214 | SERVER=yoursshLoginUserName@yourhost.yourdomain
215 | LOCALVM=your.local.ubuntu.virtual.machine
216 |
217 | # 首先把源代码打包并传输到虚拟机上
218 | tar czvf $TGZ Package.swift Sources
219 | scp $TGZ $LOCALVM:/tmp
220 |
221 | # 通过虚拟机进行编译
222 | ssh $LOCALVM "cd /tmp;rm -rf $RPO;mkdir $RPO; cd $RPO; tar xzvf $TGZ;swift build -c release;cd .build/release;tar czvf $APP PerfectTemplate *.so"
223 |
224 | # 然后再从虚拟机上取回编译好的二进制文件并上传至生产服务器
225 | scp $LOCALVM:$APP $APP
226 | scp $APP $SERVER:$APP
227 | scp $SVC $SERVER:/tmp/$SVC
228 | scp $CFG $SERVER:/tmp/$CFG
229 |
230 | # 在生产服务器上执行安装并将新编应用程序注册为Linux操作系统服务
231 | ssh $SERVER "cd /opt;sudo -S rm -rf $RPO;sudo -S mkdir $RPO;cd $RPO;sudo -S tar xzvf $APP;sudo -S cp /tmp/$SVC .;sudo -S cp /tmp/$CFG .;sudo -S systemctl disable $RPO;sudo -S systemctl enable /opt/$RPO/$SVC;sudo -S systemctl start $RPO;sudo -S systemctl status $RPO"
232 | ```
233 |
234 | ### 第六步:返回到Slack应用程序控制台
235 |
236 | 一旦重启服务器后,请回到Slack应用程序的控制台网页确认上述服务器并激活所有功能,特别时OAuth配置认证页面:
237 |
238 | - 验证事件订阅请求接口`Request URL`
239 | - 现在打开Slack应用,进入您的目标频道,并将机器人邀请到频道。⚠️注意⚠️选择增加一个测试频道专门用于调试聊天机器人是一个好主意
240 | - 测试聊天机器人,可以直接对它发起会话聊天
241 |
242 | ## 问题报告、内容贡献和客户支持
243 |
244 | 我们目前正在过渡到使用JIRA来处理所有源代码资源合并申请、修复漏洞以及其它有关问题。因此,GitHub 的“issues”问题报告功能已经被禁用了。
245 |
246 | 如果您发现了问题,或者希望为改进本文提供意见和建议,[请在这里指出](http://jira.perfect.org:8080/servicedesk/customer/portal/1).
247 |
248 | 在您开始之前,请参阅[目前待解决的问题清单](http://jira.perfect.org:8080/projects/ISS/issues).
249 |
250 |
251 | ## 更多信息
252 | 关于本项目更多内容,请参考[perfect.org](http://perfect.org).
253 |
254 | ## 扫一扫 Perfect 官网微信号
255 | 
256 |
--------------------------------------------------------------------------------
/Sources/config.swift:
--------------------------------------------------------------------------------
1 | //
2 | // config.swift
3 | // Perfect Slack bot
4 | //
5 | // Created by Rockford Wei on 2017-03-17.
6 | // Copyright (C) 2017 PerfectlySoft, Inc.
7 | //
8 | //===----------------------------------------------------------------------===//
9 | //
10 | // This source file is part of the Perfect.org open source project
11 | //
12 | // Copyright (c) 2015 - 2017 PerfectlySoft Inc. and the Perfect project authors
13 | // Licensed under Apache License v2.0
14 | //
15 | // See http://perfect.org/licensing.html for license information
16 | //
17 | //===----------------------------------------------------------------------===//
18 | //
19 |
20 | import PerfectLib
21 | import PerfectCURL
22 | import cURL
23 | import PerfectThread
24 | import SQLite
25 |
26 | #if os(Linux)
27 | import SwiftGlibc
28 | #else
29 | import Darwin
30 | #endif
31 |
32 | extension String {
33 | /// fix some non-zero ending of buffer issue
34 | public init(buffer: [UInt8]) {
35 | var buf = buffer
36 | buf.append(0)
37 | self = String(cString: buf)
38 | }//end init
39 | }//end ext
40 |
41 | /// Get the current time stamp
42 | public func Now(_ GMT: Bool = false) -> String {
43 | var t = time(nil)
44 | let s = GMT ? gmtime(&t) : localtime(&t)
45 | guard let p = asctime(s) else {
46 | return ""
47 | }//end p
48 | p.advanced(by: Int(strlen(p)) - 1).pointee = 0
49 | return String(cString: p)
50 | }//end extension
51 |
52 | /// A simple log file
53 | let LogLock = Threading.Lock()
54 | let LogFilePath = "/var/run/slackbot.log"
55 | let LogFile = File(LogFilePath)
56 |
57 | /// Simple Thread Safe Log Writter
58 | func Print(_ info: String) {
59 | print(info)
60 | LogLock.doWithLock {
61 | do {
62 | try LogFile.open(.append)
63 | let now = Now()
64 | let _ = try LogFile.write(string: "\(now):\t\(info)\n")
65 | LogFile.close()
66 | }catch {
67 |
68 | }
69 | }
70 | }
71 |
72 | /// an integrated configuration with db read / write & curl functions
73 | public struct Settings {
74 |
75 | /// oauth token to access slack api
76 | public var token = ""
77 |
78 | /// your bot name, will display in the channel
79 | public var bot = ""
80 |
81 | /// your bot slack id, MUST BE mannual acquired from slack app configuration
82 | public var botId = ""
83 |
84 | /// your app client id
85 | public var client_id = ""
86 |
87 | /// your app client secret
88 | public var client_secret = ""
89 |
90 | /// verify token sent by Slack API, optional but essential for preventing
91 | /// unauthorized access other than slack.com
92 | public var verify_token = ""
93 |
94 | /// uri for oauth
95 | public var oauth_uri = ""
96 |
97 | /// uri for incoming message
98 | public var message_uri = ""
99 |
100 | /// uri for slack interactive message confirmations
101 | public var confirm_uri = ""
102 |
103 | /// your server name, MUST BE full qualified domain name
104 | /// with a valid intermediate certificate
105 | public var serverName = ""
106 |
107 | /// certificate file path, for example, a.crt is your own certificate
108 | /// and b.crt is the intermediate certificate, then you can merge the
109 | /// both file by `$ cat a.crt b.crt > c.crt` where c.crt is what we place here
110 | public var cerPath = ""
111 |
112 | /// your private certificate key
113 | public var keyPath = ""
114 |
115 | /// your database file path (sqlite3)
116 | public var dbPath = ""
117 |
118 | /// common user name of the server will run as other than root for security consideration
119 | public var runAs = ""
120 |
121 | /// the only valid port for a slack api production server is 443: HTTPS
122 | public let port = 443
123 |
124 | /// cache for channel members [id: name] dictionary
125 | public static var members:[String:String] = [:]
126 |
127 | /// authroized access channel name; although a bot can join as many channels as need,
128 | /// this is an example of how to restrict bot to join only authroized channels.
129 | public var channels: [String:String] = [:]
130 |
131 | /// database handler
132 | private var db: SQLite
133 |
134 | /// internal configuration handle
135 | private var json:[String:Any] = [:]
136 |
137 | /// internal configuration path
138 | private var configurationPath = ""
139 |
140 | /// write configuration if need
141 | public func saveConfig() {
142 | do {
143 | let f = File(configurationPath)
144 | let config = try json.jsonEncodedString()
145 | try f.open(.write)
146 | let _ = try f.write(string: config)
147 | f.close()
148 | }catch (let err) {
149 | Print("Save Config \(configurationPath) failed -> \(err)")
150 | }//end do
151 | }//end save
152 |
153 | /// configration constructor
154 | /// - parameters:
155 | /// - configFilePath, path of configration file
156 | public init(configFilePath: String = "/etc/slackbot.json") {
157 |
158 | configurationPath = configFilePath
159 | Print("=============== Starting Slack Bot Server ===============")
160 | let configFile = File(configFilePath)
161 | do {
162 | try configFile.open(.read)
163 | let config = try configFile.readString()
164 | guard let jsonConfig = try config.jsonDecode() as? [String:Any] else {
165 | Print("configuration file \(configFilePath) fault")
166 | exit(-1)
167 | }//end guard
168 | json = jsonConfig
169 | token = json["token"] as? String ?? ""
170 | bot = json["bot"] as? String ?? ""
171 | botId = json["bot_id"] as? String ?? ""
172 | client_id = json["client_id"] as? String ?? ""
173 | client_secret = json["client_secret"] as? String ?? ""
174 | verify_token = json["verify_token"] as? String ?? ""
175 | oauth_uri = json["oauth_uri"] as? String ?? "/oauth"
176 | message_uri = json["message_uri"] as? String ?? "/message"
177 | confirm_uri = json["confirm_uri"] as? String ?? "/confirm"
178 | serverName = json["serverName"] as? String ?? "localhost"
179 | // port = json["port"] as? Int ?? 443
180 | cerPath = json["cerPath"] as? String ?? "/etc/certificates/certificate.crt"
181 | keyPath = json["keyPath"] as? String ?? "/etc/certificates/private.key"
182 | dbPath = json["dbPath"] as? String ?? "/var/local/cmweb.db"
183 | channels = json["channels"] as? [String:String] ?? [:]
184 | configFile.close()
185 | }catch(let err) {
186 | Print("General Failure: Invalid Configuration \(configFilePath) -> \(err)")
187 | exit(-2)
188 | }//end do
189 |
190 | /// initialize the database
191 | do {
192 | db = try SQLite(dbPath)
193 | let _ = try db.execute(statement: "CREATE TABLE IF NOT EXISTS bank (id INTEGER PRIMARY KEY AUTOINCREMENT, moment REAL NOT NULL, channel TEXT NOT NULL, receiver TEXT NOT NULL, sender TEXT NOT NULL, value INTEGER NOT NULL);CREATE UNIQUE INDEX IF NOT EXISTS eventIndex on bank (moment, channel, receiver, sender);")
194 | }catch (let err) {
195 | Print("General Failure: SQL \(dbPath) -> \(err)")
196 | exit(-3)
197 | }//end do
198 | }// init
199 |
200 | public func close(_ msg: String = "") {
201 | Print(msg)
202 | db.close()
203 | }//end quit
204 |
205 | /// get information from a web api asynchronously.
206 | /// - parameters:
207 | /// - completion: closure for request completion. The parameter is the server response, nil for error.
208 | public func Curl(_ url: String, completion: @escaping (String?)->Void ) {
209 | Threading.dispatch {
210 | let curl = CURL(url: url)
211 | let _ = curl.setOption(CURLOPT_TIMEOUT, int: 10)
212 | let (code, _, body) = curl.performFully()
213 | if code > -1 && body.count > 0 {
214 | completion( String(buffer: body) )
215 | } else {
216 | completion(nil)
217 | }//end if
218 | curl.close()
219 | }//end thread
220 | }//end Curl
221 |
222 | /// deposit one treat (cookie) into the database
223 | /// - parameters:
224 | /// - moment: time stamp
225 | /// - channel: channel of the event taking place
226 | /// - receiver: user name who received the treat
227 | /// - sender: user name who sent the treat
228 | /// - value: quantity of the treat
229 | public func deposit(moment: String, channel: String, receiver: String, sender: String, value: Int) -> Int {
230 | let sql = "INSERT INTO bank (moment, channel, receiver, sender, value) VALUES (\(moment), '\(channel)', '\(receiver)', '\(sender)', \(value));"
231 | do {
232 | let _ = try db.execute(statement: sql)
233 | }catch(let err) {
234 | Print("deposit failed: \(err)")
235 | db.close()
236 | exit(0)
237 | }//end do
238 | return 0
239 | }//end deposit
240 |
241 | /// calculate the treats of a user
242 | /// - parameters:
243 | /// - me: the user name in database
244 | public func about(me: String) -> Int {
245 | var sum = 0
246 | do {
247 | try db.forEachRow(statement: "SELECT SUM(value) FROM bank WHERE receiver = '\(me)'") { stmt, _ in
248 | sum += stmt.columnInt(position: 0)
249 | }//end
250 | }catch(let err) {
251 | Print("about:: \(err)")
252 | }//end catch
253 | return sum
254 | }//end func
255 |
256 | /// a sample leader board
257 | /// - parameters:
258 | /// - top: top listed rows, which restricts the sql result set.
259 | /// - returns:
260 | /// an tuple array - [(name:String, total:Int)] - ordered by the treats
261 | public func leaderBoard(top: Int = 50) -> [(name:String, total:Int)] {
262 | var board = [(name:String, total:Int)]()
263 | do {
264 | try db.forEachRow(statement: "SELECT receiver, SUM(value) AS total FROM bank GROUP BY receiver ORDER BY total DESC LIMIT \(top)") { stmt, _ in
265 | let name = stmt.columnText(position: 0)
266 | let sum = stmt.columnInt (position: 1)
267 | board.append((name, sum))
268 | }//end
269 | }catch(let err) {
270 | Print("about:: \(err)")
271 | }//end catch
272 | return board
273 | }//end leaderBoard
274 |
275 | /// get the user display name from a slack query
276 | /// - parameters:
277 | /// - slackReturn: the response from a slack query
278 | /// - returns:
279 | /// user name or nil if failed
280 | private func parseUserName(_ slackReturn: String?) -> String? {
281 | do {
282 | guard let b = slackReturn,
283 | let info = try b.jsonDecode() as? [String:Any],
284 | let ok = info["ok"] as? Bool,
285 | let u = info["user"] as? [String: Any] else {
286 | Print("parse::ok(fault)")
287 | return nil
288 | }//end guard
289 | guard ok, let user = u["name"] as? String else {
290 | Print("lookup::ok(\(ok))")
291 | return nil
292 | }//end
293 | return user
294 | }catch(let err) {
295 | Print("parseUserName::\(err)")
296 | return nil
297 | }// end do
298 | }//end func
299 |
300 | /// lookup a user name by id asynchronously
301 | /// - parameters:
302 | /// - uid: user id in slack
303 | /// - found: closure for query callback, which will return the user name or nil if failed.
304 | public func lookup(uid: String, found: @escaping (String?)->Void ) {
305 |
306 | if let user = Settings.members[uid] {
307 | found(user)
308 | return
309 | }//end if
310 |
311 | Curl("https://slack.com/api/users.info?token=\(token)&user=\(uid)") { ret in
312 | found(self.parseUserName(ret))
313 | }//end curl
314 | }//end lookupSlackUser
315 |
316 | /// lookup a group of users by a set of IDs
317 | /// - parameters:
318 | /// - uids: [String], the input set of user identifications
319 | /// - found: a callback once all user IDs were confirmed; user's name could be found in the result dictionary
320 | public func lookup(uids: [String], found: @escaping ([String:String]) -> Void) {
321 |
322 | /// the returning dictionary
323 | var names: [String:String] = [:]
324 |
325 | /// the actual IDs to lookup
326 | let candidates = uids.filter { uid in
327 | // check if the uid was in cache
328 | guard let name = Settings.members[uid] else {
329 | return true
330 | }//end guard
331 | names[uid] = name
332 | return false
333 | }//end candidates
334 |
335 | // if fulfilled by cache, then callback & return
336 | if candidates.isEmpty {
337 | found(names)
338 | return
339 | }//end if
340 |
341 | // preform the real online lookup
342 |
343 | /// thread counter
344 | var total = 0
345 |
346 | /// lock for thread writing to names / total / cache
347 | let searchingLock = Threading.Lock()
348 |
349 | candidates.forEach { uid in
350 |
351 | // each lookup is a thread
352 | self.lookup(uid: uid) { ret in
353 |
354 | // the thread has returned
355 | searchingLock.doWithLock {
356 |
357 | // inc one for each thread return
358 | total += 1
359 |
360 | // check the result
361 | if let name = ret {
362 |
363 | // append it to cache
364 | Settings.members[uid] = name
365 |
366 | // append it to the return set
367 | names[uid] = name
368 |
369 | }//end if
370 |
371 | // check if the thread is the last arrival among the jobs
372 | if total == candidates.count {
373 |
374 | // the last arrival will do the callback
375 | found(names)
376 | }//end if
377 | }//end lock
378 | }//end lookup
379 | }//next
380 | }//end lookup
381 |
382 | /// reply a message to slack
383 | /// - parameters:
384 | /// - channel: the channel id that the message will display
385 | /// - msg: message body
386 | /// - attachements: a json string for interactive messages, see slack api for more info
387 | /// - confirmation: slack callback to confirm receiving this message
388 | func reply (channel: String, msg: String, attachements: String = "", confirmation: @escaping (String?)-> Void = { _ in }) {
389 | let m = msg.stringByEncodingURL
390 | let a = attachements.stringByEncodingURL
391 | let url = "https://slack.com/api/chat.postMessage?token=\(token)&channel=\(channel)&text=\(m)&username=\(bot)&as_user=true&attachments=\(a)"
392 | Curl(url) { confirmation($0) }
393 | }//end reply
394 | }//end config
395 |
--------------------------------------------------------------------------------
/Sources/main.swift:
--------------------------------------------------------------------------------
1 | //
2 | // main.swift
3 | // Perfect Slack Bot
4 | //
5 | // Created by Rockford Wei on 2017-03-17.
6 | // Copyright (C) 2017 PerfectlySoft, Inc.
7 | //
8 | //===----------------------------------------------------------------------===//
9 | //
10 | // This source file is part of the Perfect.org open source project
11 | //
12 | // Copyright (c) 2015 - 2017 PerfectlySoft Inc. and the Perfect project authors
13 | // Licensed under Apache License v2.0
14 | //
15 | // See http://perfect.org/licensing.html for license information
16 | //
17 | //===----------------------------------------------------------------------===//
18 | //
19 |
20 | import Regex
21 | import PerfectLib
22 | import PerfectHTTP
23 | import PerfectHTTPServer
24 | import PerfectNet
25 | #if os(Linux)
26 | import SwiftGlibc
27 | #else
28 | import Darwin
29 | #endif
30 |
31 | let global = Settings()
32 |
33 | /// Primary Incoming Slack Message Handler
34 | func WEBMessage(data: [String:Any]) throws -> RequestHandler {
35 | return {
36 | request, response in
37 | do {
38 | guard
39 | // Step 1. Get the Slack Post
40 | let post = request.postBodyString,
41 |
42 | // Step 2. Verify if this message is coming from Slack
43 | let _ = strstr(post, global.verify_token),
44 |
45 | // Step 3. Decode the JSON post into a dictionary
46 | let json = try post.jsonDecode() as? [String:Any]
47 | else
48 | {
49 | Print("slack::json(failed)")
50 | response.completed(status: .forbidden)
51 | return
52 | }//end json
53 |
54 | // Step 4. If this is an OAuth challenge, reply it.
55 | if let challenge = json["challenge"] as? String {
56 | response.appendBody(string: "\(challenge)\n").completed()
57 | return
58 | }//end json
59 |
60 | // Step 5. Confirm it is a valid Slack message calling.
61 | response.completed()
62 |
63 | // Step 6. Get the Event Object from this message
64 | guard
65 | let event = json["event"] as? [String:Any],
66 | let eventType = event["type"] as? String,
67 | let now = event["event_ts"] as? String,
68 | let sender = event["user"] as? String
69 | else
70 | {
71 | Print("slack::json(event attributes)")
72 | return
73 | }//end event
74 |
75 | // Step 7. Ignore the message sent by the bot itself.
76 | if sender == global.botId { return }
77 |
78 | var depositValue = 0
79 | switch eventType {
80 |
81 | case "message":
82 | let channel = event["channel"] as? String ?? ""
83 | // Step 8. If the message is a direct message from user, reply him / her
84 | guard let channelName = global.channels[channel] else
85 | {
86 | // in the direct message, ignore the speaker's request
87 | global.lookup(uid: sender)
88 | { ret in
89 | guard let snd = ret else
90 | {
91 | Print("sender::unknown")
92 | return
93 | }//end guard
94 |
95 | // In this demo, the bot will reply user for his/her own records with a leader board
96 | let sum = global.about(me: snd)
97 | let cookies = sum > 1 ? "cookies" : "cookie"
98 | let msg = sum > 0 ? "You have \(sum) \(cookies)." : "You have no cookies."
99 | let top = 20
100 | let table = global.leaderBoard(top: top).reduce("Name\tCookies")
101 | { previous, next in
102 | return previous + "\n\(next.name)\t\(next.total)"
103 | }//end table
104 | let fullMsg = "\(msg)\n*Top \(top) Cookie Monsters V7*\n```\n\(table)\n```\n"
105 | global.reply(channel: channel, msg: fullMsg)
106 | }//end lookup
107 | return
108 | }//end if
109 |
110 | // Step 9. Parse the message for a specific pattern.
111 | // In this demo, the bot will collect all cookies sent by users
112 | // So it will identify who sent whom with how many cookies
113 | // You can do whatever kind of message filter / parser in such a form
114 | guard let text = event["text"] as? String,
115 | let _ = strstr(text, ":cookie:") else
116 | {
117 | // normal message, ignore
118 | return
119 | }//end
120 |
121 | // use regular expression to get the receivers and filter out the sender himself / herself
122 | let receivers = text.matches(pattern: "<@[^>]+>")
123 | .map { String($0.extraction.characters.dropLast().dropFirst(2)) }
124 | .filter { $0 != sender }
125 |
126 | // if no valid user name mentioned in this message, simply ignore it.
127 | guard receivers.count > 0 else { return }
128 |
129 | // get the user display name to store into the database
130 | global.lookup(uids: receivers)
131 | { list in
132 | receivers.forEach
133 | { uid in
134 | guard let name = list[uid] else { return }
135 | global.lookup(uid: sender) { realName in
136 | guard let senderName = realName else { return }
137 | _ = global.deposit(moment: now, channel: channelName, receiver: name, sender: senderName, value: 1)
138 | }
139 | }//next
140 | }//end lookup
141 | return
142 |
143 | // Step 10. Check if the event is a reaction add or remve operation
144 | case "reaction_added":
145 | depositValue = 1
146 | break
147 | case "reaction_removed":
148 | depositValue = -1
149 | break
150 | default:
151 | Print("slack::event(unknown\(eventType))")
152 | return
153 | }//end case
154 |
155 | // In this demo, we listed `cookie` as the same as in the text for recording
156 | guard let event_item = event["item"] as? [String: Any],
157 | let channel = event_item["channel"] as? String,
158 | let reaction = event["reaction"] as? String,
159 | let itemUser = event["item_user"] as? String,
160 | let channelFullName = global.channels[channel],
161 | itemUser != sender,
162 | reaction == "cookie"
163 | else
164 | {
165 | Print("slack::json(item attributes)")
166 | return
167 | }//end if
168 |
169 | global.lookup(uids: [itemUser, sender]) { users in
170 | guard let objUsr = users[itemUser], let snd = users[sender] else {
171 | Print("slack::(receiver / sender) not found")
172 | return
173 | }//end guard
174 | let _ = global.deposit(moment: now, channel: channelFullName, receiver: objUsr, sender: snd, value: depositValue)
175 | }//end lookup
176 |
177 | }catch(let err){
178 | Print("slack:: \(err)")
179 | response.completed(status: .forbidden)
180 | }//end do
181 | }//end return
182 | }//end handler
183 |
184 | /// Slack Confirm URI, required by interactive messaging
185 | func WEBConfirm(data: [String:Any]) throws -> RequestHandler {
186 | return {
187 | request, response in
188 | //do confirm if need
189 | response.completed()
190 | }//end return
191 | }//end handler
192 |
193 | /// Slack OAuth URI, required & also may be customized (to store the data or present a welcome page) if need.
194 | func WEBOAuth(data: [String:Any]) throws -> RequestHandler {
195 | return {
196 | request, response in
197 | guard let code = request.param(name: "code") else {
198 | Print("oauth::rejected")
199 | response.completed(status: .forbidden)
200 | return
201 | }//end guard
202 | let oauth = [
203 | "client_id":global.client_id,
204 | "client_secret": global.client_secret,
205 | "redirect_uri": global.oauth_uri]
206 | let url = oauth.reduce("https://slack.com/api/oauth.access?code=\(code)") { $0 + "&\($1.key)=\($1.value)".stringByEncodingURL}
207 | global.Curl(url) { ret in
208 | guard let b = ret else {
209 | Print("oauth::url(failed)")
210 | response.completed(status: .forbidden)
211 | return
212 | }//end guard
213 | Print("oauth returned: \(b)")
214 | response.appendBody(string:
215 | "CookieMonsterThank you for choosing Perfect!
\n")
216 | response.completed()
217 | }//end curl
218 | }//end return
219 | }//end handler
220 |
221 | // load the uri into routers
222 | let confData = [
223 | "servers": [
224 | [
225 | "name": global.serverName,
226 | "port": global.port,
227 | "routes":[
228 | ["method":"post", "uri":global.confirm_uri, "handler":WEBConfirm],
229 | ["method":"get", "uri":global.oauth_uri, "handler":WEBOAuth],
230 | ["method":"post", "uri":global.message_uri, "handler":WEBMessage]
231 | ],
232 | "tlsConfig": [
233 | "certPath" : global.cerPath,
234 | "keyPath": global.keyPath
235 | ],
236 | "runAs": global.runAs
237 | ]
238 | ]
239 | ]
240 |
241 | // run the server
242 | do {
243 | // Launch the servers based on the configuration data.
244 | try HTTPServer.launch(configurationData: confData)
245 | } catch(let err) {
246 | global.close("General Failure: \(err)")
247 | fatalError("\(err)") // fatal error launching one of the servers
248 | }
249 |
--------------------------------------------------------------------------------
/bot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PerfectServers/SlackBot/5766f953fb8b32f87e3153fe3a0689e63fb3911a/bot.png
--------------------------------------------------------------------------------
/botuser.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PerfectServers/SlackBot/5766f953fb8b32f87e3153fe3a0689e63fb3911a/botuser.png
--------------------------------------------------------------------------------
/channels.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PerfectServers/SlackBot/5766f953fb8b32f87e3153fe3a0689e63fb3911a/channels.png
--------------------------------------------------------------------------------
/config.json.sample:
--------------------------------------------------------------------------------
1 | {
2 | "token": "xoxb-YOURAPP-TOKENXXXXXXXXXXXXXXXXX",
3 | "bot" : "yourBotName",
4 | "bot_id": "YOUR_BOT_ID",
5 | "client_id": "XXXXXXXX.YYYYYYYYYY",
6 | "client_secret": "your-client-secret",
7 | "verify_token": "token-to-verify-by-your-app",
8 | "oauth_uri": "/v1/oauth",
9 | "message_uri": "/v1/message",
10 | "confirm_uri": "/v1/confirm",
11 | "serverName": "yourhost.yourcompany.domain",
12 | "cerPath": "/opt/certificates/yourcertificate.crt",
13 | "keyPath": "/opt/certificates/yourcertificate.key",
14 | "dbPath": "/var/opt/yoursqlite.db",
15 | "runAs": "yourUserName",
16 | "port": 443,
17 | "channels": {
18 | "channel1_id": "channel1_name",
19 | "channel2_id": "channel2_name"
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/config.service.sample:
--------------------------------------------------------------------------------
1 | [Unit]
2 | Description=Your Slack Bot Server
3 |
4 | [Service]
5 | Type=simple
6 | WorkingDirectory=/var/opt
7 | ExecStart=/path/to/yourApp/PerfectTemplate
8 | Restart=always
9 | PIDFile=/var/run/yourSlackBotApp.pid
10 | Environment="LD_LIBRARY_PATH=/usr/lib:/usr/local/lib:/usr/local/lib/swift"
11 |
12 | [Install]
13 | WantedBy=multi-user.target
14 |
--------------------------------------------------------------------------------
/events.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PerfectServers/SlackBot/5766f953fb8b32f87e3153fe3a0689e63fb3911a/events.png
--------------------------------------------------------------------------------
/install.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PerfectServers/SlackBot/5766f953fb8b32f87e3153fe3a0689e63fb3911a/install.png
--------------------------------------------------------------------------------
/install.sh.sample:
--------------------------------------------------------------------------------
1 | # Installation Script Example
2 | # Suppose your server app is named as `slackbot`
3 | # Please make sure your server installed Swift runtime binaries,
4 | # i.e., LD_LIBRARY_PATH="/usr/lib/yourSwiftInstalationPath"
5 | # define the variables
6 | RPO=slackbot
7 | TGZ=/tmp/$RPO.tgz
8 | SVC=$RPO.service
9 | CFG=$RPO.json
10 | APP=/tmp/app.tgz
11 | SERVER=yoursshLoginUserName@yourhost.yourdomain
12 | LOCALVM=your.local.ubuntu.virtual.machine
13 |
14 | # pack source code to local vm
15 | tar czvf $TGZ Package.swift Sources
16 | scp $TGZ $LOCALVM:/tmp
17 |
18 | # build the binary on local VM
19 | ssh $LOCALVM "cd /tmp;rm -rf $RPO;mkdir $RPO; cd $RPO; tar xzvf $TGZ;swift build -c release;cd .build/release;tar czvf $APP PerfectTemplate *.so"
20 |
21 | # ship the binaries back to your production server
22 | scp $LOCALVM:$APP $APP
23 | scp $APP $SERVER:$APP
24 | scp $SVC $SERVER:/tmp/$SVC
25 | scp $CFG $SERVER:/tmp/$CFG
26 |
27 | # perform installation & register your new app as a service .
28 | ssh $SERVER "cd /opt;sudo -S rm -rf $RPO;sudo -S mkdir $RPO;cd $RPO;sudo -S tar xzvf $APP;sudo -S cp /tmp/$SVC .;sudo -S cp /tmp/$CFG .;sudo -S systemctl disable $RPO;sudo -S systemctl enable /opt/$RPO/$SVC;sudo -S systemctl start $RPO;sudo -S systemctl status $RPO"
29 |
--------------------------------------------------------------------------------
/perm.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PerfectServers/SlackBot/5766f953fb8b32f87e3153fe3a0689e63fb3911a/perm.png
--------------------------------------------------------------------------------
/url.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PerfectServers/SlackBot/5766f953fb8b32f87e3153fe3a0689e63fb3911a/url.png
--------------------------------------------------------------------------------
/userlist.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PerfectServers/SlackBot/5766f953fb8b32f87e3153fe3a0689e63fb3911a/userlist.png
--------------------------------------------------------------------------------