Description:
This n8n workflow automates a Discord bot to fetch messages from a specified channel and send AI-generated responses in threads. It ensures smooth message processing and interaction, making it ideal for managing community discussions, customer support, or AI-based engagement. This workflow leverages Redis for memory persistence, ensuring that conversation history is maintained even if the workflow restarts, providing a seamless user experience.
Create a new folder discord-bot and navigate into it:
Create and configure an .env file to store your bot token:
Copy the code to .env: (You can copy the webhook URL from the n8n workflow)
TOKEN=your-bot-token-here WEBHOOK_URL=https://your-domain.tld/webhook/getmessage
Create file main.py copy the below code and save it:
Copy this Bot script to main.py:
import discord import requests import json import os from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
TOKEN = os.getenv("TOKEN")
WEBHOOK_URL = os.getenv("WEBHOOK_URL")
# Bot Configuration
LISTEN_CHANNELS = ["YOUR_CHANNEL_ID_1", "YOUR_CHANNEL_ID_2"] # Replace with your target channel IDs
# Intents setup
intents = discord.Intents.default()
intents.messages = True # Enable message event
intents.guilds = True
intents.message_content = True # Required to read messages
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'Logged in as {client.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return # Ignore bot's own messages
if str(message.channel.id) in LISTEN_CHANNELS:
try:
fetched_message = await message.channel.fetch_message(message.id) # Ensure correct fetching
payload = {
"channel_id": str(fetched_message.channel.id), # Ensure it's string
"chat_message": fetched_message.content,
"timestamp": str(fetched_message.created_at), # Ensure proper formatting
"message_id": str(fetched_message.id), # Ensure ID is a string
"user_id": str(fetched_message.author.id) # Ensure user ID is also string
}
headers = {'Content-Type': 'application/json'}
response = requests.post(WEBHOOK_URL, data=json.dumps(payload), headers=headers)
if response.status_code == 200:
print(f"Message sent successfully: {payload}")
else:
print(f"Failed to send message: {response.status_code}, Response: {response.text}")
except Exception as e:
print(f"Error fetching message: {e}")
client.run(TOKEN)
6. Create requirements.txt and copy:
discord
python-dotenv
Note: Free Plan will expire after 24 hours, so please opt for the Paid Plan in Pella to keep your bot running.
The n8n workflow consists of the following nodes:
channel_id, chat_message, timestamp, message_id, and user_id from Discord when a new message is posted in the configured channel. Its webhook path is /getmessage and it expects a POST request.chat_message). It is configured as a conversational agent, integrating the language model and memory to generate an appropriate response. It also has a prompt to keep the reply concise, under 1800 characters.gpt-4o-mini-2024-07-18 model for generating AI responses. It is the core AI component of the workflow.Chat Agent maintains context for each user based on their user_id. This is critical for coherent multi-turn conversations.message_id) in the specified channel_id..env file, requirements.txt, the Python bot code, and general recommendations for channel configuration and adding tools.✅ redis-for-n8n is properly set up with your Redis instance details (host, port, password).ai_languageModel input of the "Chat Agent" node.text parameter in the "Chat Agent" node to change the AI's persona, provide specific instructions, or adjust the response length.ai_tool input of the "Chat Agent" node to extend the AI's capabilities. Refer to the "Sticky Note5" in the workflow for a reminder.LISTEN_CHANNELS list in the main.py file of your Discord bot to include or exclude specific Discord channel IDs where the bot should listen for messages.message_reference).main.py script is running on Pella.LISTEN_CHANNELS in your Discord server and send a message.✅ Now your bot is running in the background! 🚀


