Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import openai
- import nextcord
- from nextcord.ext import commands
- from dotenv import load_dotenv
- load_dotenv() # reads our secret of our .env file and makes them accessible using os.getenv()
- intents = nextcord.Intents.default()
- intents.message_content = True
- bot = commands.Bot(command_prefix="$", description="bananas", intents=intents)
- @bot.event
- async def on_ready():
- print(f"Logged in as {bot.user} (ID: {bot.user.id})")
- # add a new command
- @bot.slash_command(description='Chat with AI')
- async def chat(interaction: nextcord.Interaction,
- # this makes it so people can enter their prompt when using the slash command
- prompt: str = SlashOption(description='Chatbot Prompt', required=True)
- ):
- partial_message = await interaction.send('') # just writes an empty message
- message = await partial_message.fetch() # prepares this message to be used
- # set the configuration for the AI access
- openai.api_base = 'https://api.nova-oss.com/v1'
- openai.api_key = os.getenv('NOVA_KEY')
- async with interaction.channel.typing(): # so Discord displays the "[Bot name] is typing..." at the bottom
- try:
- completion = openai.ChatCompletion.create(
- model='gpt-3.5-turbo',
- messages=[{'role': 'user', 'content': prompt}],
- stream=True # this is really important to get the streaming (realtime updates) to work
- )
- # from now on, we will get new completions in the background which are saved in the completion variable
- except Exception as exc:
- await interaction.send(':x: Error - could not generate an AI response. Look in the console.')
- raise exc # so the error shows up in the console
- # we want to save the text that was generated using the AI
- text = ''
- for event in completion: # loop through word generation in real time
- try:
- new_text = event['choices'][0]['delta']['content'] # add the newly generated word to the variable
- except KeyError: # end or an error occured
- break # stop the loop
- text += new_text # ad the new word to the complete text variable
- if text: # we get errors if the new text we're editing the message to is empty
- await message.edit(content=text) # finally edit the message to include the entire new text
- # put any code in here if you want anything to happen when the AI is done with the completion
- # starts the Discord bot
- bot.run(os.getenv('DISCORD_TOKEN'))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement