Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

slack-boltへ置き換え, flaskアップデート #3482

Merged
merged 10 commits into from
Dec 9, 2023
4 changes: 2 additions & 2 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ opencv-python = "==4.8.1.78"
pyperclip = "==1.8.2"
click = "==8.1.7"
psycopg2-binary = "==2.9.9"
slackeventsapi = "==3.0.1"
slack-bolt = "==1.18.1"
slack-sdk = "==3.26.1"
gitpython = "==3.1.40"
pandas = "==2.1.4"
Expand All @@ -37,7 +37,7 @@ openai = "==1.3.8"
"discord.py" = "==2.3.2"
"misskey.py" = "==4.1.0"
websockets = "==12.0"
flask = "==2.3.3"
flask = "==3.0.0"
markupsafe = "==2.1.3"
numpy = "==1.26.2"

Expand Down
70 changes: 47 additions & 23 deletions Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 4 additions & 6 deletions library/clientclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@
import discord
from slack_sdk import WebClient

import slackbot_settings as conf


class BaseClient(metaclass=ABCMeta):
"""
Expand Down Expand Up @@ -52,8 +50,8 @@ class SlackClient(BaseClient):
Slackを操作するClient
"""

def __init__(self, channel, send_user):
self.client = WebClient(token=conf.SLACK_API_TOKEN)
def __init__(self, client: WebClient, channel, send_user):
self.client = client
self.slack_channel = channel
self.send_user = send_user
self.send_user_name = self.client.users_info(user=send_user)["user"]["name"]
Expand All @@ -64,8 +62,8 @@ def post(self, message):

def upload(self, file, filename):
"""ファイルを投稿する"""
self.client.files_upload(
channels=self.slack_channel, file=file, filename=filename
self.client.files_upload_v2(
channel=self.slack_channel, file=file, filename=filename
)

def get_send_user(self):
Expand Down
11 changes: 9 additions & 2 deletions plugins/analyze.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,19 @@
"""

from functools import partial
from typing import Callable
from typing import Callable, List

from library.clientclass import BaseClient
from library.clientclass import BaseClient, SlackClient
from plugins import hato


def analyze_slack_message(messages: List[dict]) -> Callable[[SlackClient], None]:
"""Slackコマンド解析"""

message = "".join([m["text"] for m in messages if "text" in m]).strip()
return analyze_message(message)


def analyze_message(message: str) -> Callable[[BaseClient], None]:
"""コマンド解析"""

Expand Down
6 changes: 0 additions & 6 deletions renovate.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,6 @@
"github>dev-hato/renovate-config"
],
"packageRules": [
{
"matchPackageNames": [
"flask"
],
"allowedVersions": "<3.0.0"
},
{
"matchPackageNames": [
"postgres"
Expand Down
52 changes: 27 additions & 25 deletions run.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from typing import Callable, List

import discord
import slack_bolt
import websockets
from flask import Flask, jsonify, request
from markupsafe import escape
from misskey import Misskey
from requests.exceptions import ReadTimeout
from slackeventsapi import SlackEventAdapter
from slack_bolt.adapter.flask import SlackRequestHandler

import slackbot_settings as conf
from library.clientclass import (
Expand All @@ -32,9 +32,10 @@

app = Flask(__name__)

slack_events_adapter = SlackEventAdapter(
signing_secret=conf.SLACK_SIGNING_SECRET, endpoint="/slack/events", server=app
slack_app = slack_bolt.App(
token=conf.SLACK_API_TOKEN, signing_secret=conf.SLACK_SIGNING_SECRET
)
slack_handler = SlackRequestHandler(slack_app)


def __init__():
Expand All @@ -50,25 +51,14 @@ def __init__():
)


def analyze_slack_message(messages: List[dict]) -> Callable[[SlackClient], None]:
"""Slackコマンド解析"""
@slack_app.event("app_mention")
def on_app_mention(body):
channel = body["event"]["channel"]
blocks = body["event"]["blocks"]
authed_users = body["authed_users"]
client_msg_id = body["event"]["client_msg_id"]

message = "".join([m["text"] for m in messages if "text" in m]).strip()
return analyze.analyze_message(message)


@slack_events_adapter.on("app_mention")
def on_app_mention(event_data):
"""
appにメンションが送られたらここが呼ばれる
"""

channel = event_data["event"]["channel"]
blocks = event_data["event"]["blocks"]
authed_users = event_data["authed_users"]
client_msg_id = event_data["event"]["client_msg_id"]

print(f"event_data: {event_data}")
print(f"body: {body}")
print(f"channel: {channel}")
print(f"blocks: {blocks}")
print(f"authed_users: {authed_users}")
Expand Down Expand Up @@ -109,13 +99,25 @@ def on_app_mention(event_data):
and block_element_elements[0]["user_id"] in authed_users
):
tpe.submit(
analyze_slack_message(block_element_elements[1:]),
analyze.analyze_slack_message(
block_element_elements[1:]
),
SlackClient(
channel, block_element_elements[0]["user_id"]
slack_app.client,
channel,
block_element_elements[0]["user_id"],
),
)


@app.route("/slack/events", methods=["POST"])
def slack_events():
"""
appにメンションが送られたらここが呼ばれる
"""
return slack_handler.handle(request)


@app.route("/", methods=["GET", "POST"])
def http_app():
"""
Expand All @@ -132,7 +134,7 @@ def http_app():
msg = request.json["message"]
channel = request.json["channel"]
user = request.json["user"]
client = SlackClient(channel, user)
client = SlackClient(slack_app.client, channel, user)
client.post(f"コマンド: {msg}")
analyze.analyze_message(msg)(client)
return "success"
Expand Down
34 changes: 33 additions & 1 deletion tests/plugins/test_analyze.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,42 @@
import unittest

from plugins import hato
from plugins.analyze import analyze_message
from plugins.analyze import analyze_message, analyze_slack_message
from tests.plugins import TestClient


class TestAnalyzeSlackMessage(unittest.TestCase):
"""
Slackコマンドを正しく解析できるかテストする
"""

def test_telephone_link(self):
"""電話番号のリンクを含むコマンドを正しく解析できる"""
client1 = TestClient()
messages = [
{"type": "text", "text": ">< "},
{"type": "link", "url": "tel:09012345678", "text": "09012345678"},
]
analyze_slack_message(messages)(client1)
client2 = TestClient()
# pylint: disable=E1121
hato.totuzensi(client2, "09012345678")
self.assertEqual(client1.get_post_message(), client2.get_post_message())

def test_code(self):
"""コードを含むコマンドを正しく解析できる"""
client1 = TestClient()
messages = [
{"type": "text", "text": ">< "},
{"type": "text", "text": "09012345678", "style": {"code": True}},
]
analyze_slack_message(messages)(client1)
client2 = TestClient()
# pylint: disable=E1121
hato.totuzensi(client2, "09012345678")
self.assertEqual(client1.get_post_message(), client2.get_post_message())


class TestAnaryzeMessage(unittest.TestCase):
"""
コマンドを正しく解析できるかテストする
Expand Down
Loading