Key Benefits for your App
Create a fully functional bidirectional chat integration between Discord and brainCloud
Real-time message syncing between platforms
No additional client-side coding required
Overview
This guide walks you through creating a bidirectional chat integration between Discord and brainCloud.
enabling users on both platforms to communicate seamlessly without requiring additional application code changes.
What You'll Build:
A Discord bot that monitors specific channels and forwards messages to brainCloud
A webhook system that allows brainCloud to post messages back to Discord
Automatic message synchronization between Discord channels and brainCloud chat channels
Use Cases:
Enable community members to chat with in-app users
Provide customer support across platforms
Share announcements and updates bidirectionally
Create a unified communication experience
Architecture Overview
Flow 1: Discord brainCloud
User posts message in monitored Discord channel
Bot captures message via
messageCreateeventBot sends message data to brainCloud webhook
brainCloud Cloud Code processes and adds to app chat
Flow 2: brainCloud Discord
App user posts message in brainCloud chat
brainCloud post hook triggers
brainCloud posts message to Discord channel via webhook
Prerequisites
Discord Requirements
A Discord account
Administrator access to a Discord server (or ability to create one)
Discord Developer Portal access
brainCloud Requirements
A brainCloud application
Access to Cloud Code and Webhooks
Basic understanding of brainCloud's chat system
Technical Requirements
Node.js (v16 or higher)
npm or yarn package manager
A server or hosting environment to run the bot 24/7
Basic knowledge of JavaScript/Node.js
Part 1: Discord Setup
Step 1.1: Create a Discord Application
Go to Discord Developer Portal
Click "New Application"
Enter a name (e.g., "brainCloud Chat Bot")
Click "Create"
Navigate to the "Bot" section in the left sidebar
Click "Add Bot" Confirm
Under Token, click "Reset Token" and copy it
Keep this token secret! Treat it like a password
Scroll down to "Privileged Gateway Intents"
Enable the following intents:
Message Content Intent (required to read message content)
Server Members Intent (optional, for member info)
Step 1.2: Invite Bot to Your Server
In the Discord Developer Portal, go to OAuth2 URL Generator
Under SCOPES, select:
botapplications.commands
Under BOT PERMISSIONS, select:
Read Messages/View Channels
Send Messages
Manage Webhooks (important!)
Read Message History
Or simply select Administrator for testing
Copy the generated URL at the bottom
Paste the URL in your browser
Select your server from the dropdown
Click "Authorize"
Complete the CAPTCHA
Step 1.3: Create Channel Webhooks
For each Discord channel you want to sync with brainCloud:
Right-click the channel (e.g.,
#braincloud-chat)Select "Edit Channel"
Go to "Integrations" tab
Click "Webhooks" "New Webhook"
Configure the webhook:
Name: "brainCloud Bot" (or your preferred name)
Channel: Confirm correct channel
(Optional) Upload an avatar
Click "Copy Webhook URL"
Save the webhook URL securely
Click "Save Changes"
Repeat for all channels you want to sync.
Example Channel Mapping:
Discord Channel brainCloud Chat Channel
#braincloud-general bc-general
#braincloud-support bc-support
#braincloud-feedback bc-feedback
Part 2: Bot Development
Step 2.1: Initialize Node.js Project
Open the terminal and enter the following:
# Create project directory
mkdir discord-braincloud-bot
cd discord-braincloud-bot
# Initialize npm project
npm init -y
# Install dependencies
npm install discord.js axios express
Step 2.2: Create Bot Code
Create a file named bot.js:
const { Client, GatewayIntentBits } = require('discord.js')
const axios = require('axios')
const express = require('express')
// ==================== CONFIGURATION ====================
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent
]
})
// Discord Configuration
const DISCORD_BOT_TOKEN = 'YOUR_DISCORD_BOT_TOKEN'
const ALLOWED_CHANNELS = [
'braincloud-general',
'braincloud-support',
'braincloud-feedback'
]
// Discord Webhooks (for brainCloud Discord)
const DISCORD_WEBHOOKS = {
'braincloud-general': 'api/webhooks/...',
'braincloud-support': 'api/webhooks/...',
'braincloud-feedback': 'api/webhooks/...'
}
// brainCloud Configuration
const BRAINCLOUD_WEBHOOK_URL =
'https://api.braincloudservers.com/webhook/YOUR_APP_ID/YOUR_WEBHOOK_NAME'
const BRAINCLOUD_WEBHOOK_SECRET = 'YOUR_WEBHOOK_SECRET'
// Security token for incoming requests
const API_SECRET = 'YOUR_SECURE_RANDOM_TOKEN'
// ==================== FUNCTIONS ====================
/**
* Send Discord message to brainCloud
*/
async function sendToBrainCloud(messageData) {
try {
const response = await axios.post(BRAINCLOUD_WEBHOOK_URL, messageData, {
headers: {
'x-bc-secret': BRAINCLOUD_WEBHOOK_SECRET
}
})
console.log(`Sent to brainCloud: ${response.status}`)
return response.status === 200
} catch (error) {
console.error('Error sending to brainCloud:', error.message)
return false
}
}
// ==================== DISCORD BOT EVENTS ====================
client.on('clientReady', () => {
console.log(`Bot logged in as ${client.user.tag}`)
console.log(`Monitoring channels: ${ALLOWED_CHANNELS.join(', ')}`)
})
client.on('messageCreate', async message => {
// Ignore messages from bots
if (message.author.bot) return
// Handle !help command
if (message.content.toLowerCase() === '!help') {
const helpInfo = {
embeds: [
{
title: 'brainCloud Discord Bot',
description:
'I help bridge communication between Discord, brainCloud, and Slack. I monitor specific channels and forward messages to keep everyone in sync!',
color: 0x5865f2,
fields: [
{
name: 'Available Commands',
value:
'• `!help` - Display this help message\n• `!api` - Show brainCloud API resources and documentation links',
inline: false
},
{
name: 'Monitored Channels',
value:
'• #braincloud-news\n• #bc-code\n• #bc-braincloud\n• #bc-feedback',
inline: false
},
{
name: 'ℹWhat I Do',
value:
'Messages posted in the monitored channels are automatically forwarded to brainCloud and Slack to keep all platforms synchronized.',
inline: false
}
],
footer: {
text: 'brainCloud Bot v1.0'
},
timestamp: new Date()
}
]
}
await message.reply(helpInfo)
return
}
// Handle !api command (works in any channel)
if (message.content.toLowerCase() === '!api') {
const apiInfo = {
embeds: [
{
title: '📚 brainCloud API Resources',
color: 0x0099ff,
fields: [
{
name: 'API Reference',
value:
'[View Reference](https://docs.braincloudservers.com/api/introduction)',
inline: false
},
{
name: 'Video Tutorials',
value:
'[View Tutorials](https://bootcamp.braincloudservers.com/)',
inline: false
},
{
name: 'SDK Tutorials',
value:
'[View Support](https://docs.braincloudservers.com/learn/sdk-tutorials/)',
inline: false
},
{
name: 'Portal Tutorials',
value:
'[View Tutorials](https://docs.braincloudservers.com/learn/portal-tutorials/)',
inline: false
},
{
name: 'Knowledge Base',
value: '[ViewKnowledge Base](https://help.getbraincloud.com/)',
inline: false
},
{
name: 'Forums',
value:
'[View Forums](https://forumsdev.braincloudservers.com/categories)',
inline: false
},
{
name: 'Roadmap',
value: '[View Roadmap](https://getbraincloud.com/roadmap)',
inline: false
}
],
footer: {
text: 'brainCloud - Backend as a Service'
}
}
]
}
await message.reply(apiInfo)
return
}
// Only process messages from allowed channels for forwarding
if (ALLOWED_CHANNELS.includes(message.channel.name)) {
const messageData = {
channel: message.channel,
author: message.author,
content: message.content,
timestamp: message.createdAt.toISOString()
}
console.log(
`Discord message from #${message.channel.name}: "${message.content}"`
)
await sendToBrainCloud(messageData)
}
})
// ==================== START BOT ====================
client.login(DISCORD_BOT_TOKEN)Step 2.3: Configuration Checklist
Before running the bot, please check the Security Best Practices and replace the following placeholders:
[ ]
YOUR_DISCORD_BOT_TOKEN- From Discord Developer Portal[ ]
YOUR_BRAINCLOUD_WEBHOOK_URL- From brainCloud webhook setup[ ]
YOUR_BRAINCLOUD_WEBHOOK_SECRET- From brainCloud webhook setup[ ]
YOUR_SECURE_RANDOM_TOKEN- Generate a secure random string[ ] Discord webhook URLs for each channel
[ ] Update
ALLOWED_CHANNELSarray with your channel names
Step 2.4: Test Locally
# Run the bot
node bot.js
# You should see:
# Bot logged in as YourBot#1234
# Monitoring channels: braincloud-general, braincloud-support, braincloud-feedback
Test Discord Bot:
Send a message in a monitored channel
Check bot console for log:
Discord message from #channel-name: "message"
Test Bot Health:
curl http://localhost:3000/health
# Should return: {"status":"ok","bot":"YourBot#1234","uptime":123.45}
Part 3: brainCloud Setup
Step 3.1: Create Incoming Webhook (Discord brainCloud)
This webhook receives messages from Discord and adds them to brainCloud chat.
Log into brainCloud Portal
Navigate to Design Cloud Code Webhooks
Click "Create Webhook"
Configure:
Name:
discordIncoming(or your choice)Description: "Receives messages from Discord bot"
Secret: Generate a secure random string (copy this!)
Click "Create"
Click "Edit Script"
Add the following Cloud Code:
// discordIncoming webhook
// Receives messages from Discord and posts to brainCloud chat
function main() {
var response = {}
// this data is coming in from a bot above
const channel = bridge.getAppId() + ':gl:' + data.jsonBody.channel.name.replace('-', '_')
const recordInHistory = true
const fromData = {
name: data.jsonBody.author.globalName,
pic: data.jsonBody.author.displayAvatarURL
}
const content = data.jsonBody.content
var chatProxy = bridge.getChatServiceProxy()
var postChatMessageToChannel = chatProxy.sysPostChatMessageSimple(
channel,
content,
recordInHistory,
fromData
)
// Construct a response
response.jsonResponse = postChatMessageToChannel
response.message = 'Webhook received'
return response
}
main()
Click "Save"
Copy the webhook URL (you'll need this for the bot configuration)
Step 3.2: Create Post Hook (brainCloud Discord)
This Cloud Code script runs after every chat message and forwards it to Discord.
In brainCloud Portal, go to Design Cloud Code Scripts
Click "Create Script"
Configure:
Name:
PostChatToDiscordType: Post Hook
Service: Chat
Operation: POST_CHAT_MESSAGE (or POST_CHAT_MESSAGE_SIMPLE)
Click "Create"
Add the following code:
// PostChatToDiscord - Post Hook
// Forwards brainCloud chat messages to Discord
'use strict'
function main() {
var response = {}
const message = data.callingMessage.content.text
// this was just setup as the base discord url
var serviceCode = 'discord'
// customize as you see fit
// this will be integrated with discord channel
const channelId = data.callingMessage.channelId
const channelName = channelId.split(':')[2]
// bccode
const bccodePath = 'api/webhooks/** YOUR INFORMATION**'
// feedback
const feedback = 'api/webhooks/** YOUR INFORMATION**'
// news
const news = 'api/webhooks/** YOUR INFORMATION**'
// brainCloud
const brainCloudPath = 'api/webhooks/** YOUR INFORMATION**'
var path = ''
switch (channelName) {
case 'bc_code':
{
path = bccodePath
}
break
case 'bc_feedback':
{
path = feedback
}
break
case 'braincloud_news':
{
path = news
}
break
case 'bc_braincloud':
{
path = brainCloudPath
}
break
default:
break
}
if (path == '') {
return response
}
var readUserState = bridge.getPlayerStateServiceProxy()
var readData = readUserState.readUserState().data
var userName = readData.playerName
var headers = {}
// let's post this to the correct discord location
var json = {
content: message,
username: userName
}
var httpClientProxy = bridge.getHttpClientServiceProxy()
var postResult = httpClientProxy.postJsonResponseJson(
serviceCode,
path,
{},
headers,
json
)
response.data = postResult
return response
}
main()
Important: From the code above, where you see “
'api/webhooks/** YOUR INFORMATION**'" trim or extend the channels listed with your own, and replace those placeholder consts with your own.Click "Save"
Step 3.3: Configure Chat Channels
Create or configure chat channels in brainCloud:
Go to Design Messaging Chat
For each channel you want to sync:
Click "Create Channel" or edit existing
Channel ID: Match your mapping (e.g.,
bc-general)Type: Choose appropriate type (Global, Group, etc.)
Configure other settings as needed
Click "Save"
Part 4: Testing
Test 1: Discord brainCloud
Open Discord
Send message in
#braincloud-general: "Test from Discord!"Check bot logs: Should see
Discord message from #braincloud-generalLog into brainCloud app
Navigate to chat channel
bc-generalVerify message appears
Test 2: brainCloud Discord
Log into brainCloud app
Send message in chat channel
bc-general: "Test from brainCloud!"Check bot logs: Should see
Posted to Discord #braincloud-generalOpen Discord
Check
#braincloud-generalVerify message appears from "brainCloud User"
Test 3: Commands
In Discord:
Type
!helpShould show help embedType
!apiShould show API resources
Test 4: Health Check
curl https://your-bot-domain.com/health
Should return bot status and uptime.
Troubleshooting
Bot Not Receiving Discord Messages
Problem: Messages in Discord don't trigger the bot
Solutions:
Verify Message Content Intent is enabled in Discord Developer Portal
Check bot has permission to read messages in the channel
Confirm channel name is in
ALLOWED_CHANNELSarrayCheck bot logs for errors
Messages Not Appearing in brainCloud
Problem: Discord messages don't show up in brainCloud chat
Solutions:
Verify brainCloud webhook URL is correct
Check webhook secret matches in bot config
Test webhook directly using API explorer in brainCloud Portal
Verify channel mapping in webhook Cloud Code
Check brainCloud chat channel exists and is configured
Messages Not Appearing in Discord
Problem: brainCloud messages don't show up in Discord
Solutions:
Verify Discord webhook URLs are correct in bot config
Test Discord webhook using curl
Check bot server is accessible from internet
Verify API_SECRET matches in both bot and Post Hook
Check Post Hook is enabled and saved
Review Post Hook logs in brainCloud Portal
Authorization Errors
Problem: 401 Unauthorized errors
Solutions:
Verify all secrets match between systems
Check API_SECRET in Post Hook matches bot
Verify brainCloud webhook secret is correct
Security Best Practices
1. Protect Secrets
// BAD - Hardcoded in code
const TOKEN = 'MTQ3MDQ5ODYyNDg4O...'
// GOOD - Use environment variables const TOKEN = process.env.DISCORD_BOT_TOKEN
2. Validate All Inputs
// Always validate incoming data
if (!channel || !message || !secret) {
return res.status(400).json({ error: 'Missing required fields' })
}
if (secret !== API_SECRET) {
return res.status(401).json({ error: 'Unauthorized' })
}
3. Use HTTPS
Always use HTTPS for production
Use services like Let's Encrypt for free SSL certificates
Never send secrets over HTTP
4. Rotate Secrets Regularly
Change bot token every 6-12 months
Update webhook secrets periodically
Use different secrets for each environment (dev/staging/prod)
Support & Resources
Discord Resources
brainCloud Resources
Community
Conclusion
You now have a fully functional bidirectional chat integration between Discord and brainCloud! This setup enables:
Real-time message syncing between platforms
No additional client-side coding required

