Advertisement
OrFeAsGr

Untitled

Sep 14th, 2023 (edited)
1,289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.56 KB | None | 0 0
  1. import os
  2. import openai
  3. import nextcord
  4. from nextcord.ext import commands
  5. from dotenv import load_dotenv
  6.  
  7. load_dotenv() # reads our secret of our .env file and makes them accessible using os.getenv()
  8.  
  9. intents = nextcord.Intents.default()
  10. intents.message_content = True
  11.  
  12. bot = commands.Bot(command_prefix="$", description="bananas", intents=intents)
  13.  
  14. @bot.event
  15. async def on_ready():
  16.     print(f"Logged in as {bot.user} (ID: {bot.user.id})")
  17.  
  18. # add a new command
  19. @bot.slash_command(description='Chat with AI')
  20. async def chat(interaction: nextcord.Interaction,
  21.     # this makes it so people can enter their prompt when using the slash command
  22.     prompt: str = SlashOption(description='Chatbot Prompt', required=True)
  23. ):
  24.     partial_message = await interaction.send('‎') # just writes an empty message
  25.     message = await partial_message.fetch() # prepares this message to be used
  26.  
  27.     # set the configuration for the AI access
  28.     openai.api_base = 'https://api.nova-oss.com/v1'
  29.     openai.api_key = os.getenv('NOVA_KEY')
  30.  
  31.     async with interaction.channel.typing(): # so Discord displays the "[Bot name] is typing..." at the bottom
  32.         try:
  33.             completion = openai.ChatCompletion.create(
  34.                 model='gpt-3.5-turbo',
  35.                 messages=[{'role': 'user', 'content': prompt}],
  36.                 stream=True # this is really important to get the streaming (realtime updates) to work
  37.             )
  38.             # from now on, we will get new completions in the background which are saved in the completion variable
  39.         except Exception as exc:
  40.             await interaction.send(':x: Error - could not generate an AI response. Look in the console.')
  41.             raise exc # so the error shows up in the console
  42.  
  43.         # we want to save the text that was generated using the AI
  44.         text = ''
  45.  
  46.         for event in completion: # loop through word generation in real time
  47.             try:
  48.                 new_text = event['choices'][0]['delta']['content'] # add the newly generated word to the variable
  49.             except KeyError: # end or an error occured
  50.                 break # stop the loop
  51.  
  52.             text += new_text # ad the new word to the complete text variable
  53.  
  54.             if text: # we get errors if the new text we're editing the message to is empty
  55.                 await message.edit(content=text) # finally edit the message to include the entire new text
  56.  
  57.     # put any code in here if you want anything to happen when the AI is done with the completion
  58.  
  59. # starts the Discord bot
  60. bot.run(os.getenv('DISCORD_TOKEN'))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement