AskRobots-Discord is a scalable, plugin-oriented bot for Discord, offering dynamic interactions including AI-powered text conversations with GPT-3.5-Turbo and GPT-4 integration.
app.py · 3.8 KB · 110 lines
| 1 | import openai |
| 2 | import discord |
| 3 | import pprint |
| 4 | import os |
| 5 | import aiohttp |
| 6 | from transformers import GPT2Tokenizer |
| 7 | |
| 8 | tokenizer = GPT2Tokenizer.from_pretrained("gpt2") |
| 9 | # Set up OpenAI API credentials |
| 10 | openai.api_key = os.environ.get("OPENAI_KEY") |
| 11 | token = os.environ.get("DISCORD_TOKEN") |
| 12 | engine = os.environ.get("OPENAI_ENGINE", "text-davinci-002") |
| 13 | |
| 14 | intents = discord.Intents.default() |
| 15 | pp = pprint.PrettyPrinter(indent=4) |
| 16 | bot = discord.Client(intents=intents) |
| 17 | |
| 18 | # Dictionary to store chat history by channel |
| 19 | chat_histories = {} |
| 20 | |
| 21 | |
| 22 | # Asynchronous function to call the OpenAI API |
| 23 | async def call_openai_api(channel_id, message, api_model): |
| 24 | # Get the chat history for the channel or set up a new history |
| 25 | history = chat_histories.get(channel_id, [{"role": "system", "content": "You are a helpful assistant."}]) |
| 26 | |
| 27 | # Add the user's message to the history |
| 28 | history.append({"role": "user", "content": message.content}) |
| 29 | |
| 30 | # Calculate the token count of the chat history and remove messages if the count is over the specified limit |
| 31 | token_limit = 8000 if api_model == "gpt-4" else 4000 |
| 32 | token_count = sum(len(tokenizer(text["content"]).input_ids) for text in history) |
| 33 | while token_count > token_limit: |
| 34 | removed_message = history.pop(0) |
| 35 | token_count -= len(tokenizer(removed_message["content"]).input_ids) |
| 36 | |
| 37 | headers = { |
| 38 | "Authorization": f"Bearer {openai.api_key}", |
| 39 | "Content-Type": "application/json", |
| 40 | } |
| 41 | data = { |
| 42 | "model": api_model, |
| 43 | "messages": history, |
| 44 | } |
| 45 | |
| 46 | async with aiohttp.ClientSession() as session: |
| 47 | async with session.post("https://api.openai.com/v1/chat/completions", json=data, headers=headers) as response: |
| 48 | result = await response.json() |
| 49 | print("Result:", result) # Add the print statement here |
| 50 | if "error" in result: |
| 51 | print("Error from OpenAI API:", result["error"]) |
| 52 | assistant_message = "An error occurred while processing your request. Please try again." |
| 53 | else: |
| 54 | assistant_message = result["choices"][0]["message"]["content"] |
| 55 | history.append({"role": "assistant", "content": assistant_message}) |
| 56 | chat_histories[channel_id] = history |
| 57 | return assistant_message |
| 58 | |
| 59 | |
| 60 | @bot.event |
| 61 | async def on_ready(): |
| 62 | """ |
| 63 | Print a message to the console when the bot is ready. |
| 64 | :return: |
| 65 | """ |
| 66 | print(f'We have logged in as {bot.user}') |
| 67 | |
| 68 | |
| 69 | @bot.event |
| 70 | async def on_message(message): |
| 71 | if message.author == bot.user: |
| 72 | return |
| 73 | |
| 74 | if message.content.startswith('$ping'): |
| 75 | await message.channel.send('Pong!') |
| 76 | |
| 77 | if message.content.startswith('$chat4'): |
| 78 | prompt = message.content[6:] |
| 79 | # Call OpenAI text completion API using GPT-4 |
| 80 | try: |
| 81 | response = await call_openai_api(message.channel.id, message, "gpt-4") |
| 82 | except openai.error.RateLimitError as error: |
| 83 | response = "Open API rate limit exceeded." |
| 84 | return |
| 85 | chunk_size = 2000 |
| 86 | for i in range(0, len(response), chunk_size): |
| 87 | await message.channel.send(response[i:i+chunk_size]) |
| 88 | pp.pprint(response) |
| 89 | |
| 90 | elif message.content.startswith('$chat'): |
| 91 | prompt = message.content[5:] |
| 92 | # Call OpenAI text completion API using GPT-3.5 Turbo |
| 93 | try: |
| 94 | response = await call_openai_api(message.channel.id, message, "gpt-3.5-turbo") |
| 95 | except openai.error.RateLimitError as error: |
| 96 | response = "Open API rate limit exceeded." |
| 97 | return |
| 98 | chunk_size = 2000 |
| 99 | for i in range(0, len(response), chunk_size): |
| 100 | await message.channel.send(response[i:i+chunk_size]) |
| 101 | pp.pprint(response) |
| 102 | |
| 103 | if message.author == bot.user: |
| 104 | return |
| 105 | |
| 106 | if message.content.startswith('$help'): |
| 107 | await message.channel.send('commands:\n$chat\n$chat4\n$help') |
| 108 | |
| 109 | |
| 110 | bot.run(token, reconnect=True) |