fix line endings
This commit is contained in:
parent
da90dee110
commit
35c3e23fb1
|
@ -0,0 +1,2 @@
|
||||||
|
# Set the default behavior, in case people don't have core.autocrlf set.
|
||||||
|
* text eol=lf
|
|
@ -1,3 +1,5 @@
|
||||||
/node_modules
|
/node_modules
|
||||||
.env
|
.env
|
||||||
|
/logs
|
||||||
|
/dist
|
||||||
/db/*.db
|
/db/*.db
|
|
@ -1,10 +1,12 @@
|
||||||
# Codey Bot
|
# Codey Bot
|
||||||
|
|
||||||
## Required environment variables
|
## Required environment variables
|
||||||
|
|
||||||
- `BOT_TOKEN`: the token found in the bot user account.
|
- `BOT_TOKEN`: the token found in the bot user account.
|
||||||
- `NOTIF_CHANNEL_ID`: the ID of the channel the bot will send system notifications to.
|
- `NOTIF_CHANNEL_ID`: the ID of the channel the bot will send system notifications to.
|
||||||
|
|
||||||
## Running the bot locally
|
## Running the bot locally
|
||||||
|
|
||||||
1. Run `yarn` to install dependencies.
|
1. Run `yarn` to install dependencies.
|
||||||
1. Add the required environment variables in a `.env` file in the root directory.
|
1. Add the required environment variables in a `.env` file in the root directory.
|
||||||
1. Run `yarn dev` to start the bot locally.
|
1. Run `yarn dev` to start the bot locally.
|
||||||
|
|
|
@ -1,8 +1,68 @@
|
||||||
import sqlite3 = require('sqlite3')
|
import sqlite3 = require('sqlite3')
|
||||||
export const db = new sqlite3.Database('./db/bot.db', (err) =>{
|
import { open, Database } from 'sqlite'
|
||||||
if(err){
|
import Discord from 'discord.js'
|
||||||
console.log(err.message)
|
|
||||||
|
let db : Database | null = null;
|
||||||
|
|
||||||
|
export async function openDb () {
|
||||||
|
if(db == null){
|
||||||
|
db = await open({
|
||||||
|
filename: './db/bot.db',
|
||||||
|
driver: sqlite3.Database
|
||||||
|
})
|
||||||
|
await db.run('CREATE TABLE IF NOT EXISTS saved_data (msg_id INTEGER PRIMARY KEY,data TEXT NOT NULL);')
|
||||||
}
|
}
|
||||||
});
|
return db;
|
||||||
db.run('CREATE TABLE IF NOT EXISTS saved_data (msg_id INTEGER PRIMARY KEY,data TEXT NOT NULL);')
|
}
|
||||||
|
|
||||||
|
export async function testDb(message: Discord.Message, command: string, args: string[]){
|
||||||
|
switch(command){
|
||||||
|
case 'save':
|
||||||
|
if (args.length < 1) {
|
||||||
|
await message.channel.send('no args');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await openDb().then((db) => {
|
||||||
|
db.run('INSERT INTO saved_data (msg_id,data)' + 'VALUES(?,?)', [message.id, args[0]]);
|
||||||
|
});
|
||||||
|
await message.channel.send('Saved ' + args[0] + ' with id ' + message.id);
|
||||||
|
break;
|
||||||
|
case 'dump':
|
||||||
|
await openDb().then(async (db) => {
|
||||||
|
let flag: boolean = true;
|
||||||
|
let outEmbed = new Discord.MessageEmbed()
|
||||||
|
.setColor('#0099ff')
|
||||||
|
.setTitle('Database Dump')
|
||||||
|
.setURL('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
|
||||||
|
const res = await db.all('SELECT * FROM saved_data');
|
||||||
|
for(const rows of res){
|
||||||
|
console.log(rows['msg_id'], rows['data']);
|
||||||
|
outEmbed = outEmbed.addField(rows['msg_id'], rows['data'], true);
|
||||||
|
console.log(outEmbed);
|
||||||
|
}
|
||||||
|
console.log(outEmbed);
|
||||||
|
if (flag) {
|
||||||
|
if (outEmbed.fields.length == 0) {
|
||||||
|
await message.channel.send('empty');
|
||||||
|
} else {
|
||||||
|
await message.channel.send(outEmbed);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
await message.channel.send('error');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case 'clear':
|
||||||
|
openDb()
|
||||||
|
.then((db) => {
|
||||||
|
return db.run('DELETE FROM saved_data');
|
||||||
|
})
|
||||||
|
.then(async () => {
|
||||||
|
await message.channel.send('cleared');
|
||||||
|
})
|
||||||
|
.catch();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
console.log('connected to db')
|
console.log('connected to db')
|
||||||
|
|
146
index.ts
146
index.ts
|
@ -1,98 +1,88 @@
|
||||||
import dotenv = require('dotenv')
|
import dotenv from 'dotenv';
|
||||||
dotenv.config()
|
dotenv.config();
|
||||||
|
|
||||||
import Discord = require('discord.js')
|
import Discord from 'discord.js';
|
||||||
import _ = require('lodash')
|
import _ from 'lodash';
|
||||||
import { db } from './components/db'
|
import { openDb, testDb } from './components/db';
|
||||||
|
import logger from './logger';
|
||||||
|
|
||||||
const NOTIF_CHANNEL_ID: string = process.env.NOTIF_CHANNEL_ID
|
const NOTIF_CHANNEL_ID: string = process.env.NOTIF_CHANNEL_ID || '.';
|
||||||
const BOT_TOKEN: string = process.env.BOT_TOKEN
|
const BOT_TOKEN: string = process.env.BOT_TOKEN || '.';
|
||||||
const BOT_PREFIX = "."
|
const BOT_PREFIX = '.';
|
||||||
|
const client = new Discord.Client();
|
||||||
|
|
||||||
const client = new Discord.Client()
|
const parseCommand = (message: Discord.Message): { command: string | null; args: string[] } => {
|
||||||
|
|
||||||
const parseCommand = message => {
|
|
||||||
// extract arguments by splitting by spaces and grouping strings in quotes
|
// extract arguments by splitting by spaces and grouping strings in quotes
|
||||||
// e.g. .ping 1 "2 3" => ['ping', '1', '2 3']
|
// e.g. .ping 1 "2 3" => ['ping', '1', '2 3']
|
||||||
let args = message.content.slice(BOT_PREFIX.length).match(/[^\s"']+|"([^"]*)"|'([^']*)'/g)
|
let args = message.content.slice(BOT_PREFIX.length).match(/[^\s"']+|"([^"]*)"|'([^']*)'/g);
|
||||||
args = _.map(args, arg => {
|
args = _.map(args, (arg) => {
|
||||||
if (arg[0].match(/'|"/g) && arg[arg.length-1].match(/'|"/g)) {
|
if (arg[0].match(/'|"/g) && arg[arg.length - 1].match(/'|"/g)) {
|
||||||
return arg.slice(1,arg.length-1)
|
return arg.slice(1, arg.length - 1);
|
||||||
}
|
}
|
||||||
return arg
|
return arg;
|
||||||
})
|
});
|
||||||
const firstArg = args.shift()
|
// obtain the first argument after the prefix
|
||||||
if (!firstArg) return
|
const firstArg = args.shift();
|
||||||
const command = firstArg.toLowerCase()
|
if (!firstArg) return { command: null, args: [] };
|
||||||
return { command, args }
|
const command = firstArg.toLowerCase();
|
||||||
}
|
return { command, args };
|
||||||
|
};
|
||||||
|
|
||||||
const handleCommand = async (message, command, args) => {
|
const handleCommand = async (message: Discord.Message, command: string, args: string[]) => {
|
||||||
switch(command) {
|
// log command and its author info
|
||||||
|
logger.info({
|
||||||
|
event: 'command',
|
||||||
|
messageId: message.id,
|
||||||
|
author: message.author.id,
|
||||||
|
authorName: message.author.username,
|
||||||
|
channel: message.channel.id,
|
||||||
|
command,
|
||||||
|
args
|
||||||
|
});
|
||||||
|
|
||||||
|
switch (command) {
|
||||||
case 'ping':
|
case 'ping':
|
||||||
await message.channel.send('pong')
|
await message.channel.send('pong');
|
||||||
break
|
|
||||||
|
|
||||||
//dev testing commands
|
|
||||||
case 'save':
|
|
||||||
if(args.length<1){
|
|
||||||
await message.channel.send('no args')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
db.run('INSERT INTO saved_data (msg_id,data)' +
|
|
||||||
'VALUES(?,?)', [message.id, args[0]], async (err) =>{
|
|
||||||
if(err){
|
|
||||||
await message.channel.send(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
await message.channel.send('saved "'+args[0]+'" with id '+message.id+'.')
|
|
||||||
})
|
|
||||||
break
|
|
||||||
case 'dump':
|
|
||||||
//TODO: make messages be embeds to test
|
|
||||||
db.each('SELECT * FROM saved_data', async (err, rows) =>{
|
|
||||||
if(err){
|
|
||||||
await message.channel.send(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
await message.channel.send(JSON.stringify(rows))
|
|
||||||
})
|
|
||||||
break;
|
break;
|
||||||
case 'clear':
|
|
||||||
db.run('DELETE FROM saved_data', async (err) =>{
|
|
||||||
if(err){
|
|
||||||
await message.channel.send(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
await message.channel.send("Cleared.")
|
|
||||||
|
|
||||||
})
|
//dev testing
|
||||||
|
if(process.env.NODE_ENV == "dev"){
|
||||||
|
testDb(message, command, args);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const handleMessage = async message => {
|
const handleMessage = async (message: Discord.Message) => {
|
||||||
// ignore messages without bot prefix and messages from other bots
|
// ignore messages without bot prefix and messages from other bots
|
||||||
if (!message.content.startsWith(BOT_PREFIX) || message.author.bot) return
|
if (!message.content.startsWith(BOT_PREFIX) || message.author.bot) return;
|
||||||
// obtain command and args from the command message
|
// obtain command and args from the command message
|
||||||
const { command, args } = parseCommand(message)
|
const { command, args } = parseCommand(message);
|
||||||
// TODO: log commands
|
if (!command) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await handleCommand(message, command, args)
|
await handleCommand(message, command, args);
|
||||||
} catch(e) {
|
} catch (e) {
|
||||||
// TODO: handle error
|
// log error
|
||||||
|
logger.error({
|
||||||
|
event: 'error',
|
||||||
|
messageId: message.id,
|
||||||
|
command: command,
|
||||||
|
args: args,
|
||||||
|
error: e
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const startBot = async () => {
|
const startBot = async () => {
|
||||||
client.once('ready', async () => {
|
client.once('ready', async () => {
|
||||||
const notif = await client.channels.fetch(NOTIF_CHANNEL_ID) as Discord.TextChannel
|
// log bot init event and send system notification
|
||||||
notif.send('Codey is up!')
|
logger.info({
|
||||||
})
|
event: 'init'
|
||||||
|
});
|
||||||
client.on('message', handleMessage)
|
const notif = (await client.channels.fetch(NOTIF_CHANNEL_ID)) as Discord.TextChannel;
|
||||||
|
notif.send('Codey is up!');
|
||||||
client.login(BOT_TOKEN)
|
});
|
||||||
}
|
client.on('message', handleMessage);
|
||||||
|
client.login(BOT_TOKEN);
|
||||||
startBot()
|
};
|
||||||
|
startBot();
|
||||||
|
|
|
@ -0,0 +1,40 @@
|
||||||
|
const winston = require('winston');
|
||||||
|
require('winston-daily-rotate-file');
|
||||||
|
|
||||||
|
const dailyRotateTransport = new winston.transports.DailyRotateFile({
|
||||||
|
filename: '%DATE%.log',
|
||||||
|
dirname: 'logs',
|
||||||
|
zippedArchive: true
|
||||||
|
});
|
||||||
|
|
||||||
|
const dailyRotateErrorTransport = new winston.transports.DailyRotateFile({
|
||||||
|
filename: 'error-%DATE%.log',
|
||||||
|
dirname: 'logs',
|
||||||
|
zippedArchive: true,
|
||||||
|
level: 'error'
|
||||||
|
});
|
||||||
|
|
||||||
|
const consoleTransport = new winston.transports.Console({
|
||||||
|
format: winston.format.prettyPrint()
|
||||||
|
});
|
||||||
|
|
||||||
|
const logger = winston.createLogger({
|
||||||
|
format: winston.format.combine(
|
||||||
|
winston.format.timestamp(),
|
||||||
|
winston.format.printf(
|
||||||
|
({ level, message, timestamp }: { level: string; message: string; timestamp: string }) =>
|
||||||
|
`[${timestamp}] ${level}: ${JSON.stringify(message)}`
|
||||||
|
)
|
||||||
|
),
|
||||||
|
transports: [dailyRotateTransport, dailyRotateErrorTransport]
|
||||||
|
});
|
||||||
|
|
||||||
|
if (process.env.NODE_ENV === 'dev') {
|
||||||
|
logger.add(
|
||||||
|
new winston.transports.Console({
|
||||||
|
format: winston.format.prettyPrint()
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default logger;
|
15
package.json
15
package.json
|
@ -4,21 +4,32 @@
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "nodemon index.ts",
|
"dev": "concurrently \"yarn run-dev\" \"yarn watch\"",
|
||||||
|
"run-dev": "NODE_ENV=dev nodemon index.ts",
|
||||||
|
"watch": "tsc --watch",
|
||||||
|
"build": "tsc",
|
||||||
"test": "echo \"Error: no test specified\" && exit 1"
|
"test": "echo \"Error: no test specified\" && exit 1"
|
||||||
},
|
},
|
||||||
"author": "",
|
"author": "",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"concurrently": "^6.1.0",
|
||||||
"discord.js": "^12.5.3",
|
"discord.js": "^12.5.3",
|
||||||
"dotenv": "^8.2.0",
|
"dotenv": "^8.2.0",
|
||||||
"lodash": "^4.17.21",
|
"lodash": "^4.17.21",
|
||||||
|
"moment": "^2.29.1",
|
||||||
|
"sqlite": "^4.0.22",
|
||||||
"sqlite3": "^5.0.2",
|
"sqlite3": "^5.0.2",
|
||||||
"typescript": "^4.2.4"
|
"typescript": "^4.2.4",
|
||||||
|
"winston": "^3.3.3",
|
||||||
|
"winston-daily-rotate-file": "^4.5.5"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/sqlite3": "^3.1.7",
|
||||||
|
"@tsconfig/node14": "^1.0.0",
|
||||||
"@types/lodash": "^4.14.168",
|
"@types/lodash": "^4.14.168",
|
||||||
"@types/node": "^15.0.1",
|
"@types/node": "^15.0.1",
|
||||||
|
"@types/winston": "^2.4.4",
|
||||||
"@typescript-eslint/eslint-plugin": "^4.22.0",
|
"@typescript-eslint/eslint-plugin": "^4.22.0",
|
||||||
"@typescript-eslint/parser": "^4.22.0",
|
"@typescript-eslint/parser": "^4.22.0",
|
||||||
"eslint": "^7.25.0",
|
"eslint": "^7.25.0",
|
||||||
|
|
|
@ -0,0 +1,9 @@
|
||||||
|
{
|
||||||
|
"extends": "@tsconfig/node14/tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"outDir": "dist",
|
||||||
|
"preserveConstEnums": true,
|
||||||
|
"esModuleInterop": true
|
||||||
|
},
|
||||||
|
"include": ["**/*.ts"]
|
||||||
|
}
|
Loading…
Reference in New Issue