Skip to content

Commit

Permalink
Merge pull request #11 from STF-Webdev/info_message_to_env
Browse files Browse the repository at this point in the history
Move info message to env, sanitize product names
  • Loading branch information
backjonas authored May 14, 2024
2 parents f514eb8 + ad6e9f9 commit 9ce3363
Show file tree
Hide file tree
Showing 7 changed files with 57 additions and 34 deletions.
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Spiken

Telegram bot used to keep track of user balances and consumed products.

## Prerequisites

- npm (for running the bot)
- docker (for running a local database)

## Running the bot

1. Set environment variables by creating a copy of [.env.template](backend/.env.template)

2. Start a local database

```bash
docker compose up db -d
```

3. Install dependencies

```bash
npm i
```

4. Start the bot

```bash
npm start
```
3 changes: 2 additions & 1 deletion backend/.env.template
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
INFO_MESSAGE="Mooi"
BOT_TOKEN=""
CHAT_ID=""
ADMIN_CHAT_ID=""
Expand All @@ -7,6 +8,6 @@ PGUSER="spiken"
PGPASSWORD="spiken"
NODE_ENV="development"

BANK_ACCOUNT_NUMMER="FI123"
BANK_ACCOUNT_NUMBER="FI123"
BANK_ACCOUNT_NAME="Org RF"
BANK_ACCOUNT_REF="123"
2 changes: 1 addition & 1 deletion backend/src/admin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ bot.command('admin', async (ctx) => {
'/delete_product För att ta bort en produkt',
'/exportera CSV-dump av alla transaktioner',
'/historia_all Se de senaste händelserna för alla användare',
'/saldo_all Se alal användares saldo',
'/saldo_all Se alla användares saldo',
'/saldo_upload För att lägga till transaktioner manuellt',
'/shame Skickar ett meddelande till alla med negativ saldo som påminner dem att betala. Lägg till _<nummer> för att endast pinga folk under -<nummer>.',
].join('\n')
Expand Down
15 changes: 10 additions & 5 deletions backend/src/admin/product.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ const deleteCommandAbort = bot.action(
const addProductScene = new Scenes.WizardScene<ContextWithScenes>(
'add_product_scene',
async (ctx) => {
ctx.reply('Produkt namn? (Blir automatisk små bokstäver)')
ctx.reply('Produktens namn? Endast a-z & 0-9 är tillåtna')
ctx.scene.session.newProduct = {
name: '',
description: '',
Expand All @@ -110,8 +110,10 @@ const addProductScene = new Scenes.WizardScene<ContextWithScenes>(
},
async (ctx) => {
if (ctx.message && 'text' in ctx.message) {
ctx.scene.session.newProduct.name = ctx.message.text.toLowerCase()
ctx.reply('Produkt beskrivning?')
ctx.scene.session.newProduct.name = ctx.message.text
.replace(/[\W_]+/g, '')
.toLowerCase()
ctx.reply('Produktens beskrivning?')
return ctx.wizard.next()
} else {
ctx.reply('Du måst skriva en text')
Expand All @@ -128,7 +130,7 @@ const addProductScene = new Scenes.WizardScene<ContextWithScenes>(
},
async (ctx) => {
if (ctx.message && 'text' in ctx.message) {
if (Number(ctx.message.text) < 0) {
if (Number(ctx.message.text) < 0 || isNaN(Number(ctx.message.text))) {
return ctx.reply(
'Priset måste vara positivt, det läggs sedan in i databasen som negativt!'
)
Expand Down Expand Up @@ -158,7 +160,10 @@ const addProductScene = new Scenes.WizardScene<ContextWithScenes>(
`description:"${ctx.scene.session.newProduct.description}"\n` +
`priceCents:"${ctx.scene.session.newProduct.priceCents}"\n`
)
ctx.reply('Produkten har lagts till!')
ctx.reply(
'Produkten har lagts till!\n' +
'För att den nya produkten ska synas i menyn måste botten startas om.'
)
} catch (e) {
console.log(
'The following product could not be added:\n' +
Expand Down
12 changes: 6 additions & 6 deletions backend/src/admin/saldo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const formattedAccountString =

//#region Export

const exportCommand = bot.command('exportera', async (ctx) => {
bot.command('exportera', async (ctx) => {
const res = await exportTransactions()
const csv = createCsv(res)
ctx.replyWithDocument({
Expand All @@ -38,7 +38,7 @@ const exportCommand = bot.command('exportera', async (ctx) => {

//#region Historia all

const allHistoryCommand = bot.command('historia_all', async (ctx) => {
bot.command('historia_all', async (ctx) => {
const history = await exportTransactions()

const historyString =
Expand All @@ -63,7 +63,7 @@ const allHistoryCommand = bot.command('historia_all', async (ctx) => {

//#region Saldo all

const allSaldoCommand = bot.command('saldo_all', async (ctx) => {
bot.command('saldo_all', async (ctx) => {
const balances = (await getAllBalances()).sort(
(a, b) => b.balance - a.balance
)
Expand All @@ -79,7 +79,7 @@ const allSaldoCommand = bot.command('saldo_all', async (ctx) => {
//endregion

//#region Manual saldo update
const saldoTemplateCommand = bot.command('saldo_template', async (ctx) => {
bot.command('saldo_template', async (ctx) => {
const csv = createCsv(await exportTransactionTemplate())
ctx.replyWithDocument({
source: Buffer.from(csv, 'utf-8'),
Expand Down Expand Up @@ -222,7 +222,7 @@ saldoUploadScene.command('exit', async (ctx) => {
const stage = new Scenes.Stage([saldoUploadScene])
bot.use(stage.middleware())

const saldoUploadCommand = bot.command('saldo_upload', async (ctx) => {
bot.command('saldo_upload', async (ctx) => {
await ctx.scene.enter('saldo_upload_scene')
})

Expand All @@ -235,7 +235,7 @@ const saldoUploadCommand = bot.command('saldo_upload', async (ctx) => {
* I.e sending `/shame` will send a message to all users with negative score,
* while ending `shame_20` will send a message to all users with a balance of less than -20.
*/
const shameCommand = bot.hears(/^\/shame(?:_(\d+))?$/, async (ctx) => {
bot.hears(/^\/shame(?:_(\d+))?$/, async (ctx) => {
const saldoCutOff = ctx.match[1] ? Number(ctx.match[1]) : 0

const balances = (await getAllBalances()).filter(
Expand Down
8 changes: 6 additions & 2 deletions backend/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,24 @@ import { z } from 'zod'
import 'dotenv/config'

const processEnvSchema = z.object({
INFO_MESSAGE: z.string(),
BOT_TOKEN: z.string(),
CHAT_ID: z.string().transform((val) => Number(val)),
ADMIN_CHAT_ID: z.string().transform((val) => Number(val)),
BANK_ACCOUNT_NUMMER: z.string(),
BANK_ACCOUNT_NUMBER: z.string(),
BANK_ACCOUNT_NAME: z.string(),
BANK_ACCOUNT_REF: z.string(),
})

const typedProcessEnv = processEnvSchema.parse(process.env)

export const config = {
infoMessage: typedProcessEnv.INFO_MESSAGE,
botToken: typedProcessEnv.BOT_TOKEN,
chatId: typedProcessEnv.CHAT_ID,
adminChatId: typedProcessEnv.ADMIN_CHAT_ID,
bankAccount: {
number: typedProcessEnv.BANK_ACCOUNT_NUMMER,
number: typedProcessEnv.BANK_ACCOUNT_NUMBER,
name: typedProcessEnv.BANK_ACCOUNT_NAME,
ref: typedProcessEnv.BANK_ACCOUNT_REF,
},
Expand Down
21 changes: 2 additions & 19 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import { Message, Update } from '@telegraf/types'
import adminCommands from './admin/index.js'
import { productsToArray } from './admin/product.js'
import { ContextWithScenes } from './scene.js'
import productCommands from './admin/product.js'
import {
centsToEuroString as formatCentsToEuroString,
confirmOrAbortButton,
Expand All @@ -20,20 +19,8 @@ import {
formatName,
} from './utils.js'

/*
Toiveiden tynnyri:
- Tyhjä
*/

const bot = new Telegraf<ContextWithScenes>(config.botToken)

const info_message = `Hej, välkommen till STF spik bot!
Här kan du köra köp och kolla ditt saldo.
Du hittar alla commandon under "Menu" med beskrivning.
Märk att du kan endast ångra de senaste köpet, så var aktsam!
Ifall något underligt sker ska du vara i kontakt med Croupiären!\n
Oss väl och ingen illa!`

bot.use(async (ctx, next) => {
if (!ctx.from) {
return
Expand All @@ -52,11 +39,7 @@ bot.use(async (ctx, next) => {
})

bot.use(session())
// addAdminCommands(bot)

// bot.use(admin middleware)
// bot.command...
bot.use(productCommands)
//endregion

//#region Products
Expand Down Expand Up @@ -357,11 +340,11 @@ bot.command('saldo', async (ctx) => {
})

bot.command('info', async (ctx) => {
return ctx.reply(info_message)
return ctx.reply(config.infoMessage)
})

bot.command('start', async (ctx) => {
return ctx.reply(info_message)
return ctx.reply(config.infoMessage)
})

bot.telegram.setMyCommands([
Expand Down

0 comments on commit 9ce3363

Please # to comment.