Skip to content

Commit

Permalink
Merge pull request #42 from amaoo/master
Browse files Browse the repository at this point in the history
初步增加对 slack 的支持
  • Loading branch information
zhayujie authored Feb 28, 2023
2 parents e486dd6 + ab3fa31 commit 76a4be7
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 1 deletion.
4 changes: 4 additions & 0 deletions channel/channel_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ def create_channel(channel_type):
elif channel_type == const.TELEGRAM:
from channel.telegram.telegram_channel import TelegramChannel
return TelegramChannel()

elif channel_type == const.SLACK:
from channel.slack.slack_channel import SlackChannel
return SlackChannel()

else:
raise RuntimeError
56 changes: 56 additions & 0 deletions channel/slack/slack_channel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import json
import re
from flask import Flask, request, Response
from slack_bolt import App
from slack_bolt.adapter.flask import SlackRequestHandler
from common import const
from common.log import logger
from channel.channel import Channel
from config import channel_conf

# 创建 Flask 实例
flask_app = Flask(__name__)

# 创建 Slack Bolt 实例
app = App(token=channel_conf(const.SLACK).get('slack_bot_token'),
signing_secret=channel_conf(const.SLACK).get('slack_signing_secret'))

# 创建 SlackRequestHandler 实例
handler = SlackRequestHandler(app)


# 监听 Slack app_mention 事件
@app.event("app_mention")
def handle_mention(event, say):
if 'thread_ts' in event:
ts = event["thread_ts"]
else:
ts = event["ts"]
reply_text = SlackChannel().handle(event)
say(text=f"{reply_text}", thread_ts=ts)


# 监听所有来自 Slack 的事件,并将它们转发到 Slack 应用处理
@flask_app.route("/slack/events", methods=["POST"])
def slack_events():
data = json.loads(request.data)
if data['type'] == 'url_verification':
return f"{data['challenge']}", 200
handler.handle(request)
return "ok", 200


class SlackChannel(Channel):
def startup(self):
flask_app.run(host='0.0.0.0', port=80)

def handle(self, event):
context = dict()
if 'thread_ts' in event:
ts = event["thread_ts"]
else:
ts = event["ts"]
context['from_user_id'] = str(ts)
# 使用正则表达式去除 @xxxx
plain_text = re.sub(r"<@\w+>", "", event["text"])
return super().build_reply_content(plain_text, context)
1 change: 1 addition & 0 deletions common/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
QQ = "qq"
GMAIL = "gmail"
TELEGRAM = "telegram"
SLACK = "slack"

# model
OPEN_AI = "openai"
7 changes: 6 additions & 1 deletion config-template.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,13 @@
"host_password": "GMAIL ACCESS KEY"
},

"telegram":{
"telegram": {
"bot_token": "xx:xx"
},

"slack": {
"slack_bot_token": "xoxb-xxxx",
"slack_signing_secret": "xxxx"
}
}
}

0 comments on commit 76a4be7

Please sign in to comment.