mirror of
https://github.com/ershisan99/flashcards-admin-bot.git
synced 2025-12-16 12:33:09 +00:00
initial commit
This commit is contained in:
15
.editorconfig
Normal file
15
.editorconfig
Normal file
@@ -0,0 +1,15 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
|
||||
[*.md]
|
||||
insert_final_newline = false
|
||||
trim_trailing_whitespace = false
|
||||
|
||||
[*.{js,json,ts,mts,yml,yaml}]
|
||||
indent_size = 2
|
||||
indent_style = space
|
||||
1
.env
Normal file
1
.env
Normal file
@@ -0,0 +1 @@
|
||||
BOT_TOKEN="6914299856:AAHo7emibExuNGdodkAuBIS8d5VjB0Pk8Is"
|
||||
1
.eslintignore
Normal file
1
.eslintignore
Normal file
@@ -0,0 +1 @@
|
||||
/**/*.js
|
||||
28
.eslintrc.json
Normal file
28
.eslintrc.json
Normal file
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"env": {
|
||||
"browser": false,
|
||||
"es6": true,
|
||||
"node": true
|
||||
},
|
||||
"parser": "@typescript-eslint/parser",
|
||||
"parserOptions": {
|
||||
"project": "tsconfig.json",
|
||||
"sourceType": "module",
|
||||
"ecmaVersion": 2020
|
||||
},
|
||||
"plugins": ["@typescript-eslint", "jest"],
|
||||
"extends": [
|
||||
"eslint:recommended",
|
||||
"plugin:@typescript-eslint/recommended",
|
||||
"plugin:jest/recommended",
|
||||
"prettier"
|
||||
],
|
||||
"rules": {
|
||||
// The following rule is enabled only to supplement the inline suppression
|
||||
// examples, and because it is not a recommended rule, you should either
|
||||
// disable it, or understand what it enforces.
|
||||
// https://typescript-eslint.io/rules/explicit-function-return-type/
|
||||
"@typescript-eslint/explicit-function-return-type": "warn",
|
||||
"@typescript-eslint/no-explicit-any": "off"
|
||||
}
|
||||
}
|
||||
12
.github/FUNDING.yml
vendored
Normal file
12
.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: [jsynowiec]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: # Replace with a single Ko-fi username
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
otechie: # Replace with a single Otechie username
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
17
.github/workflows/nodejs.yml
vendored
Normal file
17
.github/workflows/nodejs.yml
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
name: Node.js CI
|
||||
|
||||
on: [push]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: volta-cli/action@v1
|
||||
- run: npm ci --no-audit
|
||||
- run: npm run lint --if-present
|
||||
- run: npm test
|
||||
- run: npm run build --if-present
|
||||
env:
|
||||
CI: true
|
||||
29
.gitignore
vendored
Normal file
29
.gitignore
vendored
Normal file
@@ -0,0 +1,29 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
|
||||
# Dependencies
|
||||
node_modules/
|
||||
|
||||
# Coverage
|
||||
coverage
|
||||
|
||||
# Transpiled files
|
||||
build/
|
||||
|
||||
# VS Code
|
||||
.vscode
|
||||
!.vscode/tasks.js
|
||||
|
||||
# JetBrains IDEs
|
||||
.idea/
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
.eslintcache
|
||||
|
||||
# Misc
|
||||
.DS_Store
|
||||
12
.prettierrc
Normal file
12
.prettierrc
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all",
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["*.ts", "*.mts"],
|
||||
"options": {
|
||||
"parser": "typescript"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
201
LICENSE
Normal file
201
LICENSE
Normal file
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
30
README.md
Normal file
30
README.md
Normal file
@@ -0,0 +1,30 @@
|
||||
# Usage
|
||||
|
||||
1. Сбросить базу данных
|
||||
```bash
|
||||
pnpm run reset
|
||||
```
|
||||
2. Собрать проект
|
||||
```bash
|
||||
pnpm run build
|
||||
```
|
||||
3. Запустить сервер
|
||||
```bash
|
||||
pnpm run start
|
||||
```
|
||||
4. Остановить сервер когда все зарегались
|
||||
```bash
|
||||
ctrl + c
|
||||
```
|
||||
5. Сгенерировать группы
|
||||
```bash
|
||||
pnpm run gen
|
||||
```
|
||||
6. Отправить информацию о группах каждому юзеру
|
||||
```bash
|
||||
pnpm run send-group-info
|
||||
```
|
||||
7. Открыть страницу с таблицей
|
||||
```bash
|
||||
pnpm run open-html
|
||||
```
|
||||
1
data.json
Normal file
1
data.json
Normal file
@@ -0,0 +1 @@
|
||||
{"320185869":{"userId":"320185869","name":"Евгений Березкин","availableTime":{"from":10,"to":20},"tgUsername":"breznovic","chatId":320185869},"347996326":{"userId":"347996326","name":"Михаил Польшин","availableTime":{"from":20,"to":30},"tgUsername":"notMikle","chatId":347996326},"384611325":{"userId":"384611325","name":"Бог Бог","availableTime":{"from":40,"to":null},"tgUsername":"GoldDeDennis","chatId":384611325},"398100433":{"userId":"398100433","name":"Sergeev Dmitry","availableTime":{"from":10,"to":20},"tgUsername":"Dmitry_Sergeev_14","chatId":398100433},"453233884":{"userId":"453233884","name":"А Ю","availableTime":{"from":40,"to":null},"tgUsername":"MrUnderSan","chatId":453233884},"519261981":{"userId":"519261981","name":"Береснев Михаил","availableTime":{"from":20,"to":30},"tgUsername":"MikeJ0","chatId":519261981},"547121990":{"userId":"547121990","name":"Пучков Иван Иванович","availableTime":{"from":30,"to":40},"tgUsername":"lvrshn_a","chatId":547121990},"558491754":{"userId":"558491754","name":"Андрей Задорожный","availableTime":{"from":0,"to":10},"tgUsername":"andrei_zadorozhnyi","chatId":558491754},"738507170":{"userId":"738507170","name":"Евгений Нестеренко","availableTime":{"from":20,"to":30},"tgUsername":"EugeneNest","chatId":738507170},"836228560":{"userId":"836228560","name":"Рудакян Илья Арменович","availableTime":{"from":20,"to":30},"tgUsername":"Asap_Alh","chatId":836228560},"950709136":{"userId":"950709136","name":"Лукашевич Евгений","availableTime":{"from":20,"to":30},"tgUsername":"elukas21","chatId":950709136},"1003766210":{"userId":"1003766210","name":"Виталик Кожуров","availableTime":{"from":30,"to":40},"tgUsername":"vitalik_kazhurou","chatId":1003766210}}
|
||||
1
groups.json
Normal file
1
groups.json
Normal file
@@ -0,0 +1 @@
|
||||
[[{"userId":"558491754","name":"Андрей Задорожный","availableTime":{"from":0,"to":10},"tgUsername":"andrei_zadorozhnyi","chatId":558491754},{"userId":"320185869","name":"Евгений Березкин","availableTime":{"from":10,"to":20},"tgUsername":"breznovic","chatId":320185869},{"userId":"398100433","name":"Sergeev Dmitry","availableTime":{"from":10,"to":20},"tgUsername":"Dmitry_Sergeev_14","chatId":398100433}],[{"userId":"347996326","name":"Михаил Польшин","availableTime":{"from":20,"to":30},"tgUsername":"notMikle","chatId":347996326},{"userId":"519261981","name":"Береснев Михаил","availableTime":{"from":20,"to":30},"tgUsername":"MikeJ0","chatId":519261981},{"userId":"738507170","name":"Евгений Нестеренко","availableTime":{"from":20,"to":30},"tgUsername":"EugeneNest","chatId":738507170}],[{"userId":"836228560","name":"Рудакян Илья Арменович","availableTime":{"from":20,"to":30},"tgUsername":"Asap_Alh","chatId":836228560},{"userId":"950709136","name":"Лукашевич Евгений","availableTime":{"from":20,"to":30},"tgUsername":"elukas21","chatId":950709136},{"userId":"547121990","name":"Пучков Иван Иванович","availableTime":{"from":30,"to":40},"tgUsername":"lvrshn_a","chatId":547121990}],[{"userId":"1003766210","name":"Виталик Кожуров","availableTime":{"from":30,"to":40},"tgUsername":"vitalik_kazhurou","chatId":1003766210},{"userId":"384611325","name":"Бог Бог","availableTime":{"from":40,"to":null},"tgUsername":"GoldDeDennis","chatId":384611325},{"userId":"453233884","name":"А Ю","availableTime":{"from":40,"to":null},"tgUsername":"MrUnderSan","chatId":453233884}]]
|
||||
1
icon.svg
Normal file
1
icon.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 5.8 KiB |
15
index.html
Normal file
15
index.html
Normal file
@@ -0,0 +1,15 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Title</title>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@1/css/pico.min.css">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<main class="container">
|
||||
<div id="root"></div>
|
||||
</main>
|
||||
<script src="index.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
29
index.js
Normal file
29
index.js
Normal file
@@ -0,0 +1,29 @@
|
||||
const root = document.getElementById('root');
|
||||
async function getData() {
|
||||
const data1 = await fetch('./groups.json').then((res) => res.json());
|
||||
root.innerHTML = getHtml(data1);
|
||||
}
|
||||
function getHtml(data) {
|
||||
return `<div>${data
|
||||
.map((group) => {
|
||||
return `<table><thead>
|
||||
<tr>
|
||||
<th>Имя</th>
|
||||
<th>Время</th>
|
||||
<th>Telegram</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>${group
|
||||
.map((el) => {
|
||||
return `<tr>
|
||||
<td >${el.name}</td>
|
||||
<td style='width: 200px'">${el.availableTime.from} - ${el.availableTime.to}</td>
|
||||
<td style='width: 200px'>${el.tgUsername}</td>
|
||||
</tr>`;
|
||||
})
|
||||
.join('')}</tbody>
|
||||
</table>`;
|
||||
})
|
||||
.join('')}</div>`;
|
||||
}
|
||||
getData();
|
||||
27
index.js.template
Normal file
27
index.js.template
Normal file
@@ -0,0 +1,27 @@
|
||||
const data = /* USERS */;
|
||||
|
||||
const root = document.getElementById('root');
|
||||
|
||||
const html = `<div>${data
|
||||
.map((group) => {
|
||||
return `<table><thead>
|
||||
<tr>
|
||||
<th>Имя</th>
|
||||
<th>Время</th>
|
||||
<th>Telegram</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>${group
|
||||
.map((el) => {
|
||||
return `<tr>
|
||||
<td >${el.name}</td>
|
||||
<td style='width: 200px'">${el.availableTime.from} - ${el.availableTime.to}</td>
|
||||
<td style='width: 200px'>${el.tgUsername}</td>
|
||||
</tr>`;
|
||||
})
|
||||
.join('')}</tbody>
|
||||
</table>`;
|
||||
})
|
||||
.join('')}</div>`;
|
||||
|
||||
root.innerHTML = html;
|
||||
18
jest.config.js
Normal file
18
jest.config.js
Normal file
@@ -0,0 +1,18 @@
|
||||
export default {
|
||||
testEnvironment: 'node',
|
||||
preset: 'ts-jest/presets/default-esm',
|
||||
transform: {
|
||||
'^.+\\.m?[tj]s?$': ['ts-jest', { useESM: true }],
|
||||
},
|
||||
moduleNameMapper: {
|
||||
'^(\\.{1,2}/.*)\\.(m)?js$': '$1',
|
||||
},
|
||||
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(m)?ts$',
|
||||
coverageDirectory: 'coverage',
|
||||
collectCoverageFrom: [
|
||||
'src/**/*.ts',
|
||||
'src/**/*.mts',
|
||||
'!src/**/*.d.ts',
|
||||
'!src/**/*.d.mts',
|
||||
],
|
||||
};
|
||||
52
package.json
Normal file
52
package.json
Normal file
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"name": "node-typescript-boilerplate",
|
||||
"version": "0.0.0",
|
||||
"description": "Minimalistic boilerplate to quick-start Node.js development in TypeScript.",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">= 20.9 < 21"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@telegraf/types": "^6.9.1",
|
||||
"@types/jest": "~29.5",
|
||||
"@types/node": "~20",
|
||||
"@typescript-eslint/eslint-plugin": "~6.15",
|
||||
"@typescript-eslint/parser": "~6.15",
|
||||
"concurrently": "^8.2.2",
|
||||
"dotenv": "^16.3.1",
|
||||
"eslint": "~8.56",
|
||||
"eslint-config-prettier": "~9.1",
|
||||
"eslint-plugin-jest": "~27.6",
|
||||
"jest": "~29.7",
|
||||
"nodemon": "^3.0.2",
|
||||
"prettier": "~3.1",
|
||||
"rimraf": "~5.0",
|
||||
"ts-api-utils": "~1.0",
|
||||
"ts-jest": "~29.1",
|
||||
"typescript": "~5.3"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "node build/src/main.js",
|
||||
"gen": "node build/src/generate-groups.js",
|
||||
"open-html": "npx -y serve",
|
||||
"reset": "node scripts/reset-data.cjs",
|
||||
"send-group-info": "pnpm build && node build/src/send-group-info.js",
|
||||
"start:watch": "nodemon build/src/main.js --ignore groups.json --ignore data.json",
|
||||
"dev": "concurrently \"npm run start:watch\" \"npm run build:watch\"",
|
||||
"clean": "rimraf coverage build tmp",
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"build:watch": "tsc -w -p tsconfig.json",
|
||||
"build:release": "npm run clean && tsc -p tsconfig.release.json",
|
||||
"lint": "eslint . --ext .ts --ext .mts",
|
||||
"test": "jest --coverage",
|
||||
"prettier": "prettier --config .prettierrc --write .",
|
||||
"test:watch": "jest --watch"
|
||||
},
|
||||
"author": "Jakub Synowiec <jsynowiec@users.noreply.github.com>",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"remeda": "^1.33.0",
|
||||
"telegraf": "^4.15.3",
|
||||
"tslib": "~2.6"
|
||||
}
|
||||
}
|
||||
3520
pnpm-lock.yaml
generated
Normal file
3520
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
3
scripts/reset-data.cjs
Normal file
3
scripts/reset-data.cjs
Normal file
@@ -0,0 +1,3 @@
|
||||
const fs = require('fs');
|
||||
|
||||
fs.writeFileSync('./data.json', '{}', 'utf8');
|
||||
46
src/generate-groups.ts
Normal file
46
src/generate-groups.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import fs from 'fs';
|
||||
import { Data, UserData } from './types.js';
|
||||
|
||||
generateGroups();
|
||||
|
||||
function generateGroups() {
|
||||
const data = fs.readFileSync('./data.json', 'utf8');
|
||||
const dataObj = JSON.parse(data) as Data;
|
||||
const groupedUsers = groupByTime(dataObj);
|
||||
fs.writeFileSync('./groups.json', JSON.stringify(groupedUsers), 'utf8');
|
||||
generateJsFile(groupedUsers);
|
||||
}
|
||||
|
||||
function generateJsFile(users: UserData[][]) {
|
||||
const template = fs.readFileSync('./index.js.template', 'utf8');
|
||||
const usersString = JSON.stringify(users);
|
||||
const jsFile = template.replace('/* USERS */', usersString);
|
||||
|
||||
fs.writeFileSync('./index.js', jsFile, 'utf8');
|
||||
}
|
||||
function groupByTime(users: Record<string, UserData>): UserData[][] {
|
||||
const allUsers = Object.values(users);
|
||||
|
||||
// First, sort all users by their available time from low to high
|
||||
allUsers.sort((a, b) => a.availableTime.from - b.availableTime.from);
|
||||
|
||||
const groups: UserData[][] = [];
|
||||
let currentGroup: UserData[] = [];
|
||||
|
||||
allUsers.forEach((user) => {
|
||||
currentGroup.push(user);
|
||||
|
||||
// If the current group reaches 3 members, start a new group
|
||||
if (currentGroup.length === 3) {
|
||||
groups.push(currentGroup);
|
||||
currentGroup = []; // Reset for next group
|
||||
}
|
||||
});
|
||||
|
||||
// Add the last group if it has less than 3 members and is not empty
|
||||
if (currentGroup.length > 0) {
|
||||
groups.push(currentGroup);
|
||||
}
|
||||
|
||||
return groups;
|
||||
}
|
||||
185
src/main.ts
Normal file
185
src/main.ts
Normal file
@@ -0,0 +1,185 @@
|
||||
import dotenv from 'dotenv';
|
||||
import { session, Telegraf } from 'telegraf';
|
||||
|
||||
import { Stage, WizardScene } from 'telegraf/scenes';
|
||||
import * as fs from 'fs';
|
||||
import { Data, UserData } from './types.js';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const BOT_TOKEN = process.env.BOT_TOKEN;
|
||||
|
||||
if (!BOT_TOKEN) {
|
||||
throw new Error('BOT_TOKEN is required!');
|
||||
}
|
||||
|
||||
const superWizard = new WizardScene<any>(
|
||||
'add_to_team_wizard',
|
||||
async (ctx) => {
|
||||
console.log('step 0');
|
||||
|
||||
await ctx.reply(
|
||||
'Введи свое имя и фамилию, пожалуйста. Например, Иван Иванов',
|
||||
);
|
||||
ctx.wizard.state.data = {};
|
||||
return ctx.wizard.next();
|
||||
},
|
||||
async (ctx) => {
|
||||
console.log('step 1');
|
||||
if (ctx.message?.text) {
|
||||
ctx.wizard.state.data.name = ctx.message.text;
|
||||
}
|
||||
await ctx.reply(
|
||||
'Сколько часов ты можешь уделять проекту в среднем в неделю?',
|
||||
{
|
||||
reply_markup: {
|
||||
inline_keyboard: [
|
||||
[
|
||||
{
|
||||
text: 'До 10',
|
||||
callback_data: JSON.stringify({ from: 0, to: 10 }),
|
||||
},
|
||||
{
|
||||
text: '10-20',
|
||||
callback_data: JSON.stringify({ from: 10, to: 20 }),
|
||||
},
|
||||
{
|
||||
text: '20-30',
|
||||
callback_data: JSON.stringify({ from: 20, to: 30 }),
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
text: '30-40',
|
||||
callback_data: JSON.stringify({ from: 30, to: 40 }),
|
||||
},
|
||||
{
|
||||
text: 'Более 40',
|
||||
callback_data: JSON.stringify({ from: 40, to: null }),
|
||||
},
|
||||
{
|
||||
text: '< Назад',
|
||||
callback_data: 'back',
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
return ctx.wizard.next();
|
||||
},
|
||||
async (ctx) => {
|
||||
if (!ctx.callbackQuery) {
|
||||
await ctx.reply(
|
||||
'Что-то пошло не так, попробуй выбрать один из предложенных вариантов',
|
||||
);
|
||||
return ctx.wizard.selectStep(2);
|
||||
}
|
||||
if (ctx.callbackQuery.data === 'back') {
|
||||
console.log('step 2');
|
||||
await ctx.answerCbQuery('back');
|
||||
await ctx.wizard.selectStep(ctx.wizard.cursor - 2);
|
||||
return ctx.wizard.steps[ctx.wizard.cursor](ctx);
|
||||
}
|
||||
const data = JSON.parse(ctx.callbackQuery.data);
|
||||
|
||||
ctx.wizard.state.data.availableTime = data;
|
||||
await ctx.answerCbQuery(
|
||||
`You are willing to dedicate from ${data.from} to ${
|
||||
data.to ?? 'infinity'
|
||||
} hours per week`,
|
||||
);
|
||||
await ctx.reply(
|
||||
`Перепроверь, пожалуйста, все ли верно. Если все верно, нажми "Да", если нет, нажми "Нет" или "< Назад"
|
||||
Имя: ${ctx.wizard.state.data.name}
|
||||
Время: ${data.from} - ${data.to ?? 'infinity'}
|
||||
`,
|
||||
{
|
||||
reply_markup: {
|
||||
inline_keyboard: [
|
||||
[
|
||||
{
|
||||
text: 'Да',
|
||||
callback_data: 'yes',
|
||||
},
|
||||
{
|
||||
text: 'Нет',
|
||||
callback_data: 'no',
|
||||
},
|
||||
{
|
||||
text: '< Назад',
|
||||
callback_data: 'back',
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
return ctx.wizard.next();
|
||||
},
|
||||
async (ctx) => {
|
||||
if (!ctx.callbackQuery) {
|
||||
await ctx.reply(
|
||||
'Что-то пошло не так, попробуй выбрать один из предложенных вариантов',
|
||||
);
|
||||
return ctx.wizard.selectStep(3);
|
||||
}
|
||||
if (ctx.callbackQuery.data === 'back') {
|
||||
console.log('step 3');
|
||||
await ctx.answerCbQuery('back');
|
||||
await ctx.wizard.selectStep(ctx.wizard.cursor - 2);
|
||||
return ctx.wizard.steps[ctx.wizard.cursor](ctx);
|
||||
}
|
||||
if (ctx.callbackQuery.data === 'no') {
|
||||
console.log('step 0');
|
||||
await ctx.answerCbQuery('no');
|
||||
await ctx.wizard.selectStep(0);
|
||||
return ctx.wizard.steps[ctx.wizard.cursor](ctx);
|
||||
}
|
||||
if (ctx.callbackQuery.data === 'yes') {
|
||||
console.log('step 4');
|
||||
await ctx.answerCbQuery('yes');
|
||||
const data = ctx.wizard.state.data;
|
||||
const userId = ctx.from?.id;
|
||||
const chatId = ctx.callbackQuery.message.chat.id;
|
||||
const dataWithTgUsername = {
|
||||
...data,
|
||||
tgUsername: ctx.from?.username,
|
||||
chatId,
|
||||
};
|
||||
|
||||
updateData({ userId: userId?.toString() ?? '', ...dataWithTgUsername });
|
||||
await ctx.reply(
|
||||
`Спасибо за регистрацию! Мы свяжемся с тобой в ближайшее время.`,
|
||||
);
|
||||
return ctx.scene.leave();
|
||||
}
|
||||
await ctx.reply(
|
||||
'Что-то пошло не так, попробуй выбрать один из предложенных вариантов',
|
||||
);
|
||||
return ctx.wizard.selectStep(3);
|
||||
},
|
||||
);
|
||||
|
||||
const stage = new Stage([superWizard]);
|
||||
|
||||
const bot = new Telegraf(BOT_TOKEN);
|
||||
bot.use(session());
|
||||
bot.use(stage.middleware());
|
||||
bot.command('add_to_team', (ctx) => {
|
||||
// @ts-expect-error wtf
|
||||
ctx.scene.enter('add_to_team_wizard');
|
||||
});
|
||||
|
||||
void bot.launch();
|
||||
|
||||
process.once('SIGINT', () => bot.stop('SIGINT'));
|
||||
process.once('SIGTERM', () => bot.stop('SIGTERM'));
|
||||
|
||||
function updateData({ ...rest }: UserData) {
|
||||
const data = fs.readFileSync('./data.json', 'utf8');
|
||||
const dataObj = JSON.parse(data) as Data;
|
||||
dataObj[rest.userId] = rest;
|
||||
const newDataStr = JSON.stringify(dataObj);
|
||||
fs.writeFileSync('./data.json', newDataStr, 'utf8');
|
||||
}
|
||||
60
src/send-group-info.ts
Normal file
60
src/send-group-info.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import dotenv from 'dotenv';
|
||||
import { Telegraf } from 'telegraf';
|
||||
import * as fs from 'fs';
|
||||
import { UserData } from './types.js';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const BOT_TOKEN = process.env.BOT_TOKEN;
|
||||
|
||||
if (!BOT_TOKEN) {
|
||||
throw new Error('BOT_TOKEN is required!');
|
||||
}
|
||||
|
||||
const bot = new Telegraf(BOT_TOKEN);
|
||||
|
||||
const data = fs.readFileSync('./groups.json', 'utf8');
|
||||
const userData = JSON.parse(data) as UserData[][];
|
||||
userData.forEach((group) => {
|
||||
group.forEach((user, i, arr) => {
|
||||
const otherUsers = group.filter((u) => u.userId !== user.userId);
|
||||
if (otherUsers.length === 0) {
|
||||
bot.telegram.sendMessage(
|
||||
user.chatId,
|
||||
'К сожалению, в твою группу не попал никто.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
let message = `Привет, ${user.name}! Твои напарники:\n\n${otherUsers
|
||||
.map(
|
||||
(u) =>
|
||||
`- <a href="tg://user?id=${u.userId}">${u.name}</a> @${
|
||||
u.tgUsername
|
||||
}. Время: ${getAvailableTime(
|
||||
u.availableTime.from,
|
||||
u.availableTime.to,
|
||||
)}`,
|
||||
)
|
||||
.join(' \n')}`;
|
||||
|
||||
if (i === 0) {
|
||||
message +=
|
||||
'\n\nТебя выбрали ответственным(ой) за первоначальную коммуникацию. Создай, пожалуйста, группу в телеграме и пригласи в нее своих напарников.';
|
||||
} else {
|
||||
message += `\n\n${arr[0].name} был(а) выбран(а) ответственным за первоначальную коммуникацию. Он(а) создаст группу в телеграме и пригласит в нее всех участников.`;
|
||||
}
|
||||
bot.telegram.sendMessage(user.chatId, message, { parse_mode: 'HTML' });
|
||||
});
|
||||
});
|
||||
|
||||
process.once('SIGINT', () => bot.stop('SIGINT'));
|
||||
process.once('SIGTERM', () => bot.stop('SIGTERM'));
|
||||
|
||||
function getAvailableTime(from: number, to: number | null) {
|
||||
if (from === 0 && to === 10) return 'До 10 часов';
|
||||
if (from === 10 && to === 20) return '10-20 часов';
|
||||
if (from === 20 && to === 30) return '20-30 часов';
|
||||
if (from === 30 && to === 40) return '30-40 часов';
|
||||
if (from === 40) return 'Более 40 часов';
|
||||
return 'Unknown time';
|
||||
}
|
||||
9
src/types.ts
Normal file
9
src/types.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
export type UserData = {
|
||||
name: string;
|
||||
availableTime: { from: number; to: number | null };
|
||||
tgUsername: string;
|
||||
userId: string;
|
||||
chatId: string;
|
||||
};
|
||||
|
||||
export type Data = Record<string, UserData>;
|
||||
23
tsconfig.json
Normal file
23
tsconfig.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es2022",
|
||||
"module": "node16",
|
||||
"lib": ["ES2022"],
|
||||
"moduleResolution": "node16",
|
||||
"rootDir": ".",
|
||||
"outDir": "build",
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"importHelpers": true,
|
||||
"alwaysStrict": true,
|
||||
"sourceMap": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noImplicitReturns": true,
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false,
|
||||
"noImplicitAny": false,
|
||||
"noImplicitThis": false,
|
||||
"strictNullChecks": false
|
||||
},
|
||||
"include": ["src/**/*", "__tests__/**/*"]
|
||||
}
|
||||
8
tsconfig.release.json
Normal file
8
tsconfig.release.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"sourceMap": false,
|
||||
"removeComments": true
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
Reference in New Issue
Block a user