Skip to main content

Discord - Global Chat Configuration - Webhooks

Discord & brainCloud Bidirectional Chat Integration

Jason Liang avatar
Written by Jason Liang
Updated over a week ago

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

  1. User posts message in monitored Discord channel

  2. Bot captures message via messageCreate event

  3. Bot sends message data to brainCloud webhook

  4. brainCloud Cloud Code processes and adds to app chat

Flow 2: brainCloud Discord

  1. App user posts message in brainCloud chat

  2. brainCloud post hook triggers

  3. 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

  1. Click "New Application"

  2. Enter a name (e.g., "brainCloud Chat Bot")

  3. Click "Create"

  4. Navigate to the "Bot" section in the left sidebar

  5. Click "Add Bot" Confirm

  6. Under Token, click "Reset Token" and copy it

    • Keep this token secret! Treat it like a password

  7. Scroll down to "Privileged Gateway Intents"

  8. 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

  1. In the Discord Developer Portal, go to OAuth2 URL Generator

  2. Under SCOPES, select:

    • bot

    • applications.commands

  3. Under BOT PERMISSIONS, select:

    • Read Messages/View Channels

    • Send Messages

    • Manage Webhooks (important!)

    • Read Message History

    • Or simply select Administrator for testing

  4. Copy the generated URL at the bottom

  5. Paste the URL in your browser

  6. Select your server from the dropdown

  7. Click "Authorize"

  8. Complete the CAPTCHA

Step 1.3: Create Channel Webhooks

For each Discord channel you want to sync with brainCloud:

  1. Right-click the channel (e.g., #braincloud-chat)

  2. Select "Edit Channel"

  3. Go to "Integrations" tab

  4. Click "Webhooks" "New Webhook"

  5. Configure the webhook:

    • Name: "brainCloud Bot" (or your preferred name)

    • Channel: Confirm correct channel

    • (Optional) Upload an avatar

  6. Click "Copy Webhook URL"

  7. Save the webhook URL securely

  8. 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_CHANNELS array 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:

  1. Send a message in a monitored channel

  2. 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.

  1. Log into brainCloud Portal

  2. Navigate to Design Cloud Code Webhooks

  3. Click "Create Webhook"

  4. Configure:

    • Name: discordIncoming (or your choice)

    • Description: "Receives messages from Discord bot"

    • Secret: Generate a secure random string (copy this!)

  5. Click "Create"

  6. Click "Edit Script"

  7. 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()
  1. Click "Save"

  2. 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.

  1. In brainCloud Portal, go to Design Cloud Code Scripts

  2. Click "Create Script"

  3. Configure:

    • Name: PostChatToDiscord

    • Type: Post Hook

    • Service: Chat

    • Operation: POST_CHAT_MESSAGE (or POST_CHAT_MESSAGE_SIMPLE)

  4. Click "Create"

  5. 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()
  1. 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.

  2. Click "Save"

Step 3.3: Configure Chat Channels

Create or configure chat channels in brainCloud:

  1. Go to Design Messaging Chat

  2. 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

  3. Click "Save"


Part 4: Testing

Test 1: Discord brainCloud

  1. Open Discord

  2. Send message in #braincloud-general: "Test from Discord!"

  3. Check bot logs: Should see Discord message from #braincloud-general

  4. Log into brainCloud app

  5. Navigate to chat channel bc-general

  6. Verify message appears

Test 2: brainCloud Discord

  1. Log into brainCloud app

  2. Send message in chat channel bc-general: "Test from brainCloud!"

  3. Check bot logs: Should see Posted to Discord #braincloud-general

  4. Open Discord

  5. Check #braincloud-general

  6. Verify message appears from "brainCloud User"

Test 3: Commands

In Discord:

  • Type !help Should show help embed

  • Type !api Should 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_CHANNELS array

  • Check 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

Did this answer your question?