slackapi / bolt-python

A framework to build Slack apps using Python
https://slack.dev/bolt-python/
MIT License
1.03k stars 237 forks source link

Nothing Happened When Slackbot Started #1008

Closed hans0801 closed 6 months ago

hans0801 commented 6 months ago

The slack_bolt version

slack-bolt==1.18.1
slack-sdk==3.26.1

Python runtime version

Python 3.11.3

OS info

ProductName:            macOS
ProductVersion:         13.6.1
BuildVersion:           22G313
Darwin Kernel Version 22.6.0: Wed Oct  4 21:25:26 PDT 2023; root:xnu-8796.141.3.701.17~4/RELEASE_X86_64

Steps to reproduce:

(Share the commands to run, source code, and project settings (e.g., setup.py))

  1. Enable socket mode on Slack App Screenshot 2024-01-04 at 19 15 22

  2. source .venv/bin/activate

  3. python slackbolt.py

Here is my code:

import os
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler

# Initializes your app with your bot token and socket mode handler
app = App(token=os.environ.get("SLACK_BOT_TOKEN"))

# Listens to incoming messages that contain "hello"
@app.message("hello")
def message_hello(message, say):
    # say() sends a message to the channel where the event was triggered
    say(
        blocks=[
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": f"Hey there <@{message['user']}>!"},
                "accessory": {
                    "type": "button",
                    "text": {"type": "plain_text", "text": "Click Me"},
                    "action_id": "button_click"
                }
            }
        ],
        text=f"Hey there <@{message['user']}>!"
    )

@app.action("button_click")
def action_button_click(body, ack, say):
    # Acknowledge the action
    ack()
    say(f"<@{body['user']['id']}> clicked the button")

# Start your app
if __name__ == "__main__":
    handler = SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"])
    handler.start()

Expected result:

The python slack bolt will response the message on channel when someone write "hello"

Actual result:

Nothing happened. Just showing "Bolt app is running!"

Screenshot 2024-01-04 at 19 12 44 Screenshot 2024-01-04 at 19 12 23

Requirements

Please read the Contributing guidelines and Code of Conduct before creating this issue or pull request. By submitting, you are agreeing to those rules.

filmaj commented 6 months ago

On api.slack.com/apps, under Features -> Event Subscriptions, what events is your app subscribed to?

If you are listening for messages, then your app needs to subscribe to the relevant event to get notified of them. In this case, since you are listening for specific messages using the @app.message decorator, you will need to subscribe to the message.channels event. This event also requires that your app request the channels:history scope.

hans0801 commented 6 months ago

Hi @filmaj ,

Thanks for your kindly response. Yes sure I already subscribed those events but the result is still same.

Thanks

On Fri, Jan 5, 2024, 02:20 Fil Maj @.***> wrote:

On api.slack.com/apps, under Features -> Event Subscriptions, what events is your app subscribed to?

If you are listening for messages, then your app needs to subscribe to the relevant event to get notified of them. In this case, since you are listening for specific messages using the @app.message decorator, you will need to subscribe to the message.channels event https://api.slack.com/events/message.channels. This event also requires that your app request the channels:history scope https://api.slack.com/scopes/channels:history.

— Reply to this email directly, view it on GitHub https://github.com/slackapi/bolt-python/issues/1008#issuecomment-1877635996, or unsubscribe https://github.com/notifications/unsubscribe-auth/AGZ3BIHBBKWP5SN6KLBFBC3YM36GLAVCNFSM6AAAAABBMZ6X6OVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTQNZXGYZTKOJZGY . You are receiving this because you authored the thread.Message ID: @.***>

hans0801 commented 6 months ago

Here is my capture regarding the listening messages scope: Screenshot 2024-01-05 at 06 37 45

filmaj commented 6 months ago

Is your app installed to the workspace you are sending the message to? Is the app invited into the channel you are sending your hello message in?

Another thing to try is to set your app in debug mode to see if there are any incoming events hitting your app or not, as per these docs: https://slack.dev/bolt-python/concepts#logging

hans0801 commented 6 months ago

Hi @filmaj , Yes my app already installed on my workspace and already invited to the channel.

Screenshot 2024-01-05 at 06 49 07

I already added "logger" on my code but still nothing happened.

import os
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler

# Initializes your app with your bot token and socket mode handler
app = App(token=os.environ.get("SLACK_BOT_TOKEN"))

# Listens to incoming messages that contain "hello"
@app.message("hello")
def message_hello(message, say):
    # say() sends a message to the channel where the event was triggered
    say(
        blocks=[
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": f"Hey there <@{message['user']}>!"},
                "accessory": {
                    "type": "button",
                    "text": {"type": "plain_text", "text": "Click Me"},
                    "action_id": "button_click"
                }
            }
        ],
        text=f"Hey there <@{message['user']}>!"
    )
    logger.debug(message)

@app.action("button_click")
def action_button_click(body, ack, say):
    # Acknowledge the action
    ack()
    say(f"<@{body['user']['id']}> clicked the button")

# Start your app
if __name__ == "__main__":
    handler = SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"])
    handler.start()
Screenshot 2024-01-05 at 06 52 37
filmaj commented 6 months ago

You did not add the debug logging mode I linked to, just debug logged a message from within your message handler. Please review my link from earlier to turn debug logging generally on for the app. It should result in much more logging output on bootup.

hans0801 commented 6 months ago

Hi @filmaj , apologies my bad for not enabled the debug mode. I already enabled the debug mode and the result is like this:

Screenshot 2024-01-05 at 09 37 02

I saw no error found, because the result message is:

INFO:slack_bolt.App:A new session has been established (session id: 0cd15778-b136-41b0-9c0d-388ca6e5b3b8)
INFO:slack_bolt.App:⚡️ Bolt app is running!
INFO:slack_bolt.App:Starting to receive messages from a new connection (session id: 0cd15778-b136-41b0-9c0d-388ca6e5b3b8)
DEBUG:slack_bolt.App:on_message invoked: (message: {"type":"hello","num_connections":4,"debug_info":{"host":"applink-4","build_number":42,"approximate_connection_time":18060},"connection_info":{"app_id":"A06C15UL879"}})
DEBUG:slack_bolt.App:A new message enqueued (current queue size: 1)
DEBUG:slack_bolt.App:A message dequeued (current queue size: 0)
DEBUG:slack_bolt.App:Message processing started (type: hello, envelope_id: None)
DEBUG:slack_bolt.App:Message processing completed (type: hello, envelope_id: None)
filmaj commented 6 months ago

Something is off here with tokens or workspace membership or channel membership, because in debug mode, all events that the app is subscribed that are pushed to the app should be logged out to your console.

My theory is one of these things is not true:

Another way you can try to test these assumptions out:

  1. Copy the bot token you are providing to your app (environment variable SLACK_BOT_TOKEN, based on your code).
  2. Go into the channel that you are testing your app out, click the channel name at the top of the Slack client. A modal with an "About" tab will open up. Scroll down to the bottom and copy the Channel ID.
  3. Head to the chat.postMessage API reference document and flip the tab at the top to the 'tester' (this URL: https://api.slack.com/methods/chat.postMessage/test). Under the "Arguments" tab of the API tester, enter the following arguments:
    • Under 'provide your own token', paste your bot token
    • Under 'channel', paste your channel ID
    • Scroll down to the text argument and enter some message text, e.g. "hello from API tester"
  4. Scroll down to the bottom of the tester page and click 'Test method'
  5. If successful, you should see a message in the channel. If it fails, then there was likely a problem with one of the assumptions I listed out at the start of this comment.
hans0801 commented 6 months ago

Hi @filmaj ,

Thank you so much for your kindly explaination and information regarding the test case. Yes, I already tried the way that you gave to us. The result is successfull for sent the messages to my channel, here is the log and capture:

Screenshot 2024-01-05 at 23 07 25
{
    "ok": true,
    "channel": "XXXXXXXXXXX",
    "ts": "1704470831.292129",
    "message": {
        "bot_id": "XXXXXXXXXXX",
        "type": "message",
        "text": "hello from API tester",
        "user": "XXXXXXXXXXX",
        "ts": "1704470831.292129",
        "app_id": "XXXXXXXXXXX",
        "blocks": [
            {
                "type": "rich_text",
                "block_id": "MCe0",
                "elements": [
                    {
                        "type": "rich_text_section",
                        "elements": [
                            {
                                "type": "text",
                                "text": "hello from API tester"
                            }
                        ]
                    }
                ]
            }
        ],
        "team": "XXXXXXXXXXX",
        "bot_profile": {
            "id": "B06CTH53EHX",
            "app_id": "XXXXXXXXXXX",
            "name": "XXXXXXXXX Bot",
            "icons": {
                "image_36": "https://avatars.slack-edge.com/2024-01-04/6416303112150_1d84c71817b9bd5d0f6b_36.png",
                "image_48": "https://avatars.slack-edge.com/2024-01-04/6416303112150_1d84c71817b9bd5d0f6b_48.png",
                "image_72": "https://avatars.slack-edge.com/2024-01-04/6416303112150_1d84c71817b9bd5d0f6b_72.png"
            },
            "deleted": false,
            "updated": 1704368181,
            "team_id": "XXXXXXXXXXX"
        }
    }
}

It's weird, any idea?

Thanks

filmaj commented 6 months ago

I am at a complete loss then 🤷

At this point I am shooting in the dark and guessing, but some things to try to get a better understanding of what is happening:

  1. Try testing it in a different channel, ensuring the app is present.
  2. Try subscribing to a different event. For example, the app_mention event, and again in a public channel that both the user mentioning the app and the app are present in, try mentioning the app in a message. I bring this up as an avenue for testing because with your app in debug mode, you should at the very minimum see an incoming event payload show up in your app logs for any event the app is subscribed to - even if your app event handlers are not handling the event. To me this is the first step in understanding what is going on: we need to ensure your app can receive events it is subscribed to.
  3. Deleting and re-creating the app token. This token is used to establish the socket connection between Slack and your app.
  4. Another thing to try: a different event delivery mechanism. Instead of socket mode, can you instead use HTTP and provide Slack with an event URL to deliver payloads to?

Again, I am just listing out different things to try but at this point there is no logic behind this. Sorry 😞

hans0801 commented 6 months ago

Hi @filmaj , Thank you so much for your kindly explaination and information. After a long way for trying another options. I can view the error message. The message is like this:

Screenshot 2024-01-06 at 07 19 59
slack_sdk.errors.SlackApiError: The request to the Slack API failed. (url: https://www.slack.com/api/chat.postMessage)
The server responded with: {'ok': False, 'error': 'not_allowed_token_type'}

have you ever met those messages or case? Thanks

filmaj commented 6 months ago

@hans0801 that error means you are not using a user token or a bot token when trying to post a message using the postMessage API. Those are the only two tokens that are accepted.

hans0801 commented 6 months ago

Hi @filmaj , ah i see, thank you so much for your kindly help and explaination. Now it's working like a charm. After i re-create the bot token that i Used. Thanks