Skip to content

Instantly share code, notes, and snippets.

@imptype
Created March 31, 2023 16:30
Show Gist options
  • Save imptype/d8fe692acd9d4d632c5c6698ab6f12e9 to your computer and use it in GitHub Desktop.
Save imptype/d8fe692acd9d4d632c5c6698ab6f12e9 to your computer and use it in GitHub Desktop.
ChatGPT Discord Bot
import os
import openai
import discord
openai.api_key = os.getenv('OPENAI_API_KEY')
client = discord.Client(intents = discord.Intents(messages = True, message_content = True))
client.processing = 0
@client.event
async def on_ready():
print('We have logged in as {}'.format(client.user))
@client.event
async def on_message(message):
if message.author.bot: # ignore self and other bots
return
if message.content.startswith('c!ping') and message.author.id == 364487161250316289: # bot owner ping command
return await message.channel.send('Pong!')
if message.channel.id == 1091364771779067924: # prompt channel
async with message.channel.typing():
if len(message.content) > 256: # anti abuse
return await message.reply('Sorry, your prompt was too long.')
if (await openai.Moderation.acreate(message.content)).results[0].flagged: # anti abuse 2
return await message.reply('Sorry, your prompt was flagged.')
if client.processing > 5: # anti spam
return await message.reply('Sorry, I\'m busy replying to other prompts right now.')
client.processing += 1
try:
completion = await openai.ChatCompletion.acreate(
model = 'gpt-3.5-turbo',
messages = [{'role': 'user', 'content': message.content}]
)
return await message.reply(completion.choices[0].message.content)
except Exception as error:
print(error)
return await message.reply('Sorry, an error has occured.')
finally:
client.processing -= 1
client.run(os.getenv('DISCORD_BOT_TOKEN'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment