AiCredits
Slack Bot Guide

Building a Slack Bot with an OpenAI-Compatible API in One Afternoon

Build a working Slack bot in one afternoon with Slack Bolt, Socket Mode, and an OpenAI-compatible API, plus runnable Python code and useful practical tips.

Published 2026-10-27 Updated 2026-10-27 9 min

Why one afternoon is realistic

Most Slack bot tutorials spend the first half on OAuth, web servers, and tunnels. You do not need any of that for a useful internal bot. Slack Bolt handles the Slack protocol, Socket Mode gives you a WebSocket connection without a public URL, and the OpenAI SDK gives you one familiar chat-completions interface. The only custom code is the prompt, thread memory, and the handler that calls your model.

Using an OpenAI-compatible endpoint means the bot is not tied to one SDK. You point the OpenAI client at AiCredits, choose a DeepSeek model, and keep the same request shape. That makes the afternoon build small enough to finish and test before you over-engineer it.

What you need before you code

  • A Slack workspace where you can install apps.

  • An AiCredits API key from aicreditsapi.com. International cards and PayPal work; no Chinese phone or bank account is needed.

  • Python and two packages: slack-bolt and openai.

  • A bot token (xoxb-) and an app-level token (xapp-).

  • A channel or DM where you can test the bot. In channels, invite the bot before mentioning it.

Create the Slack app and tokens

Create a new app at api.slack.com/apps. The settings below are enough for a mention-driven bot plus direct messages.

SettingValue
Socket ModeOn
App-level tokenconnections:write
Bot token scopesapp_mentions:read, chat:write, im:history, im:read
Event subscriptionsapp_mention, message.im

Generate the app-level token after enabling Socket Mode. Install the app to your workspace to get the bot token. If you change scopes later, reinstall. For channel testing, type /invite @your-bot inside the channel.

Install and configure

pip install slack-bolt openai

export SLACK_BOT_TOKEN='xoxb-your-bot-token'
export SLACK_APP_TOKEN='xapp-your-app-token'
export AICREDITS_API_KEY='your-aicredits-key'

Keep these values in environment variables, not in source control. If you use a .env file locally, do not commit it.

The complete runnable bot

Save this as main.py. It answers @mentions in channels and direct messages, keeps short per-thread memory, and calls deepseek-v4-flash through the OpenAI SDK.

import os
import re

from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
from openai import OpenAI

app = App(token=os.environ['SLACK_BOT_TOKEN'])
client = OpenAI(
    api_key=os.environ['AICREDITS_API_KEY'],
    base_url='https://api.aicreditsapi.com/v1',
)

SYSTEM_PROMPT = (
    'You are a concise Slack assistant. '
    'Answer in short paragraphs or bullets. '
    'If you are unsure, say so and ask one clarifying question.'
)

history = {}
SEEN = set()

def duplicate(body):
    event_id = body.get('event_id')
    if not event_id:
        return False
    if event_id in SEEN:
        return True
    SEEN.add(event_id)
    return False

def ask_model(text, key):
    turns = history.setdefault(key, [])
    messages = [{'role': 'system', 'content': SYSTEM_PROMPT}] + turns[-8:] + [{'role': 'user', 'content': text}]
    try:
        response = client.chat.completions.create(
            model='deepseek-v4-flash',
            messages=messages,
            temperature=0.2,
            max_tokens=700,
        )
    except Exception as exc:
        return f'Sorry - the model call failed: {exc}'

    answer = (response.choices[0].message.content or '').strip()
    turns.extend([
        {'role': 'user', 'content': text},
        {'role': 'assistant', 'content': answer},
    ])
    history[key] = turns[-12:]
    return answer

@app.event('app_mention')
def on_mention(event, say, body):
    if duplicate(body):
        return
    text = re.sub('<@[^>]+>', '', event.get('text', '')).strip()
    thread_ts = event.get('thread_ts') or event['ts']
    if not text:
        say('Hi - mention me with a question.', thread_ts=thread_ts)
        return
    key = str(event['channel']) + ':' + thread_ts
    say(ask_model(text, key), thread_ts=thread_ts)

@app.event('message')
def on_message(event, say, body):
    if event.get('channel_type') != 'im':
        return
    if event.get('subtype') or event.get('bot_id'):
        return
    if duplicate(body):
        return
    text = event.get('text', '').strip()
    if not text:
        return
    thread_ts = event.get('thread_ts') or event['ts']
    key = str(event['channel']) + ':' + thread_ts
    say(ask_model(text, key), thread_ts=thread_ts)

if __name__ == '__main__':
    SocketModeHandler(app, os.environ['SLACK_APP_TOKEN']).start()

Run it with python main.py. In Slack, mention the bot in a channel or send it a DM. The first reply should arrive after the model call, so test with a short question.

What the code is doing

  • Socket Mode removes the public URL requirement. Bolt handles the WebSocket and event envelopes.

  • The app_mention listener strips the <@USER> mention and replies in the same thread.

  • The message listener only handles DMs (channel_type == 'im') so channel traffic is not double-answered.

  • History is keyed by channel plus thread timestamp. It keeps the last 12 messages to control context size.

  • The duplicate guard uses Slack's event ID so a retried event does not produce a second answer.

Practical upgrades that are worth it

Use durable memory. The dictionary resets on restart. For a team bot, store the same message list in Redis keyed by channel and thread. Add a TTL so old threads expire. This is a small change with a large reliability payoff.

Route only hard requests to deepseek-v4-pro. Most Slack questions are short: summarize this, rewrite that, explain this error. deepseek-v4-flash is the right default. For long architecture discussions or code review, switch the model string to deepseek-v4-pro; it costs more, so route deliberately rather than by default.

Handle Slack's retry behavior. Slack can retry event delivery. The duplicate set in the sample is enough for a single process. In production, use Redis with a short TTL. Also catch model errors and return a short, useful message instead of letting the handler fail.

Keep replies Slack-sized. Slack messages have a practical length limit. Keep max_tokens modest and ask the model for short paragraphs. If you need long output, post the summary in Slack and link to the full result.

Why an OpenAI-compatible endpoint matters here

The bot only depends on the OpenAI SDK surface: chat.completions.create with messages and a model name. That is deliberate. If you later change providers, the handler stays almost the same; you change base_url, key, and model. The Slack code does not care.

AiCredits sells DeepSeek API credits to international developers, with card and PayPal checkout and no Chinese phone or bank requirement. The endpoint is OpenAI-compatible, so this tutorial works as written. Check aicreditsapi.com/pricing for current rates and off-peak differences. Cache hits cost less, and deepseek-v4-pro costs more than deepseek-v4-flash, so keep the default fast model unless a request needs more reasoning.

Troubleshooting checklist

  • not_in_channel: invite the bot to the channel.

  • missing_scope: add the scope, reinstall the app, and restart the bot.

  • invalid_auth: check that xoxb and xapp tokens are in the right variables.

  • No reply in DMs: confirm message.im is subscribed and im:history is granted.

  • Model errors: print the exception text, check the API key, and verify base_url has /v1.

  • Duplicate replies: keep the event-ID guard and, in multi-process deployments, move it to shared storage.

FAQ

Do I need a public server or ngrok?

No. Socket Mode opens an outbound WebSocket, so the bot can run on your laptop or a private VM.

Can I stream tokens into Slack?

Slack does not stream tokens into a single message the way a web UI does. For v1, send the final answer. For a nicer UX, post a placeholder and update it with chat.update, but that adds complexity.

How do I keep conversation memory across restarts?

Replace the in-memory dictionary with Redis or another shared store, keyed by channel and thread timestamp. Add a TTL and trim old turns.

Should I use deepseek-v4-flash or deepseek-v4-pro?

Use deepseek-v4-flash for normal Slack answers, summaries, and rewrites. Switch to deepseek-v4-pro for long analysis or code review where quality matters more than cost.

Is this safe for a private workspace?

Treat the bot token and API key as secrets. Do not commit them. Limit the app to the scopes listed, and remove the app if you stop using it.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×