Skip to content

Instantly share code, notes, and snippets.

@alessandroraffa
Created January 29, 2023 15:11
Show Gist options
  • Save alessandroraffa/fd46c941e1d995e4499ef0afaf18c3a3 to your computer and use it in GitHub Desktop.
Save alessandroraffa/fd46c941e1d995e4499ef0afaf18c3a3 to your computer and use it in GitHub Desktop.
A GPT-3 Discord chat bot in TypeScript with OpenAI
import {
Client,
Events,
GatewayIntentBits,
Message,
PartialMessage,
Partials,
} from "discord.js";
import { Configuration, OpenAIApi } from "openai";
const openAIConfiguration = new Configuration({
apiKey: "YOUR_OPENAI_API_KEY",
});
const openai = new OpenAIApi(openAIConfiguration);
const client = new Client({
intents: [
GatewayIntentBits.DirectMessageReactions,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.DirectMessageTyping,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMessageTyping,
GatewayIntentBits.Guilds,
GatewayIntentBits.MessageContent,
],
partials: [Partials.Channel],
});
client.once(Events.ClientReady, async (c) => {
console.log(`Logged in as ${c.user.tag}`);
});
const handleMessage = async (message: Message | PartialMessage) => {
console.log("handleMessage", {
channelId: message.channelId,
guildId: message.guildId,
id: message.id,
content: message.content,
author: message?.author?.username,
authorId: message?.author?.id,
});
const author = message?.author;
if (author) {
const { id: authorId } = author;
if (authorId !== "YOUR_DISCORD_BOT_ID") {
const prompt = message.content;
const completion = await openai.createCompletion({
prompt,
model: "text-davinci-002",
max_tokens: 2048,
});
const responseText = completion.data?.choices?.[0]?.text || "";
await message.channel.send(responseText);
}
}
};
client.on("messageCreate", async (message) => {
await handleMessage(message);
});
client
.login("YOUR_DISCORD_BOT_TOKEN")
.catch((error) => console.error("Discord.Client.Login.Error", error));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment