├── .dockerignore ├── .editorconfig ├── .gitattributes ├── .github ├── dependabot.yml └── workflows │ ├── container.yml │ └── nodejs.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── botfather-settings ├── description.txt ├── inline_placeholder.txt ├── share_text.txt └── userpic.svg ├── init-debug-environment.sh ├── locales └── de.ftl ├── package-lock.json ├── package.json ├── source ├── hawhh-calendarbot-telegrambot.ts ├── lib │ ├── all-events.ts │ ├── async.ts │ ├── calendar-helper.ts │ ├── change-helper.ts │ ├── chatconfig.ts │ ├── event-creation-menu-options.ts │ ├── inline-menu-filter.ts │ ├── inline-menu.ts │ ├── meal.ts │ ├── mensa-git.ts │ ├── mensa-helper.filter-meals.test.ts │ ├── mensa-helper.generate-meal-text.test.ts │ ├── mensa-helper.meal-to-html.test.ts │ ├── mensa-helper.ts │ ├── mensa-meals.ts │ ├── telegram-broadcast.ts │ └── types.ts ├── menu │ ├── about.ts │ ├── admin │ │ ├── broadcast.ts │ │ ├── index.ts │ │ └── user-quicklook.ts │ ├── data.ts │ ├── events │ │ ├── add.ts │ │ ├── changes │ │ │ ├── add │ │ │ │ ├── date-selector.ts │ │ │ │ ├── index.ts │ │ │ │ └── time-selector.ts │ │ │ ├── details.ts │ │ │ └── index.ts │ │ ├── details.ts │ │ └── index.ts │ ├── index.ts │ ├── mensa │ │ ├── index.ts │ │ └── settings.ts │ └── subscribe │ │ ├── index.ts │ │ ├── removed-style.ts │ │ └── suffix.ts ├── migrate-stuff.ts └── parts │ ├── changes-inline.ts │ └── easter-eggs.ts └── tsconfig.json /.dockerignore: -------------------------------------------------------------------------------- 1 | .* 2 | *.md 3 | **/*.test.* 4 | **/test.* 5 | dist 6 | Dockerfile 7 | node_modules 8 | test 9 | 10 | botfather-settings 11 | init-debug-environment.sh 12 | 13 | # botfiles 14 | additionalEvents 15 | eventfiles 16 | meals 17 | mensa-data 18 | userconfig 19 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | [*] 2 | charset = utf-8 3 | end_of_line = lf 4 | indent_style = tab 5 | insert_final_newline = true 6 | trim_trailing_whitespace = true 7 | 8 | # https://projectfluent.org/ 9 | [*.ftl] 10 | indent_size = 2 11 | indent_style = space 12 | 13 | [*.{yml,yaml}] 14 | indent_size = 2 15 | indent_style = space 16 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # Please see the documentation for all configuration options: 2 | # https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file 3 | 4 | version: 2 5 | updates: 6 | - package-ecosystem: "npm" 7 | directory: "/" 8 | open-pull-requests-limit: 30 9 | versioning-strategy: increase 10 | schedule: 11 | interval: "monthly" 12 | time: "02:42" # UTC 13 | commit-message: 14 | prefix: "build(npm):" 15 | groups: 16 | patches: 17 | update-types: ["patch"] 18 | ignore: 19 | - dependency-name: "@types/node" 20 | update-types: ["version-update:semver-major"] 21 | -------------------------------------------------------------------------------- /.github/workflows/container.yml: -------------------------------------------------------------------------------- 1 | name: Build container 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | tags: 8 | - v* 9 | workflow_dispatch: 10 | # Build regularly in order to have up to date base image in the edge image 11 | schedule: 12 | - cron: '42 2 * * 6' # weekly on Saturday 2:42 UTC 13 | 14 | concurrency: 15 | group: ${{ github.workflow }}-${{ github.ref }} 16 | cancel-in-progress: true 17 | 18 | permissions: 19 | contents: read 20 | packages: write 21 | 22 | jobs: 23 | docker: 24 | runs-on: ubuntu-latest 25 | steps: 26 | - uses: docker/metadata-action@v5 27 | id: meta 28 | with: 29 | images: | 30 | ghcr.io/${{ github.repository }} 31 | tags: | 32 | type=edge 33 | type=semver,pattern={{version}} 34 | type=semver,pattern={{major}}.{{minor}} 35 | type=semver,pattern={{major}},enable=${{ !startsWith(github.ref, 'refs/tags/v0.') }} 36 | 37 | - uses: docker/setup-qemu-action@v3 38 | - uses: docker/setup-buildx-action@v3 39 | 40 | - name: Login to GHCR 41 | uses: docker/login-action@v3 42 | with: 43 | registry: ghcr.io 44 | username: ${{ github.repository_owner }} 45 | password: ${{ secrets.GITHUB_TOKEN }} 46 | 47 | - uses: docker/build-push-action@v6 48 | with: 49 | platforms: linux/amd64, linux/arm64/v8 50 | push: true 51 | tags: ${{ steps.meta.outputs.tags }} 52 | labels: ${{ steps.meta.outputs.labels }} 53 | -------------------------------------------------------------------------------- /.github/workflows/nodejs.yml: -------------------------------------------------------------------------------- 1 | name: Node.js 2 | 3 | on: 4 | push: 5 | pull_request: 6 | workflow_dispatch: 7 | 8 | jobs: 9 | test: 10 | name: Node.js 11 | runs-on: ubuntu-latest 12 | timeout-minutes: 15 13 | steps: 14 | - uses: actions/setup-node@v4 15 | with: 16 | node-version: 22 17 | - uses: actions/checkout@v4 18 | - run: npm ci 19 | - run: npm test 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | botfather-settings/userpic.png 2 | 3 | # node 4 | dist 5 | node_modules 6 | 7 | # botfiles 8 | additionalEvents 9 | eventfiles 10 | meals 11 | mensa-data 12 | userconfig 13 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM docker.io/library/node:22-alpine AS builder 2 | RUN apk upgrade --no-cache 3 | WORKDIR /build 4 | COPY package.json package-lock.json ./ 5 | RUN npm ci --no-audit --no-fund --no-update-notifier 6 | COPY . ./ 7 | RUN node_modules/.bin/tsc 8 | 9 | 10 | FROM docker.io/library/node:22-alpine AS packages 11 | RUN apk upgrade --no-cache 12 | WORKDIR /build 13 | COPY package.json package-lock.json ./ 14 | RUN npm ci --no-audit --no-fund --no-update-notifier --omit=dev 15 | 16 | 17 | FROM docker.io/library/alpine:3.21 AS final 18 | RUN apk upgrade --no-cache \ 19 | && apk add --no-cache nodejs git 20 | 21 | WORKDIR /app 22 | ENV NODE_ENV=production 23 | ENV TZ=Europe/Berlin 24 | VOLUME /app/eventfiles 25 | VOLUME /app/mensa-data 26 | VOLUME /app/userconfig 27 | 28 | COPY package.json ./ 29 | COPY --from=packages /build/node_modules ./node_modules 30 | COPY locales locales 31 | COPY --from=builder /build/dist ./ 32 | 33 | ENTRYPOINT ["node", "--enable-source-maps"] 34 | CMD ["hawhh-calendarbot-telegrambot.js"] 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HAW HH Kalender Bot 2 | 3 | ## Telegram Bot 4 | 5 | See more at 6 | -------------------------------------------------------------------------------- /botfather-settings/description.txt: -------------------------------------------------------------------------------- 1 | Mit diesem Bot kannst du dir deinen eigenen, auf dich abgestimmten Kalender von HAW Vorlesungen erstellen. 2 | 3 | Erstellt von @EdJoPaTo 4 | 5 | -------------------------------------------------------------------------------- /botfather-settings/inline_placeholder.txt: -------------------------------------------------------------------------------- 1 | Durchsuche deine Veranstaltungsänderungen… 2 | -------------------------------------------------------------------------------- /botfather-settings/share_text.txt: -------------------------------------------------------------------------------- 1 | Lasse dir einen auf dich abgestimmten HAW Vorlesungs-Kalender erstellen! Bot von @EdJoPaTo 2 | -------------------------------------------------------------------------------- /botfather-settings/userpic.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /init-debug-environment.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | 4 | # assumes other repos were cloned next to this repo (and executed) 5 | ln -rfs ../downloader/eventfiles . 6 | ln -rfs ../mensa-data . 7 | 8 | mkdir -p userconfig 9 | -------------------------------------------------------------------------------- /locales/de.ftl: -------------------------------------------------------------------------------- 1 | help = 2 | Dieser Bot hilft dir bei deinem Vorlesungskalender. 3 | Trage unter /events deine Vorlesungen ein, die du dieses Semester besuchen wirst. Daraus wird ein Kalender für dich generiert, den du mit deinen Geräten abbonieren kannst. Anleitungen für dein Gerät gibts unter /subscribe. 4 | 5 | Wenn Veranstaltungen ausfallen oder sich ändern kannst du diese zur jeweiligen Veranstaltung ebenfalls unter /events eintragen. Diese Änderungen werden dann automatisch mit in deinen Kalender übernommen. Außerdem lassen sich die Änderungen teilen, sodass du auch anderen Leuten diese Änderung bereitstellen kannst. 6 | 7 | Unter /mensa gibts die Hamburger Mensen zur Auswahl, mittels /about findest du Statistiken über diesen Bot und unter /privacy kannst du die über dich gespeicherten Daten einsehen. 8 | 9 | changes-help = 10 | Wenn sich eine Änderung an einer Veranstaltung ergibt, die nicht in den offiziellen Veranstaltungsplan eingetragen wird, kannst du diese hier nachtragen. Dein Kalender wird dann automatisch aktualisiert und du hast die Änderung in deinem Kalender. 11 | Außerdem lassen sich die Änderungen teilen, sodass du auch anderen Leuten diese Änderung bereitstellen kannst. 12 | 13 | ⚠️ Du bist in der Lage, unlogische Veranstaltungstermine zu kreieren. Beispielsweise kannst du einen Termin so verändern, dass dieser aufhört bevor er beginnt. Den Bot interessiert das nicht und tut nur genau das, was du sagst. Dein Kalenderprogramm ist damit dann allerdings häufig nicht so glücklich… 14 | 15 | website-stalker-help = 16 | Der website-stalker prüft regelmäßig auf Änderungen an relevanten Webseiten. 17 | 18 | Hier wird beispielsweise StISys auf Änderungen betrachtet und wenn sich etwas ändert, kannst du direkt benachrichtigt werden. Folge dazu dem Telegram Kanal @HAWHHWebsiteStalker. 19 | 20 | Alternativ kannst du die Änderungen auch als RSS-Feed mit deinem Feedreader abonnieren. Abonniere dazu folgende URL: https://github.com/HAWHHCalendarBot/study-website-stalker/commits/main.atom 21 | 22 | privacy-overview = 23 | Auf dem Server wird geloggt, wenn Aktionen von Nutzern zu einem neu Bauen von Kalendern oder ungewollten Fehlern führen. Diese Logs werden nicht persistent gespeichert und sind nur bis zum Neustart des Servers verfügbar. 24 | Der Quellcode dieses Bots ist auf GitHub verfügbar. 25 | 26 | privacy-telegram = 27 | Jeder Telegram Bot kann diese User Infos abrufen, wenn du mit ihm interagierst. Um dies zu verhindern, blockiere den Bot. 28 | 29 | privacy-persistent = 30 | Damit dein Kalender generiert oder deine Mensa Einstellungen gespeichert werden können, werden einige Daten persistent auf dem Server hinterlegt. Wenn du alle Daten über dich löschen lassen möchtest, wähle "Alles löschen". 31 | 32 | privacy-tmp = 33 | Diese Daten werden nur temporär gehalten und sind nur bis zum Neustart des Servers im RAM hinterlegt. 34 | 35 | subscribe-overview = 36 | Kalender abonnieren 37 | Bitte wähle die Art aus, mit der du den Kalender abonnieren willst. 38 | 39 | Ich empfehle über iOS / macOS Boardmittel oder über den HAW-Mailer. 40 | 41 | subscribe-empty = 42 | ⚠️ Du hast aktuell keine Veranstaltungen in deinem Kalender! Füge zuerst Veranstaltungen über /events hinzu! 43 | 44 | subscribe-apple = 45 | Kalender abonnieren mit iOS / macOS 46 | Auf den ersten Button klicken und die URL in Safari öffnen. Auf der nun geöffneten Website auf das Kalender Icon klicken und bestätigen. Fertig. 47 | 48 | Unter macOS den Haken bei Remove Alerts herausnehmen, damit die Erinnerungen im Kalender bleiben und nicht entfernt werden. 49 | Unter iOS ist dies bereits der Standard und funktioniert direkt. 50 | 51 | subscribe-exchange = 52 | Kalender abonnieren mit Office.com HAW Account 53 | Im Office.com-Kalender links in der Menüleiste mittig auf "Kalender hinzufügen". Dann im aufgehenden Fenster links mittig auf "Aus dem Internet abbonieren". In das Textfeld "Beispiel: webcal://www.contoso.com/calendar.ics" die folgende URL einfügen: 54 | https://{$url} 55 | 56 | Der Kalender wird nun alle paar Stunden von Office.com aktualisiert. Wenn du dein Handy mit dem Office.com Account (Exchange) synchronisierst, ist der Kalender ebenfalls enthalten. Funktioniert mit iOS, Android und Gnome Online Accounts sehr entspannt und du hast gleich deine HAW E-Mails mit dabei. 57 | 58 | Erinnerungen scheinen nicht zu funktionieren, da diese automatisch beim Abonnieren entfernt werden. Ein Deaktivieren des automatischen Löschens dieser habe ich leider bisher nicht gefunden. Hinweise gern an @EdJoPaTo 😇 59 | 60 | subscribe-google = 61 | Kalender abonnieren mit dem Google Kalender 62 | ⚠️ Der Google Kalender ist manchmal etwas… anstrengend. Erklärung unten. 63 | 🔅 Alternativvorschlag: Kannst du vielleicht auch über den HAW-Mailer synchronisieren? Dann hast du auch gleich deine HAW E-Mails. 64 | 65 | In der linken Seitenleiste im Google Kalender gibt es den Eintrag "Weitere Kalender". Dort auf das kleine Dropdown Dreieck klicken und den Menüpunkt "per URL" auswählen. Hier muss die folgende URL hineinkopiert werden: 66 | https://{$url} 67 | 68 | Nach dem Bestätigen einen Moment warten, bis der Kalender im Google Kalender erschienen ist. 69 | 70 | Wenn dein Kalender "@HAWHHCalendarBot ({$firstname})" heißt, wie er eigentlich heißen soll, bist du ein glücklicher Sonderfall Googles und du bist fertig. Wenn dein Kalender jedoch den Namen der URL trägt, muss der Kalender umbenannt werden, damit dieser auf Android-Geräte synchronisiert wird. Verwende einen einfachen Namen dafür, den Google nicht überfordernd findet. 71 | 72 | Fun Fact: Auf iOS-Geräte wird der Google Kalender unabhängig vom Namen fehlerfrei synchronisiert. 73 | 74 | Erinnerungen scheinen nicht zu funktionieren, da diese automatisch beim Abonnieren entfernt werden. Ein Deaktivieren des automatischen Löschens dieser habe ich leider bisher nicht gefunden. Hinweise gern an @EdJoPaTo 😇 75 | 76 | ⚠️ In der Vergangenheit hat der Google Kalender jeweils zwischen 30 Minuten und 40 Stunden gebraucht, um einen Kalender zu aktualisieren. Außerdem cacht Google (meiner Meinung nach) ein wenig zu viel, was für teilweise interessantes/sonderbares Verhalten gesorgt hat. 77 | 78 | subscribe-freestyle = 79 | Kalender abonnieren Freestyle Edition 😎 80 | Wenn dein Kalender Standards unterstützt, benutz den ersten Button an dieser Nachricht und öffne die Website. 81 | Klicke auf das Kalender Icon. Der Browser fragt nun, mit welchem Tool der webcal:// Link geöffnet werden soll. Wähle dein Kalenderprogramm. 82 | 83 | Wenn das nicht funktioniert, finde einen Weg die folgende URL zu abonnieren. Achte dabei darauf, das du nicht importierst, sondern abonnierst. Nur dann aktualisiert sich der Kalender selbstständig bei Änderungen im Bot. 84 | https://{$url} 85 | 86 | Viel Erfolg 😎 87 | 88 | subscribe-suffix = 89 | Die Kalender liegen für jeden frei zugänglich im Internet. Wenn die URL nur aus deiner Telegram Nutzer ID ({$userId}) bestehen würde, könnte jeder mit dieser ID deinen Kalender einsehen. 90 | Wird der URL eine zufällige Zeichenkette angefügt (aktuell {$calendarfileSuffix}), muss diese erraten werden und erhöht so deine Privatsphäre. Eine Zeichenkette, die deiner Kalender URL angefügt wird, kannst du entweder generieren lassen (Generieren…) oder Manuell setzen…. Jedoch musst du nach jedem Ändern dieser Einstellung deinen Kalender neu abonnieren, da sich die URL ändert. 91 | 92 | Deine Nutzer ID ({$userId}) ist nicht deine Telefonnummer oder Teil deines Usernamens und innerhalb von Telegram eindeutig. Wenn man eine Nachricht von dir hat oder in einer Gruppe mit dir ist, kann man deine Nutzer ID erhalten. 93 | 94 | Deine URL lautet: 95 | https://{$url} 96 | 97 | subscribe-removed-setting = 98 | Anzeigeart entfernter Termine 99 | 100 | Veranstaltungsänderungen, die du mit diesem Bot anlegst, können Termine entfernen. Diese ausfallenden Termine werden nach dem iCal Standard mit dem Status CANCELLED markiert. Jedoch arbeiten nicht alle Kalendertools standardkonform 🙄. 101 | 102 | Der iOS und macOS Systemkalender halten sich an den Standard. Hier solltest du Standard wählen. 103 | Veranstaltungen können in den jeweiligen Einstellungen vom Kalendertool ein- oder ausgeblendet werden. 104 | Der Google Kalender ist nicht in der Lage, entfernte Veranstaltungen einzublenden. Sie werden immer ausgeblendet. Um diese trotzdem anzuzeigen, wähle erzwungen oder bleibe bei Standard. 105 | Der Exchange Kalender ignoriert den Status und zeigt die Veranstaltung an, als wäre nichts gewesen. Du kannst diese Veranstaltungen komplett entfernen oder erzwingen. 106 | 107 | 👌 Standard: Der erzeugte Kalender wird standardkonform sein. 108 | 🗑 komplett entfernen: Der erzeugte Kalender enthält keine entfernten Veranstaltungen mehr. Du kannst nur noch im Bot sehen, welche Veranstaltungen ausfallen. 109 | 🚫 erzwungen: Die Veranstaltung wird auf jeden Fall angezeigt und der Name enthält den 🚫 Emoji. 110 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "hawhh-calendarbot-telegrambot", 3 | "version": "9.4.3", 4 | "private": true, 5 | "license": "AGPL-3.0-or-later", 6 | "repository": { 7 | "type": "git", 8 | "url": "https://github.com/HAWHHCalendarBot/telegrambot.git" 9 | }, 10 | "scripts": { 11 | "start": "tsc && node --enable-source-maps dist/hawhh-calendarbot-telegrambot.js", 12 | "test": "tsc && xo && node --enable-source-maps --test" 13 | }, 14 | "type": "module", 15 | "engines": { 16 | "node": ">=20" 17 | }, 18 | "dependencies": { 19 | "@grammyjs/i18n": "^1.1.2", 20 | "@grammyjs/stateless-question": "^4.0.0", 21 | "array-filter-unique": "^3.0.0", 22 | "grammy": "^1.36.1", 23 | "grammy-inline-menu": "^9.2.0", 24 | "json-stable-stringify": "^1.3.0", 25 | "telegraf-middleware-console-time": "^3.0.0", 26 | "telegram-format": "^3.1.0" 27 | }, 28 | "devDependencies": { 29 | "@sindresorhus/tsconfig": "^7.0.0", 30 | "@types/node": "^20.17.32", 31 | "typescript": "^5.8.3", 32 | "xo": "^0.60.0" 33 | }, 34 | "xo": { 35 | "rules": { 36 | "unicorn/prevent-abbreviations": "off", 37 | "@typescript-eslint/naming-convention": "off" 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /source/hawhh-calendarbot-telegrambot.ts: -------------------------------------------------------------------------------- 1 | import {env} from 'node:process'; 2 | import {I18n} from '@grammyjs/i18n'; 3 | import {Bot, session} from 'grammy'; 4 | import {generateUpdateMiddleware} from 'telegraf-middleware-console-time'; 5 | import {html as format} from 'telegram-format'; 6 | import {Chatconfig} from './lib/chatconfig.js'; 7 | import type {MyContext, Session} from './lib/types.js'; 8 | import {bot as menu} from './menu/index.js'; 9 | import {bot as migrateStuffBot} from './migrate-stuff.js'; 10 | import * as changesInline from './parts/changes-inline.js'; 11 | import * as easterEggs from './parts/easter-eggs.js'; 12 | 13 | const token = env['BOT_TOKEN']; 14 | if (!token) { 15 | throw new Error( 16 | 'You have to provide the bot-token from @BotFather via environment variable (BOT_TOKEN)', 17 | ); 18 | } 19 | 20 | const baseBot = new Bot(token); 21 | 22 | if (env['NODE_ENV'] !== 'production') { 23 | baseBot.use(generateUpdateMiddleware()); 24 | } 25 | 26 | const bot = baseBot.errorBoundary(async ({error, ctx}) => { 27 | if (error instanceof Error && error.message.includes('Too Many Requests')) { 28 | console.warn('grammY Too Many Requests error. Skip.', error); 29 | return; 30 | } 31 | 32 | console.error( 33 | 'try to send error to user', 34 | ctx.update, 35 | error, 36 | (error as any)?.on?.payload, 37 | ); 38 | let text = `🔥 Da ist wohl ein Fehler aufgetreten… 39 | 40 | Schreib mal @EdJoPaTo dazu an oder erstell ein ${ 41 | format.url( 42 | 'Issue auf GitHub', 43 | 'https://github.com/HAWHHCalendarBot/TelegramBot/issues', 44 | ) 45 | }. Dafür findet sich sicher eine Lösung. ☺️ 46 | 47 | Error: `; 48 | 49 | const errorText = error instanceof Error ? error.message : String(error); 50 | text += format.monospace(errorText.replaceAll(token, '')); 51 | 52 | const target = (ctx.chat ?? ctx.from!).id; 53 | await ctx.api.sendMessage(target, text, { 54 | link_preview_options: {is_disabled: true}, 55 | parse_mode: format.parse_mode, 56 | }); 57 | }); 58 | 59 | export const i18n = new I18n({ 60 | defaultLocale: 'de', 61 | directory: 'locales', 62 | }); 63 | bot.use(i18n); 64 | 65 | async function startMessage(ctx: MyContext) { 66 | const name = ctx.from?.first_name ?? 'du'; 67 | let text = `Hey ${name}!`; 68 | text += '\n\n'; 69 | text += ctx.t('help'); 70 | await ctx.reply(text, { 71 | reply_markup: { 72 | inline_keyboard: [ 73 | [{ 74 | text: 'hawhh.de/calendarbot/', 75 | url: 'https://hawhh.de/calendarbot/', 76 | }], 77 | [{text: '🦑 Quellcode', url: 'https://github.com/HAWHHCalendarBot'}], 78 | ], 79 | }, 80 | }); 81 | } 82 | 83 | bot.command(['start', 'help'], startMessage); 84 | 85 | bot.use(session({ 86 | initial() { 87 | return {}; 88 | }, 89 | })); 90 | 91 | const chatconfig = new Chatconfig('userconfig'); 92 | bot.use(chatconfig); 93 | 94 | bot.use(migrateStuffBot); 95 | 96 | bot.use(changesInline.bot); 97 | bot.use(easterEggs.bot); 98 | 99 | bot.use(menu); 100 | 101 | // Fallback for the old main menu 102 | bot.callbackQuery(/^\//, async ctx => { 103 | await ctx.answerCallbackQuery(); 104 | await startMessage(ctx); 105 | }); 106 | 107 | const COMMANDS = { 108 | mensa: 'zeige das heutige Mensaessen deiner Mensa', 109 | events: 'verwalte deine aktuellen Veranstaltungen', 110 | subscribe: 'abboniere deinen persönlichen Kalender', 111 | help: 'kurze Beschreibung, was dieser Bot kann', 112 | about: 'Infos und Statistiken über den Bot', 113 | privacy: 'über dich gespeicherte Daten', 114 | stop: 'stoppe den Bot und lösche alle Daten über dich', 115 | } as const; 116 | await baseBot.api.setMyCommands( 117 | Object.entries(COMMANDS) 118 | .map(([command, description]) => ({command, description})), 119 | ); 120 | 121 | await baseBot.start({ 122 | onStart(botInfo) { 123 | console.log(new Date(), 'Bot starts as', botInfo.username); 124 | }, 125 | }); 126 | -------------------------------------------------------------------------------- /source/lib/all-events.ts: -------------------------------------------------------------------------------- 1 | import {readFile} from 'node:fs/promises'; 2 | 3 | async function getAll(): Promise { 4 | const data = await readFile('eventfiles/all.txt', 'utf8'); 5 | const list = data.split('\n').filter(element => element !== ''); 6 | return list; 7 | } 8 | 9 | export async function count(): Promise { 10 | const allEvents = await getAll(); 11 | return allEvents.length; 12 | } 13 | 14 | export async function exists(name: string): Promise { 15 | const allEvents = await getAll(); 16 | return allEvents.includes(name); 17 | } 18 | 19 | export async function nonExisting(names: readonly string[]): Promise { 20 | const allEvents = new Set(await getAll()); 21 | const result: string[] = []; 22 | for (const event of names) { 23 | if (!allEvents.has(event)) { 24 | result.push(event); 25 | } 26 | } 27 | 28 | return result; 29 | } 30 | 31 | export async function find( 32 | pattern: string | RegExp, 33 | ignore: readonly string[] = [], 34 | ): Promise { 35 | const allEvents = await getAll(); 36 | const regex = new RegExp(pattern, 'i'); 37 | const filtered = allEvents.filter(event => 38 | regex.test(event) && !ignore.includes(event), 39 | ); 40 | return filtered; 41 | } 42 | -------------------------------------------------------------------------------- /source/lib/async.ts: -------------------------------------------------------------------------------- 1 | export async function sequentialLoop( 2 | inputs: readonly Argument[], 3 | func: (input: Argument) => Promise, 4 | ): Promise { 5 | const results: Result[] = []; 6 | 7 | for (const arg of inputs) { 8 | // eslint-disable-next-line no-await-in-loop 9 | results.push(await func(arg)); 10 | } 11 | 12 | return results; 13 | } 14 | 15 | export async function sleep(ms: number): Promise { 16 | await new Promise(resolve => { 17 | setTimeout(resolve, ms); 18 | }); 19 | } 20 | -------------------------------------------------------------------------------- /source/lib/calendar-helper.ts: -------------------------------------------------------------------------------- 1 | import type {MyContext, Userconfig} from './types.js'; 2 | 3 | export function getUrl(id: number, userconfig: Userconfig): string { 4 | let filename = `${id}`; 5 | const {calendarfileSuffix} = userconfig; 6 | if (calendarfileSuffix) { 7 | filename += `-${calendarfileSuffix}`; 8 | } 9 | 10 | const full = `calendarbot.hawhh.de/tg/${filename}.ics`; 11 | return full; 12 | } 13 | 14 | export function getUrlFromContext(context: MyContext): string { 15 | return getUrl(context.from!.id, context.userconfig.mine); 16 | } 17 | 18 | export function formatDateToHumanReadable(isoDateString: string): string { 19 | const date = new Date(Date.parse(isoDateString + 'Z')); 20 | return date.toLocaleString('de-DE', { 21 | timeZone: 'Europe/Berlin', 22 | hour12: false, 23 | year: undefined, 24 | month: 'long', 25 | day: 'numeric', 26 | hour: 'numeric', 27 | minute: '2-digit', 28 | }); 29 | } 30 | 31 | export function formatDateToStoredChangeDate(date: Readonly): string { 32 | return date.toISOString().replace(/:\d{2}.\d{3}Z$/, ''); 33 | } 34 | 35 | export function parseDateTimeToDate(dateTime: string): Date { 36 | if (dateTime.includes('(')) { 37 | const unixTime = Number(/(\d+)\+/.exec(dateTime)![1]); 38 | const date = new Date(unixTime); 39 | return date; 40 | } 41 | 42 | return new Date(Date.parse(dateTime)); 43 | } 44 | -------------------------------------------------------------------------------- /source/lib/change-helper.ts: -------------------------------------------------------------------------------- 1 | import {readFile} from 'node:fs/promises'; 2 | import {html as format} from 'telegram-format'; 3 | import { 4 | formatDateToHumanReadable, 5 | parseDateTimeToDate, 6 | } from './calendar-helper.js'; 7 | import type { 8 | Change, 9 | EventEntryFileContent, 10 | EventEntryInternal, 11 | } from './types.js'; 12 | 13 | export function generateChangeDescription(change: Change): string { 14 | let text = ''; 15 | if (change.remove) { 16 | text += '🚫 Entfällt\n'; 17 | } 18 | 19 | if (change.namesuffix) { 20 | text += `🗯 Namenszusatz: ${change.namesuffix}\n`; 21 | } 22 | 23 | if (change.starttime) { 24 | text += `🕗 Startzeit: ${change.starttime}\n`; 25 | } 26 | 27 | if (change.endtime) { 28 | text += `🕓 Endzeit: ${change.endtime}\n`; 29 | } 30 | 31 | if (change.room) { 32 | text += `📍 Raum: ${change.room}\n`; 33 | } 34 | 35 | return text; 36 | } 37 | 38 | export function generateChangeText(change: Change): string { 39 | let text = generateChangeTextHeader(change); 40 | 41 | if (Object.keys(change).length > 2) { 42 | text += '\nÄnderungen:\n'; 43 | text += format.escape(generateChangeDescription(change)); 44 | } 45 | 46 | return text; 47 | } 48 | 49 | export function generateChangeTextHeader(change: Change): string { 50 | let text = ''; 51 | text += format.bold('Veranstaltungsänderung'); 52 | text += '\n'; 53 | text += format.bold(format.escape(change.name)); 54 | if (change.date) { 55 | text += ` ${formatDateToHumanReadable(change.date)}`; 56 | } 57 | 58 | text += '\n'; 59 | return text; 60 | } 61 | 62 | export function generateShortChangeText(change: Change): string { 63 | return `${change.name} ${formatDateToHumanReadable(change.date)}`; 64 | } 65 | 66 | export async function loadEvents( 67 | eventname: string, 68 | ): Promise { 69 | try { 70 | const filename = eventname.replaceAll('/', '-'); 71 | const content = await readFile(`eventfiles/${filename}.json`, 'utf8'); 72 | const array = JSON.parse(content) as EventEntryFileContent[]; 73 | const parsed = array.map((o): EventEntryInternal => ({ 74 | ...o, 75 | StartTime: parseDateTimeToDate(o.StartTime), 76 | EndTime: parseDateTimeToDate(o.EndTime), 77 | })); 78 | 79 | return parsed; 80 | } catch (error) { 81 | console.error('ERROR while loading events for change date picker', error); 82 | return []; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /source/lib/chatconfig.ts: -------------------------------------------------------------------------------- 1 | import { 2 | readdir, readFile, unlink, writeFile, 3 | } from 'node:fs/promises'; 4 | import type {Api, MiddlewareFn} from 'grammy'; 5 | import type {User} from 'grammy/types'; 6 | import stringify from 'json-stable-stringify'; 7 | import {sequentialLoop} from './async.js'; 8 | import * as telegramBroadcast from './telegram-broadcast.js'; 9 | import type {MyContext, OtherSendMessage, Userconfig} from './types.js'; 10 | 11 | type ChatConfigFileContent = { 12 | chat: User; 13 | config: Userconfig; 14 | }; 15 | 16 | export type ContextProperty = { 17 | readonly all: ( 18 | filter?: (o: ChatConfigFileContent) => boolean, 19 | ) => Promise; 20 | readonly allIds: () => Promise; 21 | readonly broadcast: ( 22 | text: string, 23 | extra: OtherSendMessage, 24 | filter?: (o: ChatConfigFileContent) => boolean, 25 | ) => Promise; 26 | readonly forwardBroadcast: ( 27 | originChat: string | number, 28 | messageId: number, 29 | filter?: (o: ChatConfigFileContent) => boolean, 30 | ) => Promise; 31 | readonly load: (id: number) => Promise; 32 | readonly loadConfig: (id: number) => Promise; 33 | 34 | // Data deletion will delete this property but thats only there and only in that place 35 | readonly mine: Userconfig; 36 | }; 37 | 38 | export class Chatconfig { 39 | constructor( 40 | public readonly folder: string, 41 | ) { 42 | // Creating the folder is not needed. It should already be there 43 | } 44 | 45 | middleware(): MiddlewareFn { 46 | return async (ctx, next) => { 47 | if (!ctx.from) { 48 | console.warn(new Date(), 'Chatconfig', 'ctx.from empty', ctx.update); 49 | return next(); 50 | } 51 | 52 | const wholeconfig = await this.load(ctx.from.id); 53 | const configOfUser = this.configFromWholeConfig(wholeconfig); 54 | 55 | const contextProperty: ContextProperty = { 56 | all: async (filter?: (o: ChatConfigFileContent) => boolean) => 57 | this.all(filter), 58 | allIds: async () => this.allIds(), 59 | broadcast: async ( 60 | text: string, 61 | extra: OtherSendMessage, 62 | filter?: (o: ChatConfigFileContent) => boolean, 63 | ) => this.broadcast(ctx.api, text, extra, filter), 64 | forwardBroadcast: async ( 65 | originChat: string | number, 66 | messageId: number, 67 | filter?: (o: ChatConfigFileContent) => boolean, 68 | ) => this.forwardBroadcast(ctx.api, originChat, messageId, filter), 69 | load: async (id: number) => this.load(id), 70 | loadConfig: async (id: number) => this.loadConfig(id), 71 | mine: configOfUser, 72 | }; 73 | 74 | // @ts-expect-error write to readonly 75 | ctx.userconfig = contextProperty; 76 | 77 | const before = stringify(ctx.userconfig.mine); 78 | await next(); 79 | if (!ctx.userconfig.mine) { 80 | console.log(new Date(), 'request to delete data', ctx.from); 81 | // Request to remove the userconfig 82 | return this.removeConfig(ctx.from.id); 83 | } 84 | 85 | const after = stringify(ctx.userconfig.mine); 86 | const userString = stringify(wholeconfig?.chat); 87 | const currentUserString = stringify(ctx.from); 88 | 89 | if (before !== after || userString !== currentUserString) { 90 | await this.saveConfig(ctx.from, ctx.userconfig.mine); 91 | } 92 | }; 93 | } 94 | 95 | async load(id: number): Promise { 96 | try { 97 | const content = await readFile( 98 | this.filenameFromId(id), 99 | 'utf8', 100 | ); 101 | return JSON.parse(content) as ChatConfigFileContent; 102 | } catch { 103 | return undefined; 104 | } 105 | } 106 | 107 | async loadConfig(id: number): Promise { 108 | const content = await this.load(id); 109 | return this.configFromWholeConfig(content); 110 | } 111 | 112 | async saveConfig(from: User, config: Userconfig): Promise { 113 | const json: ChatConfigFileContent = { 114 | chat: from, 115 | config, 116 | }; 117 | 118 | await writeFile( 119 | this.filenameFromId(from.id), 120 | stringify(json, {space: 2}) + '\n', 121 | 'utf8', 122 | ); 123 | } 124 | 125 | async removeConfig(id: number): Promise { 126 | await unlink(this.filenameFromId(id)); 127 | } 128 | 129 | async allIds(): Promise { 130 | const files = await readdir(this.folder); 131 | const ids = files 132 | .map(s => s.replace('.json', '')) 133 | .map(Number); 134 | return ids; 135 | } 136 | 137 | async all( 138 | filter: (o: ChatConfigFileContent) => boolean = () => true, 139 | ): Promise { 140 | const ids = await this.allIds(); 141 | 142 | const fileContents = await Promise.all( 143 | ids.map(async id => readFile(this.filenameFromId(id), 'utf8')), 144 | ); 145 | 146 | const configs = fileContents 147 | .map(o => JSON.parse(o) as ChatConfigFileContent) 148 | .filter(o => filter(o)); 149 | 150 | return configs; 151 | } 152 | 153 | async broadcast( 154 | telegram: Api, 155 | text: string, 156 | extra: OtherSendMessage, 157 | filter: (o: ChatConfigFileContent) => boolean = () => true, 158 | ): Promise { 159 | const allConfigs = await this.all(filter); 160 | const allIds = allConfigs.map(config => config.chat.id); 161 | const failedIds = await telegramBroadcast.broadcast( 162 | telegram, 163 | allIds, 164 | text, 165 | extra, 166 | ); 167 | await sequentialLoop(failedIds, async id => this.removeConfig(id)); 168 | } 169 | 170 | async forwardBroadcast( 171 | telegram: Api, 172 | originChat: string | number, 173 | messageId: number, 174 | filter: (o: ChatConfigFileContent) => boolean = () => true, 175 | ): Promise { 176 | const allConfigs = await this.all(filter); 177 | const allIds = allConfigs.map(config => config.chat.id); 178 | const failedIds = await telegramBroadcast.forwardBroadcast( 179 | telegram, 180 | allIds, 181 | originChat, 182 | messageId, 183 | ); 184 | await sequentialLoop(failedIds, async id => this.removeConfig(id)); 185 | } 186 | 187 | private filenameFromId(id: number): string { 188 | return `${this.folder}/${id}.json`; 189 | } 190 | 191 | private configFromWholeConfig( 192 | content: ChatConfigFileContent | undefined, 193 | ): Userconfig { 194 | const config: Userconfig = content?.config ?? { 195 | calendarfileSuffix: '', 196 | changes: [], 197 | events: {}, 198 | mensa: {}, 199 | }; 200 | return {...config}; 201 | } 202 | } 203 | -------------------------------------------------------------------------------- /source/lib/event-creation-menu-options.ts: -------------------------------------------------------------------------------- 1 | function generateNumberArray( 2 | start: number, 3 | end: number, 4 | interval = 1, 5 | ): number[] { 6 | const array: number[] = []; 7 | for (let i = start; i <= end; i += interval) { 8 | array.push(i); 9 | } 10 | 11 | return array; 12 | } 13 | 14 | export const MONTH_NAMES = [ 15 | 'Januar', 16 | 'Februar', 17 | 'März', 18 | 'April', 19 | 'Mai', 20 | 'Juni', 21 | 'Juli', 22 | 'August', 23 | 'September', 24 | 'Oktober', 25 | 'November', 26 | 'Dezember', 27 | ] as const; 28 | export type MonthName = typeof MONTH_NAMES[number]; 29 | 30 | export const DAY_OPTIONS: readonly number[] = generateNumberArray(1, 31); 31 | export const HOUR_OPTIONS: readonly number[] = generateNumberArray(7, 21); 32 | export const MINUTE_OPTIONS: readonly number[] = generateNumberArray(0, 55, 5); 33 | 34 | export const MONTH_OPTIONS = Object.fromEntries( 35 | MONTH_NAMES.map((name, i) => [i + 1, name]), 36 | ) as Readonly>; 37 | 38 | export function generateYearOptions() { 39 | const currentYear = new Date(Date.now()).getFullYear(); 40 | return generateNumberArray(currentYear - 1, currentYear + 1); 41 | } 42 | -------------------------------------------------------------------------------- /source/lib/inline-menu-filter.ts: -------------------------------------------------------------------------------- 1 | export const DEFAULT_FILTER = '.+'; 2 | 3 | export function filterButtonText( 4 | getCurrentFilterFunction: (context: T) => string | undefined, 5 | ): (context: T) => string { 6 | return context => { 7 | let text = '🔎 Filter'; 8 | const currentFilter = getCurrentFilterFunction(context); 9 | if (currentFilter && currentFilter !== '.+') { 10 | text += ': ' + currentFilter; 11 | } 12 | 13 | return text; 14 | }; 15 | } 16 | -------------------------------------------------------------------------------- /source/lib/inline-menu.ts: -------------------------------------------------------------------------------- 1 | import {createBackMainMenuButtons} from 'grammy-inline-menu'; 2 | 3 | export const BACK_BUTTON_TEXT = '🔙 zurück…'; 4 | 5 | export const backMainButtons = createBackMainMenuButtons( 6 | BACK_BUTTON_TEXT, 7 | '🔝 zum Hauptmenü', 8 | ); 9 | -------------------------------------------------------------------------------- /source/lib/meal.ts: -------------------------------------------------------------------------------- 1 | // See: https://github.com/HAWHHCalendarBot/mensa-crawler/blob/main/src/meal.rs 2 | type PriceInEuro = number; 3 | 4 | export type MealPrices = { 5 | readonly PriceAttendant: PriceInEuro; 6 | readonly PriceGuest: PriceInEuro; 7 | readonly PriceStudent: PriceInEuro; 8 | }; 9 | 10 | export type MealContents = { 11 | readonly Alcohol?: boolean; 12 | readonly Beef?: boolean; 13 | readonly Fish?: boolean; 14 | readonly Game?: boolean; 15 | readonly Gelatine?: boolean; 16 | readonly LactoseFree?: boolean; 17 | readonly Lamb?: boolean; 18 | readonly Pig?: boolean; 19 | readonly Poultry?: boolean; 20 | readonly Vegan?: boolean; 21 | readonly Vegetarian?: boolean; 22 | }; 23 | 24 | export type Meal = MealContents & MealPrices & { 25 | readonly Name: string; 26 | readonly Category: string; 27 | readonly Date: `${number}-${number}-${number}`; 28 | readonly Additives: Readonly>; 29 | }; 30 | -------------------------------------------------------------------------------- /source/lib/mensa-git.ts: -------------------------------------------------------------------------------- 1 | import {exec} from 'node:child_process'; 2 | import {existsSync} from 'node:fs'; 3 | import {promisify} from 'node:util'; 4 | 5 | const run = promisify(exec); 6 | 7 | export async function pull(): Promise { 8 | try { 9 | if (existsSync('mensa-data/.git')) { 10 | await run('git -C mensa-data pull'); 11 | } else { 12 | await run( 13 | 'git clone -q --depth 1 https://github.com/HAWHHCalendarBot/mensa-data.git mensa-data', 14 | ); 15 | } 16 | } catch {} 17 | } 18 | -------------------------------------------------------------------------------- /source/lib/mensa-helper.filter-meals.test.ts: -------------------------------------------------------------------------------- 1 | import {deepStrictEqual, strictEqual} from 'node:assert'; 2 | import {test} from 'node:test'; 3 | import type {Meal} from './meal.js'; 4 | import {filterMeals} from './mensa-helper.js'; 5 | 6 | const BASE_MEAL = { 7 | Additives: {}, 8 | Category: 'Test Meal', 9 | Date: '2021-05-18', 10 | PriceAttendant: 0, 11 | PriceGuest: 0, 12 | PriceStudent: 0, 13 | } as const; 14 | 15 | const TEST_MEALS = [ 16 | { 17 | ...BASE_MEAL, 18 | Alcohol: false, 19 | Beef: false, 20 | Fish: true, 21 | LactoseFree: false, 22 | Name: 'Fisch', 23 | Pig: false, 24 | Poultry: false, 25 | Vegan: false, 26 | Vegetarian: false, 27 | }, 28 | { 29 | ...BASE_MEAL, 30 | Alcohol: false, 31 | Beef: false, 32 | Fish: false, 33 | LactoseFree: false, 34 | Name: 'Pasta Sahne', 35 | Pig: false, 36 | Poultry: false, 37 | Vegan: false, 38 | Vegetarian: true, 39 | }, 40 | { 41 | ...BASE_MEAL, 42 | Alcohol: false, 43 | Beef: false, 44 | Fish: false, 45 | LactoseFree: false, 46 | Name: 'Pasta Speck', 47 | Pig: true, 48 | Poultry: false, 49 | Vegan: false, 50 | Vegetarian: false, 51 | }, 52 | { 53 | ...BASE_MEAL, 54 | Alcohol: false, 55 | Beef: false, 56 | Fish: false, 57 | LactoseFree: true, 58 | Name: 'Pasta', 59 | Pig: false, 60 | Poultry: false, 61 | Vegan: true, 62 | Vegetarian: false, 63 | }, 64 | { 65 | ...BASE_MEAL, 66 | Alcohol: false, 67 | Beef: true, 68 | Fish: false, 69 | LactoseFree: false, 70 | Name: 'Rindstuff', 71 | Pig: false, 72 | Poultry: false, 73 | Vegan: false, 74 | Vegetarian: false, 75 | }, 76 | ] as const satisfies readonly Meal[]; 77 | 78 | await test('filter-meals filterfrei', () => { 79 | const filtered = filterMeals(TEST_MEALS, {}); 80 | strictEqual(filtered.length, TEST_MEALS.length); 81 | }); 82 | 83 | await test('filter-meals vegan', () => { 84 | const filtered = filterMeals(TEST_MEALS, {vegan: true}); 85 | deepStrictEqual(filtered.map(o => o.Name), [ 86 | 'Pasta', 87 | ]); 88 | }); 89 | 90 | await test('filter-meals vegetarisch', () => { 91 | const filtered = filterMeals(TEST_MEALS, {vegetarian: true}); 92 | deepStrictEqual(filtered.map(o => o.Name), [ 93 | 'Pasta Sahne', 94 | 'Pasta', 95 | ]); 96 | }); 97 | 98 | await test('filter-meals laktosefrei', () => { 99 | const filtered = filterMeals(TEST_MEALS, {lactoseFree: true}); 100 | deepStrictEqual(filtered.map(o => o.Name), [ 101 | 'Pasta', 102 | ]); 103 | }); 104 | 105 | await test('filter-meals ohne Schwein', () => { 106 | const filtered = filterMeals(TEST_MEALS, {noPig: true}); 107 | deepStrictEqual(filtered.map(o => o.Name), [ 108 | 'Fisch', 109 | 'Pasta Sahne', 110 | 'Pasta', 111 | 'Rindstuff', 112 | ]); 113 | }); 114 | 115 | await test('filter-meals ohne Rind', () => { 116 | const filtered = filterMeals(TEST_MEALS, {noBeef: true}); 117 | deepStrictEqual(filtered.map(o => o.Name), [ 118 | 'Fisch', 119 | 'Pasta Sahne', 120 | 'Pasta Speck', 121 | 'Pasta', 122 | ]); 123 | }); 124 | 125 | await test('filter-meals ohne Geflügel', () => { 126 | const filtered = filterMeals(TEST_MEALS, {noPoultry: true}); 127 | deepStrictEqual(filtered.map(o => o.Name), [ 128 | 'Fisch', 129 | 'Pasta Sahne', 130 | 'Pasta Speck', 131 | 'Pasta', 132 | 'Rindstuff', 133 | ]); 134 | }); 135 | 136 | await test('filter-meals ohne Fisch', () => { 137 | const filtered = filterMeals(TEST_MEALS, {noFish: true}); 138 | deepStrictEqual(filtered.map(o => o.Name), [ 139 | 'Pasta Sahne', 140 | 'Pasta Speck', 141 | 'Pasta', 142 | 'Rindstuff', 143 | ]); 144 | }); 145 | -------------------------------------------------------------------------------- /source/lib/mensa-helper.generate-meal-text.test.ts: -------------------------------------------------------------------------------- 1 | import {strictEqual} from 'node:assert'; 2 | import {test} from 'node:test'; 3 | import type {Meal} from './meal.js'; 4 | import {generateMealText} from './mensa-helper.js'; 5 | 6 | const example = { 7 | Additives: { 8 | La: 'Milch/-erzeugnisse (einschl. Laktose)', 9 | }, 10 | Alcohol: false, 11 | Beef: false, 12 | Category: 'Food', 13 | Date: '2018-09-14', 14 | Fish: false, 15 | LactoseFree: false, 16 | Name: '4 Röstiecken, Kräuterquark (La), Gurkensalat (La)', 17 | Pig: false, 18 | Poultry: false, 19 | PriceAttendant: 3.75, 20 | PriceGuest: 4.7, 21 | PriceStudent: 2.45, 22 | Vegan: false, 23 | Vegetarian: true, 24 | } as const satisfies Meal; 25 | 26 | // Shortened 27 | const bracketsInNameExample = { 28 | Additives: { 29 | 1: 'Farbstoffe', 30 | 2: 'Konservierungsstoffe', 31 | Gl: 'Glutenhaltiges Getreide und daraus hergestellte Erzeugnissse', 32 | Ei: 'Ei/-erzeugnisse', 33 | La: 'Milch/-erzeugnisse (einschl. Laktose)', 34 | }, 35 | Alcohol: false, 36 | Beef: true, 37 | Category: 'Campus Spezial', 38 | Date: '2019-04-30', 39 | Fish: false, 40 | LactoseFree: false, 41 | Name: 42 | 'Hamburger (100%Rind) mit gegrilltem Spargel und Parmesanspäne (1, 2, Gl, Ei, La), Kartoffeltwister (Gl)', 43 | Pig: false, 44 | Poultry: false, 45 | PriceAttendant: 4.5, 46 | PriceGuest: 5.65, 47 | PriceStudent: 3.5, 48 | Vegan: false, 49 | Vegetarian: false, 50 | } as const satisfies Meal; 51 | 52 | await test('generate-meal-test shows hint when something is filtered', () => { 53 | const result = generateMealText([example], { 54 | vegan: true, 55 | }); 56 | strictEqual(result.includes('Sonderwünsche'), true); 57 | }); 58 | 59 | await test('generate-meal-test does not show hint when nothing is filtered while having filters', () => { 60 | const result = generateMealText([example], { 61 | noPig: true, 62 | }); 63 | strictEqual(result.includes('Sonderwünsche'), false); 64 | }); 65 | 66 | await test('generate-meal-test show no meals today', () => { 67 | const result = generateMealText([], {}); 68 | strictEqual(result.includes('bietet heute nichts an'), true); 69 | }); 70 | 71 | await test('generate-meal-test has meal', () => { 72 | const result = generateMealText([example], {}); 73 | strictEqual(result.includes('Gurkensalat'), true); 74 | }); 75 | 76 | await test('generate-meal-test even amount of bold markers without showAdditives', () => { 77 | const result = generateMealText([example], { 78 | showAdditives: false, 79 | }); 80 | const occurrences = result.match(/<\/?b>/g)?.length; 81 | strictEqual(occurrences, 2); 82 | }); 83 | 84 | await test('generate-meal-test even amount of bold markers with showAdditives', () => { 85 | const result = generateMealText([example], { 86 | showAdditives: true, 87 | }); 88 | const occurrences = result.match(/<\/?b>/g)?.length; 89 | strictEqual(occurrences, 4); 90 | }); 91 | 92 | await test('generate-meal-test Name without showAdditives', () => { 93 | const result = generateMealText([example], { 94 | showAdditives: false, 95 | }).trim(); 96 | const lines = result.split('\n'); 97 | strictEqual(lines[0], '4 Röstiecken, Kräuterquark, Gurkensalat'); 98 | }); 99 | 100 | await test('generate-meal-test Name with showAdditives', () => { 101 | const result = generateMealText([example], { 102 | showAdditives: true, 103 | }).trim(); 104 | const lines = result.split('\n'); 105 | strictEqual( 106 | lines[0], 107 | '4 Röstiecken, Kräuterquark (La), Gurkensalat (La)', 108 | ); 109 | }); 110 | 111 | await test('generate-meal-test Name with brackets without showAdditives', () => { 112 | const result = generateMealText([bracketsInNameExample], { 113 | showAdditives: false, 114 | }).trim(); 115 | const lines = result.split('\n'); 116 | strictEqual( 117 | lines[0], 118 | 'Hamburger (100%Rind) mit gegrilltem Spargel und Parmesanspäne, Kartoffeltwister', 119 | ); 120 | }); 121 | 122 | await test('generate-meal-test Name with brackets with showAdditives', () => { 123 | const result = generateMealText([bracketsInNameExample], { 124 | showAdditives: true, 125 | }).trim(); 126 | const lines = result.split('\n'); 127 | strictEqual( 128 | lines[0], 129 | 'Hamburger (100%Rind) mit gegrilltem Spargel und Parmesanspäne (1, 2, Gl, Ei, La), Kartoffeltwister (Gl)', 130 | ); 131 | }); 132 | -------------------------------------------------------------------------------- /source/lib/mensa-helper.meal-to-html.test.ts: -------------------------------------------------------------------------------- 1 | import {strictEqual} from 'node:assert'; 2 | import {test} from 'node:test'; 3 | import type {Meal} from './meal.js'; 4 | import {mealNameToHtml, mealToHtml} from './mensa-helper.js'; 5 | 6 | const example = { 7 | Additives: { 8 | La: 'Milch/-erzeugnisse (einschl. Laktose)', 9 | }, 10 | Alcohol: false, 11 | Beef: false, 12 | Category: 'Food', 13 | Date: '2018-09-14', 14 | Fish: false, 15 | LactoseFree: false, 16 | Name: '4 Röstiecken, Kräuterquark (La), Gurkensalat (La)', 17 | Pig: false, 18 | Poultry: false, 19 | PriceAttendant: 3.75, 20 | PriceGuest: 4.7, 21 | PriceStudent: 2.45, 22 | Vegan: false, 23 | Vegetarian: true, 24 | } as const satisfies Meal; 25 | 26 | await test('meal-to-html example student without Additives', () => { 27 | let expected = '4 Röstiecken, Kräuterquark, Gurkensalat'; 28 | expected += '\n2,45 € vegetarisch'; 29 | const result = mealToHtml(example, 'student', false); 30 | strictEqual(result, expected); 31 | }); 32 | 33 | await test('meal-to-html example guest without Additives', () => { 34 | let expected = '4 Röstiecken, Kräuterquark, Gurkensalat'; 35 | expected += '\n4,70 € vegetarisch'; 36 | const result = mealToHtml(example, 'guest', false); 37 | strictEqual(result, expected); 38 | }); 39 | 40 | await test('meal-to-html example student with Additives', () => { 41 | let expected 42 | = '4 Röstiecken, Kräuterquark (La), Gurkensalat (La)'; 43 | expected += '\n2,45 € vegetarisch'; 44 | const result = mealToHtml(example, 'student', true); 45 | strictEqual(result, expected); 46 | }); 47 | 48 | await test('meal-to-html example name with end bracket without Additives', () => { 49 | const expected = 'Soja Bolognese mit Gemüse, bunte Fusilli (VEGAN)'; 50 | const result = mealNameToHtml( 51 | 'Soja Bolognese mit Gemüse (So,Sl), bunte Fusilli (VEGAN) (Gl)', 52 | false, 53 | ); 54 | strictEqual(result, expected); 55 | }); 56 | 57 | await test('meal-to-html example name with end bracket with Additives', () => { 58 | const expected 59 | = 'Soja Bolognese mit Gemüse (So,Sl), bunte Fusilli (VEGAN) (Gl)'; 60 | const result = mealNameToHtml( 61 | 'Soja Bolognese mit Gemüse (So,Sl), bunte Fusilli (VEGAN) (Gl)', 62 | true, 63 | ); 64 | strictEqual(result, expected); 65 | }); 66 | -------------------------------------------------------------------------------- /source/lib/mensa-helper.ts: -------------------------------------------------------------------------------- 1 | import {arrayFilterUnique} from 'array-filter-unique'; 2 | import type {Meal} from './meal.js'; 3 | import type {MealWishes, MensaPriceClass, MensaSettings} from './types.js'; 4 | 5 | export function filterMeals( 6 | meals: readonly Meal[], 7 | specialWishes: Readonly, 8 | ): Meal[] { 9 | return meals 10 | .filter(m => !specialWishes.noAlcohol || !m.Alcohol) 11 | .filter(m => !specialWishes.noBeef || !m.Beef) 12 | .filter(m => !specialWishes.noFish || !m.Fish) 13 | .filter(m => !specialWishes.noGame || !m.Game) 14 | .filter(m => !specialWishes.noGelatine || !m.Gelatine) 15 | .filter(m => !specialWishes.noLamb || !m.Lamb) 16 | .filter(m => !specialWishes.noPig || !m.Pig) 17 | .filter(m => !specialWishes.noPoultry || !m.Poultry) 18 | .filter(m => !specialWishes.lactoseFree || m.LactoseFree) 19 | .filter(m => !specialWishes.vegan || m.Vegan) 20 | .filter(m => 21 | !specialWishes.vegetarian || Boolean(m.Vegan) || m.Vegetarian, 22 | ); 23 | } 24 | 25 | export function generateMealText( 26 | meals: readonly Meal[], 27 | mensaSettings: Readonly, 28 | ): string { 29 | if (meals.length === 0) { 30 | return 'Die Mensa bietet heute nichts an.'; 31 | } 32 | 33 | const hints: string[] = []; 34 | 35 | const filtered = filterMeals(meals, mensaSettings); 36 | const mealTexts = filtered.map(m => 37 | mealToHtml(m, mensaSettings.price, mensaSettings.showAdditives), 38 | ); 39 | 40 | if (meals.length !== filtered.length) { 41 | hints.push( 42 | '⚠️ Durch deine Sonderwünsche siehst du nicht jede Mahlzeit. Dies kannst du in den Mensa Einstellungen einstellen.', 43 | ); 44 | } 45 | 46 | const hintText = hints 47 | .map(o => o + '\n') 48 | .join('\n'); 49 | if (mealTexts.length === 0) { 50 | return hintText + '\nDie Mensa hat heute nichts für dich.'; 51 | } 52 | 53 | let text = ''; 54 | text += hintText; 55 | text += '\n'; 56 | text += mealTexts.join('\n\n'); 57 | 58 | if (mensaSettings.showAdditives) { 59 | text += '\n\n'; 60 | text += mealAdditivesToHtml(filtered); 61 | } 62 | 63 | return text; 64 | } 65 | 66 | export function mealNameToHtml( 67 | name: string, 68 | showAdditives: boolean | undefined, 69 | ): string { 70 | const parsedName = name 71 | // Remove / un-bold additives at the end 72 | .replaceAll(/ \(([\d\w, ]+)\)$/g, showAdditives ? ' ($1)' : '') 73 | // Remove / un-bold additives within the name 74 | .replaceAll(/ \(([\d\w, ]+)\), /g, showAdditives ? ' ($1), ' : ', '); 75 | 76 | const fullName = `${parsedName}`; 77 | return fullName.replaceAll('', ''); 78 | } 79 | 80 | export function mealAdditivesToHtml(meals: readonly Meal[]): string { 81 | return meals 82 | .flatMap(meal => 83 | Object.entries(meal.Additives).map(([short, full]) => `${short}: ${full}`), 84 | ) 85 | .sort() 86 | .filter(arrayFilterUnique()) 87 | .join('\n'); 88 | } 89 | 90 | export function mealToHtml( 91 | meal: Meal, 92 | priceClass: MensaPriceClass | undefined, 93 | showAdditives: boolean | undefined, 94 | ): string { 95 | const name = mealNameToHtml(meal.Name, showAdditives); 96 | 97 | const price = priceClass === 'student' 98 | ? meal.PriceStudent 99 | : (priceClass === 'attendant' ? meal.PriceAttendant : meal.PriceGuest); 100 | const priceString = price.toLocaleString('de-DE', { 101 | minimumFractionDigits: 2, 102 | }).replace('.', ','); 103 | 104 | let text = `${name}\n`; 105 | text += `${priceString} €`; 106 | 107 | const infos: string[] = []; 108 | 109 | if (meal.Pig) { 110 | infos.push('🐷'); 111 | } 112 | 113 | if (meal.Beef) { 114 | infos.push('🐮'); 115 | } 116 | 117 | if (meal.Poultry) { 118 | infos.push('🐔'); 119 | } 120 | 121 | if (meal.Fish) { 122 | infos.push('🐟'); 123 | } 124 | 125 | if (meal.Alcohol) { 126 | infos.push('🍷'); 127 | } 128 | 129 | if (meal.LactoseFree) { 130 | infos.push('laktosefrei'); 131 | } 132 | 133 | if (meal.Vegan) { 134 | infos.push('vegan'); 135 | } 136 | 137 | if (meal.Vegetarian) { 138 | infos.push('vegetarisch'); 139 | } 140 | 141 | if (infos.length > 0) { 142 | text += ' ' + infos.join(' '); 143 | } 144 | 145 | return text; 146 | } 147 | -------------------------------------------------------------------------------- /source/lib/mensa-meals.ts: -------------------------------------------------------------------------------- 1 | import {readdir, readFile} from 'node:fs/promises'; 2 | import type {Meal} from './meal.js'; 3 | 4 | export async function getCanteenList(): Promise { 5 | const found = await readdir('mensa-data', {withFileTypes: true}); 6 | const dirs = found 7 | .filter(o => o.isDirectory()) 8 | .map(o => o.name) 9 | .filter(o => !o.startsWith('.')); 10 | return dirs; 11 | } 12 | 13 | function getFilename( 14 | mensa: string, 15 | year: number, 16 | month: number, 17 | day: number, 18 | ): string { 19 | const y = year.toLocaleString(undefined, { 20 | minimumIntegerDigits: 4, 21 | useGrouping: false, 22 | }); 23 | const m = month.toLocaleString(undefined, {minimumIntegerDigits: 2}); 24 | const d = day.toLocaleString(undefined, {minimumIntegerDigits: 2}); 25 | return `mensa-data/${mensa}/${y}/${m}/${d}.json`; 26 | } 27 | 28 | export async function getMealsOfDay( 29 | mensa: string, 30 | year: number, 31 | month: number, 32 | day: number, 33 | ): Promise { 34 | try { 35 | const filename = getFilename(mensa, year, month, day); 36 | const content = await readFile(filename, 'utf8'); 37 | return JSON.parse(content) as Meal[]; 38 | } catch { 39 | return []; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /source/lib/telegram-broadcast.ts: -------------------------------------------------------------------------------- 1 | import type {Api} from 'grammy'; 2 | import {sequentialLoop, sleep} from './async.js'; 3 | import type {OtherSendMessage} from './types.js'; 4 | 5 | const SLEEP_MS = 250; 6 | 7 | export async function broadcast( 8 | telegram: Api, 9 | targetIds: readonly number[], 10 | text: string, 11 | extra: OtherSendMessage, 12 | ): Promise { 13 | const goneUserIds: number[] = []; 14 | 15 | await sequentialLoop(targetIds, async id => { 16 | try { 17 | await sleep(SLEEP_MS); 18 | await telegram.sendMessage(id, text, extra); 19 | } catch (error) { 20 | console.warn( 21 | 'broadcast failed. Target:', 22 | id, 23 | error instanceof Error ? error.message : error, 24 | ); 25 | if (isUserGoneError(error)) { 26 | goneUserIds.push(id); 27 | } 28 | } 29 | }); 30 | 31 | return goneUserIds; 32 | } 33 | 34 | export async function forwardBroadcast( 35 | telegram: Api, 36 | targetIds: readonly number[], 37 | originChat: string | number, 38 | messageId: number, 39 | ): Promise { 40 | const goneUserIds: number[] = []; 41 | 42 | await sequentialLoop(targetIds, async id => { 43 | try { 44 | await sleep(SLEEP_MS); 45 | await telegram.forwardMessage(id, originChat, messageId); 46 | } catch (error) { 47 | console.warn( 48 | 'forwardBroadcast failed. Target:', 49 | id, 50 | error instanceof Error ? error.message : error, 51 | ); 52 | if (isUserGoneError(error)) { 53 | goneUserIds.push(id); 54 | } 55 | } 56 | }); 57 | 58 | return goneUserIds; 59 | } 60 | 61 | function isUserGoneError(error: unknown): boolean { 62 | const errorDescription = error instanceof Error 63 | ? error.message 64 | : String(error); 65 | return errorDescription.includes('user is deactivated') 66 | || errorDescription.includes('bot was blocked by the user'); 67 | } 68 | -------------------------------------------------------------------------------- /source/lib/types.ts: -------------------------------------------------------------------------------- 1 | import type {I18nFlavor} from '@grammyjs/i18n'; 2 | import type {Api, Context as BaseContext, SessionFlavor} from 'grammy'; 3 | import type {ContextProperty} from './chatconfig.js'; 4 | 5 | export type OtherSendMessage = Parameters[2]; 6 | 7 | type ContextFlavour = { 8 | readonly userconfig: ContextProperty; 9 | }; 10 | 11 | export type MyContext = 12 | & BaseContext 13 | & I18nFlavor 14 | & SessionFlavor 15 | & ContextFlavour; 16 | 17 | export type Session = { 18 | adminBroadcast?: number; // Message ID 19 | adminuserquicklook?: number; // User ID 20 | adminuserquicklookfilter?: string; 21 | eventfilter?: string; 22 | generateChange?: Partial; 23 | page?: number; 24 | privacySection?: 'telegram' | 'persistent' | 'tmp'; 25 | mensa?: { 26 | mensa?: string; 27 | date?: number; 28 | }; 29 | }; 30 | 31 | export type Userconfig = { 32 | readonly admin?: true; 33 | calendarfileSuffix: string; 34 | changes: Change[]; 35 | events: Record; 36 | mensa: MensaSettings; 37 | removedEvents?: RemovedEventsDisplayStyle; 38 | /** @deprecated use channel https://t.me/HAWHHWebsiteStalker instead */ 39 | stisysUpdate?: boolean; 40 | /** @deprecated use channel https://t.me/HAWHHWebsiteStalker instead */ 41 | websiteStalkerUpdate?: true; 42 | }; 43 | 44 | export type RemovedEventsDisplayStyle = 'cancelled' | 'removed' | 'emoji'; 45 | 46 | export type EventDetails = { 47 | alertMinutesBefore?: number; 48 | notes?: string; 49 | }; 50 | 51 | export type Change = { 52 | add?: true; 53 | name: string; 54 | date: string; 55 | remove?: true; 56 | namesuffix?: string; 57 | starttime?: string; 58 | endtime?: string; 59 | room?: string; 60 | }; 61 | 62 | export type MensaPriceClass = 'student' | 'attendant' | 'guest'; 63 | 64 | export type MealWishes = { 65 | lactoseFree?: boolean; 66 | noAlcohol?: boolean; 67 | noBeef?: boolean; 68 | noFish?: boolean; 69 | noGame?: boolean; 70 | noGelatine?: boolean; 71 | noLamb?: boolean; 72 | noPig?: boolean; 73 | noPoultry?: boolean; 74 | vegan?: boolean; 75 | vegetarian?: boolean; 76 | }; 77 | export type MealWish = keyof MealWishes; 78 | 79 | export type MensaSettings = MealWishes & { 80 | main?: string; 81 | more?: readonly string[]; 82 | price?: MensaPriceClass; 83 | showAdditives?: boolean; 84 | }; 85 | 86 | export type EventEntryFileContent = { 87 | readonly Name: string; 88 | readonly Location: string; 89 | readonly Description: string; 90 | readonly StartTime: string; 91 | readonly EndTime: string; 92 | }; 93 | 94 | export type EventEntryInternal = { 95 | readonly Name: string; 96 | readonly Location: string; 97 | readonly Description: string; 98 | readonly StartTime: Date; 99 | readonly EndTime: Date; 100 | }; 101 | -------------------------------------------------------------------------------- /source/menu/about.ts: -------------------------------------------------------------------------------- 1 | import {MenuTemplate} from 'grammy-inline-menu'; 2 | import {html as format} from 'telegram-format'; 3 | import * as allEvents from '../lib/all-events.js'; 4 | import {getCanteenList} from '../lib/mensa-meals.js'; 5 | import type {MyContext} from '../lib/types.js'; 6 | 7 | export const menu = new MenuTemplate(async context => { 8 | const userIds = await context.userconfig.allIds(); 9 | const userCount = userIds.length; 10 | 11 | const canteens = await getCanteenList(); 12 | const canteenCount = canteens.length; 13 | const eventCount = await allEvents.count(); 14 | 15 | const websiteLink = format.url( 16 | 'hawhh.de/calendarbot/', 17 | 'https://hawhh.de/calendarbot/', 18 | ); 19 | const githubIssues = format.url( 20 | 'GitHub', 21 | 'https://github.com/HAWHHCalendarBot/telegrambot/issues', 22 | ); 23 | 24 | let text = ''; 25 | text 26 | += `Ich habe aktuell ${eventCount} Veranstaltungen und ${canteenCount} Mensen, die ich ${userCount} begeisterten Nutzern 😍 zur Verfügung stelle.`; 27 | text += '\n\n'; 28 | text 29 | += 'Wenn ich für dich hilfreich bin, dann erzähl gern anderen von mir, denn ich will gern allen helfen, denen noch zu helfen ist. ☺️'; 30 | text += '\n\n'; 31 | text += `Wie ich funktioniere wird auf ${websiteLink} genauer beschrieben.`; 32 | text += '\n'; 33 | text 34 | += `Du hast Probleme, Ideen oder Vorschläge, was ich noch können sollte? Dann wende dich an @EdJoPaTo oder erstelle ein Issue auf ${githubIssues}.`; 35 | 36 | return { 37 | disable_web_page_preview: true, 38 | parse_mode: format.parse_mode, 39 | text, 40 | }; 41 | }); 42 | 43 | menu.url({ 44 | text: 'hawhh.de/calendarbot/', 45 | url: 'https://hawhh.de/calendarbot/', 46 | }); 47 | 48 | menu.url({ 49 | text: '😌 PayPal Spende', 50 | url: 'https://www.paypal.com/donate?hosted_button_id=L2EMBSGTEXK42', 51 | }); 52 | 53 | menu.url({ 54 | text: '🦑 Quellcode', 55 | url: 'https://github.com/HAWHHCalendarBot', 56 | }); 57 | menu.url({ 58 | joinLastRow: true, 59 | text: '🦑 Änderungshistorie', 60 | url: 'https://github.com/HAWHHCalendarBot/TelegramBot/releases', 61 | }); 62 | -------------------------------------------------------------------------------- /source/menu/admin/broadcast.ts: -------------------------------------------------------------------------------- 1 | import {StatelessQuestion} from '@grammyjs/stateless-question'; 2 | import {Composer} from 'grammy'; 3 | import { 4 | getMenuOfPath, 5 | MenuTemplate, 6 | replyMenuToContext, 7 | } from 'grammy-inline-menu'; 8 | import {backMainButtons} from '../../lib/inline-menu.js'; 9 | import type {MyContext} from '../../lib/types.js'; 10 | 11 | export const bot = new Composer(); 12 | export const menu = new MenuTemplate('Broadcast'); 13 | 14 | const broadcastQuestion = new StatelessQuestion( 15 | 'admin-broadcast', 16 | async (context, path) => { 17 | context.session.adminBroadcast = context.message.message_id; 18 | await replyMenuToContext(menu, context, path); 19 | }, 20 | ); 21 | 22 | bot.use(broadcastQuestion.middleware()); 23 | 24 | menu.interact('set', { 25 | text(context) { 26 | return context.session.adminBroadcast 27 | ? '✏️ Ändere Nachricht…' 28 | : '✏️ Setze Nachricht…'; 29 | }, 30 | async do(context, path) { 31 | await broadcastQuestion.replyWithHTML( 32 | context, 33 | 'Hey admin! Was willst du broadcasten?', 34 | getMenuOfPath(path), 35 | ); 36 | return false; 37 | }, 38 | }); 39 | 40 | menu.interact('send', { 41 | text: '📤 Versende Broadcast', 42 | hide: context => !context.session.adminBroadcast, 43 | async do(context) { 44 | // eslint-disable-next-line @typescript-eslint/no-floating-promises 45 | handleOngoingBroadcast(context, context.session.adminBroadcast!); 46 | 47 | delete context.session.adminBroadcast; 48 | await context.editMessageText('wird versendet…'); 49 | 50 | return false; 51 | }, 52 | }); 53 | 54 | async function handleOngoingBroadcast( 55 | context: MyContext, 56 | messageId: number, 57 | ): Promise { 58 | let text: string; 59 | try { 60 | await context.userconfig.forwardBroadcast(context.from!.id, messageId); 61 | text = 'Broadcast finished'; 62 | } catch (error) { 63 | text = 'Broadcast failed: ' + String(error); 64 | } 65 | 66 | await context.reply(text, { 67 | reply_to_message_id: messageId, 68 | reply_markup: { 69 | remove_keyboard: true, 70 | }, 71 | }); 72 | 73 | if (context.callbackQuery?.data) { 74 | await replyMenuToContext( 75 | menu, 76 | context, 77 | getMenuOfPath(context.callbackQuery.data), 78 | ); 79 | } 80 | } 81 | 82 | menu.manualRow(backMainButtons); 83 | -------------------------------------------------------------------------------- /source/menu/admin/index.ts: -------------------------------------------------------------------------------- 1 | import {Composer} from 'grammy'; 2 | import {MenuTemplate} from 'grammy-inline-menu'; 3 | import type {MyContext} from '../../lib/types.js'; 4 | import * as broadcastMenu from './broadcast.js'; 5 | import * as userMenu from './user-quicklook.js'; 6 | 7 | export const bot = new Composer(); 8 | export const menu = new MenuTemplate('Hey Admin!'); 9 | 10 | bot.use(broadcastMenu.bot); 11 | bot.use(userMenu.bot); 12 | 13 | menu.submenu('broadcast', broadcastMenu.menu, {text: 'Broadcast'}); 14 | menu.submenu('u', userMenu.menu, {text: 'User Quicklook'}); 15 | -------------------------------------------------------------------------------- /source/menu/admin/user-quicklook.ts: -------------------------------------------------------------------------------- 1 | import {StatelessQuestion} from '@grammyjs/stateless-question'; 2 | import {Composer} from 'grammy'; 3 | import { 4 | deleteMenuFromContext, 5 | getMenuOfPath, 6 | MenuTemplate, 7 | replyMenuToContext, 8 | } from 'grammy-inline-menu'; 9 | import type {User} from 'grammy/types'; 10 | import {html as format} from 'telegram-format'; 11 | import {getUrl} from '../../lib/calendar-helper.js'; 12 | import { 13 | DEFAULT_FILTER, 14 | filterButtonText, 15 | } from '../../lib/inline-menu-filter.js'; 16 | import {backMainButtons} from '../../lib/inline-menu.js'; 17 | import type {MyContext} from '../../lib/types.js'; 18 | 19 | function nameOfUser({first_name, last_name, username}: User): string { 20 | let name = first_name; 21 | if (last_name) { 22 | name += ' ' + last_name; 23 | } 24 | 25 | if (username) { 26 | name += ` (${username})`; 27 | } 28 | 29 | return name; 30 | } 31 | 32 | export const bot = new Composer(); 33 | export const menu = new MenuTemplate(async context => { 34 | if (!context.session.adminuserquicklook) { 35 | return 'Wähle einen Nutzer…'; 36 | } 37 | 38 | const config = await context.userconfig.load( 39 | context.session.adminuserquicklook, 40 | ); 41 | 42 | let text = ''; 43 | text += 'URL: '; 44 | text += format.monospace( 45 | 'https://' + getUrl(context.session.adminuserquicklook, config!.config), 46 | ); 47 | text += '\n\n'; 48 | text += format.monospaceBlock(JSON.stringify(config, null, 2), 'json'); 49 | 50 | return {text, parse_mode: format.parse_mode}; 51 | }); 52 | 53 | menu.url({ 54 | hide: context => !context.session.adminuserquicklook, 55 | text: 'Kalender', 56 | async url(context) { 57 | const config = await context.userconfig.loadConfig( 58 | context.session.adminuserquicklook!, 59 | ); 60 | return `https://${getUrl(context.session.adminuserquicklook!, config)}`; 61 | }, 62 | }); 63 | 64 | const question = new StatelessQuestion( 65 | 'admin-user-filter', 66 | async (context, path) => { 67 | if ('text' in context.message) { 68 | context.session.adminuserquicklookfilter = context.message.text; 69 | delete context.session.adminuserquicklook; 70 | } 71 | 72 | await replyMenuToContext(menu, context, path); 73 | }, 74 | ); 75 | 76 | bot.use(question.middleware()); 77 | 78 | menu.interact('filter', { 79 | text: filterButtonText(context => context.session.adminuserquicklookfilter), 80 | async do(context, path) { 81 | await question.replyWithHTML( 82 | context, 83 | 'Wonach möchtest du die Nutzer filtern?', 84 | getMenuOfPath(path), 85 | ); 86 | await deleteMenuFromContext(context); 87 | return false; 88 | }, 89 | }); 90 | 91 | menu.interact('filter-clear', { 92 | joinLastRow: true, 93 | text: 'Filter aufheben', 94 | hide(context) { 95 | return (context.session.adminuserquicklookfilter ?? DEFAULT_FILTER) 96 | === DEFAULT_FILTER; 97 | }, 98 | do(context) { 99 | delete context.session.adminuserquicklookfilter; 100 | delete context.session.adminuserquicklook; 101 | return true; 102 | }, 103 | }); 104 | 105 | menu.select('u', { 106 | maxRows: 5, 107 | columns: 2, 108 | async choices(context) { 109 | const filter = context.session.adminuserquicklookfilter ?? DEFAULT_FILTER; 110 | const filterRegex = new RegExp(filter, 'i'); 111 | const allConfigs = await context.userconfig.all( 112 | config => filterRegex.test(JSON.stringify(config)), 113 | ); 114 | const allChats = allConfigs.map(o => o.chat); 115 | allChats.sort((a, b) => { 116 | const nameA = nameOfUser(a); 117 | const nameB = nameOfUser(b); 118 | return nameA.localeCompare(nameB); 119 | }); 120 | return Object.fromEntries( 121 | allChats.map(chat => [chat.id, nameOfUser(chat)]), 122 | ); 123 | }, 124 | isSet: (context, selected) => 125 | context.session.adminuserquicklook === Number(selected), 126 | async set(context, selected) { 127 | context.session.adminuserquicklook = Number(selected); 128 | return true; 129 | }, 130 | getCurrentPage: context => context.session.page, 131 | setPage(context, page) { 132 | context.session.page = page; 133 | }, 134 | }); 135 | 136 | menu.manualRow(backMainButtons); 137 | -------------------------------------------------------------------------------- /source/menu/data.ts: -------------------------------------------------------------------------------- 1 | import {StatelessQuestion} from '@grammyjs/stateless-question'; 2 | import {Composer} from 'grammy'; 3 | import { 4 | getMenuOfPath, 5 | MenuTemplate, 6 | replyMenuToContext, 7 | } from 'grammy-inline-menu'; 8 | import {html as format} from 'telegram-format'; 9 | import type {MyContext, Userconfig} from '../lib/types.js'; 10 | 11 | async function getActualUserconfigContent( 12 | context: MyContext, 13 | ): Promise { 14 | if (!context.userconfig.mine) { 15 | return undefined; 16 | } 17 | 18 | const userconfig = await context.userconfig.load(context.from!.id); 19 | return userconfig?.config; 20 | } 21 | 22 | const PRIVACY_SECTIONS = { 23 | telegram: 'Telegram', 24 | persistent: 'Persistent', 25 | tmp: 'Temporär', 26 | } as const; 27 | type PrivacySection = keyof typeof PRIVACY_SECTIONS; 28 | 29 | export const bot = new Composer(); 30 | export const menu = new MenuTemplate(async context => { 31 | const part = privacyInfoPart( 32 | context, 33 | context.session.privacySection ?? 'persistent', 34 | ); 35 | 36 | let text = context.t('privacy-overview'); 37 | text += '\n\n'; 38 | text += format.bold(part.title); 39 | text += '\n'; 40 | text += part.text; 41 | text += '\n'; 42 | text += format.monospaceBlock(JSON.stringify(part.data, null, 1), 'json'); 43 | 44 | return { 45 | disable_web_page_preview: true, 46 | parse_mode: format.parse_mode, 47 | text, 48 | }; 49 | }); 50 | 51 | function privacyInfoPart(ctx: MyContext, section: PrivacySection) { 52 | const text = ctx.t('privacy-' + section); 53 | if (section === 'telegram') { 54 | return {text, title: 'Telegram User Info', data: ctx.from}; 55 | } 56 | 57 | if (section === 'persistent') { 58 | return { 59 | text, 60 | title: 'Persistente Einstellungen im Bot', 61 | data: ctx.userconfig.mine, 62 | }; 63 | } 64 | 65 | return {text, title: 'Temporäre Daten des Bots', data: ctx.session}; 66 | } 67 | 68 | const deleteConfirmString = 'Ja, ich will!'; 69 | const deleteQuestion 70 | = `Bist du dir sicher, das du deinen Kalender und alle Einstellungen löschen willst?\n\nWenn du wirklich alles löschen willst, antworte mit "${deleteConfirmString}"`; 71 | 72 | menu.select('section', { 73 | choices: PRIVACY_SECTIONS, 74 | isSet: (ctx, key) => (ctx.session.privacySection ?? 'persistent') === key, 75 | set(ctx, key) { 76 | ctx.session.privacySection = key as PrivacySection; 77 | return true; 78 | }, 79 | }); 80 | 81 | menu.url({text: '🦑 Quellcode', url: 'https://github.com/HAWHHCalendarBot'}); 82 | 83 | const deleteAllQuestion = new StatelessQuestion( 84 | 'delete-everything', 85 | async (context, path) => { 86 | if ( 87 | 'text' in context.message 88 | && context.message.text === deleteConfirmString 89 | ) { 90 | // @ts-expect-error delete readonly 91 | delete context.userconfig.mine; 92 | context.session = undefined; 93 | await context.reply('Deine Daten werden gelöscht…'); 94 | } else { 95 | await context.reply('Du hast mir aber einen Schrecken eingejagt! 🙀'); 96 | await replyMenuToContext(menu, context, path); 97 | } 98 | }, 99 | ); 100 | 101 | bot.use(deleteAllQuestion.middleware()); 102 | 103 | menu.interact('delete-all', { 104 | text: '⚠️ Alles löschen ⚠️', 105 | hide: async context => !(await getActualUserconfigContent(context)), 106 | async do(context, path) { 107 | await deleteAllQuestion.replyWithHTML( 108 | context, 109 | deleteQuestion, 110 | getMenuOfPath(path), 111 | ); 112 | return false; 113 | }, 114 | }); 115 | -------------------------------------------------------------------------------- /source/menu/events/add.ts: -------------------------------------------------------------------------------- 1 | import {StatelessQuestion} from '@grammyjs/stateless-question'; 2 | import {Composer} from 'grammy'; 3 | import { 4 | deleteMenuFromContext, 5 | getMenuOfPath, 6 | MenuTemplate, 7 | replyMenuToContext, 8 | } from 'grammy-inline-menu'; 9 | import {html as format} from 'telegram-format'; 10 | import { 11 | count as allEventsCount, 12 | exists as allEventsExists, 13 | find as allEventsFind, 14 | } from '../../lib/all-events.js'; 15 | import { 16 | DEFAULT_FILTER, 17 | filterButtonText, 18 | } from '../../lib/inline-menu-filter.js'; 19 | import {backMainButtons} from '../../lib/inline-menu.js'; 20 | import type {MyContext} from '../../lib/types.js'; 21 | 22 | const MAX_RESULT_ROWS = 10; 23 | const RESULT_COLUMNS = 2; 24 | 25 | export const bot = new Composer(); 26 | export const menu = new MenuTemplate(async context => { 27 | const total = await allEventsCount(); 28 | 29 | let text = format.bold('Veranstaltungen'); 30 | text += '\nWelche Events möchtest du hinzufügen?'; 31 | text += '\n\n'; 32 | 33 | try { 34 | const filteredEvents = await findEvents(context); 35 | 36 | const filter = context.session.eventfilter ?? DEFAULT_FILTER; 37 | text += filter === DEFAULT_FILTER 38 | ? `Ich habe ${total} Veranstaltungen. Nutze den Filter um die Auswahl einzugrenzen.` 39 | : `Mit deinem Filter konnte ich ${filteredEvents.length} passende Veranstaltungen finden.`; 40 | } catch (error) { 41 | const errorText = error instanceof Error ? error.message : String(error); 42 | text += 'Filter Error: '; 43 | text += format.monospace(errorText); 44 | } 45 | 46 | return {text, parse_mode: format.parse_mode}; 47 | }); 48 | 49 | async function findEvents(context: MyContext): Promise { 50 | const filter = context.session.eventfilter ?? DEFAULT_FILTER; 51 | const ignore = Object.keys(context.userconfig.mine.events); 52 | return allEventsFind(filter, ignore); 53 | } 54 | 55 | const question = new StatelessQuestion( 56 | 'events-add-filter', 57 | async (context, path) => { 58 | if ('text' in context.message) { 59 | context.session.eventfilter = context.message.text; 60 | } 61 | 62 | await replyMenuToContext(menu, context, path); 63 | }, 64 | ); 65 | 66 | bot.use(question.middleware()); 67 | 68 | menu.interact('filter', { 69 | text: filterButtonText(context => context.session.eventfilter), 70 | async do(context, path) { 71 | await question.replyWithHTML( 72 | context, 73 | 'Wonach möchtest du die Veranstaltungen filtern?', 74 | getMenuOfPath(path), 75 | ); 76 | await deleteMenuFromContext(context); 77 | return false; 78 | }, 79 | }); 80 | 81 | menu.interact('filter-clear', { 82 | text: 'Filter aufheben', 83 | joinLastRow: true, 84 | hide: context => 85 | (context.session.eventfilter ?? DEFAULT_FILTER) === DEFAULT_FILTER, 86 | do(context) { 87 | delete context.session.eventfilter; 88 | return true; 89 | }, 90 | }); 91 | 92 | menu.choose('a', { 93 | maxRows: MAX_RESULT_ROWS, 94 | columns: RESULT_COLUMNS, 95 | async choices(context) { 96 | try { 97 | const all = await findEvents(context); 98 | return Object.fromEntries( 99 | all.map(event => [event.replaceAll('/', ';'), event]), 100 | ); 101 | } catch { 102 | return {}; 103 | } 104 | }, 105 | async do(context, key) { 106 | const event = key.replaceAll(';', '/'); 107 | const isExisting = await allEventsExists(event); 108 | const isAlreadyInCalendar = Object.keys(context.userconfig.mine.events) 109 | .includes(event); 110 | 111 | if (!isExisting) { 112 | await context.answerCallbackQuery(`${event} existiert nicht!`); 113 | return true; 114 | } 115 | 116 | if (isAlreadyInCalendar) { 117 | await context.answerCallbackQuery( 118 | `${event} ist bereits in deinem Kalender!`, 119 | ); 120 | return true; 121 | } 122 | 123 | context.userconfig.mine.events[event] = {}; 124 | await context.answerCallbackQuery( 125 | `${event} wurde zu deinem Kalender hinzugefügt.`, 126 | ); 127 | return true; 128 | }, 129 | getCurrentPage: context => context.session.page, 130 | setPage(context, page) { 131 | context.session.page = page; 132 | }, 133 | }); 134 | 135 | menu.manualRow(backMainButtons); 136 | -------------------------------------------------------------------------------- /source/menu/events/changes/add/date-selector.ts: -------------------------------------------------------------------------------- 1 | import {MenuTemplate} from 'grammy-inline-menu'; 2 | import {formatDateToStoredChangeDate} from '../../../../lib/calendar-helper.js'; 3 | import { 4 | DAY_OPTIONS, 5 | generateYearOptions, 6 | MONTH_NAMES, 7 | MONTH_OPTIONS, 8 | } from '../../../../lib/event-creation-menu-options.js'; 9 | import {BACK_BUTTON_TEXT} from '../../../../lib/inline-menu.js'; 10 | import type {MyContext} from '../../../../lib/types.js'; 11 | 12 | const menuText = 'Wann findet der Termin statt?'; 13 | 14 | function getCurrent(context: MyContext): Date { 15 | const {date} = context.session.generateChange!; 16 | if (date) { 17 | return new Date(Date.parse(date + 'Z')); 18 | } 19 | 20 | return new Date(); 21 | } 22 | 23 | export function createDatePickerButtons( 24 | menu: MenuTemplate, 25 | hide: (context: MyContext) => boolean, 26 | ): void { 27 | menu.submenu('d', dayMenu, { 28 | hide, 29 | text: context => getCurrent(context).getDate().toString(), 30 | }); 31 | menu.submenu('m', monthMenu, { 32 | joinLastRow: true, 33 | hide, 34 | text: context => MONTH_NAMES[getCurrent(context).getMonth()]!, 35 | }); 36 | menu.submenu('y', yearMenu, { 37 | joinLastRow: true, 38 | hide, 39 | text: context => getCurrent(context).getFullYear().toString(), 40 | }); 41 | } 42 | 43 | const dayMenu = new MenuTemplate(menuText); 44 | const monthMenu = new MenuTemplate(menuText); 45 | const yearMenu = new MenuTemplate(menuText); 46 | 47 | dayMenu.select('', { 48 | columns: 7, 49 | choices: DAY_OPTIONS, 50 | isSet: (context, date) => getCurrent(context).getDate() === Number(date), 51 | async set(context, date) { 52 | const current = getCurrent(context); 53 | current.setDate(Number(date)); 54 | context.session.generateChange!.date = formatDateToStoredChangeDate( 55 | current, 56 | ); 57 | return '..'; 58 | }, 59 | }); 60 | 61 | monthMenu.select('', { 62 | columns: 2, 63 | choices: MONTH_OPTIONS, 64 | isSet: (context, month) => 65 | getCurrent(context).getMonth() + 1 === Number(month), 66 | async set(context, month) { 67 | const current = getCurrent(context); 68 | current.setMonth(Number(month) - 1); 69 | context.session.generateChange!.date = formatDateToStoredChangeDate( 70 | current, 71 | ); 72 | return '..'; 73 | }, 74 | }); 75 | 76 | yearMenu.select('', { 77 | choices: generateYearOptions(), 78 | isSet: (context, year) => getCurrent(context).getFullYear() === Number(year), 79 | async set(context, year) { 80 | const current = getCurrent(context); 81 | current.setFullYear(Number(year)); 82 | context.session.generateChange!.date = formatDateToStoredChangeDate( 83 | current, 84 | ); 85 | return '..'; 86 | }, 87 | }); 88 | 89 | dayMenu.navigate('..', {text: BACK_BUTTON_TEXT}); 90 | monthMenu.navigate('..', {text: BACK_BUTTON_TEXT}); 91 | yearMenu.navigate('..', {text: BACK_BUTTON_TEXT}); 92 | -------------------------------------------------------------------------------- /source/menu/events/changes/add/index.ts: -------------------------------------------------------------------------------- 1 | import {StatelessQuestion} from '@grammyjs/stateless-question'; 2 | import {arrayFilterUnique} from 'array-filter-unique'; 3 | import {Composer} from 'grammy'; 4 | import { 5 | deleteMenuFromContext, 6 | getMenuOfPath, 7 | MenuTemplate, 8 | replyMenuToContext, 9 | } from 'grammy-inline-menu'; 10 | import { 11 | formatDateToHumanReadable, 12 | formatDateToStoredChangeDate, 13 | } from '../../../../lib/calendar-helper.js'; 14 | import { 15 | generateChangeText, 16 | loadEvents, 17 | } from '../../../../lib/change-helper.js'; 18 | import type {Change, MyContext} from '../../../../lib/types.js'; 19 | import * as changeDetails from '../details.js'; 20 | import {createDatePickerButtons} from './date-selector.js'; 21 | import {createTimeSelectionSubmenuButtons} from './time-selector.js'; 22 | 23 | function changesOfEvent(context: MyContext, name: string) { 24 | const allChanges = context.userconfig.mine.changes; 25 | return allChanges.filter(o => o.name === name); 26 | } 27 | 28 | export const bot = new Composer(); 29 | export const menu = new MenuTemplate(context => { 30 | context.session.generateChange ??= {}; 31 | 32 | if (context.match) { 33 | context.session.generateChange.name = context.match[1]! 34 | .replaceAll(';', '/'); 35 | } 36 | 37 | const {name, date, add} = context.session.generateChange; 38 | let text = ''; 39 | 40 | if (!date) { 41 | text = 'Zu welchem Termin willst du eine Änderung hinzufügen?'; 42 | const changes = changesOfEvent(context, name!); 43 | if (changes.length > 0) { 44 | text 45 | += '\n\nFolgende Termine habe bereits eine Veränderung. Entferne die Veränderung zuerst, bevor du eine neue erstellen kannst.'; 46 | text += '\n'; 47 | 48 | const dates = changes.map(o => o.date); 49 | dates.sort(); 50 | text += dates 51 | .map(o => formatDateToHumanReadable(o)) 52 | .map(o => `- ${o}`) 53 | .join('\n'); 54 | } 55 | } 56 | 57 | if (date) { 58 | text = generateChangeText(context.session.generateChange as Change); 59 | text += add 60 | ? '\nSpezifiziere den zusätzlichen Termin.' 61 | : '\nWelche Art von Änderung willst du vornehmen?'; 62 | } 63 | 64 | return {text, parse_mode: 'HTML'}; 65 | }); 66 | 67 | function hidePickDateStep(context: MyContext): boolean { 68 | const {name, date} = context.session.generateChange ?? {}; 69 | return !name || Boolean(date); 70 | } 71 | 72 | function hideGenerateChangeStep(context: MyContext): boolean { 73 | const {name, date} = context.session.generateChange ?? {}; 74 | return !name || !date; 75 | } 76 | 77 | function hideGenerateAddStep(context: MyContext): boolean { 78 | const {name, date, add} = context.session.generateChange ?? {}; 79 | return !name || !date || !add; 80 | } 81 | 82 | function generationDataIsValid(context: MyContext): boolean { 83 | const keys = Object.keys(context.session.generateChange ?? []); 84 | // Required (2): name and date 85 | // There have to be other changes than that in order to do something. 86 | return keys.length > 2; 87 | } 88 | 89 | menu.interact('new-date', { 90 | text: '➕ Zusätzlicher Termin', 91 | hide: hidePickDateStep, 92 | do(context) { 93 | // Set everything that has to be set to be valid. 94 | // When the user dont like the data they can change it but they are not able to create invalid data. 95 | context.session.generateChange!.add = true; 96 | context.session.generateChange!.date = formatDateToStoredChangeDate( 97 | new Date(), 98 | ); 99 | context.session.generateChange!.starttime = new Date().toLocaleTimeString( 100 | 'de-DE', 101 | {hour12: false, hour: '2-digit', minute: '2-digit'}, 102 | ); 103 | context.session.generateChange!.endtime = '23:45'; 104 | return true; 105 | }, 106 | }); 107 | 108 | menu.choose('date', { 109 | columns: 2, 110 | hide: hidePickDateStep, 111 | async choices(context) { 112 | const name = context.match![1]!.replaceAll(';', '/'); 113 | const {date} = context.session.generateChange ?? {}; 114 | if (date) { 115 | // Date already selected 116 | return {}; 117 | } 118 | 119 | const existingChangeDates = new Set( 120 | changesOfEvent(context, name).map(o => o.date), 121 | ); 122 | const events = await loadEvents(name); 123 | const dates = events 124 | .map(o => o.StartTime) 125 | .map(o => formatDateToStoredChangeDate(o)) 126 | .filter(o => !existingChangeDates.has(o)) 127 | .filter(arrayFilterUnique()); 128 | return Object.fromEntries( 129 | dates.map(date => [date, formatDateToHumanReadable(date)]), 130 | ); 131 | }, 132 | do(context, key) { 133 | context.session.generateChange!.date = key; 134 | return true; 135 | }, 136 | getCurrentPage: context => context.session.page, 137 | setPage(context, page) { 138 | context.session.page = page; 139 | }, 140 | }); 141 | 142 | menu.interact('remove', { 143 | text: '🚫 Entfällt', 144 | async do(context) { 145 | context.session.generateChange!.remove = true; 146 | return finish(context); 147 | }, 148 | hide(context) { 149 | if (hideGenerateChangeStep(context)) { 150 | return true; 151 | } 152 | 153 | return Object.keys(context.session.generateChange!).length > 2; 154 | }, 155 | }); 156 | 157 | createDatePickerButtons(menu, hideGenerateAddStep); 158 | 159 | createTimeSelectionSubmenuButtons(menu, hideGenerateChangeStep); 160 | 161 | const namesuffixQuestion = new StatelessQuestion( 162 | 'change-add-suffix', 163 | async (context, path) => { 164 | if ('text' in context.message) { 165 | context.session.generateChange!.namesuffix = context.message.text; 166 | } 167 | 168 | await replyMenuToContext(menu, context, path); 169 | }, 170 | ); 171 | 172 | const roomQuestion = new StatelessQuestion( 173 | 'change-add-room', 174 | async (context, path) => { 175 | if ('text' in context.message) { 176 | context.session.generateChange!.room = context.message.text; 177 | } 178 | 179 | await replyMenuToContext(menu, context, path); 180 | }, 181 | ); 182 | 183 | bot.use(namesuffixQuestion.middleware()); 184 | bot.use(roomQuestion.middleware()); 185 | 186 | function questionButtonText( 187 | property: 'namesuffix' | 'room', 188 | emoji: string, 189 | fallback: string, 190 | ): (context: MyContext) => string { 191 | return context => { 192 | const value = context.session.generateChange![property]; 193 | const text = value ?? fallback; 194 | return emoji + ' ' + text; 195 | }; 196 | } 197 | 198 | menu.interact('namesuffix', { 199 | text: questionButtonText('namesuffix', '🗯', 'Namenszusatz'), 200 | hide: hideGenerateChangeStep, 201 | async do(context, path) { 202 | await namesuffixQuestion.replyWithHTML( 203 | context, 204 | 'Welche Zusatzinfo möchtest du dem Termin geben? Dies sollte nur ein Wort oder eine kurze Info sein, wie zum Beispiel "Klausurvorbereitung". Diese Info wird dann dem Titel des Termins angehängt.', 205 | getMenuOfPath(path), 206 | ); 207 | await deleteMenuFromContext(context); 208 | return false; 209 | }, 210 | }); 211 | 212 | menu.interact('room', { 213 | text: questionButtonText('room', '📍', 'Raum'), 214 | hide: hideGenerateChangeStep, 215 | async do(context, path) { 216 | await roomQuestion.replyWithHTML( 217 | context, 218 | 'In welchen Raum wurde der Termin verschoben?', 219 | getMenuOfPath(path), 220 | ); 221 | await deleteMenuFromContext(context); 222 | return false; 223 | }, 224 | }); 225 | 226 | menu.interact('finish', { 227 | text: '✅ Fertig stellen', 228 | do: finish, 229 | hide: context => !generationDataIsValid(context), 230 | }); 231 | 232 | async function finish(context: MyContext): Promise { 233 | const change = context.session.generateChange!; 234 | change.name = context.match![1]!.replaceAll(';', '/'); 235 | 236 | if (change.add) { 237 | const date = new Date(Date.parse(change.date!)); 238 | const [hour, minute] = change.starttime!.split(':').map(Number); 239 | date.setHours(hour!); 240 | date.setMinutes(minute!); 241 | change.date = formatDateToStoredChangeDate(date); 242 | delete change.starttime; 243 | } 244 | 245 | context.userconfig.mine.changes ??= []; 246 | 247 | const {name, date} = change; 248 | const alreadyExists = context.userconfig.mine.changes 249 | .some(o => o.name === name && o.date === date); 250 | if (alreadyExists) { 251 | // Dont do something when there is already a change for the date 252 | // This shouldn't occour but it can when the user adds a shared change 253 | // Also the user can add an additional date that they already have 'used' 254 | await context.answerCallbackQuery( 255 | 'Du hast bereits eine Veranstaltungsänderung für diesen Termin.', 256 | ); 257 | return true; 258 | } 259 | 260 | context.userconfig.mine.changes.push(change as Change); 261 | delete context.session.generateChange; 262 | 263 | const actionPart = changeDetails.generateChangeAction(change as Change); 264 | return `../d:${actionPart}/`; 265 | } 266 | 267 | menu.interact('abort', { 268 | joinLastRow: true, 269 | text: '🛑 Abbrechen', 270 | do(context) { 271 | delete context.session.generateChange; 272 | return '..'; 273 | }, 274 | }); 275 | -------------------------------------------------------------------------------- /source/menu/events/changes/add/time-selector.ts: -------------------------------------------------------------------------------- 1 | import {MenuTemplate} from 'grammy-inline-menu'; 2 | import { 3 | HOUR_OPTIONS, 4 | MINUTE_OPTIONS, 5 | } from '../../../../lib/event-creation-menu-options.js'; 6 | import {BACK_BUTTON_TEXT} from '../../../../lib/inline-menu.js'; 7 | import type {MyContext} from '../../../../lib/types.js'; 8 | 9 | export function createTimeSelectionSubmenuButtons( 10 | menu: MenuTemplate, 11 | hide: (context: MyContext) => boolean, 12 | ): void { 13 | createTimeSelectionSubmenuButton(menu, 'starttime', hide); 14 | createTimeSelectionSubmenuButton(menu, 'endtime', hide); 15 | } 16 | 17 | function createTimeSelectionSubmenuButton( 18 | menu: MenuTemplate, 19 | time: 'starttime' | 'endtime', 20 | hide: (context: MyContext) => boolean, 21 | ): void { 22 | const subMenu = new MenuTemplate( 23 | time === 'starttime' 24 | ? 'Zu welchem Zeitpunkt beginnt diese Veranstaltung stattdessen?' 25 | : 'Zu welchem Zeitpunkt endet diese Veranstaltung stattdessen?', 26 | ); 27 | 28 | menu.submenu(time, subMenu, { 29 | joinLastRow: time === 'endtime', 30 | hide, 31 | text(context) { 32 | const prefix = time === 'starttime' ? '▶️ ' : '⏹ '; 33 | const alreadySet = context.session.generateChange![time]; 34 | const fallback = time === 'starttime' ? 'Startzeit' : 'Endzeit'; 35 | return prefix + (alreadySet ?? fallback); 36 | }, 37 | }); 38 | 39 | subMenu.select('h', { 40 | columns: 3, 41 | choices: HOUR_OPTIONS, 42 | isSet: (context, key) => 43 | Number(context.session.generateChange![time]?.split(':')[0]) 44 | === Number(key), 45 | set(context, key) { 46 | const {minute} = getCurrent(context, time); 47 | context.session.generateChange![time] = formatTime(key, minute); 48 | return true; 49 | }, 50 | }); 51 | 52 | subMenu.select('m', { 53 | columns: 4, 54 | choices: MINUTE_OPTIONS, 55 | buttonText: (_, number) => ':' + numberToTwoDigit(number), 56 | isSet: (context, key) => 57 | Number(context.session.generateChange![time]?.split(':')[1]) 58 | === Number(key), 59 | set(context, key) { 60 | const {hour} = getCurrent(context, time); 61 | context.session.generateChange![time] = formatTime(hour, key); 62 | return true; 63 | }, 64 | }); 65 | 66 | subMenu.navigate('..', {text: BACK_BUTTON_TEXT}); 67 | } 68 | 69 | function formatTime(hour: number | string, minute: number | string): string { 70 | return numberToTwoDigit(hour) + ':' + numberToTwoDigit(minute); 71 | } 72 | 73 | function numberToTwoDigit(number: number | string): string { 74 | return Number(number) < 10 ? `0${number}` : String(number); 75 | } 76 | 77 | function getCurrent( 78 | context: MyContext, 79 | time: 'starttime' | 'endtime', 80 | ): {hour: number; minute: number} { 81 | const current = context.session.generateChange![time]; 82 | const fallback = time === 'starttime' ? '8:00' : '16:00'; 83 | const [hour, minute] = (current ?? fallback).split(':').map(Number); 84 | return {hour: hour!, minute: minute!}; 85 | } 86 | -------------------------------------------------------------------------------- /source/menu/events/changes/details.ts: -------------------------------------------------------------------------------- 1 | import {MenuTemplate} from 'grammy-inline-menu'; 2 | import { 3 | generateChangeText, 4 | generateShortChangeText, 5 | } from '../../../lib/change-helper.js'; 6 | import {backMainButtons} from '../../../lib/inline-menu.js'; 7 | import type {Change, MyContext} from '../../../lib/types.js'; 8 | 9 | export function generateChangeAction(change: Change): string { 10 | return change.date; 11 | } 12 | 13 | function getChangeFromContext(context: MyContext): Change | undefined { 14 | const name = context.match![1]!.replaceAll(';', '/'); 15 | const date = context.match![2]!; 16 | 17 | return context.userconfig.mine.changes 18 | .find(c => c.name === name && c.date === date); 19 | } 20 | 21 | export const menu = new MenuTemplate(context => { 22 | const change = getChangeFromContext(context); 23 | if (!change) { 24 | return 'Change does not exist anymore'; 25 | } 26 | 27 | const text = generateChangeText(change); 28 | return {text, parse_mode: 'HTML'}; 29 | }); 30 | 31 | menu.switchToChat({ 32 | text: 'Teilen…', 33 | query: context => generateShortChangeText(getChangeFromContext(context)!), 34 | hide(context) { 35 | const change = getChangeFromContext(context); 36 | return !change; 37 | }, 38 | }); 39 | menu.interact('r', { 40 | text: '⚠️ Änderung entfernen', 41 | async do(context) { 42 | const change = getChangeFromContext(context); 43 | context.userconfig.mine.changes = context.userconfig.mine.changes 44 | .filter(o => o.name !== change?.name || o.date !== change?.date); 45 | await context.answerCallbackQuery('Änderung wurde entfernt.'); 46 | return '..'; 47 | }, 48 | }); 49 | 50 | menu.manualRow(backMainButtons); 51 | -------------------------------------------------------------------------------- /source/menu/events/changes/index.ts: -------------------------------------------------------------------------------- 1 | import {Composer} from 'grammy'; 2 | import {MenuTemplate} from 'grammy-inline-menu'; 3 | import {html as format} from 'telegram-format'; 4 | import {formatDateToHumanReadable} from '../../../lib/calendar-helper.js'; 5 | import {backMainButtons} from '../../../lib/inline-menu.js'; 6 | import type {MyContext} from '../../../lib/types.js'; 7 | import * as changeAdd from './add/index.js'; 8 | import * as changeDetails from './details.js'; 9 | 10 | export const bot = new Composer(); 11 | export const menu = new MenuTemplate(ctx => { 12 | const event = ctx.match![1]!.replaceAll(';', '/'); 13 | 14 | let text = ''; 15 | text += format.bold('Veranstaltungsänderungen'); 16 | text += '\n'; 17 | text += format.escape(event); 18 | text += '\n\n'; 19 | text += format.escape(ctx.t('changes-help')); 20 | 21 | return {text, parse_mode: format.parse_mode}; 22 | }); 23 | 24 | bot.use(changeAdd.bot); 25 | 26 | menu.submenu('a', changeAdd.menu, {text: '➕ Änderung hinzufügen'}); 27 | 28 | menu.chooseIntoSubmenu('d', changeDetails.menu, { 29 | columns: 1, 30 | choices(ctx) { 31 | const event = ctx.match![1]!.replaceAll(';', '/'); 32 | const changes = ctx.userconfig.mine.changes 33 | .filter(o => o.name === event); 34 | return Object.fromEntries(changes.map(change => [ 35 | changeDetails.generateChangeAction(change), 36 | formatDateToHumanReadable(change.date), 37 | ])); 38 | }, 39 | getCurrentPage: ctx => ctx.session.page, 40 | setPage(ctx, page) { 41 | ctx.session.page = page; 42 | }, 43 | }); 44 | 45 | menu.manualRow(backMainButtons); 46 | -------------------------------------------------------------------------------- /source/menu/events/details.ts: -------------------------------------------------------------------------------- 1 | import {StatelessQuestion} from '@grammyjs/stateless-question'; 2 | import {Composer} from 'grammy'; 3 | import { 4 | deleteMenuFromContext, 5 | getMenuOfPath, 6 | MenuTemplate, 7 | replyMenuToContext, 8 | } from 'grammy-inline-menu'; 9 | import {html as format} from 'telegram-format'; 10 | import {backMainButtons} from '../../lib/inline-menu.js'; 11 | import type {MyContext} from '../../lib/types.js'; 12 | import * as changesMenu from './changes/index.js'; 13 | 14 | function getNameFromPath(path: string): string { 15 | const match = /\/d:([^/]+)\//.exec(path)!; 16 | return match[1]!.replaceAll(';', '/'); 17 | } 18 | 19 | export const bot = new Composer(); 20 | bot.use(changesMenu.bot); 21 | 22 | export const menu = new MenuTemplate((context, path) => { 23 | const name = getNameFromPath(path); 24 | const event = context.userconfig.mine.events[name]!; 25 | const changes = context.userconfig.mine.changes 26 | .filter(o => o.name === name) 27 | .length; 28 | 29 | let text = format.bold('Veranstaltung'); 30 | text += '\n'; 31 | text += name; 32 | text += '\n'; 33 | 34 | if (changes > 0) { 35 | text += '\n'; 36 | text += '✏️'; 37 | text += 'Änderungen'; 38 | text += ': '; 39 | text += String(changes); 40 | text += '\n'; 41 | } 42 | 43 | if (event.alertMinutesBefore !== undefined) { 44 | text += '\n'; 45 | text += '⏰'; 46 | text += 'Erinnerung'; 47 | text += ': '; 48 | text += `${event.alertMinutesBefore} Minuten vorher`; 49 | text += '\n'; 50 | } 51 | 52 | if (event.notes) { 53 | text += '\n'; 54 | text += '🗒'; 55 | text += format.bold('Notizen'); 56 | text += '\n'; 57 | text += format.escape(event.notes); 58 | text += '\n\n'; 59 | } 60 | 61 | return { 62 | disable_web_page_preview: true, 63 | parse_mode: format.parse_mode, 64 | text, 65 | }; 66 | }); 67 | 68 | menu.submenu('c', changesMenu.menu, { 69 | text: '✏️ Änderungen', 70 | hide: context => Object.keys(context.userconfig.mine.events).length === 0, 71 | }); 72 | 73 | const alertMenu = new MenuTemplate((_, path) => { 74 | const name = getNameFromPath(path); 75 | return `Wie lange im vorraus möchtest du an einen Termin der Veranstaltung ${name} erinnert werden?`; 76 | }); 77 | 78 | alertMenu.interact('nope', { 79 | text: '🔕 Garnicht', 80 | do(context, path) { 81 | const name = getNameFromPath(path); 82 | delete context.userconfig.mine.events[name]!.alertMinutesBefore; 83 | return '..'; 84 | }, 85 | }); 86 | 87 | alertMenu.choose('t', { 88 | columns: 3, 89 | choices: { 90 | 0: 'Beginn', 91 | 5: '5 Minuten', 92 | 10: '10 Minuten', 93 | 15: '15 Minuten', 94 | 30: '30 Minuten', 95 | 45: '45 Minuten', 96 | 60: '1 Stunde', 97 | 120: '2 Stunden', 98 | 1337: '1337 Minuten', 99 | }, 100 | do(context, key) { 101 | if (!context.callbackQuery?.data) { 102 | throw new Error('how?'); 103 | } 104 | 105 | const name = getNameFromPath(context.callbackQuery.data); 106 | const minutes = Number(key); 107 | context.userconfig.mine.events[name]!.alertMinutesBefore = minutes; 108 | return '..'; 109 | }, 110 | }); 111 | 112 | alertMenu.manualRow(backMainButtons); 113 | 114 | menu.submenu('alert', alertMenu, {text: '⏰ Erinnerung'}); 115 | 116 | const noteQuestion = new StatelessQuestion( 117 | 'event-notes', 118 | async (context, path) => { 119 | const name = getNameFromPath(path); 120 | if ('text' in context.message) { 121 | const notes = context.message.text; 122 | 123 | context.userconfig.mine.events[name]!.notes = notes; 124 | } 125 | 126 | await replyMenuToContext(menu, context, path); 127 | }, 128 | ); 129 | 130 | bot.use(noteQuestion.middleware()); 131 | 132 | menu.interact('set-notes', { 133 | text: '🗒 Schreibe Notiz', 134 | async do(context, path) { 135 | const name = getNameFromPath(path); 136 | const text = `Welche Notizen möchtest du an den Kalendereinträgen von ${ 137 | format.escape(name) 138 | } stehen haben?`; 139 | await noteQuestion.replyWithHTML(context, text, getMenuOfPath(path)); 140 | await deleteMenuFromContext(context); 141 | return false; 142 | }, 143 | }); 144 | 145 | menu.interact('remove-notes', { 146 | text: 'Notiz löschen', 147 | joinLastRow: true, 148 | hide(context, path) { 149 | const name = getNameFromPath(path); 150 | return !context.userconfig.mine.events[name]!.notes; 151 | }, 152 | do(context, path) { 153 | const name = getNameFromPath(path); 154 | delete context.userconfig.mine.events[name]!.notes; 155 | return true; 156 | }, 157 | }); 158 | 159 | const removeMenu = new MenuTemplate(context => { 160 | const event = context.match![1]!.replaceAll(';', '/'); 161 | return event 162 | + '\n\nBist du dir sicher, dass du diese Veranstaltung entfernen möchtest?'; 163 | }); 164 | removeMenu.interact('y', { 165 | text: 'Ja ich will!', 166 | async do(context) { 167 | const event = context.match![1]!.replaceAll(';', '/'); 168 | // eslint-disable-next-line @typescript-eslint/no-dynamic-delete 169 | delete context.userconfig.mine.events[event]; 170 | 171 | // Only keep changes of events the user still has 172 | context.userconfig.mine.changes = context.userconfig.mine.changes 173 | .filter(o => 174 | Object.keys(context.userconfig.mine.events).includes(o.name), 175 | ); 176 | 177 | await context.answerCallbackQuery( 178 | `${event} wurde aus deinem Kalender entfernt.`, 179 | ); 180 | return true; 181 | }, 182 | }); 183 | removeMenu.navigate('..', {joinLastRow: true, text: '🛑 Abbrechen'}); 184 | 185 | menu.submenu('r', removeMenu, {text: '🗑 Veranstaltung entfernen'}); 186 | 187 | menu.manualRow(backMainButtons); 188 | -------------------------------------------------------------------------------- /source/menu/events/index.ts: -------------------------------------------------------------------------------- 1 | import {Composer} from 'grammy'; 2 | import {MenuTemplate} from 'grammy-inline-menu'; 3 | import {html as format} from 'telegram-format'; 4 | import * as allEvents from '../../lib/all-events.js'; 5 | import {backMainButtons} from '../../lib/inline-menu.js'; 6 | import type {MyContext} from '../../lib/types.js'; 7 | import * as addMenu from './add.js'; 8 | import * as detailsMenu from './details.js'; 9 | 10 | export const bot = new Composer(); 11 | export const menu = new MenuTemplate(async context => { 12 | let text = format.bold('Veranstaltungen'); 13 | text += '\n\n'; 14 | 15 | const events = Object.keys(context.userconfig.mine.events); 16 | events.sort(); 17 | if (events.length > 0) { 18 | const nonExisting = new Set(await allEvents.nonExisting(events)); 19 | text += 'Du hast folgende Veranstaltungen im Kalender:'; 20 | text += '\n'; 21 | text += events 22 | .map(o => { 23 | let line = '- '; 24 | if (nonExisting.has(o)) { 25 | line += '⚠️ '; 26 | } 27 | 28 | line += format.escape(o); 29 | return line; 30 | }) 31 | .join('\n'); 32 | 33 | if (nonExisting.size > 0) { 34 | text += '\n\n'; 35 | text += '⚠️ Du hast Veranstaltungen, die nicht mehr existieren.'; 36 | } 37 | } else { 38 | text += 'Du hast aktuell keine Veranstaltungen in deinem Kalender. 😔'; 39 | } 40 | 41 | text += '\n\n'; 42 | const additionalEventsLink = format.url( 43 | 'AdditionalEvents', 44 | 'https://github.com/HAWHHCalendarBot/AdditionalEvents', 45 | ); 46 | text 47 | += `Du bist Tutor und deine Veranstaltung fehlt im Kalenderbot? Wirf mal einen Blick auf ${additionalEventsLink} oder schreib @EdJoPaTo an. ;)`; 48 | 49 | return { 50 | disable_web_page_preview: true, 51 | parse_mode: format.parse_mode, 52 | text, 53 | }; 54 | }); 55 | 56 | bot.use(addMenu.bot); 57 | bot.use(detailsMenu.bot); 58 | 59 | menu.interact('remove-old', { 60 | text: '🗑 Entferne nicht mehr Existierende', 61 | async hide(context) { 62 | const nonExisting = await allEvents.nonExisting( 63 | Object.keys(context.userconfig.mine.events), 64 | ); 65 | return nonExisting.length === 0; 66 | }, 67 | async do(context) { 68 | const nonExisting = new Set( 69 | await allEvents.nonExisting(Object.keys(context.userconfig.mine.events)), 70 | ); 71 | for (const name of nonExisting) { 72 | // eslint-disable-next-line @typescript-eslint/no-dynamic-delete 73 | delete context.userconfig.mine.events[name]; 74 | } 75 | 76 | // Only keep changes of events the user still has 77 | context.userconfig.mine.changes = context.userconfig.mine.changes 78 | .filter(o => 79 | Object.keys(context.userconfig.mine.events).includes(o.name), 80 | ); 81 | 82 | return true; 83 | }, 84 | }); 85 | 86 | menu.submenu('a', addMenu.menu, {text: '➕ Veranstaltung hinzufügen'}); 87 | 88 | menu.chooseIntoSubmenu('d', detailsMenu.menu, { 89 | columns: 1, 90 | choices(context) { 91 | const {changes} = context.userconfig.mine; 92 | const result: Record = {}; 93 | 94 | for ( 95 | const [name, details] of Object.entries(context.userconfig.mine.events) 96 | ) { 97 | let title = name + ' '; 98 | 99 | if (changes.some(o => o.name === name)) { 100 | title += '✏️'; 101 | } 102 | 103 | if (details.alertMinutesBefore !== undefined) { 104 | title += '⏰'; 105 | } 106 | 107 | if (details.notes) { 108 | title += '🗒'; 109 | } 110 | 111 | result[name.replaceAll('/', ';')] = title.trim(); 112 | } 113 | 114 | return result; 115 | }, 116 | getCurrentPage: context => context.session.page, 117 | setPage(context, page) { 118 | context.session.page = page; 119 | }, 120 | }); 121 | 122 | menu.manualRow(backMainButtons); 123 | -------------------------------------------------------------------------------- /source/menu/index.ts: -------------------------------------------------------------------------------- 1 | import {Composer} from 'grammy'; 2 | import {MenuMiddleware} from 'grammy-inline-menu'; 3 | import type {MyContext} from '../lib/types.js'; 4 | import * as about from './about.js'; 5 | import * as admin from './admin/index.js'; 6 | import * as data from './data.js'; 7 | import * as events from './events/index.js'; 8 | import * as mensa from './mensa/index.js'; 9 | import * as subscribe from './subscribe/index.js'; 10 | 11 | export const bot = new Composer(); 12 | 13 | const mensaMiddleware = new MenuMiddleware('mensa/', mensa.menu); 14 | bot.command('mensa', async ctx => mensaMiddleware.replyToContext(ctx)); 15 | bot.use(mensaMiddleware); 16 | 17 | const eventMiddleware = new MenuMiddleware('e/', events.menu); 18 | bot.command('events', async ctx => eventMiddleware.replyToContext(ctx)); 19 | bot.use(events.bot); 20 | bot.use(eventMiddleware); 21 | 22 | const subscribeMiddleware = new MenuMiddleware('subscribe/', subscribe.menu); 23 | bot.command('subscribe', async ctx => { 24 | // eslint-disable-next-line unicorn/prefer-ternary 25 | if (Object.keys(ctx.userconfig.mine.events).length === 0) { 26 | await ctx.reply(ctx.t('subscribe-empty')); 27 | } else { 28 | await subscribeMiddleware.replyToContext(ctx); 29 | } 30 | }); 31 | bot.use(subscribe.bot); 32 | bot.use(subscribeMiddleware); 33 | 34 | const aboutMiddleware = new MenuMiddleware('about/', about.menu); 35 | bot.command('about', async ctx => aboutMiddleware.replyToContext(ctx)); 36 | bot.use(aboutMiddleware); 37 | 38 | const dataMiddleware = new MenuMiddleware('data/', data.menu); 39 | bot.command( 40 | ['data', 'privacy', 'stop'], 41 | async ctx => dataMiddleware.replyToContext(ctx), 42 | ); 43 | bot.use(data.bot); 44 | bot.use(dataMiddleware); 45 | 46 | const adminComposer = new Composer(); 47 | const adminMiddleware = new MenuMiddleware('admin/', admin.menu); 48 | adminComposer.command( 49 | 'admin', 50 | async ctx => adminMiddleware.replyToContext(ctx), 51 | ); 52 | adminComposer.use(admin.bot); 53 | adminComposer.use(adminMiddleware); 54 | // False positive 55 | // eslint-disable-next-line unicorn/no-array-method-this-argument 56 | bot.filter(ctx => Boolean(ctx.userconfig.mine.admin), adminComposer); 57 | -------------------------------------------------------------------------------- /source/menu/mensa/index.ts: -------------------------------------------------------------------------------- 1 | import {MenuTemplate} from 'grammy-inline-menu'; 2 | import * as mensaGit from '../../lib/mensa-git.js'; 3 | import {generateMealText} from '../../lib/mensa-helper.js'; 4 | import {getMealsOfDay} from '../../lib/mensa-meals.js'; 5 | import type {MyContext} from '../../lib/types.js'; 6 | import {menu as mensaSettingsMenu} from './settings.js'; 7 | 8 | const WEEKDAYS = [ 9 | 'Sonntag', 10 | 'Montag', 11 | 'Dienstag', 12 | 'Mittwoch', 13 | 'Donnerstag', 14 | 'Freitag', 15 | 'Samstag', 16 | ] as const; 17 | const DAY_IN_MS = 1000 * 60 * 60 * 24; 18 | 19 | setInterval(async () => mensaGit.pull(), 1000 * 60 * 30); // Every 30 minutes 20 | // eslint-disable-next-line @typescript-eslint/no-floating-promises 21 | mensaGit.pull(); 22 | 23 | function getYearMonthDay( 24 | date: Readonly, 25 | ): Readonly<{year: number; month: number; day: number}> { 26 | const year = date.getFullYear(); 27 | const month = date.getMonth() + 1; 28 | const day = date.getDate(); 29 | return {year, month, day}; 30 | } 31 | 32 | function stringifyEqual(first: unknown, second: unknown): boolean { 33 | if (!first || !second) { 34 | return false; 35 | } 36 | 37 | if (first === second) { 38 | return true; 39 | } 40 | 41 | return JSON.stringify(first) === JSON.stringify(second); 42 | } 43 | 44 | function dateEqual(first: Readonly, second: Readonly): boolean { 45 | return stringifyEqual(getYearMonthDay(first), getYearMonthDay(second)); 46 | } 47 | 48 | function getCurrentSettings( 49 | context: MyContext, 50 | ): Readonly<{mensa?: string; date: Date}> { 51 | let {mensa, date} = context.session.mensa ?? {}; 52 | mensa ||= context.userconfig.mine.mensa.main; 53 | date ??= Date.now(); 54 | 55 | const now = Date.now(); 56 | // When that date is more than a day ago, update it 57 | if ((now - date) > DAY_IN_MS) { 58 | date = Date.now(); 59 | mensa = context.userconfig.mine.mensa.main; 60 | } 61 | 62 | return {mensa, date: new Date(date)}; 63 | } 64 | 65 | export const menu = new MenuTemplate(async context => { 66 | const {mensa, date} = getCurrentSettings(context); 67 | const mensaSettings = context.userconfig.mine.mensa; 68 | 69 | if (!mensa || mensa === 'undefined') { 70 | return '⚠️ Du hast keine Mensa gesetzt, zu der du dein Angebot bekommen möchtest. Diese kannst du in den Einstellungen setzen.'; 71 | } 72 | 73 | const weekday = WEEKDAYS[date.getDay()]!; 74 | const {year, month, day} = getYearMonthDay(date); 75 | let text = ''; 76 | text += `${mensa}`; 77 | text += '\n'; 78 | text += `${weekday} ${day}.${month}.${year}`; 79 | text += '\n'; 80 | 81 | const meals = await getMealsOfDay(mensa, year, month, day); 82 | text += generateMealText(meals, mensaSettings); 83 | 84 | return {text, parse_mode: 'HTML'}; 85 | }); 86 | 87 | function parseDateString(actionCode: string): Readonly { 88 | const date = new Date(Date.parse(actionCode)); 89 | return date; 90 | } 91 | 92 | function generateDateString(date: Date): string { 93 | const {year, month, day} = getYearMonthDay(date); 94 | return `${year}-${month}-${day}`; 95 | } 96 | 97 | // Select day 98 | menu.select('t', { 99 | columns: 3, 100 | choices(context) { 101 | const {mensa} = getCurrentSettings(context); 102 | if (!mensa) { 103 | return {}; 104 | } 105 | 106 | const dateOptions: Date[] = []; 107 | const daysInFuture = 6; 108 | 109 | for (let i = 0; i < daysInFuture; i++) { 110 | dateOptions.push(new Date(Date.now() + (DAY_IN_MS * i))); 111 | } 112 | 113 | const result: Record = {}; 114 | for (const date of dateOptions) { 115 | const weekday = WEEKDAYS[date.getDay()]! 116 | .slice(0, 2); 117 | const day = date.getDate(); 118 | const key = generateDateString(date); 119 | result[key] = `${weekday} ${day}.`; 120 | } 121 | 122 | return result; 123 | }, 124 | isSet: (context, key) => 125 | dateEqual(getCurrentSettings(context).date, parseDateString(key)), 126 | set(context, key) { 127 | context.session.mensa ??= {}; 128 | context.session.mensa.date = parseDateString(key).getTime(); 129 | return true; 130 | }, 131 | formatState: (_, textResult, state) => 132 | state ? `🕚 ${textResult}` : textResult, 133 | }); 134 | 135 | // Select mensa 136 | menu.choose('m', { 137 | columns: 1, 138 | choices(context) { 139 | const current = getCurrentSettings(context).mensa; 140 | const {main, more} = context.userconfig.mine.mensa; 141 | return [main, ...(more ?? [])] 142 | .filter(o => o !== current) 143 | .filter(o => typeof o === 'string') 144 | .filter(Boolean); 145 | }, 146 | buttonText: (_, key) => '🍽 ' + key, 147 | do(context, key) { 148 | context.session.mensa ??= {}; 149 | context.session.mensa.mensa = key; 150 | return true; 151 | }, 152 | }); 153 | 154 | menu.submenu('settings', mensaSettingsMenu, {text: '⚙️ Mensa Einstellungen'}); 155 | -------------------------------------------------------------------------------- /source/menu/mensa/settings.ts: -------------------------------------------------------------------------------- 1 | import {MenuTemplate} from 'grammy-inline-menu'; 2 | import {html as format} from 'telegram-format'; 3 | import {backMainButtons} from '../../lib/inline-menu.js'; 4 | import {getCanteenList} from '../../lib/mensa-meals.js'; 5 | import { 6 | type MealWish, 7 | type MensaPriceClass, 8 | type MyContext, 9 | } from '../../lib/types.js'; 10 | 11 | function enabledEmoji(truthy: boolean | undefined): '✅' | '🚫' { 12 | return truthy ? '✅' : '🚫'; 13 | } 14 | 15 | const settingName = { 16 | vegan: 'vegan', 17 | vegetarian: 'vegetarisch', 18 | lactoseFree: 'laktosefrei', 19 | noAlcohol: 'kein Alkohol', 20 | noBeef: 'kein Rindfleisch', 21 | noFish: 'kein Fisch', 22 | noGame: 'kein Wild', 23 | noGelatine: 'keine Gelatine', 24 | noLamb: 'kein Lamm', 25 | noPig: 'kein Schweinefleisch', 26 | noPoultry: 'kein Geflügel', 27 | } as const satisfies Record; 28 | const MealWishOptions = Object.keys(settingName) as readonly MealWish[]; 29 | 30 | async function updateMore(context: MyContext, set: ReadonlySet) { 31 | const {main} = context.userconfig.mine.mensa; 32 | const allAvailableCanteens = new Set(await getCanteenList()); 33 | const more = [...set] 34 | .filter(canteen => canteen !== main) 35 | .filter(canteen => allAvailableCanteens.has(canteen)); 36 | 37 | if (more.length > 0) { 38 | context.userconfig.mine.mensa.more = more.sort(); 39 | } else { 40 | delete context.userconfig.mine.mensa.more; 41 | } 42 | } 43 | 44 | export const menu = new MenuTemplate({ 45 | parse_mode: format.parse_mode, 46 | text: format.bold('Mensa Einstellungen'), 47 | }); 48 | 49 | const mainMensaMenu = new MenuTemplate({ 50 | parse_mode: format.parse_mode, 51 | text: format.bold('Mensa Einstellungen') + '\nHauptmensa', 52 | }); 53 | menu.submenu('main', mainMensaMenu, { 54 | text(context) { 55 | const {main} = context.userconfig.mine.mensa; 56 | let text = 'Hauptmensa'; 57 | if (main) { 58 | text += `: ${main}`; 59 | } 60 | 61 | return text; 62 | }, 63 | }); 64 | mainMensaMenu.select('set', { 65 | columns: 1, 66 | choices: getCanteenList, 67 | async set(context, mensa) { 68 | const more = new Set(context.userconfig.mine.mensa.more ?? []); 69 | 70 | const oldMain = context.userconfig.mine.mensa.main; 71 | if (oldMain) { 72 | more.add(oldMain); 73 | } 74 | 75 | context.userconfig.mine.mensa.main = mensa; 76 | await updateMore(context, more); 77 | return '..'; 78 | }, 79 | isSet: (context, mensa) => mensa === context.userconfig.mine.mensa.main, 80 | getCurrentPage: context => context.session.page, 81 | setPage(context, page) { 82 | context.session.page = page; 83 | }, 84 | }); 85 | 86 | mainMensaMenu.manualRow(backMainButtons); 87 | 88 | function isAdditionalMensa(context: MyContext, mensa: string): boolean { 89 | const selected = context.userconfig.mine.mensa.more ?? []; 90 | return selected.includes(mensa); 91 | } 92 | 93 | const moreMenu = new MenuTemplate({ 94 | parse_mode: format.parse_mode, 95 | text: format.bold('Mensa Einstellungen') 96 | + '\nWähle weitere Mensen, in den du gelegentlich bist', 97 | }); 98 | menu.submenu('more', moreMenu, { 99 | hide: context => !context.userconfig.mine.mensa.main, 100 | text(context) { 101 | const selected = context.userconfig.mine.mensa.more ?? []; 102 | let text = 'Weitere Mensen'; 103 | if (selected.length > 0) { 104 | text += ` (${selected.length})`; 105 | } 106 | 107 | return text; 108 | }, 109 | }); 110 | moreMenu.select('more', { 111 | columns: 1, 112 | choices: getCanteenList, 113 | isSet: (context, mensa) => isAdditionalMensa(context, mensa), 114 | async set(context, mensa) { 115 | if (context.userconfig.mine.mensa.main === mensa) { 116 | await context.answerCallbackQuery( 117 | mensa + ' ist bereits deine Hauptmensa', 118 | ); 119 | return false; 120 | } 121 | 122 | const more = new Set(context.userconfig.mine.mensa.more ?? []); 123 | if (more.has(mensa)) { 124 | more.delete(mensa); 125 | } else { 126 | more.add(mensa); 127 | } 128 | 129 | await updateMore(context, more); 130 | return true; 131 | }, 132 | formatState(context, mensa, state) { 133 | if (context.userconfig.mine.mensa.main === mensa) { 134 | return '🍽 ' + mensa; 135 | } 136 | 137 | return enabledEmoji(state) + ' ' + mensa; 138 | }, 139 | getCurrentPage: context => context.session.page, 140 | setPage(context, page) { 141 | context.session.page = page; 142 | }, 143 | }); 144 | moreMenu.manualRow(backMainButtons); 145 | 146 | const PRICE_OPTIONS = { 147 | student: 'Student', 148 | attendant: 'Angestellt', 149 | guest: 'Gast', 150 | } as const satisfies Record; 151 | 152 | menu.select('price', { 153 | choices: PRICE_OPTIONS, 154 | set(context, price) { 155 | context.userconfig.mine.mensa.price = price as MensaPriceClass; 156 | return true; 157 | }, 158 | isSet: (context, price) => context.userconfig.mine.mensa.price === price, 159 | hide: context => !context.userconfig.mine.mensa.main, 160 | }); 161 | 162 | const specialWishMenu = new MenuTemplate(context => { 163 | let text = format.bold('Mensa Einstellungen'); 164 | text += '\nWelche Sonderwünsche hast du zu deinem Essen?'; 165 | text += '\n\n'; 166 | 167 | const anyWishesSelected = MealWishOptions 168 | .some(o => context.userconfig.mine.mensa[o]); 169 | 170 | text += anyWishesSelected 171 | ? 'Aktuell werden die Angebote für dich nach deinen Wünschen gefiltert.' 172 | : 'Aktuell siehst du alle ungefilterten Angebote.'; 173 | 174 | return {text, parse_mode: format.parse_mode}; 175 | }); 176 | menu.submenu('s', specialWishMenu, { 177 | text: 'Extrawünsche Essen', 178 | hide: context => !context.userconfig.mine.mensa.main, 179 | }); 180 | 181 | function showWishAsOption(context: MyContext, wish: MealWish): boolean { 182 | const wishes = context.userconfig.mine.mensa; 183 | switch (wish) { 184 | case 'noBeef': 185 | case 'noFish': 186 | case 'noGame': 187 | case 'noGelatine': 188 | case 'noLamb': 189 | case 'noPig': 190 | case 'noPoultry': { 191 | return !wishes.vegan && !wishes.vegetarian; 192 | } 193 | 194 | case 'vegetarian': 195 | case 'lactoseFree': { 196 | return !wishes.vegan; 197 | } 198 | 199 | case 'noAlcohol': 200 | case 'vegan': { 201 | return true; 202 | } 203 | } 204 | } 205 | 206 | specialWishMenu.select('w', { 207 | columns: 1, 208 | choices: context => 209 | Object.fromEntries( 210 | MealWishOptions 211 | .filter(wish => showWishAsOption(context, wish)) 212 | .map(wish => [wish, settingName[wish]]), 213 | ), 214 | isSet: (context, wish) => 215 | Boolean(context.userconfig.mine.mensa[wish as MealWish]), 216 | set(context, wish, newState) { 217 | if (newState) { 218 | context.userconfig.mine.mensa[wish as MealWish] = true; 219 | } else { 220 | // eslint-disable-next-line @typescript-eslint/no-dynamic-delete 221 | delete context.userconfig.mine.mensa[wish as MealWish]; 222 | } 223 | 224 | return true; 225 | }, 226 | }); 227 | specialWishMenu.interact('warm', { 228 | text: 'warm… nicht versalzen… kein Spüli…', 229 | async do(context) { 230 | await context.answerCallbackQuery('das wär mal was… 😈'); 231 | return false; 232 | }, 233 | }); 234 | 235 | specialWishMenu.manualRow(backMainButtons); 236 | 237 | menu.toggle('showAdditives', { 238 | text: 'zeige Inhaltsstoffe', 239 | set(context, newState) { 240 | if (newState) { 241 | context.userconfig.mine.mensa.showAdditives = true; 242 | } else { 243 | delete context.userconfig.mine.mensa.showAdditives; 244 | } 245 | 246 | return true; 247 | }, 248 | isSet: context => context.userconfig.mine.mensa.showAdditives === true, 249 | hide: context => !context.userconfig.mine.mensa.main, 250 | }); 251 | 252 | menu.manualRow(backMainButtons); 253 | -------------------------------------------------------------------------------- /source/menu/subscribe/index.ts: -------------------------------------------------------------------------------- 1 | import {Composer} from 'grammy'; 2 | import {type Body, MenuTemplate} from 'grammy-inline-menu'; 3 | import {getUrlFromContext} from '../../lib/calendar-helper.js'; 4 | import {backMainButtons} from '../../lib/inline-menu.js'; 5 | import type {MyContext} from '../../lib/types.js'; 6 | import {menu as removedStyleMenu} from './removed-style.js'; 7 | import * as suffixMenu from './suffix.js'; 8 | 9 | export const bot = new Composer(); 10 | export const menu = new MenuTemplate(generateBody('overview')); 11 | 12 | bot.use(suffixMenu.bot); 13 | 14 | const appleMenu = new MenuTemplate(generateBody('apple')); 15 | appleMenu.url({ 16 | text: 'Kalender abonnieren', 17 | url: ctx => 18 | `https://calendarbot.hawhh.de/ics.html?url=${getUrlFromContext(ctx)}`, 19 | }); 20 | appleMenu.manualRow(backMainButtons); 21 | menu.submenu('apple', appleMenu, {text: '🍏 iOS / macOS'}); 22 | 23 | const exchangeMenu = new MenuTemplate(generateBody('exchange')); 24 | exchangeMenu.url({ 25 | text: 'Office.com', 26 | url: 'https://outlook.office.com/calendar', 27 | }); 28 | exchangeMenu.manualRow(backMainButtons); 29 | menu.submenu('exchange', exchangeMenu, {text: '🗂 Office.com (HAW Account)'}); 30 | 31 | const googleMenu = new MenuTemplate(generateBody('google')); 32 | menu.submenu('google', googleMenu, {text: '🍰 Google Kalender'}); 33 | googleMenu.url({ 34 | text: 'Google Calendar', 35 | url: 'https://calendar.google.com/', 36 | }); 37 | googleMenu.url({ 38 | text: 'Google Sync Settings', 39 | url: 'https://www.google.com/calendar/syncselect', 40 | }); 41 | googleMenu.navigate('../exchange/', { 42 | text: 'abonnieren mit dem Office.com HAW Account', 43 | }); 44 | googleMenu.manualRow(backMainButtons); 45 | 46 | const freestyleMenu = new MenuTemplate(generateBody('freestyle')); 47 | freestyleMenu.url({ 48 | text: 'Kalender abonnieren', 49 | url: ctx => 50 | `https://calendarbot.hawhh.de/ics.html?url=${getUrlFromContext(ctx)}`, 51 | }); 52 | freestyleMenu.manualRow(backMainButtons); 53 | menu.submenu('freestyle', freestyleMenu, {text: 'Freestyle 😎'}); 54 | 55 | menu.submenu('suffix', suffixMenu.menu, {text: '⚙️ URL Privacy'}); 56 | menu.submenu('showRemoved', removedStyleMenu, { 57 | text: '⚙️ Anzeigeart entfernter Termine', 58 | }); 59 | 60 | function generateBody(resourceKeySuffix: string): (ctx: MyContext) => Body { 61 | return ctx => ({ 62 | parse_mode: 'HTML', 63 | text: ctx.t('subscribe-' + resourceKeySuffix, { 64 | firstname: ctx.from!.first_name, 65 | url: getUrlFromContext(ctx), 66 | }) 67 | // Remove Isolate Characters which are inserted automatically by Fluent. 68 | // They are useful to prevent the variables from inserting annoying stuff but here they destroy the url 69 | .replaceAll(/[\u2068\u2069]+/g, ''), 70 | }); 71 | } 72 | -------------------------------------------------------------------------------- /source/menu/subscribe/removed-style.ts: -------------------------------------------------------------------------------- 1 | import {MenuTemplate} from 'grammy-inline-menu'; 2 | import {backMainButtons} from '../../lib/inline-menu.js'; 3 | import type {MyContext, RemovedEventsDisplayStyle} from '../../lib/types.js'; 4 | 5 | const CHOICES = { 6 | cancelled: '👌 Standard', 7 | removed: '🗑 komplett entfernen', 8 | emoji: '🚫 erzwungen', 9 | } as const satisfies Record; 10 | 11 | export const menu = new MenuTemplate(ctx => ({ 12 | parse_mode: 'HTML', 13 | text: ctx.t('subscribe-removed-setting'), 14 | })); 15 | 16 | menu.select('s', { 17 | columns: 1, 18 | choices: CHOICES, 19 | set(context, key) { 20 | context.userconfig.mine.removedEvents = key as RemovedEventsDisplayStyle; 21 | return true; 22 | }, 23 | isSet: (context, key) => 24 | (context.userconfig.mine.removedEvents ?? 'cancelled') === key, 25 | }); 26 | 27 | menu.manualRow(backMainButtons); 28 | -------------------------------------------------------------------------------- /source/menu/subscribe/suffix.ts: -------------------------------------------------------------------------------- 1 | import {StatelessQuestion} from '@grammyjs/stateless-question'; 2 | import {Composer} from 'grammy'; 3 | import { 4 | deleteMenuFromContext, 5 | getMenuOfPath, 6 | MenuTemplate, 7 | replyMenuToContext, 8 | } from 'grammy-inline-menu'; 9 | import {getUrlFromContext} from '../../lib/calendar-helper.js'; 10 | import {backMainButtons} from '../../lib/inline-menu.js'; 11 | import type {MyContext} from '../../lib/types.js'; 12 | 13 | export const bot = new Composer(); 14 | export const menu = new MenuTemplate(context => { 15 | const {calendarfileSuffix} = context.userconfig.mine; 16 | return { 17 | parse_mode: 'HTML', 18 | text: context.t('subscribe-suffix', { 19 | calendarfileSuffix, 20 | url: getUrlFromContext(context), 21 | userId: context.from!.id.toString(), 22 | }) 23 | // Remove Isolate Characters which are inserted automatically by Fluent. 24 | // They are useful to prevent the variables from inserting annoying stuff but here they destroy the url 25 | .replaceAll(/[\u2068\u2069]+/g, ''), 26 | }; 27 | }); 28 | 29 | const SUFFIX_MAX_LENGTH = 15; 30 | const SUFFIX_MIN_LENGTH = 3; 31 | 32 | async function setSuffix(context: MyContext, value: string): Promise { 33 | value = String(value) 34 | .replaceAll(/[^\w\d]/g, '') 35 | .slice(0, SUFFIX_MAX_LENGTH); 36 | if (value.length < SUFFIX_MIN_LENGTH) { 37 | return; 38 | } 39 | 40 | context.userconfig.mine.calendarfileSuffix = value; 41 | await sendHintText(context); 42 | } 43 | 44 | async function sendHintText(context: MyContext): Promise { 45 | const hintText = '⚠️ Hinweis: Dein Kalender muss nun neu abonniert werden!'; 46 | if (context.callbackQuery) { 47 | await context.answerCallbackQuery({text: hintText, show_alert: true}); 48 | return; 49 | } 50 | 51 | await context.reply(hintText); 52 | } 53 | 54 | menu.interact('g', { 55 | text: 'Generieren…', 56 | async do(context) { 57 | // 10^8 -> 10 ** 8 58 | const fromTime = Date.now() % (10 ** 8); 59 | await setSuffix(context, String(fromTime)); 60 | return true; 61 | }, 62 | }); 63 | 64 | const manualSuffixQuestion = new StatelessQuestion( 65 | 'subscribe-suffix-manual', 66 | async (context, path) => { 67 | if (context.message.text) { 68 | await setSuffix(context, context.message.text); 69 | } 70 | 71 | await replyMenuToContext(menu, context, path); 72 | }, 73 | ); 74 | 75 | bot.use(manualSuffixQuestion.middleware()); 76 | 77 | menu.interact('s', { 78 | text: 'Manuell setzen…', 79 | async do(context, path) { 80 | await manualSuffixQuestion.replyWithHTML( 81 | context, 82 | `Gib mir Tiernamen! 🦁🦇🐌🦍\nOder andere zufällige Buchstaben und Zahlen Kombinationen.\nSonderzeichen werden heraus gefiltert. Muss mindestens ${SUFFIX_MIN_LENGTH} Zeichen lang sein. Romane werden leider auf ${SUFFIX_MAX_LENGTH} Zeichen gekürzt.`, 83 | getMenuOfPath(path), 84 | ); 85 | 86 | await deleteMenuFromContext(context); 87 | return false; 88 | }, 89 | }); 90 | 91 | menu.manualRow(backMainButtons); 92 | -------------------------------------------------------------------------------- /source/migrate-stuff.ts: -------------------------------------------------------------------------------- 1 | import {Composer} from 'grammy'; 2 | import {getCanteenList} from './lib/mensa-meals.js'; 3 | import type {EventDetails, MyContext} from './lib/types.js'; 4 | 5 | export const bot = new Composer(); 6 | 7 | bot.use(async (ctx, next) => { 8 | if (!ctx.userconfig.mine.calendarfileSuffix) { 9 | const fromTime = Date.now() % (10 ** 8); 10 | ctx.userconfig.mine.calendarfileSuffix = String(fromTime); 11 | } 12 | 13 | ctx.userconfig.mine.changes ??= []; 14 | ctx.userconfig.mine.events ??= {}; 15 | 16 | if (Array.isArray(ctx.userconfig.mine.events)) { 17 | const array = ctx.userconfig.mine.events as string[]; 18 | const map: Record = {}; 19 | for (const name of array) { 20 | map[name] = {}; 21 | } 22 | 23 | ctx.userconfig.mine.events = map; 24 | } 25 | 26 | if ( 27 | Boolean(ctx.userconfig.mine.websiteStalkerUpdate) 28 | || Boolean(ctx.userconfig.mine.stisysUpdate) 29 | ) { 30 | await ctx.reply( 31 | 'Das beobachten von StISys ist nicht mehr Teil dieses Bots und wurde in den Channel @HAWHHWebsiteStalker verlagert.', 32 | ); 33 | } 34 | 35 | ctx.userconfig.mine.mensa ??= {}; 36 | let more = ctx.userconfig.mine.mensa.more ?? []; 37 | 38 | if (more.length > 0) { 39 | const allAvailableCanteens = new Set(await getCanteenList()); 40 | more = [...new Set(more)] 41 | // Remove main from more 42 | .filter(canteen => canteen !== ctx.userconfig.mine.mensa.main) 43 | // Remove not anymore existing 44 | .filter(canteen => allAvailableCanteens.has(canteen)) 45 | .sort(); 46 | } 47 | 48 | if (more.length > 0) { 49 | ctx.userconfig.mine.mensa.more = more; 50 | } else { 51 | delete ctx.userconfig.mine.mensa.more; 52 | } 53 | 54 | delete (ctx as any).userconfig.mine.additionalEvents; 55 | delete (ctx as any).userconfig.mine.mensa.student; 56 | delete (ctx as any).userconfig.mine.settings; 57 | delete (ctx as any).userconfig.mine.showRemovedEvents; 58 | delete (ctx as any).userconfig.mine.stisysUpdate; 59 | delete (ctx as any).userconfig.mine.websiteStalkerUpdate; 60 | 61 | return next(); 62 | }); 63 | -------------------------------------------------------------------------------- /source/parts/changes-inline.ts: -------------------------------------------------------------------------------- 1 | import {Composer} from 'grammy'; 2 | import type {InlineQueryResultArticle, User} from 'grammy/types'; 3 | import {html as format} from 'telegram-format'; 4 | import { 5 | generateChangeDescription, 6 | generateChangeText, 7 | generateChangeTextHeader, 8 | generateShortChangeText, 9 | } from '../lib/change-helper.js'; 10 | import type {Change, MyContext} from '../lib/types.js'; 11 | 12 | export const bot = new Composer(); 13 | 14 | function generateInlineQueryResultFromChange( 15 | change: Change, 16 | from: User, 17 | ): InlineQueryResultArticle { 18 | const id = `${change.name}#${change.date}#${from.id}`; 19 | return { 20 | description: generateChangeDescription(change), 21 | id, 22 | input_message_content: { 23 | message_text: generateChangeText(change), 24 | parse_mode: format.parse_mode, 25 | }, 26 | reply_markup: { 27 | inline_keyboard: [[ 28 | {text: 'zu meinem Kalender hinzufügen', callback_data: 'c:a:' + id}, 29 | ]], 30 | }, 31 | title: generateShortChangeText(change), 32 | type: 'article', 33 | }; 34 | } 35 | 36 | function escapeRegexSpecificChars(input: string): string { 37 | return input 38 | .replaceAll('[', '\\[') 39 | .replaceAll(']', '\\]') 40 | .replaceAll('(', '\\(') 41 | .replaceAll(')', '\\)'); 42 | } 43 | 44 | bot.on('inline_query', async context => { 45 | const regex = new RegExp( 46 | escapeRegexSpecificChars(context.inlineQuery.query), 47 | 'i', 48 | ); 49 | 50 | const filtered = context.userconfig.mine.changes 51 | .filter(o => regex.test(generateShortChangeText(o))); 52 | const results = filtered.map(c => 53 | generateInlineQueryResultFromChange(c, context.from), 54 | ); 55 | 56 | await context.answerInlineQuery(results, { 57 | cache_time: 20, 58 | is_personal: true, 59 | button: { 60 | start_parameter: 'changes', 61 | text: 'Zum Bot', 62 | }, 63 | }); 64 | }); 65 | 66 | type ChangeRelatedInfos = { 67 | name: string; 68 | date: string; 69 | fromId: number; 70 | change: Change; 71 | }; 72 | 73 | async function getChangeFromContextMatch( 74 | context: MyContext, 75 | ): Promise { 76 | const name = context.match![1]!; 77 | const date = context.match![2]!; 78 | const fromId = Number(context.match![3]!); 79 | 80 | if (!Object.keys(context.userconfig.mine.events).includes(name)) { 81 | await context.answerCallbackQuery( 82 | 'Du besuchst diese Veranstaltung garnicht. 🤔', 83 | ); 84 | return undefined; 85 | } 86 | 87 | try { 88 | const fromconfig = await context.userconfig.loadConfig(fromId); 89 | const searchedChange = fromconfig.changes 90 | .find(o => o.name === name && o.date === date); 91 | if (!searchedChange) { 92 | throw new Error('User does not have this change'); 93 | } 94 | 95 | return { 96 | name, 97 | date, 98 | fromId, 99 | change: searchedChange, 100 | }; 101 | } catch { 102 | await context.editMessageText( 103 | 'Die Veranstaltungsänderung existiert nicht mehr. 😔', 104 | ); 105 | return undefined; 106 | } 107 | } 108 | 109 | bot.callbackQuery(/^c:a:(.+)#(.+)#(.+)$/, async context => { 110 | const meta = await getChangeFromContextMatch(context); 111 | if (!meta) { 112 | return; 113 | } 114 | 115 | const {name, date, fromId, change} = meta; 116 | 117 | if (context.from?.id === Number(fromId)) { 118 | await context.answerCallbackQuery('Das ist deine eigene Änderung 😉'); 119 | return; 120 | } 121 | 122 | // Prüfen ob man bereits eine Änderung mit dem Namen und dem Datum hat. 123 | const myChangeToThisEvent = context.userconfig.mine.changes 124 | .filter(o => o.name === name && o.date === date); 125 | 126 | if (myChangeToThisEvent.length > 0) { 127 | const warning 128 | = '⚠️ Du hast bereits eine Änderung zu diesem Termin in deinem Kalender.'; 129 | await context.answerCallbackQuery(warning); 130 | 131 | const currentChange = myChangeToThisEvent[0]!; 132 | 133 | let text = warning + '\n'; 134 | text += generateChangeTextHeader(currentChange); 135 | 136 | text += '\nDiese Veränderung ist bereits in deinem Kalender:'; 137 | text += '\n' + format.escape(generateChangeDescription(currentChange)); 138 | 139 | text += '\nDiese Veränderung wolltest du hinzufügen:'; 140 | text += '\n' + format.escape(generateChangeDescription(change)); 141 | 142 | const inline_keyboard = [[ 143 | { 144 | text: 'Überschreiben', 145 | callback_data: `c:af:${name}#${date}#${fromId}`, 146 | }, 147 | {text: 'Abbrechen', callback_data: 'c:cancel'}, 148 | ]]; 149 | 150 | await context.api.sendMessage(context.from.id, text, { 151 | parse_mode: format.parse_mode, 152 | reply_markup: {inline_keyboard}, 153 | }); 154 | return; 155 | } 156 | 157 | context.userconfig.mine.changes.push(change); 158 | await context.answerCallbackQuery('Die Änderung wurde hinzugefügt'); 159 | }); 160 | 161 | bot.callbackQuery( 162 | 'c:cancel', 163 | async context => context.editMessageText('Ich habe nichts verändert. 🙂'), 164 | ); 165 | 166 | // Action: change add force 167 | bot.callbackQuery(/^c:af:(.+)#(.+)#(.+)$/, async context => { 168 | const meta = await getChangeFromContextMatch(context); 169 | if (!meta) { 170 | return; 171 | } 172 | 173 | const {name, date, change} = meta; 174 | context.userconfig.mine.changes = context.userconfig.mine.changes 175 | .filter(o => o.name !== name || o.date !== date); 176 | context.userconfig.mine.changes.push(change); 177 | return context.editMessageText('Die Änderung wurde hinzugefügt.'); 178 | }); 179 | -------------------------------------------------------------------------------- /source/parts/easter-eggs.ts: -------------------------------------------------------------------------------- 1 | import {Composer} from 'grammy'; 2 | import type {MyContext} from '../lib/types.js'; 3 | 4 | export const bot = new Composer(); 5 | 6 | bot.on( 7 | 'edited_message', 8 | async ctx => 9 | ctx.reply( 10 | 'Hui, jetzt wirds stressig. 😨\n\nIch kann doch nicht auch noch auf vergangene Nachrichten aufpassen!', 11 | {reply_to_message_id: ctx.editedMessage.message_id}, 12 | ), 13 | ); 14 | 15 | bot.on('channel_post', async ctx => { 16 | await ctx.reply( 17 | 'Adding a random bot as an admin to your channel is maybe not the best idea…\n\nSincerely, a random bot, added as an admin to this channel.', 18 | ); 19 | console.log(new Date(), 'leave the channel…', ctx.chat); 20 | await ctx.leaveChat(); 21 | }); 22 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@sindresorhus/tsconfig", 3 | "include": [ 4 | "source" 5 | ], 6 | "compilerOptions": { 7 | "declaration": false, 8 | "removeComments": true, 9 | "sourceMap": true, 10 | "outDir": "dist" 11 | } 12 | } 13 | --------------------------------------------------------------------------------