Skip to content

Instantly share code, notes, and snippets.

@brycepg
Created November 28, 2023 23:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brycepg/cd414ad9091e99f4a1ff4c834d3d9b3b to your computer and use it in GitHub Desktop.
Save brycepg/cd414ad9091e99f4a1ff4c834d3d9b3b to your computer and use it in GitHub Desktop.
Example ChatGPT Discord Bot
import dotenv from "dotenv";
import { Client, GatewayIntentBits, Partials } from "discord.js";
import OpenAI from 'openai';
dotenv.config();
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.DirectMessages,
],
partials: [
Partials.Channel,
Partials.MESSAGE
],
});
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
client.on('messageCreate', async function (message) {
// console.log(message);
if (message.content && message.content.trim() == "/ping") {
return message.reply("pong");
}
if (message.author.bot) return;
if (message.guild && message.channel.name !== "zombie-cat") return;
try {
const response = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [
{"role": "system", "content": "Act as a sage oracle zombie cat who can speak like a human and responds succinctly. Try to roleplay as much as possible using emotes when appropriate"},
{"role": "user", "content": message.content}
],
max_tokens: 200,
});
console.log(response);
const content = response.choices[0].message;
return message.reply(content);
} catch (err) {
if (err instanceof OpenAI.APIError) {
console.error(err.status); // e.g. 401
console.error(err.message); // e.g. The authentication token you passed was invalid...
console.error(err.code); // e.g. 'invalid_api_key'
console.error(err.type); // e.g. 'invalid_request_err'
} else {
console.log(err);
}
return message.reply(
"As an AI zombie cat, I errored out: " + err.message
);
}
});
client.login(process.env.BOT_TOKEN);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment