Skip to content

Commit 51ebf06

Browse files
committed
migrate to granny framework
1 parent c2ca8ef commit 51ebf06

37 files changed

+3769
-1953
lines changed

Diff for: .env.sample

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
TOKEN=123
2-
MONGO=mongodb://localhost:27017/magiceraser
2+
MONGO=mongodb://localhost:27017/magiceraser

Diff for: .eslintrc.json

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
{
2+
"env": {
3+
"es2021": true,
4+
"node": true
5+
},
6+
"parser": "@typescript-eslint/parser",
7+
"parserOptions": {
8+
"ecmaVersion": 12,
9+
"sourceType": "module",
10+
"project": "./tsconfig.json"
11+
},
12+
"plugins": [
13+
"@typescript-eslint",
14+
"prettier",
15+
"sort-imports-es6-autofix",
16+
"import",
17+
"no-relative-import-paths",
18+
"eslint-plugin-node"
19+
],
20+
"extends": [
21+
"eslint:recommended",
22+
"plugin:@typescript-eslint/recommended",
23+
"plugin:prettier/recommended"
24+
],
25+
"rules": {
26+
"node/no-process-env": "error",
27+
"no-relative-import-paths/no-relative-import-paths": "error",
28+
"@typescript-eslint/no-unsafe-argument": "error",
29+
"@typescript-eslint/no-floating-promises": "error",
30+
"require-await": "error",
31+
"@typescript-eslint/explicit-function-return-type": "off",
32+
"@typescript-eslint/explicit-module-boundary-types": "off",
33+
"prettier/prettier": [
34+
"error",
35+
{
36+
"trailingComma": "es5",
37+
"tabWidth": 2,
38+
"semi": false,
39+
"singleQuote": true,
40+
"endOfLine": "auto"
41+
}
42+
],
43+
"sort-imports-es6-autofix/sort-imports-es6": [
44+
2,
45+
{
46+
"ignoreCase": false,
47+
"ignoreMemberSort": false,
48+
"memberSyntaxSortOrder": ["none", "all", "multiple", "single"]
49+
}
50+
],
51+
"import/prefer-default-export": "error"
52+
}
53+
}

Diff for: .github/pull_request_template.md

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
- Explain what this PR changes
2+
- in one or more
3+
- bullet points

Diff for: .github/workflows/workflow.yml

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
name: Compile and lint code
2+
3+
on:
4+
pull_request:
5+
types: [synchronize, opened]
6+
7+
jobs:
8+
compile-code:
9+
runs-on: ubuntu-latest
10+
steps:
11+
- uses: actions/checkout@v2
12+
- name: Install modules
13+
run: yarn
14+
- name: Compile code
15+
run: yarn tsc --skipLibCheck
16+
- name: Lint code
17+
run: yarn lint

Diff for: .gitignore

+10-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
11
node_modules
22
dist
3-
outputs
4-
data_folder
5-
lama
63
.env
7-
*.log
4+
*.log
5+
6+
# yarn
7+
.pnp.*
8+
.yarn/*
9+
!.yarn/patches
10+
!.yarn/plugins
11+
!.yarn/releases
12+
!.yarn/sdks
13+
!.yarn/versions

Diff for: .prettierrc.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,6 @@
22
"trailingComma": "es5",
33
"tabWidth": 2,
44
"semi": false,
5-
"singleQuote": true
5+
"singleQuote": true,
6+
"endOfLine": "auto"
67
}

Diff for: .vscode/extensions.json

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"recommendations": [
3+
"dbaeumer.vscode-eslint",
4+
"esbenp.prettier-vscode",
5+
"hnw.vscode-auto-open-markdown-preview",
6+
"naumovs.color-highlight",
7+
"oderwat.indent-rainbow"
8+
]
9+
}

Diff for: .vscode/settings.json

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{
2+
"editor.defaultFormatter": "esbenp.prettier-vscode",
3+
"editor.formatOnSave": true,
4+
"editor.codeActionsOnSave": { "source.fixAll.eslint": true },
5+
"eslint.enable": true,
6+
"eslint.validate": [
7+
"javascript",
8+
"javascriptreact",
9+
"typescript",
10+
"typescriptreact"
11+
]
12+
}

Diff for: .yarn/plugins/yarn-up-all-plugin.cjs

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
module.exports={name:"yarn-up-all-plugin",factory:a=>{const{Configuration:b,Project:c}=a("@yarnpkg/core"),{Cli:d,Command:e,Option:f}=a("clipanion"),g=a("@yarnpkg/plugin-essentials"),h=a("typanion"),i=(a,b)=>a?`@${a}/${b}`:b,j=(a,b)=>{const c=[...a.values()];return b?c.filter(a=>{const c=i(a[1].scope,a[1].name);return!b.includes(c)}):c};class k extends e{constructor(){super(),this.exclude=f.String("-e,--exclude",{validator:h.isString()})}async execute(){if(!g.default.commands)throw new Error("Yarn commands are not available!");const a=await b.find(this.context.cwd,this.context.plugins),{workspace:e}=await c.find(a,this.context.cwd),f=[...e.manifest.dependencies,...e.manifest.devDependencies],h=j(f,this.exclude?this.exclude.split(" "):null),k=h.map(a=>i(a[1].scope,a[1].name)),l=d.from(g.default.commands);return l.runExit(["up",...k],this.context)}}return k.paths=[["up-all"]],k.usage={category:"Utilities",description:"Yarn 2 plugin that will upgrade all dependencies to their latest version with one simple command",details:"This command will upgrade all dependencies to their latest version. You can exclude certain dependencies from being upgraded by using the `-e,--exclude` option.",examples:[["Upgrade all dependencies","yarn up-all"],["Upgrade all dependencies but exclude a single dependency","yarn up-all --exclude package"],["Upgrade all dependencies but exclude a single dependency","yarn up-all -e package"],["Upgrade all dependencies but exclude multiple dependencies","yarn up-all --exclude \"package1 package2\""]]},{commands:[k]}}};

Diff for: .yarn/releases/yarn-3.1.0.cjs

+768
Large diffs are not rendered by default.

Diff for: .yarnrc.yml

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
nodeLinker: node-modules
2+
3+
plugins:
4+
- path: .yarn/plugins/yarn-up-all-plugin.cjs
5+
spec: "https://github.com/e5mode/yarn-up-all/releases/download/1.1.0/index.js"
6+
7+
yarnPath: .yarn/releases/yarn-3.1.0.cjs

Diff for: LICENSE

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
MIT License
22

3-
Copyright (c) 2021 Cristian Padureac
3+
Copyright (c) 2022 Cristian Padureac
44

55
Permission is hereby granted, free of charge, to any person obtaining a copy
66
of this software and associated documentation files (the "Software"), to deal

Diff for: README.md

+5-4
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@ MagicEraser - Telegram Bot for removing objects from pictures<br>
33
Just send two photos:<br>
44
<b>Bot</b> can delete objects from your photos, just follow next steps:<br>
55
1- Send original image<br>
6-
2- Reply to original image and choose that image again<br>
7-
3- Edit that image by coloring what you want to remove(Telegram has an built-in function for this)<br>
8-
4- Press send button<br>
6+
2- Edit that image by coloring what you want to remove(Telegram has an built-in function for this)<br>
7+
3- Send edited image<br>
8+
4- Wait for results<br>
9+
5- Use /new command to start again<br>
910

1011
And you should be good to go! Feel free to fork and submit pull requests. Thanks!
1112

@@ -20,6 +21,6 @@ Also, please, consider looking at `.env.sample`.
2021

2122
MIT — use for any purpose. Would be great if you could leave a note about the original developers. Thanks!
2223

23-
Inspired from: https://github.com/backmeupplz/telegraf-template <br/>
24+
Inspired from: https://github.com/Borodutch/telegram-bot-starter <br/>
2425
Big thanks to https://github.com/saic-mdal/lama for amazing DeepLearning models
2526
Model and pre-processing code can be found here: https://github.com/Moldoteck/lama

Diff for: data_folder/.keep

-1
Original file line numberDiff line numberDiff line change
@@ -1 +0,0 @@
1-
This folder is used to create a folder structure for saving temporary image files

Diff for: locales/en.yaml

+5-4
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@ name: English
22
help: |
33
<b>Bot</b> can delete objects from your photos, just follow next steps:
44
1- Send original image
5-
2- Reply to original image and choose that image again
6-
3- Edit that image by coloring what you want to remove(Telegram has an built-in function for this)
7-
4- Press send button
5+
2- Edit that image by coloring what you want to remove(Telegram has an built-in function for this)
6+
3- Send the edited image(can do steps 2-3 multiple times)
7+
4- Wait for the result
8+
5- Use /new to start over
89
* The color that you choose can impact the result, so try different options
910
* You cannot process simultaneously more than one image
1011
<b>Send /help</b> to see this message
@@ -16,4 +17,4 @@ unsupported_file: Files are unsupported now. Stay tuned!
1617
wait_task: Wait until previous task is finished!
1718
painting_error: Error during painting, try again later
1819
queue_task: Task added to queue...
19-
execution_task: Started execution...
20+
execution_task: Started execution...

Diff for: locales/ru.yaml

+5-4
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@ name: Русский
22
help: |
33
<b>Бот</b> может удалять объекты с фотографий, просто выполните следующие действия:
44
1- Отправьте исходное изображение
5-
2- Ответьте на исходное изображение и снова выберите её же
6-
3- Отредактируйте это изображение, раскрасив то, что вы хотите удалить (в Telegramе есть встроенная функция для этого)
7-
4- Нажмите кнопку отправки
5+
2- Отредактируйте его, закрасив то, что хотите удалить(в Telegram есть встроенная функция для этого)
6+
3- Отправьте отредактированное изображение(можно повторять шаги 2-3 несколько раз)
7+
4- Дождитесь результата
8+
5- Используйте /new чтобы начать заново
89
* Выбранный цвет может повлиять на результат, поэтому попробуйте разные варианты.
910
* Вы не можете обрабатывать одновременно более одного изображения
1011
<b> Отправьте /help</b>, чтобы увидеть это сообщение
@@ -16,4 +17,4 @@ unsupported_file: Файлы сейчас не поддерживаются. Б
1617
wait_task: Дождитесь завершения предыдущей задачи!
1718
painting_error: Ошибка во время обработки, повторите попытку позже
1819
queue_task: Задача добавлена ​​в очередь ...
19-
execution_task: Начато выполнение ...
20+
execution_task: Начато выполнение ...

Diff for: package.json

+38-26
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,53 @@
11
{
2-
"name": "magic-eraser",
2+
"name": "telegram-bot-starter",
33
"version": "1.0.0",
4-
"description": "Telegram bot for removing objects from photos",
4+
"description": "Telegram bot starter based on grammY",
55
"main": "dist/app.js",
6-
"repository": "https://github.com/Moldoteck/telegraf-template",
6+
"repository": "https://github.com/Moldoteck/MagicEraser",
77
"author": "Moldoteck <moldotecko@gmail.com>",
88
"license": "MIT",
9-
"private": false,
109
"scripts": {
1110
"distribute": "yarn build-ts && node dist/app.js",
12-
"develop": "concurrently -k -i -p \"[{name}]\" -n \"Node,TypeScript\" -c \"yellow.bold,cyan.bold\" \"yarn watch-js\" \"yarn watch-ts\"",
11+
"develop": "tsc-watch --skipLibCheck --onSuccess 'node dist/app.js'",
1312
"build-ts": "tsc --skipLibCheck",
14-
"watch-ts": "tsc -w --skipLibCheck",
15-
"watch-js": "nodemon dist/app.js"
16-
},
17-
"devDependencies": {
18-
"@types/mongoose": "^5.10.18",
19-
"@types/node": "^15.12.1",
20-
"concurrently": "^6.2.0",
21-
"nodemon": "^2.0.7",
22-
"ansi-regex": ">=5.0.1",
23-
"mpath": ">=0.8.4",
24-
"mquery": ">=3.2.3"
13+
"pretty": "prettier --check src",
14+
"lint": "yarn pretty && eslint --max-warnings 0 --ext ts,tsx,json src"
2515
},
2616
"dependencies": {
27-
"@typegoose/typegoose": "^7.6.1",
17+
"@grammyjs/i18n": "^0.5.0",
18+
"@grammyjs/menu": "^1.0.4",
19+
"@grammyjs/runner": "^1.0.3",
2820
"dotenv": "^10.0.0",
29-
"glob": "^7.2.0",
21+
"envalid": "^7.2.2",
22+
"grammy": "^1.5.0",
23+
"grammy-middlewares": "^1.0.11",
24+
"mongoose": "^6.1.0",
25+
"queue": "^6.0.2",
26+
"uuid": "^9.0.0",
27+
"needle": "^3.1.0"
28+
},
29+
"devDependencies": {
30+
"@typegoose/typegoose": "^9.3.1",
31+
"@types/js-yaml": "^4.0.5",
32+
"@types/node": "^16.11.12",
33+
"@types/uuid": "^8.3.4",
34+
"@typescript-eslint/eslint-plugin": "^5.6.0",
35+
"@typescript-eslint/parser": "^5.6.0",
36+
"eslint": "^8.4.1",
37+
"eslint-config-prettier": "^8.3.0",
38+
"eslint-plugin-import": "^2.25.3",
39+
"eslint-plugin-no-relative-import-paths": "^1.0.8",
40+
"eslint-plugin-node": "^11.1.0",
41+
"eslint-plugin-prettier": "^4.0.0",
42+
"eslint-plugin-sort-imports-es6-autofix": "^0.6.0",
3043
"module-alias": "^2.2.2",
31-
"mongoose": "5.10.18",
32-
"needle": "3.0.0",
33-
"telegraf": "^4.3.0",
34-
"telegraf-i18n": "^6.6.0",
35-
"typescript": "^4.3.5",
36-
"queue": "6.0.2"
44+
"prettier": "^2.5.1",
45+
"source-map-support": "^0.5.21",
46+
"tsc-watch": "^4.5.0",
47+
"typescript": "^4.5.2"
3748
},
3849
"_moduleAliases": {
3950
"@": "dist"
40-
}
41-
}
51+
},
52+
"packageManager": "yarn@3.1.0"
53+
}

Diff for: src/app.ts

+41-36
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,45 @@
1-
import { localeActions } from './handlers/language'
2-
// Setup @/ aliases for modules
31
import 'module-alias/register'
4-
// Config dotenv
5-
import * as dotenv from 'dotenv'
6-
dotenv.config({ path: `${__dirname}/../.env` })
7-
// Dependencies
8-
import { bot } from '@/helpers/bot'
9-
import { ignoreOldMessageUpdates } from '@/middlewares/ignoreOldMessageUpdates'
10-
import { sendHelp } from '@/handlers/sendHelp'
11-
import { i18n, attachI18N } from '@/helpers/i18n'
12-
import { setLanguage, sendLanguage } from '@/handlers/language'
13-
import { attachUser } from '@/middlewares/attachUser'
14-
import { countAllUsers, processPhoto, resetLimits, sendSegmentationResult, setProcessLimit } from './handlers/magiceraser'
15-
import { emptyLimits } from './models'
2+
import 'reflect-metadata'
3+
import 'source-map-support/register'
164

17-
// Middlewares
18-
bot.use(ignoreOldMessageUpdates)
19-
bot.use(attachUser)
20-
bot.use(i18n.middleware(), attachI18N)
21-
// Commands
22-
bot.command(['help', 'start'], sendHelp)
23-
bot.command('language', sendLanguage)
24-
bot.command('limit', setProcessLimit)
25-
bot.command('countChats', countAllUsers)
26-
bot.command('reset', resetLimits)
27-
bot.command('segmentation', sendSegmentationResult)
5+
import { ignoreOld, sequentialize } from 'grammy-middlewares'
6+
import { run } from '@grammyjs/runner'
7+
import attachUser from '@/middlewares/attachUser'
8+
import bot from '@/helpers/bot'
9+
import configureI18n from '@/middlewares/configureI18n'
10+
import handleLanguage from '@/handlers/language'
11+
import i18n from '@/helpers/i18n'
12+
import languageMenu from '@/menus/language'
13+
import sendHelp from '@/handlers/help'
14+
import startMongo from '@/helpers/startMongo'
15+
import { handleNew, handleReset, processPhoto } from './handlers/magiceraser'
2816

29-
30-
bot.on('photo',processPhoto)
31-
bot.on('message',processPhoto)
32-
// Actions
33-
bot.action(localeActions, setLanguage)
34-
// Errors
35-
bot.catch(console.error)
36-
// Start bot
37-
bot.launch().then(async () => {
38-
await emptyLimits()
17+
async function runApp() {
18+
console.log('Starting app...')
19+
// Mongo
20+
await startMongo()
21+
console.log('Mongo connected')
22+
bot
23+
// Middlewares
24+
.use(sequentialize())
25+
.use(ignoreOld())
26+
.use(attachUser)
27+
.use(i18n.middleware())
28+
.use(configureI18n)
29+
// Menus
30+
.use(languageMenu)
31+
// Commands
32+
bot.command(['help', 'start'], sendHelp)
33+
bot.command('language', handleLanguage)
34+
bot.command('new', handleNew)
35+
bot.command('reset', handleReset)
36+
bot.on(':photo', processPhoto)
37+
// Errors
38+
bot.catch(console.error)
39+
// Start bot
40+
await bot.init()
41+
run(bot)
3942
console.info(`Bot ${bot.botInfo.username} is up and running`)
40-
})
43+
}
44+
45+
void runApp()

Diff for: src/handlers/help.ts

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import Context from '@/models/Context'
2+
import sendOptions from '@/helpers/sendOptions'
3+
4+
export default function handleHelp(ctx: Context) {
5+
return ctx.replyWithLocalization('help', sendOptions(ctx))
6+
}

0 commit comments

Comments
 (0)