Certainly! I'll help you build a Character AI Discord bot with the features you've described. We'll break down the process into manageable steps, including setting up the bot, creating characters with customizable settings, implementing voice and text modes, and using ollama with the specified models. We'll also integrate Coqui TTS for voice responses.
Table of Contents
- Prerequisites
- Setting Up the Discord Bot
- Installing Required Libraries
- Loading Environment Variables
- Creating Admin Commands and Control Panel
- Character Creation and Configuration
- Implementing Message Handling
- Integrating Ollama Models
- Implementing Voice and Text Modes
- Using Coqui TTS for Voice Responses
- Complete Bot Code
- Running the Bot
- Conclusion
Prerequisites
- Python 3.8 or higher
- Discord server with the specified categories and channels.
- Ollama installed and configured with
openhermes and llama3.1 models.
- Coqui TTS installed for generating voice responses.
- GPU support for Coqui TTS if you plan to use GPU acceleration.
Setting Up the Discord Bot
First, create a new Discord bot application and invite it to your server.
- Go to the Discord Developer Portal.
- Create a new application and give it a name.
- Navigate to Bot section and add a bot to your application.
- Enable the Privileged Gateway Intents: Server Members Intent and Message Content Intent.
- Copy the bot token—we'll store it in a
.env file.
- Invite the bot to your server using the OAuth2 URL Generator with the appropriate scopes and permissions.
Installing Required Libraries
We'll use the following Python libraries:
discord.py for interacting with Discord.
dotenv for loading environment variables.
asyncio for asynchronous operations.
coqui_tts for text-to-speech.
ollama Python client (if available) or HTTP requests to interact with Ollama.
Install the libraries using pip:
pip install discord.py python-dotenv coqui-tts
Loading Environment Variables
Create a .env file in your project directory to store your bot token securely.
.env
DISCORD_TOKEN=YOUR_DISCORD_BOT_TOKEN
Add .env to your .gitignore if you're using version control.
In your Python script, load the environment variable:
import os
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
Creating Admin Commands and Control Panel
We'll create an admin command !create_character that opens a modal (panel) for character creation.
import discord
from discord.ext import commands
from discord.ui import Modal, TextInput
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='!', intents=intents)
# Check if the user has the administrator permission
def is_admin():
async def predicate(ctx):
return ctx.author.guild_permissions.administrator
return commands.check(predicate)
Character Creation and Configuration
Create a modal for character creation:
class CharacterCreationModal(Modal):
def __init__(self):
super().__init__(title='Create a New Character')
self.add_item(TextInput(label='Character Name', placeholder='Enter character name...'))
self.add_item(TextInput(label='Personality Prompt', style=discord.TextStyle.long, placeholder='Describe the character’s personality...'))
self.add_item(TextInput(label='Example Response', style=discord.TextStyle.long, placeholder='Provide an example response from the character...'))
self.add_item(TextInput(label='Model Choice', placeholder='openhermes or llama3.1'))
self.add_item(TextInput(label='Mode', placeholder='voice, text, or both'))
async def on_submit(self, interaction: discord.Interaction):
# Extract input values
name = self.children[0].value
personality = self.children[1].value
example_response = self.children[2].value
model_choice = self.children[3].value.lower()
mode = self.children[4].value.lower()
# Save character configuration (store in database or file)
character = {
'name': name,
'personality': personality,
'example_response': example_response,
'model_choice': model_choice,
'mode': mode,
'history': []
}
# For simplicity, we'll store it in a dictionary
characters[name] = character
await interaction.response.send_message(f'Character **{name}** has been created!', ephemeral=True)
Set up the command to invoke this modal:
@bot.command()
@is_admin()
async def create_character(ctx):
await ctx.send('Opening character creation panel...', delete_after=1)
await ctx.author.send_modal(CharacterCreationModal())
Implementing Message Handling
We'll handle messages in the character channels and pass them along with the username.
@bot.event
async def on_message(message):
if message.author.bot:
return
# Check if the message is in one of the character channels
if message.channel.category and message.channel.category.id == 1288358719314460692:
character_name = message.channel.name
if character_name in characters:
character = characters[character_name]
# Add message to history
character['history'].append({'user': message.author.name, 'content': message.content})
if len(character['history']) > 15:
character['history'].pop(0)
# Generate response
response = await generate_character_response(character)
# Send response based on mode
if character['mode'] == 'text':
await message.channel.send(response)
elif character['mode'] == 'voice':
if message.author.voice and message.author.voice.channel:
await send_voice_response(message.channel, response)
else:
await message.channel.send("You need to be in a voice channel to receive voice responses.")
elif character['mode'] == 'both':
await message.channel.send(response)
if message.author.voice and message.author.voice.channel:
await send_voice_response(message.channel, response)
else:
await message.channel.send("Character not found.")
else:
await bot.process_commands(message)
Integrating Ollama Models
We need to interact with ollama to generate responses using the specified models.
import subprocess
import json
async def generate_character_response(character):
# Prepare the prompt
prompt = f"{character['personality']}\n"
for msg in character['history']:
prompt += f"{msg['user']}: {msg['content']}\n"
prompt += f"{character['name']}:"
# Call Ollama with subprocess
model_choice = character['model_choice']
ollama_command = ['ollama', 'generate', '-m', model_choice]
process = subprocess.Popen(ollama_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
stdout, stderr = process.communicate(prompt)
if stderr:
print(f"Ollama error: {stderr}")
return "Sorry, I couldn't generate a response."
response_text = stdout.strip()
return response_text
Note: Make sure that ollama is accessible from your Python script. You might need to adjust the command based on how ollama accepts input.
Implementing Voice and Text Modes
We've already handled the mode selection in the message handler. Now, we need to implement send_voice_response.
Using Coqui TTS for Voice Responses
Install the specific Coqui TTS model for male voice:
pip install TTS
Implement the send_voice_response function:
from TTS.api import TTS
# Initialize TTS model
tts_model = TTS(model_name="tts_models/de/thorsten/tacotron2-DDC", progress_bar=False, gpu=True)
async def send_voice_response(channel, text):
# Synthesize speech
tts_model.tts_to_file(text=text, file_path="response.wav")
# Send voice file
with open("response.wav", "rb") as f:
await channel.send(file=discord.File(f, filename="response.wav"))
Complete Bot Code
Here's the consolidated code with all the components:
import os
import discord
from discord.ext import commands
from discord.ui import Modal, TextInput
from dotenv import load_dotenv
import subprocess
from TTS.api import TTS
# Load environment variables
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
# Initialize bot and TTS model
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='!', intents=intents)
tts_model = TTS(model_name="tts_models/de/thorsten/tacotron2-DDC", progress_bar=False, gpu=True)
# Store characters
characters = {}
def is_admin():
async def predicate(ctx):
return ctx.author.guild_permissions.administrator
return commands.check(predicate)
class CharacterCreationModal(Modal):
def __init__(self):
super().__init__(title='Create a New Character')
self.add_item(TextInput(label='Character Name', placeholder='Enter character name...'))
self.add_item(TextInput(label='Personality Prompt', style=discord.TextStyle.long, placeholder='Describe the character’s personality...'))
self.add_item(TextInput(label='Example Response', style=discord.TextStyle.long, placeholder='Provide an example response from the character...'))
self.add_item(TextInput(label='Model Choice', placeholder='openhermes or llama3.1'))
self.add_item(TextInput(label='Mode', placeholder='voice, text, or both'))
async def on_submit(self, interaction: discord.Interaction):
name = self.children[0].value
personality = self.children[1].value
example_response = self.children[2].value
model_choice = self.children[3].value.lower()
mode = self.children[4].value.lower()
character = {
'name': name,
'personality': personality,
'example_response': example_response,
'model_choice': model_choice,
'mode': mode,
'history': []
}
characters[name] = character
await interaction.response.send_message(f'Character **{name}** has been created!', ephemeral=True)
@bot.command()
@is_admin()
async def create_character(ctx):
await ctx.author.send('Opening character creation panel...')
await ctx.author.send_modal(CharacterCreationModal())
@bot.event
async def on_message(message):
if message.author.bot:
return
if message.channel.category and message.channel.category.id == 1288358719314460692:
character_name = message.channel.name
if character_name in characters:
character = characters[character_name]
character['history'].append({'user': message.author.name, 'content': message.content})
if len(character['history']) > 15:
character['history'].pop(0)
response = await generate_character_response(character)
if character['mode'] == 'text':
await message.channel.send(response)
elif character['mode'] == 'voice':
if message.author.voice and message.author.voice.channel:
await send_voice_response(message.channel, response)
else:
await message.channel.send("You need to be in a voice channel to receive voice responses.")
elif character['mode'] == 'both':
await message.channel.send(response)
if message.author.voice and message.author.voice.channel:
await send_voice_response(message.channel, response)
else:
await message.channel.send("Character not found.")
else:
await bot.process_commands(message)
async def generate_character_response(character):
prompt = f"{character['personality']}\n"
for msg in character['history']:
prompt += f"{msg['user']}: {msg['content']}\n"
prompt += f"{character['name']}:"
model_choice = character['model_choice']
ollama_command = ['ollama', 'generate', '-m', model_choice]
process = subprocess.Popen(ollama_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
stdout, stderr = process.communicate(prompt)
if stderr:
print(f"Ollama error: {stderr}")
return "Sorry, I couldn't generate a response."
response_text = stdout.strip()
return response_text
async def send_voice_response(channel, text):
tts_model.tts_to_file(text=text, file_path="response.wav")
with open("response.wav", "rb") as f:
await channel.send(file=discord.File(f, filename="response.wav"))
bot.run(TOKEN)
Running the Bot
- Ensure all dependencies are installed.
- Save the script to a file, e.g.,
bot.py.
- Run the script using:
python bot.py
Conclusion
You've now set up a Discord bot that allows you to create AI-powered characters with customizable personalities, using ollama for AI responses and Coqui TTS for voice output. The bot supports text, voice, or both modes and stores message history to maintain context.
Notes:
- Ensure that
ollama is correctly installed and accessible from your Python script.
- The code assumes that the character channels are named after the characters.
- For production use, consider implementing proper error handling and persistent storage (e.g., databases) for character data and message history.
- Make sure to secure your bot token and not expose it publicly.
- Test the bot thoroughly in a controlled environment before deploying it to your main server.
If you have any questions or need further assistance with specific parts of the implementation, feel free to ask!