python-3.xslack-bolt

Message sender's name not changing in Slack using Python Bolt SDK


Below is my code where using the username attribute (username="MyNotifications") I'm trying to change the sender's name in the Slack message when posted to a channel however the name always appears as the Slack application name instead:-

from typing import Optional
import os
import logging
from pathlib import Path
from dotenv import load_dotenv
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
from slack_sdk import WebClient

logging.basicConfig(level=logging.DEBUG)
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)

SLACK_VERIFICATION_TOKEN = os.environ['SLACK_VERIFICATION_TOKEN']
SLACK_SIGNING_SECRET = os.environ['SLACK_SIGNING_SECRET']
SLACK_BOT_TOKEN = os.environ['SLACK_BOT_TOKEN']
SLACK_APP_TOKEN = os.environ['SLACK_APP_TOKEN']

SLACK_MAIN_CHANNEL = "<channel id>"

# Install the Slack app and get xoxb- token in advance
app = App(token=SLACK_BOT_TOKEN, signing_secret=SLACK_SIGNING_SECRET)


@app.event("message")
def handle_message(event, say, context):
    text = event["text"]
    source_channel = event["channel"]
    if "metadata" in event and source_channel == SLACK_MAIN_CHANNEL:
        target_channel = event["metadata"]["event_payload"]["channel_name"]
        print(f"Received message '{text}' from user in channel {source_channel}")
        app.client.chat_postMessage(channel=target_channel, text=text, username="MyNotifications")
        print("message sent...")
    else:
        print("skipped...")

I have referred to this Slack documentation.


Solution

  • After getting into Slack's documentation in detail, I was finally able to solve this. I added the scope chat:write.customize in the Bot Token scopes which helped me to customize the sender's name.