askrobots / discord Public

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.

0 downloads

discord/app.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/discord.git
HTTPS
https://gitstable.com/git/askrobots/discord.git
SSH
ssh://git@gitstable.com:2222/askrobots/discord.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Example .env file. 48c6d0c 3 years, 5 months ago History
app.py · 3.8 KB · 110 lines
1import openai
2import discord
3import pprint
4import os
5import aiohttp
6from transformers import GPT2Tokenizer
7
8tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
9# Set up OpenAI API credentials
10openai.api_key = os.environ.get("OPENAI_KEY")
11token = os.environ.get("DISCORD_TOKEN")
12engine = os.environ.get("OPENAI_ENGINE", "text-davinci-002")
13
14intents = discord.Intents.default()
15pp = pprint.PrettyPrinter(indent=4)
16bot = discord.Client(intents=intents)
17
18# Dictionary to store chat history by channel
19chat_histories = {}
20
21
22# Asynchronous function to call the OpenAI API
23async 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
61async 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
70async 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
110bot.run(token, reconnect=True)