INTEGRATION GUIDE · BETA · SOURCE CHECKED 16 NOV 2026
Migrate Discord bots from the Perspective API (before 31 Dec 2026)
Perspective-shaped requests, independent scores. Change the connection, then validate the moderation decisions.
Google’s Perspective API notice gives 31 December 2026 as the shutdown date. Plan and test your migration before then.
1. Prepare a staging copy
Save the integration version, settings, current thresholds and old scores before changing providers. Create a Decision Models key in the dashboard; store it only on your server. Examples use environment variables, never real keys.
There is no single Perspective integration shared by Discord bots. Your discord.py or JavaScript bot owns its host, requested attributes and action thresholds. The examples below are new application code, not a patch to a named bot package. Follow discord.py’s bot pattern or discord.js documentation for message events and permissions.
2. Change the endpoint and key
Replace the Perspective HTTP call in your message handler, keep both tokens server-side, and start in observation mode. In Python, use an async HTTP client so the message loop is not blocked. Add this helper to your existing discord.py bot (aiohttp must be installed):
import os, aiohttp
async def toxicity(text):
async with aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=15)) as session:
async with session.post(
"https://moderation.decisionmodels.io/v1alpha1/comments:analyze",
headers={"Authorization": "Bearer " + os.environ["DM_MODERATION_KEY"]},
json={"comment": {"text": text},
"requestedAttributes": {"TOXICITY": {}}, "doNotStore": True}
) as response:
response.raise_for_status()
data = await response.json()
return data["attributeScores"]["TOXICITY"]["summaryScore"]["value"]
# In your existing handler, after bot/empty-message checks:
# score = await toxicity(message.content)
# Compare with your validated threshold; initially send to moderator review.JavaScript helper
Use this fetch helper in an existing server-side bot with built-in fetch; the last two lines are a standalone smoke check. Save as smoke.mjs to run it directly:
async function analyze(text) {
const response = await fetch(
"https://moderation.decisionmodels.io/v1alpha1/comments:analyze", {
method: "POST",
headers: {"Content-Type": "application/json",
Authorization: `Bearer ${process.env.DM_MODERATION_KEY}`},
body: JSON.stringify({comment: {text},
requestedAttributes: {TOXICITY: {}}, doNotStore: true}),
signal: AbortSignal.timeout(15000)
});
if (!response.ok) throw new Error(`Moderation HTTP ${response.status}`);
return response.json();
}
const result = await analyze("Thank you for explaining.");
console.log(result.attributeScores.TOXICITY.summaryScore.value);Attributes and compatibility
These examples request built-in TOXICITY only. Audit your existing bot’s full attribute map. A toxicity score does not establish whether a message is spam or violates a server-specific rule; SPAM is experimental here.
Built-in and experimental attribute names
Built-in: TOXICITY, IDENTITY_ATTACK, INSULT, PROFANITY, THREAT. Built-in does not mean score parity with Perspective.
Experimental, not evaluated and uncalibrated: SEVERE_TOXICITY, SEXUALLY_EXPLICIT, FLIRTATION, SPAM, ATTACK_ON_AUTHOR, ATTACK_ON_COMMENTER, INCOHERENT, INFLAMMATORY, LIKELY_TO_REJECT, OBSCENE, UNSUBSTANTIAL. Responses identify requested experimental attributes in X-DM-Experimental-Attributes. Unknown attributes return 400. Check the current attribute and language documentation before enabling automatic actions.
Re-tune the thresholds
Generic discord.py and JavaScript bots have no common Perspective threshold. Find each warning, deletion, timeout and ban comparison in your bot. Keep automatic sanctions disabled while selecting thresholds from labeled server messages with /migrate. A demonstration value such as 0.8 is not a recommended server policy.
Use the migration tool with representative comments, their saved Perspective scores and optional human labels. Compare flag rates, flagged-set overlap and, where labels exist, precision and recall. Matching a flag rate does not guarantee the same flagged comments or accuracy. Tune each attribute and action separately; do not copy the old numbers into production without review.
3. Test and re-tune
With DM_MODERATION_KEY set privately, this smoke command should return HTTP 200 and a numeric attributeScores.TOXICITY.summaryScore.value between 0 and 1. It checks transport and response shape, not moderation quality.
curl --fail-with-body --max-time 15 \
'https://moderation.decisionmodels.io/v1alpha1/comments:analyze' \
-H "Authorization: Bearer $DM_MODERATION_KEY" \
-H 'Content-Type: application/json' \
--data '{"comment":{"text":"Thank you for explaining."},"requestedAttributes":{"TOXICITY":{}},"doNotStore":true}'node smoke.mjsOr save the Python helper as smoke_bot.py, append the following and run python3 smoke_bot.py:
if __name__ == "__main__":
import asyncio
print(asyncio.run(toxicity("Thank you for explaining.")))Then send staged messages in a private test server and verify observation output without automatic sanctions. Ignore bot and empty messages before calling the API. If you use prefix commands with discord.py on_message, preserve your command-processing path.
In staging, test benign, abusive, borderline, quoted and multilingual comments; compare actual queue or warning actions with human decisions. Also test invalid keys, untested-language warnings, 429 rate limits and a timeout. Keep a manual moderation fallback rather than interpreting a failed request as a safe score. Check limits and errors and plan quotas and request rates.
4. Roll out with a fallback
Message content access depends on Discord intents and your application settings. Queue bursts within your plan’s rate limit, use bounded retries and send failures to moderator review. Scoring a message alone misses surrounding conversation and attachments. Restore the saved helper and environment configuration to roll back; keep sanctions paused if the old provider is unavailable.
Keep the saved version and settings so you can reverse this change. Before Google’s shutdown, you can restore the Google endpoint together with its Google key and old thresholds if that service remains available to your account. After shutdown, use a tested alternative or manual review. Never send a Decision Models key to the Google host, or a Google key to Decision Models.
Shared gaps: scores come from an independent model; sentence-level span annotations are unavailable (one whole-text span only). Only PLAIN_TEXT is accepted. Valid explicit language hints are accepted and echoed. Untested hints or detected languages carry X-DM-Language-Untested. Tested languages: English (5 attributes) and German (offensive-language proxy only). This is not evidence of language quality. Suggested-score feedback is acknowledged but not stored or used to train the model. See the full API contract.
Source notes
These instructions follow the linked source revisions, inspected on 16 November 2026. Your installed release may differ. Patches and examples are migration recipes, not upstream endorsements or a claim of an end-to-end verified integration.
discord.py example · discord.js source and usage · Replacement API contract