Writing slack chat robot based on perfect in swift language
This project is a template server specifically tailored for slack chat bots.
Full source code download on GitHub Https://github.com/PerfectServers/SlackBot
In this project template, a chat bot can join the authorized channel, read the "cookie" sent by all users in the channel and record it, and can answer the user's questions about cookies directly.
Pre-knowledge
Before you decide to compile, test, or deploy your own chat bot based on the perfect software framework system, here's the basics. Indispensable?? :
- Perfect Foundation
- Slack API Online Function Interface Reference
- Prepare a server with a valid domain name (FQDN) and certificate issued by a certification authority in advance
- The Perfect software assistant can be used for compiling and testing. This is optional, but if you do not have an assistant installed, it is recommended that you prepare an Ubuntu 16.04 LTS virtual Server or Docker image on your local computer and install Swift 3.0 or later on your own.
Quick Start the first step: Copy this project
Use the following command to copy this item:
$ https://github.com/PerfectServers/SlackBot.git
There is a file under the root config.json.sample
of this project, and all the content is a required configuration item:
{ "token":"xoxb-your slack app pass-tokenxxxxxxxxxxxxxxxxx", "Bot" :"Chat bot name", "bot_id":"chat bot number", "client_id":"XXXXXXXX. YYYYYYYYYY your app number ", "Client_secret":"Application Password", "Verify_token":"Reverse authentication pass, that is, slack on your server is to verify that the request is not slack", "Oauth_uri":"/v1/oauth interface function Address", "Message_uri":"/v1/msg interface function Address", "Confirm_uri":"/v1/confirm interface function Address", "ServerName":"Yourhost.yourcompany.domain Your server full domain name", "Cerpath":"/opt/certificates/yourcertificate.crt your self-signed and third-party Certificate of Incorporation", "KeyPath":"/opt/certificates/yourcertificate.key your certificate private key file", "DbPath":"/var/opt/yoursqlite.db database File", "RunAs":"YourUserName Your server's normal user name", "Port":443, "Channels":{"channel1_id": "Channel1_name needs listening channel", "channel2_id": "channel2_ Name need to listen for channel " }}
Please refer to the following sections of this document for all detailed instructions for writing the above documents.
Step Two: Register an application yourself on your slack team
- On your Slack API webpage, select "Your apps" to create a new application
Chat bot User: Name your robot and apply it to the configuration:
Increase permissions. In this case, the permission includes at least "bot user" (chat bot), "channels:history" (Public channel History), "Channels.read" (public channel readable), "channels.write" (Public channel writable) and " Chart:write:bot "(bots can send chat messages).
Subscription Events: This case requires at least the following events to be subscribed to in the slack Application console: (1) message.channels
(monitor channel messages); (2) message.im
(realization of instant communication); (3) reaction_added
(increase expression); (4) reaction_removed
(delete emoticons).
Activate the above event subscription by setting the request URL. For example, your chat bot host domain name is myhost.com
, and the interface program entry point is message_uri
configured /v1/msg
, then please set the URL to https://myhost.com/v1/msg
.?? Attention?? Currently, slack only supports HTTPS, which is port 443.
Install your application into your team.
If all the work is done, please enter the above configuration information into your config.json
file, which token
refers to the Bot User OAuth Access Token
(Chat bot authorized access Pass)
Step three: Get the chat robot number (the concept is difficult, the operation must be cautious)
Slack Chat Bots need to use their own numbers when programming (not the name displayed on the screen). To get the number you need some tips, please read the following instructions carefully:
Step three: Select the Channel to monitor (the concept is difficult, the operation must be cautious)
Options are available for this operation, but it is recommended for security reasons.
Although it is believed that many chat bot developers want their robot products to be able to join the channel or the more private chat group the better, but you may want to treat the chat robot county in a certain number of channels or group chat.
To achieve this goal, take the following actions:
- Open the browser and navigate to the
channels.list
Slack API page
Select Team Development Pass and click Test methodTest Method
If the query succeeds, click the original response data to (open raw response)
view the returned JSON data.
- Select the channel you want to monitor and record the name and code (/) of the channel to
id
name
be monitored and fill it config.json
in your file.
Note If you want your chat bot to have access to all channels, paste the following code directly into your source program:
Curl ("https://slack.com/api/channels.list?token=\ (token)") {RETinch Do{Guard Letb = ret, Letinfo =TryB.jsondecode () as? [String:any], LetOK = info["OK"] as? Bool, LetChannels = info["Channels"] as? [Any]Else{Print ("Channel Parse::ok (Fault)")returnNIL}//end GuardGuard OK, Channels.count >0 Else{Print ("Channel Parse::ok (\ (OK))")returnNIL}//endChannels.foreach {Channelinch LetCH = Channel as? [String:any]?? [:] Guard Letid = ch["id"] as? String, LetName = ch["Name"] as? StringElse{return}//end Guard //Caution:append all channels into the cacheGlobal.channels[id] = name}//next}Catch( LetERR) {Print ("parsechannels::\ (err)")returnNIL}//End do}//end Curl
Fifth step: Compiling and deploying the Chat robot server
It is recommended that you use the Perfect Assistant software Assistant to automate all compilation and deployment operations.
However, if you are not using Amazon AWS Flex Computing EC2 or Google Cloud, you need to learn more about the detailed steps for your entire installation deployment. An installation script is available under the project root directory for reference install.sh.sample
:
- (1) in your local Ubuntu 16.04, such as virtual machine or Docker, compile the server, the command behavior
$ swift build -c release
is compiled into the official release version
- (2) Upload binary executable files to server with SCP command (can be packaged and uploaded with Swift run function library)
- (3) upload the configured
config.service
and file to the config.json
server. The config.service
template file can refer to the example under the root of this project.
- (4) Place all of your certificate files under a secure, reasonable path to the server and provide sufficient but secure permissions for the operation.
- (5) Modify the file on the server
config.json
and guarantee all of the variables, especially when each path, such as the certificate path and database are fully compliant with the actual deployment.
- (6) also modify the server
config.service
to match all paths if necessary.
- (7) Use the command to
$ sudo systemctl enable config.service
register your new application as a Linux system service so that the server can be automatically started as an administrator after a reboot.
- (8) Start the server, you can choose to restart the entire server, or run the
$ sudo systemctl restart slackbot
command line to start the target service program separately (assuming the post-compilation service Command behavior slackbot
)
If you do not have a perfect software assistant, all of the steps above are difficult, so you need to be extremely careful when you do so. Please read the following sample file samples carefully:
Config.service Service Registration File Reference example
[unit] Description= your chat robot [service] type=simple workingdirectory=< Span class= "Hljs-value" >/var/opt execstart=/ Path/to/yourapp/perfecttemplate restart= Always pidfile=/var/run/yourslackbotapp.pid environment= "LD_ Library_path=/usr/lib:/usr/local/lib:/usr/local/lib/swift " [ Install] wantedby=multi-user.target
Example Installation scripts
# Example of installing a deployment script# Suppose your server application is named ' Slackbot '# Make sure you have a swift operating environment installed on your server, such as# ld_library_path= "/usr/lib/yourswiftinstalationpath"# variables are defined as follows:rpo=slackbottgz=/tmp/$RPO. tgzsvc=$RPO. servicecfg=$RPO. Jsonapp=/tmp/app.tgz[email Protected]localvm=your.local.ubuntu.virtual.machine# First Package and transfer the source code to the virtual machineTar CZVF$TGZPackage.swift SOURCESSCP$TGZ $LOCALVM:/tmp# compile with virtual machineSsh$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 "# then retrieve the compiled binaries from the virtual machine and upload them to the production serverScp$LOCALVM:$APP $APPScp$APP $SERVER:$APPScp$SVC $SERVER:/tmp/$SVCScp$CFG $SERVER:/tmp/$CFG# Perform the installation on the production server and register the new application as a Linux operating system serviceSsh$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 $RPOsudo-s systemctl enable/opt/$RPO/$SVC; sudo-s systemctl start $RPO, sudo-s systemctl status $RPO"
Sixth step: Return to the slack application console
Once the server is restarted, go back to the console page of the slack application to confirm the above server and activate all features, especially when OAuth configures the authentication page:
- Verifying the event subscription request Interface
Request URL
- Now open the Slack app, go to your target channel, and invite the robot to the channel. Attention?? Choose to add a test channel dedicated to debugging chat bots is a good idea
- Test the chat robot, and you can start a conversation chat directly with it.
More information
For more information on this project, please refer to perfect.org.
Sweep Perfect Official website number
Writing slack chat robot based on perfect in swift language