This commit is contained in:
Siwoo Jeon 2023-11-30 21:27:03 +09:00
parent c14250aa3a
commit 2aeaad3add
Signed by: migan
GPG key ID: C4151385FFD2082A
8 changed files with 69 additions and 142 deletions

View file

@ -1,6 +1,6 @@
{ {
"name": "muffin-ai-arujak", "name": "muffin-ai-arujak",
"version": "2.0.0-79-oreo", "version": "2.0.0-80-oreo",
"main": "dist/index.js", "main": "dist/index.js",
"private": true, "private": true,
"dependencies": { "dependencies": {

View file

@ -33,16 +33,6 @@ export default class MuffinAI extends Client {
if (NODE_ENV === 'development') this.on('debug', console.info) if (NODE_ENV === 'development') this.on('debug', console.info)
this.chatBot.train(this) this.chatBot.train(this)
setInterval(async () => {
const db = await this.chatBot.db.getConnection()
await db.beginTransaction()
await db.ping()
await db.commit()
db.release()
}, 600000)
readdirSync(join(__dirname, 'Commands')).forEach(file => { readdirSync(join(__dirname, 'Commands')).forEach(file => {
const a = require(join(__dirname, 'Commands', file)) const a = require(join(__dirname, 'Commands', file))
const b: Command = new a.default() const b: Command = new a.default()

View file

@ -1,5 +1,5 @@
import { Message } from 'discord.js' import { Message } from 'discord.js'
import { Command, LearnData } from '../modules' import { Command } from '../modules'
export default class extends Command { export default class extends Command {
public constructor() { public constructor() {
@ -9,32 +9,21 @@ export default class extends Command {
if (!args[0]) { if (!args[0]) {
return await msg.channel.send('```멒힌아 삭제 (지울 단어)```') return await msg.channel.send('```멒힌아 삭제 (지울 단어)```')
} }
const db = await msg.client.chatBot.db.getConnection()
const command = args[0] const command = args[0]
const [rows] = await db.execute<LearnData[]>( const db = msg.client.chatBot.db
'SELECT * FROM learn WHERE command = ?;', const data = await db.learn.findOne(command)
[command],
)
if (!rows[0]) { if (!data[0]) {
return await msg.channel.send('해당하는 걸 찾ㅈ을 수 없어요.') return await msg.channel.send('해당하는 걸 찾ㅈ을 수 없어요.')
} }
if (rows[0].user_id !== msg.author.id) { if (data[0].user_id !== msg.author.id) {
return await msg.channel.send( return await msg.channel.send(
'당신ㄴ은 해당 지식을 안가르ㄹ쳐 주셨ㅅ는데요?', '당신ㄴ은 해당 지식을 안가르ㄹ쳐 주셨ㅅ는데요?',
) )
} }
try { await db.learn.delete(command)
await db.beginTransaction()
await db.execute('DELETE FROM learn WHERE command = ?;', [command])
await msg.channel.send('해당 단어를 삭ㄱ제했어요.') await msg.channel.send('해당 단어를 삭ㄱ제했어요.')
await db.commit()
} catch (err) {
console.error(err)
} finally {
db.release()
}
} }
} }

View file

@ -1,4 +1,4 @@
import { Command, LearnData } from '../modules' import { Command } from '../modules'
import { Message } from 'discord.js' import { Message } from 'discord.js'
import config from '../../config.json' import config from '../../config.json'
@ -27,17 +27,14 @@ export default class extends Command {
'삭제', '삭제',
] ]
const disallowed = ['@everyone', '@here', `<@${config.bot.owner_ID}>`] const disallowed = ['@everyone', '@here', `<@${config.bot.owner_ID}>`]
const db = await msg.client.chatBot.db.getConnection() const db = msg.client.chatBot.db
const [learn] = await db.execute<LearnData[]>( const data = await db.learn.findOne(command)
'SELECT * FROM learn WHERE command = ?;',
[command],
)
if (learn[0]) { if (data[0]) {
if (msg.author.id !== learn[0].user_id) { if (msg.author.id !== data[0].user_id) {
return msg.channel.send( return msg.channel.send(
`해ㄷ당 단어는 이미 ${ `해ㄷ당 단어는 이미 ${
(await msg.client.users.fetch(learn[0].user_id)).username (await msg.client.users.fetch(data[0].user_id)).username
} .`, } .`,
) )
} }
@ -55,30 +52,19 @@ export default class extends Command {
} }
} }
try { if (data[0] && msg.author.id === data[0].user_id) {
await db.beginTransaction() await db.learn.update({
if (learn[0] && msg.author.id === learn[0].user_id) {
await db.execute('UPDATE learn SET result = ? WHERE command = ?;', [
result,
command, command,
]) result,
})
await msg.channel.send(`${command}을/를 다시 배ㅂ웠어요.`) await msg.channel.send(`${command}을/를 다시 배ㅂ웠어요.`)
} else { } else {
await db.execute( await db.learn.insert({
'INSERT INTO learn (command, result, user_id) VALUES (?, ?, ?);', command,
[command, result, msg.author.id], result,
) user_id: msg.author.id,
})
await msg.channel.send(`${command}을/를 배웠ㅇ어요.`) await msg.channel.send(`${command}을/를 배웠ㅇ어요.`)
} }
await db.commit()
} catch (err) {
console.error(err)
await db.rollback()
await msg.channel.send('배우는데 오류ㄹ가 생겨서 배우지 못했어ㅇ요.')
} finally {
db.release()
}
} }
} }

View file

@ -1,22 +1,22 @@
import { Command, type ResponseData, type NSFWData } from '../modules' import { Command, type ResponseData } from '../modules'
import { type Message } from 'discord.js' import { type Message } from 'discord.js'
export default class extends Command { export default class extends Command {
public constructor() { public constructor() {
super('학습데이터량') super('학습데이터량')
} }
public async execute(msg: Message, args: string[]) { public async execute(msg: Message<true>, args: string[]) {
const db = await msg.client.chatBot.db.getConnection() const db = msg.client.chatBot.db
const [rows] = await db.execute<ResponseData[]>('SELECT * FROM statement;') const data = await db.statement.all()
const [nsfw] = await db.execute<NSFWData[]>('SELECT * FROM nsfw_content;') const nsfwData = await db.nsfwContent.all()
const learnData = await db.learn.all()
const muffin: ResponseData[] = [] const muffin: ResponseData[] = []
rows.forEach(row => { data.forEach(row => {
if (row.persona === 'muffin') muffin.push(row) if (row.persona === 'muffin') muffin.push(row)
else return else return
}) })
msg.channel.send( msg.channel.send(
`머핀 데이터: ${muffin.length}\nnsfw 데이터: ${nsfw.length}`, `머핀 데이터: ${muffin.length}\nnsfw 데이터: ${nsfwData.length}\n지금까지 배운 단어: ${learnData.length}`,
) )
db.release()
} }
} }

View file

@ -1,5 +1,5 @@
import { Message, codeBlock } from 'discord.js' import { Message, codeBlock } from 'discord.js'
import { Command, LearnData } from '../modules' import { Command } from '../modules'
export default class extends Command { export default class extends Command {
public constructor() { public constructor() {
@ -7,21 +7,18 @@ export default class extends Command {
} }
public async execute(msg: Message<boolean>, args: string[]) { public async execute(msg: Message<boolean>, args: string[]) {
const db = await msg.client.chatBot.db.getConnection() const db = msg.client.chatBot.db
const [rows] = await db.execute<LearnData[]>( const data = await db.learn.findOneAnotherKey('user_id', msg.author.id)
'SELECT * FROM learn WHERE user_id = ?;',
[msg.author.id],
)
const list: string[] = [] const list: string[] = []
if (!rows) { if (!data[0]) {
return await msg.channel.send( return await msg.channel.send(
'당신ㄴ은 단어를 가르쳐준 기억이 없ㅅ는데요.', '당신ㄴ은 단어를 가르쳐준 기억이 없ㅅ는데요.',
) )
} }
for (const data of rows) { for (const listData of data) {
list.push(data.command) list.push(listData.command)
} }
await msg.channel.send({ await msg.channel.send({
@ -33,7 +30,7 @@ export default class extends Command {
list.map(item => `- ${item}`).join('\n'), list.map(item => `- ${item}`).join('\n'),
), ),
color: 0x0000ff, color: 0x0000ff,
timestamp: new Date().toISOString() timestamp: new Date().toISOString(),
}, },
], ],
}) })

View file

@ -1,26 +1,21 @@
import type { Client, Message } from 'discord.js' import type { Client, Message } from 'discord.js'
import { database, LearnData, ResponseData } from './database' import { MaaDatabase } from './database'
import { TextChannel } from 'discord.js' import { TextChannel } from 'discord.js'
import config from '../../config.json' import config from '../../config.json'
import { NODE_ENV } from '.' import { NODE_ENV } from '.'
export default class ChatBot { export default class ChatBot {
get db() { get db() {
return this.#db return new MaaDatabase()
} }
#db = database
public async getResponse(msg: Message): Promise<string> { public async getResponse(msg: Message): Promise<string> {
const db = await this.db.getConnection() const data = await this.db.statement.all()
const [rows] = await db.execute<ResponseData[]>('SELECT * FROM statement;')
const args = msg.content const args = msg.content
.slice('머핀아 '.length) .slice('머핀아 '.length)
.trim() .trim()
.split(/ +/g) .split(/ +/g)
.join(' ') .join(' ')
const [learn] = await db.execute<LearnData[]>( const learnData = await this.db.learn.findOne(args)
'SELECT * from learn WHERE command = ?;',
[args],
)
const a = Math.round(Math.random() * (2 - 1) + 1) const a = Math.round(Math.random() * (2 - 1) + 1)
if (NODE_ENV === 'development') { if (NODE_ENV === 'development') {
@ -29,11 +24,10 @@ export default class ChatBot {
} }
if (a === 1) { if (a === 1) {
if (learn[0]) { if (learnData[0]) {
if (args.startsWith(learn[0].command)) { if (args.startsWith(learnData[0].command)) {
db.release() return `${learnData[0].result}\n\`${
return `${learn[0].result}\n\`${ (await msg.client.users.fetch(learnData[0].user_id)).username
(await msg.client.users.fetch(learn[0].user_id)).username
} .\`` } .\``
} }
} }
@ -41,66 +35,44 @@ export default class ChatBot {
let response: string let response: string
if ((msg.channel as TextChannel).nsfw) { if ((msg.channel as TextChannel).nsfw) {
const [rows1] = await db.execute<ResponseData[]>( const NSFWData = await this.db.nsfwContent.all()
'SELECT * FROM nsfw_content;', const dataList = [...data, ...NSFWData]
) response = dataList[Math.floor(Math.random() * dataList.length)].text
const rows2 = [...rows, ...rows1]
response = rows2[Math.floor(Math.random() * rows2.length)].text
} else { } else {
response = rows[Math.floor(Math.random() * rows.length)].text response = data[Math.floor(Math.random() * data.length)].text
} }
if (!response) response = '살ㄹ려주세요' if (!response) response = '살ㄹ려주세요'
db.release()
return response return response
} }
public async train(client: Client): Promise<ChatBot> { public async train(client: Client): Promise<ChatBot> {
const db = await this.db.getConnection()
client.on('messageCreate', async msg => { client.on('messageCreate', async msg => {
if (msg.author.bot) return if (msg.author.bot) return
if (msg.author.id === config.train.user_ID) { if (msg.author.id === config.train.user_ID) {
const response = await this.getResponse(msg) const response = await this.getResponse(msg)
const [rows] = await db.execute<ResponseData[]>( const data = await this.db.statement.all()
'SELECT * FROM statement;', await this.db.statement.insert({
) id: ++data[data.length - 1].id,
try { text: msg.content,
await db.beginTransaction() persona: 'muffin',
await db.execute( in_response_to: response,
'INSERT INTO statement (id, text, persona, in_response_to) VALUES (?, ?, ?, ?);', })
[++rows[rows.length - 1].id, msg.content, 'muffin', response],
)
await db.commit()
} catch (err) {
console.log(err)
await db.rollback()
}
} else { } else {
if (!(msg.channel as TextChannel).nsfw) return if (!(msg.channel as TextChannel).nsfw) return
if (!msg.content.startsWith('머핀아 ')) return if (!msg.content.startsWith('머핀아 ')) return
const user = `user:${msg.author.username.slice(0, 50).toLowerCase()}` const user = `user:${msg.author.username.slice(0, 50).toLowerCase()}`
const text = msg.content.replace('머핀아 ', '') const text = msg.content.replace('머핀아 ', '')
const [rows] = await db.execute<ResponseData[]>( const data = await this.db.nsfwContent.all()
'SELECT * FROM nsfw_content;', await this.db.nsfwContent.insert({
) id: ++data[data.length - 1].id,
try { text,
await db.beginTransaction() persona: user,
await db.execute( })
`INSERT INTO nsfw_content (id, text, persona) VALUES (?, ?, ?);`,
[++rows[rows.length - 1].id, text, user],
)
await db.commit()
} catch (err) {
console.log(err)
await db.rollback()
}
} }
}) })
db.release()
setInterval(async () => { setInterval(async () => {
const db = await database.getConnection() await this.db.ping()
await db.ping()
db.release()
}, 60000) }, 60000)
return this return this
} }

View file

@ -1,18 +1,11 @@
import ChatBot from './ChatBot' import ChatBot from './ChatBot'
import Command from './Command' import Command from './Command'
import { import { ResponseData, NSFWData, LearnData, MaaDatabase } from './database'
database,
ResponseData,
NSFWData,
LearnData,
MaaDatabase,
} from './database'
import noPerm from './noPerm' import noPerm from './noPerm'
import { NODE_ENV } from './env' import { NODE_ENV } from './env'
export { export {
ChatBot, ChatBot,
Command, Command,
database,
noPerm, noPerm,
ResponseData, ResponseData,
NODE_ENV, NODE_ENV,