Дан данный код, который принимает сообщение -> заносит в таблицу для openAI -> в таблицу заносит ответ -> А далее должен быть написан код который возьмет это сообщение и отправит его в дискорд по channel_id
Естественно я пробовал написать, но каждый раз выпадает ошибка.
import random, asyncio, time, openai, discord, pymysql, threading
from discord.ext import commands
openai.api_key = ""
token = ""
intents = discord.Intents.all()
client = discord.Client(intents=intents)
@client.event
async def on_message(message):
print(message.channel.id)
print(client.get_channel(message.channel.id))
con = pymysql.connect(host='localhost', user='Admin', password='Admin', database='open_ai', port=3306)
cur = con.cursor()
try:
if message.author == client.user:
return
if '!бот' == message.content.split()[0]:
if "" == message.content.split()[1]:
return
#Проверка на юзера в базе данных
cur.execute(f"SELECT User_id FROM open_ai.user WHERE User_id = {message.author.id}")
user_id = cur.fetchone()
if user_id == None:
cur.execute(f"INSERT INTO open_ai.user (User_id) VALUES ({message.author.id})")
con.commit()
#поиск переписки с ботом
cur.execute(f"SHOW TABLES LIKE '{str(message.author.id)}'")
table = cur.fetchone()
if table == None:
sql = f"""CREATE TABLE IF NOT EXISTS open_ai.{str(message.author.id)} (Id INT NOT NULL AUTO_INCREMENT, Channel_id TEXT NOT NULL , Text TEXT NOT NULL , USER INT NOT NULL , Send INT NOT NULL DEFAULT 0 , PRIMARY KEY (Id)) ENGINE = InnoDB;"""
cur.execute(sql)
con.commit()
if cur.execute(f"SELECT Id FROM user WHERE AFK < CURRENT_TIMESTAMP AND User_id = {message.author.id}"):
response = ' '.join(message.content.split()[1:])
sql, params = f"""INSERT INTO open_ai.{str(message.author.id)} (Channel_id, Text, User, Send) VALUES ({'%s'}, {'%s'}, {'%s'}, {'%s'})""", (message.channel.id, response, "1", "1")
cur.execute(sql, params)
con.commit()
sql = f"""UPDATE user SET AFK = addtime(CURRENT_TIME, '00:00:30') WHERE User_id = {message.author.id}"""
cur.execute(sql)
con.commit()
await message.channel.send("Запрос был отправлен на обработку в ChatGPT")
cur.execute(f"UPDATE user SET Response = 0 WHERE User_id = {message.author.id}")
con.commit()
con.close()
else:
await message.channel.send("Перед следующим запросом подождите 30 секунд")
con.close()
except IndexError:
return
def OpenAI():
messages = []
openai.api_key = ""
con = pymysql.connect(host='localhost', user='Admin', password='Admin', database='open_ai', port=3306)
cur = con.cursor()
if cur.execute(f"SELECT User_id, Channel_id FROM open_ai.user WHERE Response = 0 LIMIT 1"):
id, channel_id = cur.fetchone()
print(id)
cur.execute(f"UPDATE user SET Response = 1 WHERE User_id = {str(id)}")
con.commit()
cur.execute(f"SELECT Id, Channel_id, Text, USER FROM open_ai.{str(id)}")
text = cur.fetchall()
messages = []
print(text)
for Id, Channel_id, text, user in text:
print(Id, Channel_id, text, user)
if user == 1:
messages.append({"role": "user", "content": text})
if user == 3:
messages.append({"role": "assistant", "content": text})
print(messages)
completion = openai.ChatCompletion.create(model="gpt-3.5-turbo",messages=messages)
chat_response = completion.choices[0].message.content
cur.execute(f"INSERT INTO open_ai.{str(id)} (Channel_id, Text, USER, Send) VALUES (%s, %s, %s, %s)", (str(channel_id), str(chat_response), "3", "0"))
con.commit()
con.close()
while True:
con = pymysql.connect(host='localhost', user='Admin', password='Admin', database='open_ai', port=3306)
cur = con.cursor()
cur.execute("SHOW TABLES FROM open_ai;")
tables = cur.fetchall()
print("f")
for i in tables:
if i[0] == "user":
continue
else:
threading.Thread(target=OpenAI, args=()).start()
time.sleep(1)
con.close()
client.run(token)