Skip to content

Instantly share code, notes, and snippets.

@timothycarambat
Created April 1, 2025 02:45
Show Gist options
  • Save timothycarambat/093fa6b10af0eda946978e63b3dca19a to your computer and use it in GitHub Desktop.
Save timothycarambat/093fa6b10af0eda946978e63b3dca19a to your computer and use it in GitHub Desktop.
Sample AnythingLLM Discord Bot
import discord
import requests
import json
# Initialize the Discord client with message content intent
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
# AnythingLLM API configuration
ANYTHING_LLM_API_URL = "http://localhost:3001/api/v1/workspace/hello/chat"
ANYTHING_LLM_API_KEY = "your_api_key_here" # replace with your actual API key
@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
if message.content.startswith('$anythingllm'):
# Extract the query part after '$anythingllm'
user_query = message.content[len('$anythingllm '):]
# Prepare the data to be sent to AnythingLLM API
payload = {
"message": user_query
}
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {ANYTHING_LLM_API_KEY}"
}
# Send the message to AnythingLLM workspace
response = requests.post(ANYTHING_LLM_API_URL, headers=headers, data=json.dumps(payload))
if response.status_code == 200:
# Parse the response
result = response.json()
response_text = result.get("textResponse", "No response")
sources = result.get("sources", [])
# Format the response to send back to Discord
formatted_sources = "\n".join([f"**{source['title']}**: {source['chunk']}" for source in sources])
discord_response = f"**Response:** {response_text}\n\n**Sources:**\n{formatted_sources}"
# Send the formatted response to the Discord channel
await message.channel.send(discord_response)
else:
await message.channel.send(f"Failed to get a response from AnythingLLM. Status Code: {response.status_code}")
client.run('your_discord_token_here')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment