This guide will walk you through the process of setting up the Kindness Slackbot, which sends a random image to a channel when a user types the /kindness
command.
/kindness
/kindness
Sends a random image
channels:read
groups:read
commands
chat:write
pip install slack-sdk slack-bolt python-dotenv
random_image_slackbot.py
in your project directory and copy the following Python script:import os
import random
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Set up Slack app and handler
slack_app_token = os.environ['SLACK_APP_TOKEN']
slack_bot_token = os.environ['SLACK_BOT_TOKEN']
app = App(token=slack_bot_token)
@app.command("/kindness")
def handle_kindness(ack, respond, command):
# Acknowledge the command request
ack()
# Generate random image URL
random_num = random.randint(1, 30)
image_url = f"https://kindness.equalexperts.com/images/{random_num}.png"
# Get the channel information
try:
channel_info = app.client.conversations_info(
token=slack_bot_token,
channel=command["channel_id"]
)
is_bot_member = channel_info["channel"]["is_member"]
except Exception as e:
print(f"Error fetching channel info: {e}")
is_bot_member = False
# Send the random image to the channel
try:
if is_bot_member:
response = app.client.chat_postMessage(
token=slack_bot_token,
channel=command["channel_id"],
text="Here's a random image for you!",
blocks=[
{
"type": "image",
"block_id": "random_image",
"image_url": image_url,
"alt_text": "Random image",
}
],
)
else:
response = respond(
text="Here's a random image for you!",
blocks=[
{
"type": "image",
"block_id": "random_image",
"image_url": image_url,
"alt_text": "Random image",
}
],
)
print(f"Image sent: {image_url}")
except Exception as e:
print(f"Error sending message: {e}")
if __name__ == "__main__":
handler = SocketModeHandler(app, slack_app_token)
handler.start()
.env
in your project directory and add the following lines, replacing your_app_token_here
and your_bot_token_here
with the actual tokens you obtained in Step 3:
SLACK_APP_TOKEN=your_app_token_here
SLACK_BOT_TOKEN=your_bot_token_here
python random_image_slackbot.py
/kindness
command./kindness
in a channel where the bot is a member. You have successfully set up the Kindness Slackbot. Users can now use the /kindness
command to receive random Acts of Kindness.