chore: clean up

This commit is contained in:
Chen Asraf
2020-08-15 20:22:29 +03:00
parent 0583eb0949
commit 0f69e9ea3f
7 changed files with 52 additions and 45 deletions

View File

@@ -45,6 +45,7 @@ module.exports = {
'unicorn/prevent-abbreviations': 'off',
'unicorn/filename-case': 'off',
'unicorn/no-fn-reference-in-iterator': 'off',
'unicorn/no-nested-ternary': 'off',
'no-underscore-dangle': ['error', { allowAfterThis: true }],
},
overrides: [

View File

@@ -21,7 +21,7 @@
"migrate": "ts-node ./node_modules/typeorm/cli -f ./ormconfig.ts migration:run",
"seed": "ts-node ./src/seed/index.ts",
"lint": "lint:code",
"lint:code": "eslint src/**/*.{ts,js}",
"lint:code": "eslint --no-error-on-unmatched-pattern src/**/*.{ts,js}",
"lint:markdown": "markdownlint **/*.md",
"format": "prettier \"**/*.ts\" --ignore-path ./.prettierignore --write",
"typecheck": "tsc --noEmit",

View File

@@ -19,7 +19,7 @@ const command: ICommand = {
description: 'Get random quotes from people in chat, or add quotes to the list.',
async execute(message, args, _prefix, _commands, db) {
// Get random quote
if (args.filter(s => s.trim().length).length === 0) {
if (args.filter((s) => s.trim().length).length === 0) {
getRandomQuote(message, args, db);
return;
}
@@ -40,7 +40,7 @@ const command: ICommand = {
},
};
const clean = (str: string): string => str.replace(/[\t\n|]+/g, ' ').replace(/\s+/g, ' ')
const clean = (str: string): string => str.replace(/[\t\n|]+/g, ' ').replace(/\s+/g, ' ');
const getQuoteStr = ({ author, quote }: Quote): string => `"${quote}" - ${author}`;
async function getRandomQuote(message: Discord.Message, args: string[], db: MongoService): Promise<void> {
@@ -65,7 +65,7 @@ async function searchQuotes(message: Discord.Message, args: string[], db: MongoS
});
if (q.length > 0) {
message.reply("Found a few, I'll DM you what I got!")
message.reply("Found a few, I'll DM you what I got!");
message.author.send(`Found ${q.length} quote${q.length !== 1 ? 's' : ''}:`);
q.forEach((quote) => {
message.author.send(getQuoteStr(quote));
@@ -80,8 +80,8 @@ async function addNewQuote(message: Discord.Message, args: string[], db: MongoSe
const hasAuthor = /<@!\d+>/.test(authorRaw);
const author = hasAuthor ? authorRaw : 'Anonymous';
const differentAuthor = hasAuthor && author !== `<@!${message.author.id}>`;
const authorName = differentAuthor ?
message.mentions.guild.members.cache.find(u => u.user.id === message.mentions.users.first().id)?.displayName
const authorName = differentAuthor
? message.mentions.guild.members.cache.find((u) => u.user.id === message.mentions.users.first().id)?.displayName
: message.member.displayName;
const quote = (hasAuthor ? restRaw : [authorRaw, ...restRaw]).join(' ');
@@ -90,16 +90,20 @@ async function addNewQuote(message: Discord.Message, args: string[], db: MongoSe
`are you serious? This is the best quote ever${differentAuthor ? `, ${author}` : ''}!`,
'OH. MY. GOD. Perfection.',
'I am putting this on my wall. This is a quote I will hold dear to me always.',
`is that real? Woah! Hey,${differentAuthor ? ` ${author},` : ''} did you ever consider writing a book?! This will sell for millions.`,
clean(`okay, this is spooky. I definitely dreamt of ${!hasAuthor ? 'a person' : (differentAuthor ? author : 'you')}
saying exactly that this week. ${!hasAuthor ? 'Is someone' : (differentAuthor ? `Is ${author}` : 'Are you')}
`is that real? Woah! Hey,${
differentAuthor ? ` ${author},` : ''
} did you ever consider writing a book?! This will sell for millions.`,
clean(`okay, this is spooky. I definitely dreamt of ${!hasAuthor ? 'a person' : differentAuthor ? author : 'you'}
saying exactly that this week. ${!hasAuthor ? 'Is someone' : differentAuthor ? `Is ${author}` : 'Are you'}
prying into my subconscious?`),
'consider me floored. If there was an award for amazing quotes, it would be named after this exact one.',
'why did no one say this earlier? It HAS to be said!',
"I can't believe you withold that quote from me until now. It's way too good to just remain unshared!",
'I have a pretty large memory capacity for a bot, and I gotta say, I scanned all my other quotes, this one is definitely on the top 10.',
clean(`Oh, I am DEFINITELY saving this. One day someone will interview me about
${!hasAuthor ? 'the best quote I can recall,' : (differentAuthor ? author : 'you')} and I will refer to this moment precisely.`),
${
!hasAuthor ? 'the best quote I can recall,' : differentAuthor ? author : 'you'
} and I will refer to this moment precisely.`),
clean(`you're not serious. Are you serious? You can't be serious. It's impossible there's **this** good a quote just floating around
out there. It's probably fictional. Yeah.`),
];

View File

@@ -170,7 +170,12 @@ export default class MongoService {
*
* @example `updateMany('123456', 'collectionName', { ident: 'generated-slug' }, { secondKey: 'new data'})`
*/
public async updateMany<T>(userId: string, collection: string, query: FilterQuery<T>, payload: T[]): Promise<boolean> {
public async updateMany<T>(
userId: string,
collection: string,
query: FilterQuery<T>,
payload: T[],
): Promise<boolean> {
try {
this.verifyConnection();
@@ -242,7 +247,6 @@ export default class MongoService {
}
}
/**
* Fetches the first document that matches the query
*

View File

@@ -1,14 +1,9 @@
/* eslint-disable eslint-comments/disable-enable-pair */
/* eslint-disable import/no-extraneous-dependencies */
import axios from 'axios';
import axios, { AxiosRequestConfig } from 'axios';
import cheerio from 'cheerio';
export async function getHTMLPage(url: string): Promise<CheerioStatic> {
const res = await axios.get(url, {
headers: {
'Cookie':
'asylum_session_id=15eff7783e58d06c778cd6bb6325f646; asylum_ipb_stronghold=abd5aa53bfd60af5d47195b4c1414816; asylum_member_id=1136; asylum_pass_hash=bab4442d4659cc06bd51c5ded5f2c7fd; asylum_coppa=0',
}
});
export async function getHTMLPage(url: string, config?: AxiosRequestConfig): Promise<CheerioStatic> {
const res = await axios.get(url, config);
return cheerio.load(res.data.toString());
}

View File

@@ -48,13 +48,12 @@ async function run(): Promise<void> {
const csvOut = [['author', 'quote']];
for (const row of quotes) {
csvOut.push([row.author, row.quote].map(v => {
v = v
.replace(/(\n+)/g, '\n')
.replace(/"/g, '""')
.trim();
return v.includes(' ') || v.includes('\t') ? `"${v}"` : v;
}));
csvOut.push(
[row.author, row.quote].map((v) => {
v = v.replace(/(\n+)/g, '\n').replace(/"/g, '""').trim();
return v.includes(' ') || v.includes('\t') ? `"${v}"` : v;
}),
);
}
csv.stringify.default(quotes, (err, out) => {

View File

@@ -14,25 +14,29 @@ async function run(): Promise<void> {
const outputDir = path.join(__dirname, '..', 'outputs');
fs.readFile(path.join(outputDir, 'quotes_clean.csv'), (fsErr, data) => {
if (fsErr) throw fsErr;
(csv.parse as unknown as typeof csv.parse.default)(data.toString(), {
columns: true,
}, (csvErr, rows: Quote[]) => {
if (csvErr) throw csvErr;
const client = new mongodb.MongoClient(CONNECTION_STRING, { useUnifiedTopology: true });
client.connect(async (mongoClientErr) => {
if (mongoClientErr) throw mongoClientErr;
const db = client.db(DB_NAME);
console.log('Start dumping...');
console.debug(rows.slice(5));
((csv.parse as unknown) as typeof csv.parse.default)(
data.toString(),
{
columns: true,
},
(csvErr, rows: Quote[]) => {
if (csvErr) throw csvErr;
const client = new mongodb.MongoClient(CONNECTION_STRING, { useUnifiedTopology: true });
client.connect(async (mongoClientErr) => {
if (mongoClientErr) throw mongoClientErr;
const db = client.db(DB_NAME);
console.log('Start dumping...');
console.debug(rows.slice(5));
try {
await db.collection('quotes').insertMany(rows);
console.log('Done dumping.');
} catch (error) {
console.error(error);
}
})
});
try {
await db.collection('quotes').insertMany(rows);
console.log('Done dumping.');
} catch (error) {
console.error(error);
}
});
},
);
});
}