Zack Saadioui
8/24/2024
1
2
3
bash
python -m venv myenv
source myenv/bin/activate # On Windows use `myenvinreeze`
1
discord.py
1
2
bash
pip install langchain discord.py
1
bot.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
import discord from langchain_openai import ChatOpenAI from langchain_core.messages import HumanMessage, AIMessage # Discord Client Setup client = discord.Client(intents=discord.Intents.default()) @client.event async def on_ready(): print(f'We have logged in as {client.user}') @client.event async def on_message(message): if message.author == client.user: return # Respond only if bot is mentioned if client.user.mentioned_in(message): response = await handle_message(message.content) await message.channel.send(response) async def handle_message(content): model = ChatOpenAI(model="gpt-3.5-turbo") # Create a prompt message response = model.invoke([HumanMessage(content=content)]) return response.content # Run the bot client.run('YOUR_TOKEN')
1
discord.Client
1
YOUR_TOKEN
1
handle_message
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
from langchain_core.chat_history import InMemoryChatMessageHistory # Initialize Message History message_history = InMemoryChatMessageHistory() async def handle_message(content): # Append to message history message_history.append(HumanMessage(content=content)) model = ChatOpenAI(model="gpt-3.5-turbo") # Get history history = message_history.get_history() # Retrieve history # Create response response = model.invoke(history) # Add bot response to history message_history.append(AIMessage(content=response.content)) return response.content
1
python bot.py
Copyright © Arsturn 2024