How I Built a Feishu Bot for My Team Through a Unified AI Gateway (A Manager's Perspective)
Anyone who has led a team knows how painful it is to operationalize tool permissions. When a new colleague joins and wants to use a large language model to handle inquiry messages in Feishu, the old process took three steps: request budget, register an account with some model provider, and paste the API Key in plaintext into a group chat. By the time approval was done, two days had passed; and when a departing colleague's Key was forgotten and never revoked, that became a security incident.
I later made a decision: all AI capabilities would go through a single gateway (ThisToken.AI), and the team would no longer hold any raw model Keys individually. The Feishu bot was the first scenario we integrated. This article documents the complete process, with the focus on how the workflow is defined, how permissions are controlled, and how issues are traced — the code is just the last step of the process.
1. Why Managers Should Care About "Where the Keys Live"
Calling a model provider directly from a self-built bot is technically fine, but managerially there are three pitfalls:
- Scattered Keys: Every developer holds a Key, and handovers during departures inevitably leak them.
- Out-of-control billing: Who called how much, and on what — you only see it in the month-end report, too late to control.
- Model change risk: If a model is discontinued or its price increases, you have to change code one by one.
The value of a unified gateway is consolidating these risks: there is only one copy of the Key, on the gateway side; call records are centralized and queryable; switching models is a one-parameter change. As for pricing, refer to the official pricing page, and the team just pays as they go.
2. Setup Process (Can Be Completed in One Day)
- Register an account: Visit ThisToken.AI and register with a shared team email (don't use a personal email, to make future handovers easier).
- Create an API Key: In the console, it's recommended to create Keys per "project" — for example, one each for
feishu-bot-prodandfeishu-bot-test— to make per-environment isolation and revocation easier. - Top up or enable quota: Refer to the official pricing page.
- On the Feishu Open Platform, create an enterprise self-built app, enable the "Bot" capability, configure event subscription (to receive the message event
im.message.receive_v1), and obtain the App ID and App Secret.
At this point, all the credentials the team needs are ready, but note: the model Key only goes into the gateway configuration — no one on the team should ever hold the raw model Key. That is the first red line of risk control.
3. Getting the First Code Running
The minimal viable version, in Python, depends on flask, openai (the gateway is OpenAI-protocol compatible), and the official Feishu SDK:
import os
import json
from flask import Flask, request
from openai import OpenAI
import lark_oapi as lark
from lark_oapi.api.im.v1 import ReplyMessageRequest, ReplyMessageRequestBody
app = Flask(__name__)
# Unified gateway entry: the Key only lives in environment variables, never in the codebase
client = OpenAI(
api_key=os.environ["THISTOKEN_API_KEY"],
base_url="https://api.thistoken.ai/v1",
)
lark_client = lark.Client.builder() \
.app_id(os.environ["FEISHU_APP_ID"]) \
.app_secret(os.environ["FEISHU_APP_SECRET"]) \
.build()
SYSTEM_PROMPT = "你是团队内部助手,回答保持简洁、专业,涉及不确定的信息要明确说明。"
def ask_llm(question: str) -> str:
resp = client.chat.completions.create(
model="gpt-4o-mini", # 按需替换为团队白名单内的模型
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": question},
],
)
return resp.choices[0].message.content
def reply(message_id: str, text: str):
req = ReplyMessageRequest.builder() \
.message_id(message_id) \
.request_body(ReplyMessageRequestBody.builder().content(
json.dumps({"text": text})).msg_type("text").build()) \
.build()
lark_client.im.v1.message.reply(req)
@app.route("/webhook", methods=["POST"])
def webhook():
body = request.json
event = body.get("event", {})
msg = event.get("message", {})
if msg.get("message_type") == "text":
question = json.loads(msg["content"])["text"]
answer = ask_llm(question)
reply(msg["message_id"], answer)
return {"code": 0}
if __name__ == "__main__":
app.run(port=8000)Several management details are hidden in the code:
- All Keys go through environment variables, so the codebase can be open-sourced and handed over, and audits require no data masking.
- The model name is hardcoded rather than user-specified. Combined with the team's role whitelist system, who can trigger which model is jointly constrained by the code and the Key permissions.
- The System Prompt is centrally maintained. The bot's "persona" and compliance stance are vetted by the manager, not casually written by every developer.
After it runs locally, deploy the service to your intranet or a cloud server, and set the Feishu event subscription URL to your /webhook path.
4. Three Management Actions After Launch
Getting the code running is just the beginning; what really determines whether this can run long-term is the process:
- Review the call reports weekly. The gateway has centralized usage records — who is using it, how much, and which model they're calling — all at a glance. Anomalous traffic is caught the same day, instead of a shock when the monthly bill arrives.
- Rotate Keys regularly. It's recommended to rotate the gateway Key quarterly; the test environment Key can be revoked at any time without affecting production.
- Spot-check answer quality. Have the operations or customer service lead sample a few bot replies every week, and feed insights back into the System Prompt. The bot is the team's public-facing voice — this can't rely solely on the model's own discretion.
The most tangible change after launching this setup: on the day a new colleague joins, they can @ the bot in Feishu and start using AI; on the day they leave, what gets revoked is a gateway sub-Key — not a single line of code needs to change. The efficiency of a tool ultimately depends on the process that governs it, not on how powerful the model itself is.
If you also want to consolidate your team's AI capabilities behind a unified gateway, you can register an account first and test-run the code above: https://api.thistoken.ai/register
---
Every example in this post runs with a single API key — get yours at https://api.thistoken.ai/register and start in minutes.
Хотите попробовать Token.AI?
Создайте API Key уровня проекта, включите каналы в консоли и настройте маршрутизацию, бюджеты и журналы аудита.
注册 ThisToken.AI 并获取 API Key