Sending Messages and Rich Blocks
Plain text, markdown, Block Kit JSON — formatting Slack messages.
Sending Messages and Rich Blocks is a free AI Agents lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Simple Text Messages with say()
The simplest way to post a Slack message is say(text). The text supports mrkdwn — Slack's markdown variant. Use *bold*, _italic_, ~strike~, `code`, and mentions like <@USERID>.
@app.event('app_mention')
def handle_mention(event, say):
user = event['user']
# Simple text response with mrkdwn formatting
say(
text=(
f'Hello <@{user}>!\n'
'*Agent Report:*\n'
'- Tasks completed: `42`\n'
'- Errors: `0`\n'
'- _Runtime: 3.2 seconds_'
),
mrkdwn=True # enabled by default
)
# Slack mentions
say(f'<@{user}> your request is being processed')
say('Posting to <!channel>: all hands meeting tomorrow')Introduction to Block Kit
Block Kit is Slack's UI framework for building rich, interactive messages. Instead of plain text, you compose messages from typed blocks: section, header, divider, actions, context. Blocks are passed as a list to the blocks parameter of say() or chat_postMessage().
@app.event('app_mention')
def handle_mention(event, say):
blocks = [
{
'type': 'header',
'text': {'type': 'plain_text', 'text': 'Agent Status Report'}
},
{
'type': 'divider'
},
{
'type': 'section',
'text': {
'type': 'mrkdwn',
'text': '*Status:* Running\n*Tasks:* 42 completed'
}
}
]
say(
text='Agent Status Report', # fallback for notifications
blocks=blocks
)Section Blocks with Text Fields
The section block is the most versatile. It can display text (mrkdwn or plain_text), a list of field key-value pairs, or an accessory element (button, image, overflow menu). Use fields for side-by-side key-value pairs — great for dashboards.
def build_task_summary_blocks(tasks):
blocks = [
{
'type': 'header',
'text': {'type': 'plain_text', 'text': 'Daily Task Summary'}
},
{
'type': 'section',
'text': {
'type': 'mrkdwn',
'text': f'Processed *{len(tasks)} tasks* today.'
}
},
{
'type': 'section',
'fields': [
{'type': 'mrkdwn', 'text': f'*Completed:*\n{sum(1 for t in tasks if t["status"]=="done")}'},
{'type': 'mrkdwn', 'text': f'*Failed:*\n{sum(1 for t in tasks if t["status"]=="error")}'},
{'type': 'mrkdwn', 'text': f'*Pending:*\n{sum(1 for t in tasks if t["status"]=="pending")}'},
{'type': 'mrkdwn', 'text': f'*Avg Time:*\n3.2s'}
]
}
]
return blocks
# --- demo ---
tasks = [
{'status': 'done'}, {'status': 'done'}, {'status': 'error'}, {'status': 'pending'}
]
blocks = build_task_summary_blocks(tasks)
for b in blocks:
print(b)
Header and Divider Blocks
Use header blocks for large section titles and divider blocks for visual separation. The header block only supports plain_text (no mrkdwn). Combine them to create well-structured report messages.
def build_report_message(title, sections):
blocks = []
# Header
blocks.append({
'type': 'header',
'text': {'type': 'plain_text', 'text': title, 'emoji': True}
})
for section_title, content in sections:
# Divider between sections
blocks.append({'type': 'divider'})
# Section header as bold mrkdwn
blocks.append({
'type': 'section',
'text': {'type': 'mrkdwn', 'text': f'*{section_title}*\n{content}'}
})
return blocks
blocks = build_report_message(
title='Weekly Agent Report',
sections=[
('Emails Processed', '142 emails classified, 38 replies drafted'),
('Tasks Completed', '89 tasks completed, 3 failures logged')
]
)
# --- demo ---
for b in blocks:
print(b)
Action Blocks with Buttons
Actions blocks contain interactive elements like buttons. Each button has an action_id (used to route clicks to handlers), a text, and an optional value carrying data. Use style: 'primary' for the main CTA and style: 'danger' for destructive actions.
def build_approval_message(task_id, task_description):
blocks = [
{
'type': 'section',
'text': {
'type': 'mrkdwn',
'text': f'*Task ready for approval:*\n{task_description}'
}
},
{
'type': 'actions',
'elements': [
{
'type': 'button',
'text': {'type': 'plain_text', 'text': 'Approve'},
'style': 'primary',
'action_id': 'approve_task',
'value': task_id
},
{
'type': 'button',
'text': {'type': 'plain_text', 'text': 'Reject'},
'style': 'danger',
'action_id': 'reject_task',
'value': task_id
}
]
}
]
return blocks
# --- demo ---
blocks = build_approval_message('task_42', 'Deploy backend v2.3 to production')
for b in blocks:
print(b)
Context Blocks for Metadata
Context blocks display small, secondary text at the bottom of a message — perfect for metadata like timestamps, sources, or agent version info. They support mrkdwn and images (for small icons).
import datetime
def add_context_footer(blocks, agent_version='v1.2'):
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M UTC')
blocks.append({
'type': 'context',
'elements': [
{
'type': 'mrkdwn',
'text': f'Generated by Agent {agent_version} | {timestamp}'
}
]
})
return blocks
# Full message with context footer
blocks = [
{
'type': 'section',
'text': {'type': 'mrkdwn', 'text': 'Analysis complete. See results below.'}
}
]
blocks = add_context_footer(blocks)
print(f'Message has {len(blocks)} blocks')mrkdwn in Text Fields
Slack's mrkdwn supports a subset of markdown. Key formatting options for agent messages: bold, italic, code, links, channel mentions, user mentions, and lists. Use these to make AI-generated content readable in Slack.
def format_ai_response_as_mrkdwn(title, bullet_points, code_snippet=None):
lines = [f'*{title}*']
for point in bullet_points:
lines.append(f'• {point}')
if code_snippet:
lines.append(f'```{code_snippet}```') # code block
return '\n'.join(lines)
content = format_ai_response_as_mrkdwn(
title='Security Issues Found',
bullet_points=[
'SQL injection risk in `user_search()` function',
'Hardcoded API key in `config.py` line 42',
'Missing HTTPS on login endpoint'
],
code_snippet='SELECT * FROM users WHERE id = " + userId + "\n# ^ UNSAFE: use parameterized queries'
)
print(content)Ephemeral Messages with respond()
Ephemeral messages are visible only to the user who triggered the action — not to other channel members. Use them for status updates, error messages, and confirmations that don't need to clutter the channel. Only available via respond() (slash commands) or chat_postEphemeral().
@app.command('/check-status')
def handle_status(ack, respond, body, client):
ack()
user_id = body['user_id']
channel_id = body['channel_id']
# Ephemeral: only the user who ran /check-status sees this
respond(
text='Checking agent status...',
response_type='ephemeral'
)
status = get_agent_status()
# Or use chat_postEphemeral for more control
client.chat_postEphemeral(
channel=channel_id,
user=user_id,
text=f'Agent Status: {status}',
blocks=build_status_blocks(status)
)Updating Messages After Sending
After posting a message, you can update it using client.chat_update() with the channel and message timestamp (ts). This is useful for progress updates — post an initial 'Processing...' message, then update it with the result when done.
@app.command('/analyze')
def handle_analyze(ack, say, respond, body, client):
ack()
text = body.get('text', '')
channel = body['channel_id']
# Post initial message
initial = client.chat_postMessage(
channel=channel,
text='Analyzing... this may take a moment.'
)
message_ts = initial['ts']
# Do the work
import threading
def do_work():
result = slow_ai_analysis(text)
# Update the original message with the result
client.chat_update(
channel=channel,
ts=message_ts,
text=f'Analysis complete: {result}',
blocks=build_result_blocks(result)
)
threading.Thread(target=do_work, daemon=True).start()Posting to Specific Channels
Use client.chat_postMessage(channel=channel_id, text=...) to post to any channel your bot has access to. Find channel IDs in the Slack API or by right-clicking a channel. Use conversations_list() to look up channels by name programmatically.
def post_alert_to_channel(client, channel_name, alert_message):
# Look up channel ID by name
result = client.conversations_list(
types='public_channel,private_channel',
limit=200
)
channel_id = None
for ch in result['channels']:
if ch['name'] == channel_name:
channel_id = ch['id']
break
if not channel_id:
print(f'Channel #{channel_name} not found')
return None
# Post the alert
response = client.chat_postMessage(
channel=channel_id,
text=alert_message,
unfurl_links=False, # don't expand URLs
unfurl_media=False
)
print(f'Posted to #{channel_name}: ts={response["ts"]}')
return response
# --- demo: minimal stand-in for the Slack client ---
class _FakeClient:
def conversations_list(self, **kwargs):
return {'channels': [{'name': 'alerts', 'id': 'C123'}, {'name': 'general', 'id': 'C456'}]}
def chat_postMessage(self, **kwargs):
print(f"[slack] postMessage to {kwargs['channel']}: {kwargs['text']}")
return {'ts': '1699999999.000100'}
post_alert_to_channel(_FakeClient(), 'alerts', 'Disk usage above 90% on web-1')
Block Kit Message Builder Pattern
Use a builder function that accepts data and returns a list of blocks. This separates message formatting from business logic and makes your blocks reusable across different event handlers.
def build_alert_blocks(level, title, details, link=None):
level_emoji = {'info': ':information_source:',
'warning': ':warning:', 'error': ':x:'}.get(level, '')
blocks = [
{
'type': 'header',
'text': {'type': 'plain_text', 'text': f'{level_emoji} {title}'}
},
{
'type': 'section',
'text': {'type': 'mrkdwn', 'text': details}
}
]
if link:
blocks.append({
'type': 'actions',
'elements': [{
'type': 'button',
'text': {'type': 'plain_text', 'text': 'View Details'},
'url': link,
'action_id': 'view_details'
}]
})
import datetime
blocks.append({
'type': 'context',
'elements': [{'type': 'mrkdwn',
'text': datetime.datetime.now().strftime('%Y-%m-%d %H:%M UTC')}]
})
return blocks
# --- demo ---
blocks = build_alert_blocks('warning', 'High latency', 'p95 latency is 3.2s', link='https://dash.example.com')
for b in blocks:
print(b)
Quick Check: Block Types
Test your understanding of Slack Block Kit.
Rich Messages Recap
Your agent can now post professional, interactive Slack messages:
- say(text) — simple mrkdwn text; supports *bold*, _italic_, `code`, mentions
- say(blocks=[...]) — Block Kit for structured layout
- header — large section title (plain_text only)
- section — text body with optional fields (key-value grid) or one accessory
- divider — horizontal separator line
- actions — container for buttons and interactive elements
- context — small metadata text at the bottom
- respond(response_type='ephemeral') — message visible only to the triggering user
- chat_update(ts=...) — update a previously posted message with new content
Frequently asked questions
Is the “Sending Messages and Rich Blocks” lesson free?
Yes — the full text of “Sending Messages and Rich Blocks” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.
What will I learn in “Sending Messages and Rich Blocks”?
Plain text, markdown, Block Kit JSON — formatting Slack messages. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Agents?
No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Sending Messages and Rich Blocks” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Agents lesson?
Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Slack Bolt SDK Basics
- Listening to Events and Slash Commands
- Sending Messages and Rich Blocks
- Building a Team Notification Bot