Initial release
Build and Push Docker Images / build (push) Successful in 17s

This commit is contained in:
Stardream
2026-06-02 10:58:24 +10:00
commit eace48732d
88 changed files with 11140 additions and 0 deletions
+22
View File
@@ -0,0 +1,22 @@
# ── Required ───────────────────────────────────────────────────────────────────
# Telegram Bot token from @BotFather
BOT_TOKEN=your_bot_token_here
# Public HTTPS URL of this deployment (used for webhook registration)
# Leave empty in development - bot will use polling mode instead
WEBHOOK_URL=https://your-domain.com
# Random secret for validating Telegram webhook requests (optional but recommended)
WEBHOOK_SECRET=generate_a_random_secret_here
# Full public URL to the Mini App frontend (used in bot buttons)
MINI_APP_URL=https://your-domain.com
# ── Database ───────────────────────────────────────────────────────────────────
POSTGRES_PASSWORD=change_me_in_production
# ── Optional ───────────────────────────────────────────────────────────────────
PORT=80
DEBUG=false
# How long (seconds) to cache user avatar URLs before re-fetching from Telegram (default: 3600)
AVATAR_CACHE_TTL=3600
+1
View File
@@ -0,0 +1 @@
* text=auto eol=lf
+41
View File
@@ -0,0 +1,41 @@
name: Build and Push Docker Images
on:
push:
branches:
- main
tags:
- 'v*'
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Log in to Gitea Container Registry
run: |
echo "${{ secrets.CR_TOKEN }}" | \
docker login 127.0.0.1:3333 -u ${{ github.actor }} --password-stdin
- name: Build and push
run: |
BASE=127.0.0.1:3333/stardream/tglotterybot
REF="${{ github.ref }}"
if [[ "$REF" == refs/tags/* ]]; then
VERSION="${REF#refs/tags/}"
docker build -t "${BASE}-backend:${VERSION}" -t "${BASE}-backend:latest" ./backend
docker build -t "${BASE}-frontend:${VERSION}" -t "${BASE}-frontend:latest" ./frontend
docker push "${BASE}-backend:${VERSION}"
docker push "${BASE}-backend:latest"
docker push "${BASE}-frontend:${VERSION}"
docker push "${BASE}-frontend:latest"
else
docker build -t "${BASE}-backend:latest" ./backend
docker build -t "${BASE}-frontend:latest" ./frontend
docker push "${BASE}-backend:latest"
docker push "${BASE}-frontend:latest"
fi
+23
View File
@@ -0,0 +1,23 @@
# Data
postgres_data/
redis_data/
# Python
__pycache__/
*.pyc
*.pyo
.venv/
# Frontend
node_modules/
dist/
# Environment
.env
# macOS
.DS_Store
# Dev / review docs
CODE_REVIEW.md
AGENT.md
+235
View File
@@ -0,0 +1,235 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based on the Program.
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
TGLotteryBot
Copyright (C) 2026 Stardream
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
+315
View File
@@ -0,0 +1,315 @@
<div align="center"><a name="readme-top"></a>
# TGLotteryBot
**Telegram lottery bot with built-in Mini App - create, announce, and draw lotteries without leaving Telegram**
**English** · [简体中文](./README.zh-CN.md)
[![][license-shield]][license-link]
[![][python-shield]][python-link]
[![][docker-shield]][docker-link]
[![][postgres-shield]][postgres-link]
</div>
---
- [✨ Features](#-features)
- [🚀 Quick Start](#-quick-start)
- [🤖 Bot Setup](#-bot-setup)
- [📡 Bot Commands](#-bot-commands)
- [💻 Local Development](#-local-development)
- [⚙️ Configuration](#-configuration)
- [🐳 Services](#-services)
- [📁 Project Structure](#-project-structure)
- [🤝 Contributing](#-contributing)
- [📝 License](#-license)
## ✨ Features
- **Telegram Mini App** - full lottery management UI embedded inside Telegram; no external website required
- **Lottery lifecycle** - Draft → Active → Finished flow; prizes stay editable while the lottery is in Draft or Active
- **Multi-prize draws** - each lottery supports multiple prizes with independent quantities; the draw algorithm pairs participants with prizes fairly using a shuffle-based random selection
- **Membership requirements** - optionally restrict participation to members of specific groups or channels; supports passphrase verification per chat
- **Multi-chat announcement** - announce to multiple groups or channels simultaneously; messages stay in sync as lottery details change
- **Scheduled auto-draw** - set an exact date and time for the draw to run automatically
- **Deep-link joining** - announcement messages carry a `/start lottery_<id>` deep link; users tap once to open the Mini App and join
- **Winner notifications** - each winner receives a private congratulatory message from the bot with their prize details
- **Invite links** - the bot can generate and cache persistent invite links for required chats; participants see the link before they join
## 🚀 Quick Start
**1. Download the required files**
```bash
curl -LO https://git.stdm.moe/Stardream/TGLotteryBot/raw/branch/main/docker-compose.yml
curl -LO https://git.stdm.moe/Stardream/TGLotteryBot/raw/branch/main/.env.example
mkdir -p nginx
curl -o nginx/nginx.conf https://git.stdm.moe/Stardream/TGLotteryBot/raw/branch/main/nginx/nginx.conf
```
**2. Configure environment**
```bash
cp .env.example .env
```
Open `.env` and fill in the required values:
```env
BOT_TOKEN=123456:ABC-your-bot-token-from-BotFather
MINI_APP_URL=https://your-domain.com
POSTGRES_PASSWORD=change-me
```
> [!IMPORTANT]
> `BOT_TOKEN` and `MINI_APP_URL` are required. The Mini App URL must be an HTTPS address that Telegram can reach. For production, also set `WEBHOOK_URL` and `WEBHOOK_SECRET`.
**3. Start**
```bash
docker compose up -d
```
**4. Register the Mini App**
In [@BotFather](https://t.me/BotFather), send `/newapp` and point the Web App URL to `https://your-domain.com`. Users can then open the lottery manager directly from bot messages.
**5. Open the bot**
Send `/start` to your bot in Telegram to open the Mini App.
> [!TIP]
> For production deployments, set `WEBHOOK_URL` to your public HTTPS URL. Without it, the bot falls back to long-polling, which is fine for development but less efficient in production.
**Updating to a newer version**
```bash
docker compose pull
docker compose up -d
```
<div align="right">
[![][back-to-top]](#readme-top)
</div>
## 🤖 Bot Setup
After adding the bot to your groups or channels, configure the following in [@BotFather](https://t.me/BotFather):
**Disable Privacy Mode** (`/setprivacy` - Disabled)
Required if you use passphrase verification. By default, Telegram bots only receive messages that start with `/`. Disabling Privacy Mode allows the bot to read all messages in the group so it can detect passphrases sent by users.
**Grant Admin rights for anonymous admin detection**
If your group has anonymous administrators (members who toggled "Hide my name"), Telegram does not expose their user ID to bots via the standard `getChatMember` API. Granting the bot administrator rights in the group allows it to verify anonymous admins when checking membership.
> [!NOTE]
> These settings only affect groups where you use membership requirements or passphrase verification. For channels or public lotteries without requirements, they are not needed.
<div align="right">
[![][back-to-top]](#readme-top)
</div>
## 📡 Bot Commands
| Command | Description |
|---|---|
| `/start` | Open the lottery manager Mini App |
| `/newlottery` | Create a new lottery (shortcut into the Mini App) |
| `/mylotteries` | View your lotteries |
| `/help` | Show help and project info |
All lottery management (creating, editing, announcing, drawing) happens inside the Mini App. Bot commands are entry points that open the appropriate Mini App screen.
<div align="right">
[![][back-to-top]](#readme-top)
</div>
## 💻 Local Development
**Prerequisites:** Docker and Docker Compose
The project ships a `docker-compose.override.yml` that activates automatically for development:
- Backend mounts the source tree and runs uvicorn with `--reload`
- Frontend runs the Vite dev server with filesystem polling (safe for NAS / network volumes)
- nginx serves the Vite output and proxies `/api` and `/webhook` to the backend
```bash
cp .env.example .env
# Edit .env - set BOT_TOKEN, MINI_APP_URL; leave WEBHOOK_URL empty for polling mode
docker compose up --build
```
The development stack is accessible at `http://localhost` (or whatever `PORT` you set).
Backend hot-reloads on file save. Frontend hot-reloads are handled by Vite.
<div align="right">
[![][back-to-top]](#readme-top)
</div>
## ⚙️ Configuration
All configuration is read from environment variables (or `.env` in the project root).
| Variable | Default | Required | Description |
|---|---|---|---|
| `BOT_TOKEN` | - | **Yes** | Telegram bot token from [@BotFather](https://t.me/BotFather) |
| `MINI_APP_URL` | - | **Yes** | Public HTTPS URL where the Mini App frontend is served |
| `WEBHOOK_URL` | *(empty)* | No | Public HTTPS base URL for webhook mode. Leave empty to use long-polling |
| `WEBHOOK_SECRET` | *(empty)* | No | Secret token sent by Telegram in the `X-Telegram-Bot-Api-Secret-Token` header |
| `POSTGRES_PASSWORD` | `postgres` | No | PostgreSQL password |
| `PORT` | `80` | No | Host port exposed by nginx |
| `DEBUG` | `false` | No | Enable FastAPI debug mode |
| `AVATAR_CACHE_TTL` | `3600` | No | Seconds to cache user and chat avatars server-side |
> [!WARNING]
> Always change `POSTGRES_PASSWORD` and generate a strong `WEBHOOK_SECRET` before exposing the deployment to the internet.
<div align="right">
[![][back-to-top]](#readme-top)
</div>
## 🐳 Services
The default compose stack starts four containers:
| Container | Image | Purpose |
|---|---|---|
| `backend` | `tglotterybot-backend:latest` | FastAPI REST API + aiogram Telegram bot |
| `frontend` | `tglotterybot-frontend:latest` | React + Vite Mini App (built static files) |
| `nginx` | `nginx:alpine` | Reverse proxy; routes `/api/*` and `/webhook/*` to backend, everything else to frontend |
| `postgres` | `postgres:16-alpine` | PostgreSQL persistent database |
Persistent data is stored in `./postgres_data/`.
<div align="right">
[![][back-to-top]](#readme-top)
</div>
## 📁 Project Structure
```
TGLotteryBot/
├── backend/ # Python FastAPI + aiogram bot
│ ├── app/
│ │ ├── main.py # FastAPI app entrypoint + lifespan setup
│ │ ├── core/
│ │ │ ├── config.py # Pydantic settings (reads from env / .env)
│ │ │ ├── database.py # Async SQLAlchemy engine and session factory
│ │ │ └── security.py # Telegram initData HMAC-SHA256 validation
│ │ ├── api/
│ │ │ ├── deps.py # FastAPI dependencies (authentication)
│ │ │ ├── schemas.py # Pydantic request / response models
│ │ │ └── routers/
│ │ │ ├── lotteries.py # Lottery CRUD, draw, and announce endpoints
│ │ │ ├── prizes.py # Prize management endpoints
│ │ │ ├── participants.py # Join / leave endpoints
│ │ │ ├── chats.py # Managed chat list, links, and avatars
│ │ │ └── users.py # User profile and avatar endpoints
│ │ ├── bot/
│ │ │ ├── router.py # aiogram dispatcher and router registration
│ │ │ ├── handlers/ # Bot command and event handlers
│ │ │ └── keyboards/ # Inline keyboard builders
│ │ ├── models/ # SQLAlchemy 2.0 ORM models
│ │ │ ├── lottery.py # Lottery (status enum, all lottery fields)
│ │ │ ├── prize.py # Prize (name, quantity, sort order)
│ │ │ ├── participant.py # Lottery participants
│ │ │ ├── winner.py # Draw results
│ │ │ ├── user.py # Telegram users
│ │ │ ├── managed_chat.py # Groups / channels the bot manages
│ │ │ └── passphrase_verification.py
│ │ └── services/
│ │ ├── draw_service.py # Draw algorithm (shuffle-based, SELECT FOR UPDATE)
│ │ └── scheduler.py # Auto-draw scheduler + winner notifications
│ ├── alembic/ # Alembic database migrations
│ │ └── versions/
│ ├── requirements.txt
│ └── Dockerfile
├── frontend/ # React 18 + Vite Telegram Mini App
│ ├── src/
│ │ ├── pages/ # Route-level page components
│ │ ├── components/ # Shared UI components
│ │ ├── hooks/ # Custom React hooks
│ │ ├── lib/ # API client, Telegram SDK wrapper, utilities
│ │ └── types/ # TypeScript type definitions
│ ├── package.json
│ ├── vite.config.ts
│ ├── Dockerfile # Production build
│ └── Dockerfile.dev # Dev server (Vite)
├── nginx/
│ ├── nginx.conf # Production reverse proxy config
│ └── nginx.dev.conf # Development config
├── docker-compose.yml # Production service definitions
├── docker-compose.override.yml # Development overrides (auto-applied)
└── .env.example # Environment variable template
```
<div align="right">
[![][back-to-top]](#readme-top)
</div>
## 🤝 Contributing
Issues and pull requests are welcome. Please open an issue first for major changes so the direction can be discussed.
<div align="right">
[![][back-to-top]](#readme-top)
</div>
## 📝 License
Copyright © 2026 [Stardream](https://git.stdm.moe/Stardream). This project is licensed under the [GNU Affero General Public License v3.0](./LICENSE).
**Permissions**
| | |
|---|---|
| ✅ | Commercial use |
| ✅ | Modification |
| ✅ | Distribution |
| ✅ | Private use |
**Conditions**
| | |
|---|---|
| ⚠️ | Disclose source - modified versions must also be open-source |
| ⚠️ | Same license - derivative works must use AGPL-3.0 |
| ⚠️ | Network use = distribution - if you run a modified version as a network service, you must make the source available to users |
| ⚠️ | State changes - modifications must be documented |
In short: you are free to use, modify, and self-host TGLotteryBot. If you distribute or offer a modified version as a hosted service, you must publish the full source under AGPL-3.0.
---
<!-- LINK GROUP -->
[back-to-top]: https://img.shields.io/badge/-BACK_TO_TOP-black?style=flat-square
[license-shield]: https://img.shields.io/badge/license-AGPL--3.0-white?labelColor=black&style=flat-square
[license-link]: ./LICENSE
[python-shield]: https://img.shields.io/badge/python-3.12-blue?labelColor=black&logo=python&logoColor=white&style=flat-square
[python-link]: https://www.python.org/
[docker-shield]: https://img.shields.io/badge/docker-compose-2496ED?labelColor=black&logo=docker&logoColor=white&style=flat-square
[docker-link]: https://docs.docker.com/compose/
[postgres-shield]: https://img.shields.io/badge/postgres-16-336791?labelColor=black&logo=postgresql&logoColor=white&style=flat-square
[postgres-link]: https://www.postgresql.org/
+315
View File
@@ -0,0 +1,315 @@
<div align="center"><a name="readme-top"></a>
# TGLotteryBot
**Telegram 抽奖机器人,内置 Mini App - 无需离开 Telegram 即可创建、发布和开奖**
[English](./README.md) · **简体中文**
[![][license-shield]][license-link]
[![][python-shield]][python-link]
[![][docker-shield]][docker-link]
[![][postgres-shield]][postgres-link]
</div>
---
- [✨ 功能特性](#-功能特性)
- [🚀 快速开始](#-快速开始)
- [🤖 Bot 配置](#-bot-配置)
- [📡 Bot 命令](#-bot-命令)
- [💻 本地开发](#-本地开发)
- [⚙️ 配置说明](#-配置说明)
- [🐳 服务容器](#-服务容器)
- [📁 项目结构](#-项目结构)
- [🤝 贡献](#-贡献)
- [📝 许可证](#-许可证)
## ✨ 功能特性
- **Telegram Mini App** - 完整的抽奖管理界面直接嵌入 Telegram,无需外部网站
- **抽奖生命周期** - 草稿 → 进行中 → 已结束的状态流转;草稿和进行中状态均可编辑奖品
- **多奖品抽奖** - 每个抽奖可设置多个奖品,每个奖品单独配置数量;开奖算法通过双重随机打乱实现公平分配
- **入群验证** - 可限制只有特定群组或频道的成员才能参与,支持对每个群组单独设置口令验证
- **多群同步公告** - 同时向多个群组或频道发布公告,抽奖信息修改后消息自动同步
- **定时自动开奖** - 设定具体日期和时间,到时自动开奖
- **深链接参与** - 公告消息附带 `/start lottery_<id>` 深链接,用户点击即可打开 Mini App 并参与
- **私信通知中奖者** - 每位中奖者将收到机器人发来的私信,包含中奖奖品详情
- **邀请链接管理** - 机器人可生成并缓存所需群组的永久邀请链接,用户加入前即可查看
## 🚀 快速开始
**1. 下载所需文件**
```bash
curl -LO https://git.stdm.moe/Stardream/TGLotteryBot/raw/branch/main/docker-compose.yml
curl -LO https://git.stdm.moe/Stardream/TGLotteryBot/raw/branch/main/.env.example
mkdir -p nginx
curl -o nginx/nginx.conf https://git.stdm.moe/Stardream/TGLotteryBot/raw/branch/main/nginx/nginx.conf
```
**2. 配置环境变量**
```bash
cp .env.example .env
```
编辑 `.env`,填入必填项:
```env
BOT_TOKEN=123456:ABC-your-bot-token-from-BotFather
MINI_APP_URL=https://your-domain.com
POSTGRES_PASSWORD=change-me
```
> [!IMPORTANT]
> `BOT_TOKEN` 和 `MINI_APP_URL` 为必填项。Mini App URL 必须是 Telegram 可访问的 HTTPS 地址。生产环境还需设置 `WEBHOOK_URL` 和 `WEBHOOK_SECRET`。
**3. 启动服务**
```bash
docker compose up -d
```
**4. 注册 Mini App**
在 [@BotFather](https://t.me/BotFather) 发送 `/newapp`,将 Web App URL 指向 `https://your-domain.com`,用户即可从消息中直接打开抽奖管理界面。
**5. 使用机器人**
在 Telegram 中向你的机器人发送 `/start`,即可打开 Mini App。
> [!TIP]
> 生产部署时建议设置 `WEBHOOK_URL` 为公网 HTTPS 地址。不设置则退回长轮询模式,适合开发但生产效率较低。
**更新到新版本**
```bash
docker compose pull
docker compose up -d
```
<div align="right">
[![][back-to-top]](#readme-top)
</div>
## 🤖 Bot 配置
将 Bot 添加到群组或频道后,需要在 [@BotFather](https://t.me/BotFather) 中进行以下配置:
**关闭隐私模式**`/setprivacy` - Disabled
使用口令验证时必须关闭。Telegram Bot 默认只接收以 `/` 开头的消息,关闭隐私模式后 Bot 才能读取群组中的所有消息,从而识别用户发送的口令。
**授予管理员权限以识别匿名管理员**
如果群组中存在匿名管理员(开启了"隐藏管理员身份"的成员),Telegram 不会通过标准 `getChatMember` API 暴露其用户 ID。将 Bot 设为群组管理员后,Bot 才能在验证成员资格时识别匿名管理员。
> [!NOTE]
> 以上设置仅对使用了成员资格验证或口令验证的群组有效,频道或无参与要求的公开抽奖不需要这些配置。
<div align="right">
[![][back-to-top]](#readme-top)
</div>
## 📡 Bot 命令
| 命令 | 说明 |
|---|---|
| `/start` | 打开抽奖管理 Mini App |
| `/newlottery` | 创建新抽奖(直接跳转至 Mini App 创建页) |
| `/mylotteries` | 查看我的抽奖列表 |
| `/help` | 查看帮助与项目信息 |
所有抽奖管理操作(创建、编辑、发布、开奖)均在 Mini App 内完成,Bot 命令是进入对应页面的入口。
<div align="right">
[![][back-to-top]](#readme-top)
</div>
## 💻 本地开发
**前置条件:** Docker 和 Docker Compose
项目内置 `docker-compose.override.yml`,启动时自动生效:
- 后端挂载源码目录,uvicorn 开启 `--reload` 热重载
- 前端运行 Vite 开发服务器,使用文件轮询模式(适配 NAS / 网络文件系统)
- nginx 提供 Vite 构建产物,并将 `/api``/webhook` 反向代理到后端
```bash
cp .env.example .env
# 编辑 .env,填入 BOT_TOKEN、MINI_APP_URLWEBHOOK_URL 留空使用轮询模式
docker compose up --build
```
开发环境通过 `http://localhost`(或你设置的 `PORT`)访问。
保存后端文件后自动热重载,前端热更新由 Vite 处理。
<div align="right">
[![][back-to-top]](#readme-top)
</div>
## ⚙️ 配置说明
所有配置通过环境变量读取(或项目根目录的 `.env` 文件)。
| 变量 | 默认值 | 必填 | 说明 |
|---|---|---|---|
| `BOT_TOKEN` | - | **是** | 从 [@BotFather](https://t.me/BotFather) 获取的 Telegram 机器人 Token |
| `MINI_APP_URL` | - | **是** | Mini App 前端的公网 HTTPS 地址 |
| `WEBHOOK_URL` | *(空)* | 否 | Webhook 模式的公网 HTTPS 基础地址,留空则使用长轮询 |
| `WEBHOOK_SECRET` | *(空)* | 否 | Telegram 在 `X-Telegram-Bot-Api-Secret-Token` 请求头中发送的密钥 |
| `POSTGRES_PASSWORD` | `postgres` | 否 | PostgreSQL 密码 |
| `PORT` | `80` | 否 | nginx 对外暴露的端口 |
| `DEBUG` | `false` | 否 | 启用 FastAPI 调试模式 |
| `AVATAR_CACHE_TTL` | `3600` | 否 | 用户和群组头像的服务端缓存时间(秒) |
> [!WARNING]
> 对外部署前务必修改 `POSTGRES_PASSWORD` 并生成强随机的 `WEBHOOK_SECRET`。
<div align="right">
[![][back-to-top]](#readme-top)
</div>
## 🐳 服务容器
默认 Compose 配置启动四个容器:
| 容器 | 镜像 | 用途 |
|---|---|---|
| `backend` | `tglotterybot-backend:latest` | FastAPI REST API + aiogram Telegram 机器人 |
| `frontend` | `tglotterybot-frontend:latest` | React + Vite Mini App(静态文件) |
| `nginx` | `nginx:alpine` | 反向代理;`/api/*``/webhook/*` 转发至后端,其余请求转发至前端 |
| `postgres` | `postgres:16-alpine` | PostgreSQL 持久化数据库 |
持久化数据存储在 `./postgres_data/`
<div align="right">
[![][back-to-top]](#readme-top)
</div>
## 📁 项目结构
```
TGLotteryBot/
├── backend/ # Python FastAPI + aiogram 机器人
│ ├── app/
│ │ ├── main.py # FastAPI 应用入口 + 生命周期管理
│ │ ├── core/
│ │ │ ├── config.py # Pydantic 配置(从环境变量 / .env 读取)
│ │ │ ├── database.py # 异步 SQLAlchemy 引擎与会话工厂
│ │ │ └── security.py # Telegram initData HMAC-SHA256 验证
│ │ ├── api/
│ │ │ ├── deps.py # FastAPI 依赖项(身份认证)
│ │ │ ├── schemas.py # Pydantic 请求 / 响应模型
│ │ │ └── routers/
│ │ │ ├── lotteries.py # 抽奖 CRUD、开奖、公告端点
│ │ │ ├── prizes.py # 奖品管理端点
│ │ │ ├── participants.py # 参与 / 退出端点
│ │ │ ├── chats.py # 托管群组列表、链接、头像
│ │ │ └── users.py # 用户信息与头像端点
│ │ ├── bot/
│ │ │ ├── router.py # aiogram 调度器与路由注册
│ │ │ ├── handlers/ # Bot 命令与事件处理器
│ │ │ └── keyboards/ # 内联键盘构建器
│ │ ├── models/ # SQLAlchemy 2.0 ORM 模型
│ │ │ ├── lottery.py # 抽奖(状态枚举、所有抽奖字段)
│ │ │ ├── prize.py # 奖品(名称、数量、排序)
│ │ │ ├── participant.py # 参与者
│ │ │ ├── winner.py # 开奖结果
│ │ │ ├── user.py # Telegram 用户
│ │ │ ├── managed_chat.py # 机器人管理的群组 / 频道
│ │ │ └── passphrase_verification.py
│ │ └── services/
│ │ ├── draw_service.py # 开奖算法(双重随机 + SELECT FOR UPDATE
│ │ └── scheduler.py # 定时自动开奖 + 中奖通知
│ ├── alembic/ # Alembic 数据库迁移
│ │ └── versions/
│ ├── requirements.txt
│ └── Dockerfile
├── frontend/ # React 18 + Vite Telegram Mini App
│ ├── src/
│ │ ├── pages/ # 路由级页面组件
│ │ ├── components/ # 通用 UI 组件
│ │ ├── hooks/ # 自定义 React Hooks
│ │ ├── lib/ # API 客户端、Telegram SDK 封装、工具函数
│ │ └── types/ # TypeScript 类型定义
│ ├── package.json
│ ├── vite.config.ts
│ ├── Dockerfile # 生产构建
│ └── Dockerfile.dev # 开发服务器(Vite)
├── nginx/
│ ├── nginx.conf # 生产环境反向代理配置
│ └── nginx.dev.conf # 开发环境配置
├── docker-compose.yml # 生产服务定义
├── docker-compose.override.yml # 开发覆盖配置(自动生效)
└── .env.example # 环境变量模板
```
<div align="right">
[![][back-to-top]](#readme-top)
</div>
## 🤝 贡献
欢迎提交 Issue 和 Pull Request。重大变更请先开 Issue 讨论方向。
<div align="right">
[![][back-to-top]](#readme-top)
</div>
## 📝 许可证
Copyright © 2026 [Stardream](https://git.stdm.moe/Stardream)。本项目采用 [GNU Affero General Public License v3.0](./LICENSE) 许可证。
**权利**
| | |
|---|---|
| ✅ | 商业使用 |
| ✅ | 修改 |
| ✅ | 分发 |
| ✅ | 私人使用 |
**条件**
| | |
|---|---|
| ⚠️ | 公开源码 - 修改后的版本也必须开源 |
| ⚠️ | 相同许可证 - 衍生作品必须使用 AGPL-3.0 |
| ⚠️ | 网络使用 = 分发 - 若将修改版本作为网络服务运行,必须向用户提供源码 |
| ⚠️ | 标注修改 - 修改内容必须记录在案 |
简而言之:你可以自由使用、修改和自托管 TGLotteryBot。若将修改版本作为托管服务分发或提供,必须以 AGPL-3.0 发布完整源码。
---
<!-- LINK GROUP -->
[back-to-top]: https://img.shields.io/badge/-BACK_TO_TOP-black?style=flat-square
[license-shield]: https://img.shields.io/badge/license-AGPL--3.0-white?labelColor=black&style=flat-square
[license-link]: ./LICENSE
[python-shield]: https://img.shields.io/badge/python-3.12-blue?labelColor=black&logo=python&logoColor=white&style=flat-square
[python-link]: https://www.python.org/
[docker-shield]: https://img.shields.io/badge/docker-compose-2496ED?labelColor=black&logo=docker&logoColor=white&style=flat-square
[docker-link]: https://docs.docker.com/compose/
[postgres-shield]: https://img.shields.io/badge/postgres-16-336791?labelColor=black&logo=postgresql&logoColor=white&style=flat-square
[postgres-link]: https://www.postgresql.org/
+11
View File
@@ -0,0 +1,11 @@
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
+41
View File
@@ -0,0 +1,41 @@
[alembic]
script_location = alembic
prepend_sys_path = .
version_path_separator = os
# URL is set dynamically in env.py from settings
sqlalchemy.url =
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
+52
View File
@@ -0,0 +1,52 @@
import asyncio
from logging.config import fileConfig
from alembic import context
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from app.core.config import settings
from app.models import Base # noqa: F401 - registers all models
config = context.config
# Use the app's database URL (swap driver for sync alembic operations)
db_url = settings.database_url
if config.config_file_name is not None:
fileConfig(config.config_file_name)
target_metadata = Base.metadata
def run_migrations_offline() -> None:
context.configure(
url=db_url.replace("+asyncpg", ""),
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def do_run_migrations(connection) -> None:
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
async def run_async_migrations() -> None:
engine: AsyncEngine = create_async_engine(db_url)
async with engine.connect() as connection:
await connection.run_sync(do_run_migrations)
await engine.dispose()
def run_migrations_online() -> None:
asyncio.run(run_async_migrations())
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+25
View File
@@ -0,0 +1,25 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
revision: str = ${repr(up_revision)}
down_revision: Union[str, None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}
View File
@@ -0,0 +1,134 @@
"""initial_schema
Revision ID: 86cca6d7adcb
Revises:
Create Date: 2026-05-27 16:31:52.870967
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision: str = '86cca6d7adcb'
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table(
'users',
sa.Column('id', sa.BigInteger(), nullable=False),
sa.Column('username', sa.String(255), nullable=True),
sa.Column('first_name', sa.String(255), nullable=False),
sa.Column('last_name', sa.String(255), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
)
op.create_table(
'lotteries',
sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('creator_id', sa.BigInteger(), nullable=False),
sa.Column('title', sa.String(255), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('status', sa.String(20), nullable=False),
sa.Column('target_chat_id', sa.BigInteger(), nullable=True),
sa.Column('target_chat_title', sa.String(255), nullable=True),
sa.Column('require_membership', sa.Boolean(), nullable=False),
sa.Column('required_chat_ids', sa.JSON(), nullable=True),
sa.Column('required_chat_titles', sa.JSON(), nullable=True),
sa.Column('required_chat_types', sa.JSON(), nullable=True),
sa.Column('required_chat_usernames', sa.JSON(), nullable=True),
sa.Column('announcement_targets', sa.JSON(), nullable=True),
sa.Column('max_participants', sa.Integer(), nullable=True),
sa.Column('announcement_message_id', sa.BigInteger(), nullable=True),
sa.Column('contact_info', sa.Text(), nullable=True),
sa.Column('draw_at', sa.DateTime(), nullable=True),
sa.Column('auto_draw_count', sa.Integer(), nullable=True),
sa.Column('allow_multiple_wins', sa.Boolean(), server_default=sa.text('false'), nullable=False),
sa.Column('invite_link_chat_ids', sa.JSON(), server_default=sa.text("'[]'"), nullable=False),
sa.Column('creator_timezone', sa.String(64), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('drawn_at', sa.DateTime(), nullable=True),
sa.Column('draw_trigger', sa.String(20), nullable=True),
sa.Column('required_chat_passphrases', sa.JSON(), nullable=True),
sa.ForeignKeyConstraint(['creator_id'], ['users.id']),
sa.PrimaryKeyConstraint('id'),
)
op.create_table(
'prizes',
sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('lottery_id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('name', sa.String(255), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('quantity', sa.Integer(), nullable=False),
sa.Column('sort_order', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['lottery_id'], ['lotteries.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id'),
)
op.create_table(
'participants',
sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('lottery_id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('user_id', sa.BigInteger(), nullable=False),
sa.Column('joined_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['lottery_id'], ['lotteries.id'], ondelete='CASCADE'),
sa.ForeignKeyConstraint(['user_id'], ['users.id']),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('lottery_id', 'user_id'),
)
op.create_table(
'winners',
sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('lottery_id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('user_id', sa.BigInteger(), nullable=False),
sa.Column('prize_id', postgresql.UUID(as_uuid=True), nullable=True),
sa.Column('prize_name', sa.String(255), nullable=False),
sa.Column('drawn_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['lottery_id'], ['lotteries.id'], ondelete='CASCADE'),
sa.ForeignKeyConstraint(['prize_id'], ['prizes.id'], ondelete='SET NULL'),
sa.ForeignKeyConstraint(['user_id'], ['users.id']),
sa.PrimaryKeyConstraint('id'),
)
op.create_table(
'managed_chats',
sa.Column('id', sa.BigInteger(), nullable=False),
sa.Column('title', sa.String(255), nullable=False),
sa.Column('username', sa.String(255), nullable=True),
sa.Column('chat_type', sa.String(50), nullable=False),
sa.Column('invite_link', sa.String(512), nullable=True),
sa.Column('last_message_id', sa.BigInteger(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=False),
sa.Column('added_at', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
)
op.create_table(
'passphrase_verifications',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('lottery_id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('chat_id', sa.BigInteger(), nullable=False),
sa.Column('user_id', sa.BigInteger(), nullable=False),
sa.Column('verified_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['lottery_id'], ['lotteries.id'], ondelete='CASCADE'),
sa.ForeignKeyConstraint(['user_id'], ['users.id']),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('lottery_id', 'chat_id', 'user_id'),
)
def downgrade() -> None:
op.drop_table('passphrase_verifications')
op.drop_table('managed_chats')
op.drop_table('winners')
op.drop_table('participants')
op.drop_table('prizes')
op.drop_table('lotteries')
op.drop_table('users')
@@ -0,0 +1,25 @@
"""convert_status_to_varchar
Revision ID: a1b2c3d4e5f6
Revises: 86cca6d7adcb
Create Date: 2026-06-02 12:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
revision: str = 'a1b2c3d4e5f6'
down_revision: Union[str, None] = '86cca6d7adcb'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.execute("ALTER TABLE lotteries ALTER COLUMN status TYPE VARCHAR(20) USING status::text")
op.execute("DROP TYPE IF EXISTS lotterystatus")
def downgrade() -> None:
op.execute("CREATE TYPE lotterystatus AS ENUM ('draft', 'active', 'drawing', 'finished', 'cancelled')")
op.execute("ALTER TABLE lotteries ALTER COLUMN status TYPE lotterystatus USING status::lotterystatus")
View File
View File
+74
View File
@@ -0,0 +1,74 @@
import json
import logging
from urllib.parse import parse_qsl
from fastapi import Depends, Header, HTTPException
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.config import settings
from app.core.database import get_db
from app.core.security import validate_init_data
from app.models.user import User
logger = logging.getLogger(__name__)
def _log_auth_failure(reason: str, init_data: str | None) -> None:
parsed = dict(parse_qsl(init_data or "", keep_blank_values=True))
logger.warning(
"telegram auth failed: reason=%s init_len=%s has_hash=%s has_user=%s auth_date=%s bot_token_set=%s",
reason,
len(init_data or ""),
bool(parsed.get("hash")),
bool(parsed.get("user")),
parsed.get("auth_date", ""),
bool(settings.bot_token),
)
async def get_current_user(
x_telegram_init_data: str | None = Header(None, alias="X-Telegram-Init-Data"),
db: AsyncSession = Depends(get_db),
) -> User:
if not x_telegram_init_data:
_log_auth_failure("missing_header", x_telegram_init_data)
raise HTTPException(status_code=401, detail="Open this page from the Telegram bot Mini App")
data = validate_init_data(x_telegram_init_data)
if data is None:
_log_auth_failure("invalid_init_data", x_telegram_init_data)
raise HTTPException(status_code=401, detail="Invalid Telegram auth data")
user_json = data.get("user", "{}")
try:
user_data = json.loads(user_json)
except (json.JSONDecodeError, TypeError):
_log_auth_failure("invalid_user_json", x_telegram_init_data)
raise HTTPException(status_code=401, detail="Invalid user data")
user_id = user_data.get("id")
if not user_id:
_log_auth_failure("missing_user_id", x_telegram_init_data)
raise HTTPException(status_code=401, detail="Missing user id")
result = await db.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
if user is None:
user = User(
id=user_id,
username=user_data.get("username"),
first_name=user_data.get("first_name", ""),
last_name=user_data.get("last_name"),
)
db.add(user)
await db.commit()
await db.refresh(user)
else:
user.username = user_data.get("username")
user.first_name = user_data.get("first_name") or user.first_name
user.last_name = user_data.get("last_name")
await db.commit()
return user
View File
+168
View File
@@ -0,0 +1,168 @@
import logging
import time
from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import Response
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.deps import get_current_user
from app.api.schemas import ChatInfo
from app.core.database import get_db
from app.models.managed_chat import ManagedChat
from app.models.user import User
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/chats", tags=["chats"])
# chat_id → (bytes, content_type, expires_at)
_chat_avatar_cache: dict[int, tuple[bytes, str, float]] = {}
@router.get("", response_model=list[ChatInfo])
async def list_accessible_chats(
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> list[ChatInfo]:
"""Groups: any member may use. Channels: admins/creators only."""
from app.bot.router import bot
from aiogram.exceptions import TelegramAPIError
result = await db.execute(
select(ManagedChat).where(ManagedChat.is_active == True)
)
chats = result.scalars().all()
from aiogram.exceptions import TelegramBadRequest, TelegramForbiddenError
_unverifiable = (
"user_id_invalid",
"have no rights",
"not enough rights",
"administrators only",
)
accessible: list[ChatInfo] = []
for chat in chats:
try:
member = await bot.get_chat_member(chat.id, current_user.id)
status = member.status
if chat.chat_type == "channel":
allowed = status in ("administrator", "creator")
else:
allowed = status in ("member", "administrator", "creator", "restricted")
except TelegramBadRequest as e:
msg = str(e).lower()
# Can't verify due to anonymous/privacy settings - include the chat
allowed = any(p in msg for p in _unverifiable)
if allowed:
logger.debug("Chat %s membership unverifiable for user %s (%s) - including", chat.id, current_user.id, e)
except TelegramForbiddenError:
continue
except TelegramAPIError:
continue
if allowed:
accessible.append(ChatInfo(
id=chat.id,
title=chat.title,
username=chat.username,
chat_type=chat.chat_type,
))
return accessible
@router.get("/{chat_id}/link")
async def get_chat_link(
chat_id: int,
db: AsyncSession = Depends(get_db),
_current_user: User = Depends(get_current_user),
) -> dict:
"""Return the best navigation URL for a chat (username > last_message_id > /1 fallback)."""
result = await db.execute(select(ManagedChat).where(ManagedChat.id == chat_id))
managed = result.scalar_one_or_none()
if not managed:
raise HTTPException(404, "Chat not found")
if managed.username:
return {"url": f"https://t.me/{managed.username}"}
channel_id = str(abs(chat_id))[3:] # strip -100 prefix
return {"url": f"https://t.me/c/{channel_id}/{managed.last_message_id or 1}"}
@router.get("/{chat_id}/invite")
async def get_chat_invite_link(
chat_id: int,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> dict:
"""Return a persistent invite link for a chat.
Reading an already-stored link: any authenticated user associated with a
lottery that requires this chat (owner or participant).
Generating a new link: only the chat's admin/creator.
"""
result = await db.execute(select(ManagedChat).where(ManagedChat.id == chat_id))
managed = result.scalar_one_or_none()
if not managed:
raise HTTPException(404, "Chat not found")
# Already-stored link: any authenticated user may read it.
# The admin intentionally generated it for participants to use.
if managed.invite_link:
return {"url": managed.invite_link}
# No link stored yet - only an admin/creator may trigger generation
from app.bot.router import bot
from aiogram.exceptions import TelegramAPIError, TelegramBadRequest
is_admin = False
try:
member = await bot.get_chat_member(chat_id, current_user.id)
is_admin = member.status in ("administrator", "creator")
except TelegramBadRequest as e:
msg = str(e).lower()
is_admin = any(p in msg for p in ("administrators only", "have no rights", "not enough rights"))
except TelegramAPIError:
pass
if not is_admin:
raise HTTPException(403, "Not authorized")
url: str | None = None
error: str | None = None
try:
link = await bot.create_chat_invite_link(chat_id)
url = link.invite_link
except Exception as e:
error = str(e)
logger.warning("create_chat_invite_link failed for chat %s: %s", chat_id, e)
if url:
managed.invite_link = url
await db.commit()
return {"url": url, "error": error}
@router.get("/{chat_id}/avatar")
async def chat_avatar(chat_id: int) -> Response:
from app.core.config import settings
ttl = settings.avatar_cache_ttl
cached = _chat_avatar_cache.get(chat_id)
if cached and time.monotonic() < cached[2]:
return Response(content=cached[0], media_type=cached[1],
headers={"Cache-Control": f"public, max-age={ttl}"})
from app.bot.router import bot
try:
chat = await bot.get_chat(chat_id)
if not chat.photo:
return Response(status_code=404)
data = await bot.download(chat.photo.small_file_id)
content = data.read()
content_type = "image/jpeg"
_chat_avatar_cache[chat_id] = (content, content_type, time.monotonic() + ttl)
return Response(content=content, media_type=content_type,
headers={"Cache-Control": f"public, max-age={ttl}"})
except Exception:
return Response(status_code=404)
+609
View File
@@ -0,0 +1,609 @@
import html
import uuid
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.deps import get_current_user
from app.api.schemas import LotteryCreate, LotteryResponse, LotteryUpdate, PrizeResponse, WinnerResponse
from app.core.database import get_db
from app.models.lottery import Lottery, LotteryStatus
from app.models.participant import Participant
from app.models.prize import Prize
from app.models.user import User
from app.models.winner import Winner
from app.services.draw_service import execute_draw
router = APIRouter(prefix="/lotteries", tags=["lotteries"])
async def _revoke_invite_links(db: AsyncSession, chat_ids: set[int]) -> None:
from app.bot.router import bot
from app.models.managed_chat import ManagedChat
for chat_id in chat_ids:
result = await db.execute(select(ManagedChat).where(ManagedChat.id == chat_id))
managed = result.scalar_one_or_none()
if managed and managed.invite_link:
try:
await bot.revoke_chat_invite_link(chat_id, managed.invite_link)
except Exception:
pass
managed.invite_link = None
await db.commit()
async def _build_lottery_response(
db: AsyncSession, lottery: Lottery, current_user_id: int | None = None
) -> LotteryResponse:
count_result = await db.execute(
select(func.count(Participant.id)).where(Participant.lottery_id == lottery.id)
)
participant_count = count_result.scalar() or 0
prize_result = await db.execute(
select(Prize).where(Prize.lottery_id == lottery.id).order_by(Prize.sort_order)
)
prizes = prize_result.scalars().all()
total_prizes = sum(p.quantity for p in prizes)
is_winner: bool | None = None
if current_user_id is not None and lottery.status == LotteryStatus.FINISHED:
w = await db.execute(
select(Winner).where(Winner.lottery_id == lottery.id, Winner.user_id == current_user_id).limit(1)
)
is_winner = w.scalar_one_or_none() is not None
return LotteryResponse(
id=lottery.id,
creator_id=lottery.creator_id,
title=lottery.title,
description=lottery.description,
contact_info=lottery.contact_info,
status=lottery.status,
target_chat_id=lottery.target_chat_id,
target_chat_title=lottery.target_chat_title,
require_membership=lottery.require_membership,
required_chat_ids=lottery.required_chat_ids or [],
required_chat_titles=lottery.required_chat_titles or [],
required_chat_types=lottery.required_chat_types or [],
required_chat_usernames=lottery.required_chat_usernames or [],
announcement_targets=lottery.announcement_targets or [],
allow_multiple_wins=lottery.allow_multiple_wins,
invite_link_chat_ids=lottery.invite_link_chat_ids or [],
required_chat_passphrases=lottery.required_chat_passphrases or [],
max_participants=lottery.max_participants,
draw_at=lottery.draw_at,
auto_draw_count=lottery.auto_draw_count,
creator_timezone=lottery.creator_timezone,
participant_count=participant_count,
prize_count=len(prizes),
total_prizes=total_prizes,
created_at=lottery.created_at,
drawn_at=lottery.drawn_at,
draw_trigger=lottery.draw_trigger,
prizes=[PrizeResponse.model_validate(p) for p in prizes],
is_winner=is_winner,
)
@router.get("", response_model=list[LotteryResponse])
async def list_my_lotteries(
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> list[LotteryResponse]:
result = await db.execute(
select(Lottery)
.where(Lottery.creator_id == current_user.id)
.order_by(Lottery.created_at.desc())
)
lotteries = result.scalars().all()
return [await _build_lottery_response(db, l, current_user.id) for l in lotteries]
@router.get("/joined", response_model=list[LotteryResponse])
async def list_joined_lotteries(
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> list[LotteryResponse]:
result = await db.execute(
select(Lottery)
.join(Participant, Participant.lottery_id == Lottery.id)
.where(Participant.user_id == current_user.id)
.order_by(Lottery.created_at.desc())
)
lotteries = result.scalars().all()
return [await _build_lottery_response(db, l, current_user.id) for l in lotteries]
@router.get("/active", response_model=list[LotteryResponse])
async def list_active_lotteries(
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> list[LotteryResponse]:
"""Active lotteries created by others that the user can join."""
result = await db.execute(
select(Lottery)
.where(Lottery.status == LotteryStatus.ACTIVE)
.where(Lottery.creator_id != current_user.id)
.order_by(Lottery.created_at.desc())
)
lotteries = result.scalars().all()
return [await _build_lottery_response(db, l) for l in lotteries]
@router.post("", response_model=LotteryResponse)
async def create_lottery(
data: LotteryCreate,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> LotteryResponse:
lottery = Lottery(creator_id=current_user.id, **data.model_dump())
db.add(lottery)
await db.commit()
await db.refresh(lottery)
return await _build_lottery_response(db, lottery)
@router.get("/{lottery_id}", response_model=LotteryResponse)
async def get_lottery(
lottery_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> LotteryResponse:
result = await db.execute(select(Lottery).where(Lottery.id == lottery_id))
lottery = result.scalar_one_or_none()
if lottery is None:
raise HTTPException(404, "Lottery not found")
return await _build_lottery_response(db, lottery)
@router.put("/{lottery_id}", response_model=LotteryResponse)
async def update_lottery(
lottery_id: uuid.UUID,
data: LotteryUpdate,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> LotteryResponse:
result = await db.execute(select(Lottery).where(Lottery.id == lottery_id))
lottery = result.scalar_one_or_none()
if lottery is None:
raise HTTPException(404, "Lottery not found")
if lottery.creator_id != current_user.id:
raise HTTPException(403, "Not authorized")
if lottery.status in (LotteryStatus.FINISHED, LotteryStatus.CANCELLED):
raise HTTPException(400, "Cannot edit a finished or cancelled lottery")
old_invite_ids: set[int] = set(lottery.invite_link_chat_ids or [])
for field, value in data.model_dump(exclude_unset=True).items():
setattr(lottery, field, value)
await db.commit()
await db.refresh(lottery)
new_invite_ids: set[int] = set(lottery.invite_link_chat_ids or [])
removed_ids = old_invite_ids - new_invite_ids
if removed_ids:
await _revoke_invite_links(db, removed_ids)
# Auto-sync announcement messages whenever the lottery is edited
if lottery.announcement_targets or lottery.announcement_message_id:
try:
await sync_announcement(db, lottery, force_send=False)
except Exception:
pass
return await _build_lottery_response(db, lottery)
@router.post("/{lottery_id}/activate", response_model=LotteryResponse)
async def activate_lottery(
lottery_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> LotteryResponse:
result = await db.execute(select(Lottery).where(Lottery.id == lottery_id))
lottery = result.scalar_one_or_none()
if lottery is None:
raise HTTPException(404, "Lottery not found")
if lottery.creator_id != current_user.id:
raise HTTPException(403, "Not authorized")
if lottery.status != LotteryStatus.DRAFT:
raise HTTPException(400, "Lottery is already activated")
prize_result = await db.execute(
select(Prize).where(Prize.lottery_id == lottery_id).limit(1)
)
if prize_result.scalar_one_or_none() is None:
raise HTTPException(400, "Add at least one prize before activating")
lottery.status = LotteryStatus.ACTIVE
await db.commit()
await db.refresh(lottery)
return await _build_lottery_response(db, lottery)
@router.post("/{lottery_id}/draw", response_model=list[WinnerResponse])
async def draw_lottery(
lottery_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> list[WinnerResponse]:
result = await db.execute(select(Lottery).where(Lottery.id == lottery_id))
lottery = result.scalar_one_or_none()
if lottery is None:
raise HTTPException(404, "Lottery not found")
if lottery.creator_id != current_user.id:
raise HTTPException(403, "Not authorized")
if lottery.status != LotteryStatus.ACTIVE:
raise HTTPException(400, "Lottery is not active")
try:
winners_data = await execute_draw(db, lottery_id, trigger="manual")
except ValueError as e:
raise HTTPException(400, str(e))
# Announce winners to all announcement targets
targets = lottery.announcement_targets or (
[{"chat_id": lottery.target_chat_id, "chat_title": lottery.target_chat_title or "", "message_id": lottery.announcement_message_id}]
if lottery.target_chat_id else []
)
if targets and winners_data:
from app.bot.router import bot
from aiogram.types import ReplyParameters
lines = []
for w in winners_data:
full_name = html.escape(
w["first_name"] + (f" {w['last_name']}" if w.get("last_name") else "")
)
safe_name = f'<a href="tg://user?id={w["user_id"]}">{full_name}</a>'
safe_prize = html.escape(w["prize_name"])
lines.append(f"🏆 {safe_name} - {safe_prize}")
text = (
f"🎉 <b>Draw Results: {html.escape(lottery.title)}</b>\n\n"
+ "\n".join(lines)
+ "\n\nCongratulations to all winners! 🎊"
)
for t in targets:
try:
reply = (
ReplyParameters(message_id=t["message_id"], allow_sending_without_reply=True)
if t.get("message_id")
else None
)
await bot.send_message(
t["chat_id"],
text,
parse_mode="HTML",
reply_parameters=reply,
)
except Exception:
pass
if winners_data:
from app.services.scheduler import notify_winners
import asyncio
asyncio.create_task(notify_winners(lottery.title, winners_data, lottery.contact_info, lottery_id=lottery.id))
return [WinnerResponse(**w) for w in winners_data]
@router.get("/{lottery_id}/winners", response_model=list[WinnerResponse])
async def get_winners(
lottery_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> list[WinnerResponse]:
result = await db.execute(
select(Winner, User)
.join(User, Winner.user_id == User.id)
.where(Winner.lottery_id == lottery_id)
.order_by(Winner.drawn_at)
)
return [
WinnerResponse(
user_id=user.id,
username=user.username,
first_name=user.first_name,
last_name=user.last_name,
prize_name=winner.prize_name,
drawn_at=winner.drawn_at,
)
for winner, user in result.all()
]
async def _build_announce_text(db: AsyncSession, lottery: Lottery, include_count: bool = True) -> str:
prize_result = await db.execute(
select(Prize).where(Prize.lottery_id == lottery.id).order_by(Prize.sort_order)
)
prizes = prize_result.scalars().all()
count_result = await db.execute(
select(func.count(Participant.id)).where(Participant.lottery_id == lottery.id)
)
participant_count = count_result.scalar() or 0
text = f"🎰 <b>{html.escape(lottery.title)}</b>"
if lottery.description:
text += f"\n\n{html.escape(lottery.description)}"
# Membership requirements
required_ids = lottery.required_chat_ids or []
required_titles = lottery.required_chat_titles or []
required_usernames = lottery.required_chat_usernames or []
required_passphrases = lottery.required_chat_passphrases or []
invite_link_ids = set(lottery.invite_link_chat_ids or [])
if lottery.require_membership and required_ids:
from app.models.managed_chat import ManagedChat
mc_result = await db.execute(select(ManagedChat).where(ManagedChat.id.in_(required_ids)))
managed_chats = {mc.id: mc for mc in mc_result.scalars().all()}
text += "\n\n📮 <b>Requirements:</b>"
for i, chat_id in enumerate(required_ids):
title = required_titles[i] if i < len(required_titles) else str(chat_id)
username = required_usernames[i] if i < len(required_usernames) else None
mc = managed_chats.get(chat_id)
if chat_id in invite_link_ids and mc and mc.invite_link:
link: str | None = mc.invite_link
elif username:
link = f"https://t.me/{username}"
elif mc:
channel_id = str(abs(chat_id))[3:]
link = f"https://t.me/c/{channel_id}/{mc.last_message_id or 1}"
else:
link = None
label = f'<a href="{link}">{html.escape(title)}</a>' if link else html.escape(title)
text += f"\n 🎫 Join - {label}"
if i < len(required_passphrases) and required_passphrases[i]:
text += f"\n └ 🔑 Send passphrase ﹝<code>{html.escape(required_passphrases[i])}</code>﹞"
elif lottery.require_membership and lottery.target_chat_title:
text += f"\n\n📮 <b>Requirements:</b>\n 🎫 Join - {html.escape(lottery.target_chat_title)}"
# Prizes
prize_lines = "\n".join(f" - {html.escape(p.name)} ×{p.quantity}" for p in prizes)
text += f"\n\n🎁 <b>Prizes:</b>\n{prize_lines}"
# Participant count
if include_count:
text += f"\n\n👥 Participants: {participant_count}"
# Draw conditions
if lottery.draw_at:
from datetime import timezone as _tz
draw_dt = lottery.draw_at.replace(tzinfo=_tz.utc)
tz_label = "UTC"
if lottery.creator_timezone:
try:
from zoneinfo import ZoneInfo
draw_dt = draw_dt.astimezone(ZoneInfo(lottery.creator_timezone))
offset = draw_dt.utcoffset()
if offset is not None:
total_min = int(offset.total_seconds() / 60)
sign = "+" if total_min >= 0 else "-"
h, m = divmod(abs(total_min), 60)
tz_label = f"UTC{sign}{h}" if m == 0 else f"UTC{sign}{h}:{m:02d}"
except Exception:
pass
text += f"\n\n📅 <b>Draw time:</b> {draw_dt.strftime('%Y/%m/%d %H:%M')} ({tz_label})"
if lottery.auto_draw_count:
text += f"\n🎯 Auto-draw at {lottery.auto_draw_count} participants"
return text
async def _sync_single_target(
bot,
text: str,
keyboard,
target: dict,
force_send: bool,
) -> int | None:
"""Sync announcement to one chat. Returns the resulting message_id (or None)."""
from aiogram.exceptions import TelegramBadRequest
chat_id = target["chat_id"]
msg_id = target.get("message_id")
if msg_id:
try:
await bot.edit_message_text(
chat_id=chat_id,
message_id=msg_id,
text=text,
reply_markup=keyboard,
parse_mode="HTML",
)
return msg_id
except TelegramBadRequest as e:
if "message is not modified" in str(e).lower():
return msg_id
# Message deleted or inaccessible
if not force_send:
return msg_id # keep existing id, silently skip
msg_id = None # will resend below
if force_send:
msg = await bot.send_message(
chat_id,
text,
reply_markup=keyboard,
parse_mode="HTML",
)
await _update_chat_last_message(chat_id, msg.message_id)
return msg.message_id
return None
async def _update_chat_last_message(chat_id: int, message_id: int) -> None:
from app.core.database import AsyncSessionLocal
from app.models.managed_chat import ManagedChat
from sqlalchemy import select
async with AsyncSessionLocal() as db:
result = await db.execute(select(ManagedChat).where(ManagedChat.id == chat_id))
managed = result.scalar_one_or_none()
if managed and message_id > (managed.last_message_id or 0):
managed.last_message_id = message_id
await db.commit()
async def sync_announcement(db: AsyncSession, lottery: Lottery, force_send: bool = False) -> None:
"""Edit or send announcement messages to all announcement_targets."""
from app.bot.router import bot
from app.bot.keyboards.inline import lottery_announce_keyboard
# Build target list - backward compat with old single-target lotteries
targets: list[dict] = lottery.announcement_targets or []
if not targets and lottery.target_chat_id:
targets = [{
"chat_id": lottery.target_chat_id,
"chat_title": lottery.target_chat_title or "",
"message_id": lottery.announcement_message_id,
}]
if not targets:
return
text = await _build_announce_text(db, lottery)
keyboard = lottery_announce_keyboard(str(lottery.id))
updated: list[dict] = []
changed = False
for t in targets:
new_msg_id = await _sync_single_target(bot, text, keyboard, t, force_send)
updated.append({**t, "message_id": new_msg_id})
if new_msg_id != t.get("message_id"):
changed = True
if changed:
lottery.announcement_targets = updated
await db.commit()
class _AnnounceChatItem(BaseModel):
id: int
title: str
class _AnnounceRequest(BaseModel):
chats: list[_AnnounceChatItem]
@router.post("/{lottery_id}/announce")
async def announce_lottery(
lottery_id: uuid.UUID,
data: _AnnounceRequest,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> dict:
from aiogram.exceptions import TelegramAPIError
result = await db.execute(select(Lottery).where(Lottery.id == lottery_id))
lottery = result.scalar_one_or_none()
if lottery is None:
raise HTTPException(404, "Lottery not found")
if lottery.creator_id != current_user.id:
raise HTTPException(403, "Not authorized")
if not data.chats:
raise HTTPException(400, "Select at least one chat")
if lottery.status == LotteryStatus.CANCELLED:
raise HTTPException(400, "Cannot announce a cancelled lottery")
# Build new targets, preserving existing message_ids for same chats
existing = {t["chat_id"]: t for t in (lottery.announcement_targets or [])}
new_targets = [
{
"chat_id": c.id,
"chat_title": c.title,
"message_id": existing.get(c.id, {}).get("message_id"),
}
for c in data.chats
]
lottery.announcement_targets = new_targets
# Keep legacy target_chat_id pointing to first chat for draw-result compat
lottery.target_chat_id = data.chats[0].id
lottery.target_chat_title = data.chats[0].title
await db.commit()
await db.refresh(lottery)
try:
await sync_announcement(db, lottery, force_send=True)
except TelegramAPIError as e:
raise HTTPException(500, f"Failed to send message: {e}")
return {"status": "announced"}
@router.post("/{lottery_id}/prepare-share")
async def prepare_share(
lottery_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> dict:
result = await db.execute(select(Lottery).where(Lottery.id == lottery_id))
lottery = result.scalar_one_or_none()
if lottery is None:
raise HTTPException(404, "Lottery not found")
if lottery.status == LotteryStatus.CANCELLED:
raise HTTPException(400, "Cannot share a cancelled lottery")
from app.bot.router import bot
from app.bot.keyboards.inline import lottery_announce_keyboard
from aiogram.types import InlineQueryResultArticle, InputTextMessageContent
text = await _build_announce_text(db, lottery, include_count=False)
keyboard = lottery_announce_keyboard(str(lottery.id))
try:
prepared = await bot.save_prepared_inline_message(
user_id=current_user.id,
result=InlineQueryResultArticle(
id=str(lottery.id),
title=lottery.title,
input_message_content=InputTextMessageContent(
message_text=text,
parse_mode="HTML",
),
reply_markup=keyboard,
),
allow_user_chats=True,
allow_bot_chats=False,
allow_group_chats=True,
allow_channel_chats=True,
)
except Exception as e:
raise HTTPException(500, str(e))
return {"prepared_message_id": prepared.id}
@router.delete("/{lottery_id}")
async def cancel_lottery(
lottery_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> dict:
result = await db.execute(select(Lottery).where(Lottery.id == lottery_id))
lottery = result.scalar_one_or_none()
if lottery is None:
raise HTTPException(404, "Lottery not found")
if lottery.creator_id != current_user.id:
raise HTTPException(403, "Not authorized")
if lottery.status == LotteryStatus.FINISHED:
raise HTTPException(400, "Cannot cancel a finished lottery")
lottery.status = LotteryStatus.CANCELLED
await db.commit()
return {"status": "cancelled"}
+148
View File
@@ -0,0 +1,148 @@
import uuid
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.deps import get_current_user
from app.api.schemas import ParticipantResponse
from app.core.database import get_db
from app.models.lottery import Lottery, LotteryStatus
from app.models.participant import Participant
from app.models.user import User
from app.services.membership_service import check_membership
router = APIRouter(tags=["participants"])
@router.post("/lotteries/{lottery_id}/join")
async def join_lottery(
lottery_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> dict:
# Lock the lottery row so the capacity check + insert is atomic.
# Without this, concurrent joins can all pass the count check and exceed
# max_participants before any of them commits.
result = await db.execute(
select(Lottery).where(Lottery.id == lottery_id).with_for_update()
)
lottery = result.scalar_one_or_none()
if lottery is None:
raise HTTPException(404, "Lottery not found")
if lottery.status != LotteryStatus.ACTIVE:
raise HTTPException(400, "Lottery is not active")
# Check max participants inside the lock
if lottery.max_participants is not None:
count_result = await db.execute(
select(func.count(Participant.id)).where(Participant.lottery_id == lottery_id)
)
count = count_result.scalar() or 0
if count >= lottery.max_participants:
raise HTTPException(400, "Lottery is full")
# Check membership if required
if lottery.require_membership:
chat_ids = lottery.required_chat_ids or (
[lottery.target_chat_id] if lottery.target_chat_id else []
)
for i, cid in enumerate(chat_ids):
is_member = await check_membership(cid, current_user.id)
if not is_member:
titles = lottery.required_chat_titles or []
label = titles[i] if i < len(titles) else str(cid)
raise HTTPException(403, f"You must join {label} first")
# Check passphrase if set for this group
passphrases = lottery.required_chat_passphrases or []
if i < len(passphrases) and passphrases[i]:
from app.models.passphrase_verification import PassphraseVerification
pv = await db.execute(
select(PassphraseVerification).where(
PassphraseVerification.lottery_id == lottery_id,
PassphraseVerification.chat_id == cid,
PassphraseVerification.user_id == current_user.id,
)
)
if pv.scalar_one_or_none() is None:
titles = lottery.required_chat_titles or []
label = titles[i] if i < len(titles) else str(cid)
raise HTTPException(403, f"Please send the passphrase in {label} first")
# Check already joined
existing = await db.execute(
select(Participant).where(
Participant.lottery_id == lottery_id,
Participant.user_id == current_user.id,
)
)
if existing.scalar_one_or_none() is not None:
raise HTTPException(409, "Already joined this lottery")
participant = Participant(lottery_id=lottery_id, user_id=current_user.id)
db.add(participant)
await db.commit()
# Refresh count for post-join checks
count_result = await db.execute(
select(func.count(Participant.id)).where(Participant.lottery_id == lottery_id)
)
new_count = count_result.scalar() or 0
# Always update the group announcement with the new participant count
if lottery.announcement_targets or (lottery.announcement_message_id and lottery.target_chat_id):
try:
from app.api.routers.lotteries import sync_announcement
await sync_announcement(db, lottery, force_send=False)
except Exception:
pass
# Trigger auto-draw if participant count reached the threshold
if lottery.auto_draw_count and new_count >= lottery.auto_draw_count:
import asyncio
from app.services.scheduler import run_auto_draw
asyncio.create_task(run_auto_draw(lottery_id, trigger="auto_count"))
return {"status": "joined"}
@router.get("/lotteries/{lottery_id}/passphrase-status")
async def get_passphrase_status(
lottery_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> dict:
from app.models.passphrase_verification import PassphraseVerification
result = await db.execute(
select(PassphraseVerification.chat_id).where(
PassphraseVerification.lottery_id == lottery_id,
PassphraseVerification.user_id == current_user.id,
)
)
return {"verified_chat_ids": [row[0] for row in result.all()]}
@router.get("/lotteries/{lottery_id}/participants", response_model=list[ParticipantResponse])
async def list_participants(
lottery_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> list[ParticipantResponse]:
result = await db.execute(
select(Participant, User)
.join(User, Participant.user_id == User.id)
.where(Participant.lottery_id == lottery_id)
.order_by(Participant.joined_at)
)
return [
ParticipantResponse(
user_id=user.id,
username=user.username,
first_name=user.first_name,
last_name=user.last_name,
joined_at=participant.joined_at,
)
for participant, user in result.all()
]
+102
View File
@@ -0,0 +1,102 @@
import uuid
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.deps import get_current_user
from app.api.schemas import PrizeCreate, PrizeResponse
from app.core.database import get_db
from app.models.lottery import Lottery, LotteryStatus
from app.models.prize import Prize
from app.models.user import User
router = APIRouter(tags=["prizes"])
@router.post("/lotteries/{lottery_id}/prizes", response_model=PrizeResponse)
async def add_prize(
lottery_id: uuid.UUID,
data: PrizeCreate,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> Prize:
result = await db.execute(select(Lottery).where(Lottery.id == lottery_id))
lottery = result.scalar_one_or_none()
if lottery is None:
raise HTTPException(404, "Lottery not found")
if lottery.creator_id != current_user.id:
raise HTTPException(403, "Not authorized")
if lottery.status not in (LotteryStatus.DRAFT, LotteryStatus.ACTIVE):
raise HTTPException(400, "Cannot modify prizes after activation")
# Determine next sort order
last_result = await db.execute(
select(Prize)
.where(Prize.lottery_id == lottery_id)
.order_by(Prize.sort_order.desc())
.limit(1)
)
last = last_result.scalar_one_or_none()
sort_order = (last.sort_order + 1) if last else 0
prize = Prize(lottery_id=lottery_id, sort_order=sort_order, **data.model_dump())
db.add(prize)
await db.commit()
await db.refresh(prize)
return prize
@router.put("/prizes/{prize_id}", response_model=PrizeResponse)
async def update_prize(
prize_id: uuid.UUID,
data: PrizeCreate,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> Prize:
result = await db.execute(select(Prize).where(Prize.id == prize_id))
prize = result.scalar_one_or_none()
if prize is None:
raise HTTPException(404, "Prize not found")
lottery_result = await db.execute(select(Lottery).where(Lottery.id == prize.lottery_id))
lottery = lottery_result.scalar_one()
if lottery.creator_id != current_user.id:
raise HTTPException(403, "Not authorized")
if lottery.status not in (LotteryStatus.DRAFT, LotteryStatus.ACTIVE):
raise HTTPException(400, "Cannot modify prizes after activation")
prize.name = data.name
prize.quantity = data.quantity
prize.description = data.description
await db.commit()
await db.refresh(prize)
return prize
@router.delete("/prizes/{prize_id}")
async def delete_prize(
prize_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> dict:
result = await db.execute(select(Prize).where(Prize.id == prize_id))
prize = result.scalar_one_or_none()
if prize is None:
raise HTTPException(404, "Prize not found")
lottery_result = await db.execute(select(Lottery).where(Lottery.id == prize.lottery_id))
lottery = lottery_result.scalar_one()
if lottery.creator_id != current_user.id:
raise HTTPException(403, "Not authorized")
if lottery.status not in (LotteryStatus.DRAFT, LotteryStatus.ACTIVE):
raise HTTPException(400, "Cannot modify prizes after activation")
await db.delete(prize)
await db.commit()
return {"status": "deleted"}
+33
View File
@@ -0,0 +1,33 @@
import time
from fastapi import APIRouter
from fastapi.responses import Response
router = APIRouter(tags=["users"])
# user_id → (bytes, content_type, expires_at)
_avatar_cache: dict[int, tuple[bytes, str, float]] = {}
@router.get("/users/{user_id}/avatar")
async def get_user_avatar(user_id: int) -> Response:
from app.core.config import settings
ttl = settings.avatar_cache_ttl
cached = _avatar_cache.get(user_id)
if cached and time.monotonic() < cached[2]:
return Response(content=cached[0], media_type=cached[1],
headers={"Cache-Control": f"public, max-age={ttl}"})
from app.bot.router import bot
try:
photos = await bot.get_user_profile_photos(user_id, limit=1)
if not photos.photos:
return Response(status_code=404)
file_id = photos.photos[0][-1].file_id
data = await bot.download(file_id)
content = data.read()
content_type = "image/jpeg"
_avatar_cache[user_id] = (content, content_type, time.monotonic() + ttl)
return Response(content=content, media_type=content_type,
headers={"Cache-Control": f"public, max-age={ttl}"})
except Exception:
return Response(status_code=404)
+142
View File
@@ -0,0 +1,142 @@
import uuid
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field, field_validator
class PrizeCreate(BaseModel):
name: str = Field(..., min_length=1, max_length=255)
description: Optional[str] = None
quantity: int = Field(1, ge=1, le=1000)
class PrizeResponse(BaseModel):
id: uuid.UUID
name: str
description: Optional[str] = None
quantity: int
sort_order: int
model_config = {"from_attributes": True}
def _to_naive_utc(v: datetime | None) -> datetime | None:
if v is None:
return None
if v.tzinfo is not None:
from datetime import timezone
return v.astimezone(timezone.utc).replace(tzinfo=None)
return v
class LotteryCreate(BaseModel):
title: str = Field(..., min_length=1, max_length=255)
description: Optional[str] = None
contact_info: Optional[str] = None
target_chat_id: Optional[int] = None
target_chat_title: Optional[str] = None
require_membership: bool = False
required_chat_ids: list[int] = Field(default_factory=list)
required_chat_titles: list[str] = Field(default_factory=list)
required_chat_types: list[str] = Field(default_factory=list)
required_chat_usernames: list[str] = Field(default_factory=list)
allow_multiple_wins: bool = False
invite_link_chat_ids: list[int] = Field(default_factory=list)
required_chat_passphrases: list[str] = Field(default_factory=list)
max_participants: Optional[int] = Field(None, ge=1)
draw_at: Optional[datetime] = None
auto_draw_count: Optional[int] = Field(None, ge=1)
creator_timezone: Optional[str] = Field(None, max_length=64)
@field_validator("draw_at", mode="after")
@classmethod
def normalize_draw_at(cls, v: datetime | None) -> datetime | None:
return _to_naive_utc(v)
class LotteryUpdate(BaseModel):
title: Optional[str] = Field(None, min_length=1, max_length=255)
description: Optional[str] = None
contact_info: Optional[str] = None
target_chat_id: Optional[int] = None
target_chat_title: Optional[str] = None
require_membership: Optional[bool] = None
required_chat_ids: Optional[list[int]] = None
required_chat_titles: Optional[list[str]] = None
required_chat_types: Optional[list[str]] = None
required_chat_usernames: Optional[list[str]] = None
allow_multiple_wins: Optional[bool] = None
invite_link_chat_ids: Optional[list[int]] = None
required_chat_passphrases: Optional[list[str]] = None
max_participants: Optional[int] = Field(None, ge=1)
draw_at: Optional[datetime] = None
auto_draw_count: Optional[int] = Field(None, ge=1)
creator_timezone: Optional[str] = Field(None, max_length=64)
@field_validator("draw_at", mode="after")
@classmethod
def normalize_draw_at(cls, v: datetime | None) -> datetime | None:
return _to_naive_utc(v)
class LotteryResponse(BaseModel):
id: uuid.UUID
creator_id: int
title: str
description: Optional[str] = None
contact_info: Optional[str] = None
status: str
target_chat_id: Optional[int] = None
target_chat_title: Optional[str] = None
require_membership: bool
required_chat_ids: list[int] = Field(default_factory=list)
required_chat_titles: list[str] = Field(default_factory=list)
required_chat_types: list[str] = Field(default_factory=list)
required_chat_usernames: list[str] = Field(default_factory=list)
announcement_targets: list[dict] = Field(default_factory=list)
allow_multiple_wins: bool = False
invite_link_chat_ids: list[int] = Field(default_factory=list)
required_chat_passphrases: list[str] = Field(default_factory=list)
max_participants: Optional[int] = None
draw_at: Optional[datetime] = None
auto_draw_count: Optional[int] = None
creator_timezone: Optional[str] = None
participant_count: int = 0
prize_count: int = 0
total_prizes: int = 0
created_at: datetime
drawn_at: Optional[datetime] = None
draw_trigger: Optional[str] = None
prizes: list[PrizeResponse] = Field(default_factory=list)
is_winner: Optional[bool] = None
model_config = {"from_attributes": True}
class ParticipantResponse(BaseModel):
user_id: int
username: Optional[str] = None
first_name: str
last_name: Optional[str] = None
joined_at: datetime
model_config = {"from_attributes": True}
class WinnerResponse(BaseModel):
user_id: int
username: Optional[str] = None
first_name: str
last_name: Optional[str] = None
prize_name: str
drawn_at: datetime
model_config = {"from_attributes": True}
class ChatInfo(BaseModel):
id: int
title: str
username: Optional[str] = None
chat_type: str
View File
+92
View File
@@ -0,0 +1,92 @@
from aiogram import F, Router
from aiogram.types import ChatMemberUpdated, Message
from app.core.database import AsyncSessionLocal
from app.models.managed_chat import ManagedChat
from app.models.lottery import Lottery, LotteryStatus
from app.models.passphrase_verification import PassphraseVerification
from sqlalchemy import select
router = Router()
@router.my_chat_member(F.chat.type.in_({"group", "supergroup", "channel"}))
async def bot_chat_member_updated(event: ChatMemberUpdated) -> None:
"""Record or update the bot's presence in a group/channel."""
async with AsyncSessionLocal() as db:
chat = event.chat
new_status = event.new_chat_member.status
result = await db.execute(
select(ManagedChat).where(ManagedChat.id == chat.id)
)
managed = result.scalar_one_or_none()
if new_status in ("member", "administrator"):
if managed is None:
managed = ManagedChat(
id=chat.id,
title=chat.title or "",
username=getattr(chat, 'username', None),
chat_type=chat.type,
)
db.add(managed)
else:
managed.is_active = True
managed.title = chat.title or managed.title
managed.username = getattr(chat, 'username', None)
await db.commit()
elif new_status in ("left", "kicked") and managed is not None:
managed.is_active = False
await db.commit()
@router.channel_post(F.chat.type == "channel")
@router.message(F.chat.type.in_({"group", "supergroup"}))
async def on_chat_message(message: Message) -> None:
"""Track latest message ID and detect passphrase submissions."""
async with AsyncSessionLocal() as db:
result = await db.execute(select(ManagedChat).where(ManagedChat.id == message.chat.id))
managed = result.scalar_one_or_none()
if managed is None:
managed = ManagedChat(
id=message.chat.id,
title=message.chat.title or "",
username=getattr(message.chat, "username", None),
chat_type=message.chat.type,
last_message_id=message.message_id,
)
db.add(managed)
elif message.message_id > (managed.last_message_id or 0):
managed.last_message_id = message.message_id
await db.commit()
if message.text and message.from_user:
text = message.text.strip()
uid = message.from_user.id
cid = message.chat.id
async with AsyncSessionLocal() as db2:
r = await db2.execute(
select(Lottery).where(
Lottery.status == LotteryStatus.ACTIVE,
Lottery.require_membership == True,
)
)
for lottery in r.scalars().all():
ids = lottery.required_chat_ids or []
phrases = lottery.required_chat_passphrases or []
for i, chat_id in enumerate(ids):
if chat_id == cid and i < len(phrases) and phrases[i] and text == phrases[i]:
existing = await db2.execute(
select(PassphraseVerification).where(
PassphraseVerification.lottery_id == lottery.id,
PassphraseVerification.chat_id == cid,
PassphraseVerification.user_id == uid,
)
)
if existing.scalar_one_or_none() is None:
db2.add(PassphraseVerification(
lottery_id=lottery.id, chat_id=cid, user_id=uid
))
await db2.commit()
break
+50
View File
@@ -0,0 +1,50 @@
from aiogram import Router
from aiogram.filters import Command, CommandObject, CommandStart
from aiogram.types import Message
from app.bot.keyboards.inline import create_lottery_keyboard, lottery_detail_keyboard, main_menu_keyboard
router = Router()
@router.message(CommandStart())
async def cmd_start(message: Message, command: CommandObject) -> None:
# Deep-link from group announcement: /start lottery_<uuid>
if command.args and command.args.startswith("lottery_"):
lottery_id = command.args[len("lottery_"):]
await message.answer(
"🎰 Tap the button below to join the lottery:",
reply_markup=lottery_detail_keyboard(lottery_id),
)
return
await message.answer(
"👋 Welcome to <b>TG Lottery Bot</b>!\n\n"
"Tap the button below to get started. Use /help for more information.",
reply_markup=main_menu_keyboard(),
parse_mode="HTML",
)
@router.message(Command("newlottery"))
async def cmd_new_lottery(message: Message) -> None:
await message.answer("Create a new lottery 👇", reply_markup=create_lottery_keyboard())
@router.message(Command("mylotteries"))
async def cmd_my_lotteries(message: Message) -> None:
await message.answer("View my lotteries 👇", reply_markup=main_menu_keyboard())
@router.message(Command("help"))
async def cmd_help(message: Message) -> None:
await message.answer(
"📖 <b>TG Lottery Bot</b>\n\n"
"<b>Commands</b>\n"
"/start - Open lottery manager\n"
"/newlottery - Create a new lottery\n"
"/mylotteries - View my lotteries\n"
"/help - Show this help message\n\n"
"📦 <b>Powered by</b> git.stdm.moe/Stardream/TGLotteryBot",
parse_mode="HTML",
)
+50
View File
@@ -0,0 +1,50 @@
from urllib.parse import urljoin
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo
from app.core.config import settings
def _mini_app_url(path: str = "") -> str:
base = settings.mini_app_url.rstrip("/") + "/"
return urljoin(base, path.lstrip("/"))
def main_menu_keyboard() -> InlineKeyboardMarkup:
return InlineKeyboardMarkup(inline_keyboard=[[
InlineKeyboardButton(
text="Open lottery app",
web_app=WebAppInfo(url=_mini_app_url()),
)
]])
def create_lottery_keyboard() -> InlineKeyboardMarkup:
return InlineKeyboardMarkup(inline_keyboard=[[
InlineKeyboardButton(
text="Create lottery",
web_app=WebAppInfo(url=_mini_app_url("/create")),
)
]])
def lottery_detail_keyboard(lottery_id: str, text: str = "🎰 Join lottery") -> InlineKeyboardMarkup:
"""For private chat messages - web_app is allowed here."""
return InlineKeyboardMarkup(inline_keyboard=[[
InlineKeyboardButton(
text=text,
web_app=WebAppInfo(url=_mini_app_url(f"/lottery/{lottery_id}")),
)
]])
def lottery_announce_keyboard(lottery_id: str) -> InlineKeyboardMarkup:
"""For group/channel announcements - web_app is not allowed; use t.me deep link."""
from app.bot.router import bot_username
if bot_username:
url = f"https://t.me/{bot_username}?start=lottery_{lottery_id}"
else:
url = _mini_app_url(f"/lottery/{lottery_id}")
return InlineKeyboardMarkup(inline_keyboard=[[
InlineKeyboardButton(text="🎰 Join lottery", url=url)
]])
+17
View File
@@ -0,0 +1,17 @@
from aiogram import Bot, Dispatcher
from aiogram.client.default import DefaultBotProperties
from app.core.config import settings
from app.bot.handlers import start, member
bot = Bot(
token=settings.bot_token,
default=DefaultBotProperties(parse_mode="HTML"),
)
dp = Dispatcher()
dp.include_router(start.router)
dp.include_router(member.router)
# Populated at startup by main.py after bot.get_me()
bot_username: str = ""
View File
+27
View File
@@ -0,0 +1,27 @@
from functools import lru_cache
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
bot_token: str = ""
webhook_url: str = ""
webhook_path: str = "/webhook/telegram"
webhook_secret: str = ""
database_url: str = "postgresql+asyncpg://postgres:postgres@postgres:5432/tglotterybot"
mini_app_url: str = ""
avatar_cache_ttl: int = 3600
debug: bool = False
@lru_cache()
def get_settings() -> Settings:
return Settings()
settings = get_settings()
+10
View File
@@ -0,0 +1,10 @@
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from app.core.config import settings
engine = create_async_engine(settings.database_url, echo=settings.debug)
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_db():
async with AsyncSessionLocal() as session:
yield session
+59
View File
@@ -0,0 +1,59 @@
import hmac
import hashlib
import time
from urllib.parse import parse_qsl
from app.core.config import settings
# Reject initData older than this many seconds (24 hours)
_MAX_AGE_SECONDS = 86_400
def validate_init_data(init_data: str) -> dict | None:
"""Validate Telegram WebApp initData using HMAC-SHA256.
Also rejects payloads whose auth_date is older than _MAX_AGE_SECONDS to
prevent indefinite replay of leaked initData strings.
"""
try:
# parse_qsl already URL-decodes each value. Decoding the whole query
# string first can turn escaped separators inside JSON values into real
# separators and make Telegram's HMAC check fail.
parsed = dict(parse_qsl(init_data, keep_blank_values=True))
hash_value = parsed.pop("hash", "")
if not hash_value:
return None
# Validate auth_date freshness before doing any crypto work
auth_date_str = parsed.get("auth_date")
if not auth_date_str:
return None
try:
age = time.time() - int(auth_date_str)
if age > _MAX_AGE_SECONDS:
return None
except ValueError:
return None
data_check_string = "\n".join(
f"{k}={v}" for k, v in sorted(parsed.items())
)
secret_key = hmac.new(
b"WebAppData",
settings.bot_token.encode(),
hashlib.sha256,
).digest()
expected = hmac.new(
secret_key,
data_check_string.encode(),
hashlib.sha256,
).hexdigest()
if not hmac.compare_digest(expected, hash_value):
return None
return parsed
except Exception:
return None
+85
View File
@@ -0,0 +1,85 @@
import asyncio
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from app.core.config import settings
from app.models import Base # noqa: F401 - ensure all models are registered
@asynccontextmanager
async def lifespan(app: FastAPI):
from app.bot import router as bot_router
from app.bot.router import bot, dp
me = await bot.get_me()
bot_router.bot_username = me.username or ""
from aiogram.types import BotCommand
await bot.set_my_commands([
BotCommand(command="start", description="Open lottery manager"),
BotCommand(command="newlottery", description="Create a new lottery"),
BotCommand(command="mylotteries", description="View my lotteries"),
BotCommand(command="help", description="Help and project info"),
])
from app.services.scheduler import auto_draw_scheduler
asyncio.create_task(auto_draw_scheduler())
if settings.webhook_url:
webhook_url = f"{settings.webhook_url}{settings.webhook_path}"
await bot.set_webhook(
webhook_url,
secret_token=settings.webhook_secret or None,
drop_pending_updates=True,
)
else:
# Development: long-polling mode
asyncio.create_task(dp.start_polling(bot, handle_signals=False))
yield
from app.bot.router import bot as _bot
await _bot.session.close()
app = FastAPI(title="TGLotteryBot API", lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# API routers
from app.api.routers import lotteries, prizes, participants, chats, users # noqa: E402
app.include_router(lotteries.router, prefix="/api")
app.include_router(prizes.router, prefix="/api")
app.include_router(participants.router, prefix="/api")
app.include_router(chats.router, prefix="/api")
app.include_router(users.router, prefix="/api")
@app.post(settings.webhook_path)
async def telegram_webhook(request: Request) -> Response:
"""Receive Telegram updates via webhook."""
from app.bot.router import bot, dp
from aiogram.types import Update
secret = request.headers.get("X-Telegram-Bot-Api-Secret-Token", "")
if settings.webhook_secret and secret != settings.webhook_secret:
return Response(status_code=403)
body = await request.json()
update = Update(**body)
await dp.feed_update(bot, update)
return Response(status_code=200)
@app.get("/health")
async def health() -> dict:
return {"status": "ok"}
+10
View File
@@ -0,0 +1,10 @@
from .base import Base
from .user import User
from .managed_chat import ManagedChat
from .lottery import Lottery, LotteryStatus
from .prize import Prize
from .participant import Participant
from .winner import Winner
from .passphrase_verification import PassphraseVerification
__all__ = ["Base", "User", "ManagedChat", "Lottery", "LotteryStatus", "Prize", "Participant", "Winner", "PassphraseVerification"]
+14
View File
@@ -0,0 +1,14 @@
from sqlalchemy import MetaData
from sqlalchemy.orm import DeclarativeBase
NAMING_CONVENTION = {
"ix": "ix_%(column_0_label)s",
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s",
}
class Base(DeclarativeBase):
metadata = MetaData(naming_convention=NAMING_CONVENTION)
+63
View File
@@ -0,0 +1,63 @@
import enum
import uuid
from datetime import datetime
from typing import TYPE_CHECKING
from sqlalchemy import BigInteger, Boolean, DateTime, ForeignKey, Integer, JSON, String, Text
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
from .base import Base
if TYPE_CHECKING:
from .prize import Prize
from .participant import Participant
from .winner import Winner
class LotteryStatus(str, enum.Enum):
DRAFT = "draft"
ACTIVE = "active"
DRAWING = "drawing"
FINISHED = "finished"
CANCELLED = "cancelled"
class Lottery(Base):
__tablename__ = "lotteries"
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
creator_id: Mapped[int] = mapped_column(BigInteger, ForeignKey("users.id"))
title: Mapped[str] = mapped_column(String(255))
description: Mapped[str | None] = mapped_column(Text, nullable=True)
status: Mapped[LotteryStatus] = mapped_column(String(20), default=LotteryStatus.DRAFT)
target_chat_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
target_chat_title: Mapped[str | None] = mapped_column(String(255), nullable=True)
require_membership: Mapped[bool] = mapped_column(Boolean, default=False)
required_chat_ids: Mapped[list | None] = mapped_column(JSON, nullable=True)
required_chat_titles: Mapped[list | None] = mapped_column(JSON, nullable=True)
required_chat_types: Mapped[list | None] = mapped_column(JSON, nullable=True)
required_chat_usernames: Mapped[list | None] = mapped_column(JSON, nullable=True)
announcement_targets: Mapped[list | None] = mapped_column(JSON, nullable=True)
max_participants: Mapped[int | None] = mapped_column(Integer, nullable=True)
announcement_message_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
contact_info: Mapped[str | None] = mapped_column(Text, nullable=True)
draw_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
auto_draw_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
allow_multiple_wins: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
invite_link_chat_ids: Mapped[list] = mapped_column(JSON, default=list, server_default="'[]'")
creator_timezone: Mapped[str | None] = mapped_column(String(64), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
drawn_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
draw_trigger: Mapped[str | None] = mapped_column(String(20), nullable=True)
required_chat_passphrases: Mapped[list | None] = mapped_column(JSON, nullable=True)
prizes: Mapped[list["Prize"]] = relationship(
"Prize", back_populates="lottery", order_by="Prize.sort_order", cascade="all, delete-orphan"
)
participants: Mapped[list["Participant"]] = relationship(
"Participant", back_populates="lottery", cascade="all, delete-orphan"
)
winners: Mapped[list["Winner"]] = relationship(
"Winner", back_populates="lottery", cascade="all, delete-orphan"
)
+19
View File
@@ -0,0 +1,19 @@
from datetime import datetime
from sqlalchemy import BigInteger, Boolean, DateTime, String
from sqlalchemy.orm import Mapped, mapped_column
from .base import Base
class ManagedChat(Base):
__tablename__ = "managed_chats"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True) # Telegram chat_id
title: Mapped[str] = mapped_column(String(255))
username: Mapped[str | None] = mapped_column(String(255), nullable=True)
chat_type: Mapped[str] = mapped_column(String(50)) # group, supergroup, channel
invite_link: Mapped[str | None] = mapped_column(String(512), nullable=True)
last_message_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
added_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
+28
View File
@@ -0,0 +1,28 @@
import uuid
from datetime import datetime
from typing import TYPE_CHECKING
from sqlalchemy import BigInteger, DateTime, ForeignKey, UniqueConstraint
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
from .base import Base
if TYPE_CHECKING:
from .lottery import Lottery
from .user import User
class Participant(Base):
__tablename__ = "participants"
__table_args__ = (UniqueConstraint("lottery_id", "user_id"),)
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
lottery_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True), ForeignKey("lotteries.id", ondelete="CASCADE")
)
user_id: Mapped[int] = mapped_column(BigInteger, ForeignKey("users.id"))
joined_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
lottery: Mapped["Lottery"] = relationship("Lottery", back_populates="participants")
user: Mapped["User"] = relationship("User")
@@ -0,0 +1,20 @@
import uuid
from datetime import datetime
from sqlalchemy import BigInteger, DateTime, ForeignKey, Integer, UniqueConstraint
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column
from .base import Base
class PassphraseVerification(Base):
__tablename__ = "passphrase_verifications"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
lottery_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("lotteries.id", ondelete="CASCADE"))
chat_id: Mapped[int] = mapped_column(BigInteger)
user_id: Mapped[int] = mapped_column(BigInteger, ForeignKey("users.id"))
verified_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
__table_args__ = (UniqueConstraint("lottery_id", "chat_id", "user_id"),)
+26
View File
@@ -0,0 +1,26 @@
import uuid
from typing import TYPE_CHECKING
from sqlalchemy import ForeignKey, Integer, String, Text
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
from .base import Base
if TYPE_CHECKING:
from .lottery import Lottery
class Prize(Base):
__tablename__ = "prizes"
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
lottery_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True), ForeignKey("lotteries.id", ondelete="CASCADE")
)
name: Mapped[str] = mapped_column(String(255))
description: Mapped[str | None] = mapped_column(Text, nullable=True)
quantity: Mapped[int] = mapped_column(Integer, default=1)
sort_order: Mapped[int] = mapped_column(Integer, default=0)
lottery: Mapped["Lottery"] = relationship("Lottery", back_populates="prizes")
+16
View File
@@ -0,0 +1,16 @@
from datetime import datetime
from sqlalchemy import BigInteger, DateTime, String
from sqlalchemy.orm import Mapped, mapped_column
from .base import Base
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
username: Mapped[str | None] = mapped_column(String(255), nullable=True)
first_name: Mapped[str] = mapped_column(String(255))
last_name: Mapped[str | None] = mapped_column(String(255), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
+34
View File
@@ -0,0 +1,34 @@
import uuid
from datetime import datetime
from typing import TYPE_CHECKING
from sqlalchemy import BigInteger, DateTime, ForeignKey, String
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
from .base import Base
if TYPE_CHECKING:
from .lottery import Lottery
from .user import User
from .prize import Prize
class Winner(Base):
__tablename__ = "winners"
__table_args__ = ()
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
lottery_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True), ForeignKey("lotteries.id", ondelete="CASCADE")
)
user_id: Mapped[int] = mapped_column(BigInteger, ForeignKey("users.id"))
prize_id: Mapped[uuid.UUID | None] = mapped_column(
UUID(as_uuid=True), ForeignKey("prizes.id", ondelete="SET NULL"), nullable=True
)
prize_name: Mapped[str] = mapped_column(String(255)) # snapshot at draw time
drawn_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
lottery: Mapped["Lottery"] = relationship("Lottery", back_populates="winners")
user: Mapped["User"] = relationship("User")
prize: Mapped["Prize | None"] = relationship("Prize")
View File
+121
View File
@@ -0,0 +1,121 @@
import random
import uuid
from datetime import datetime
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.lottery import Lottery, LotteryStatus
from app.models.participant import Participant
from app.models.prize import Prize
from app.models.user import User
from app.models.winner import Winner
async def execute_draw(db: AsyncSession, lottery_id: uuid.UUID, trigger: str = "manual") -> list[dict]:
"""
Draw winners by randomly pairing shuffled participants with shuffled prizes.
Both lists are shuffled independently so prize order has no bearing on results.
n_winners = min(participants, total prize slots).
Uses SELECT FOR UPDATE to prevent concurrent draws from producing duplicate
winner sets. The status is transitioned to DRAWING inside the lock before
any reads, so a second concurrent request will fail the status check.
"""
# Lock the lottery row - serialises all concurrent draw requests
lottery_result = await db.execute(
select(Lottery).where(Lottery.id == lottery_id).with_for_update()
)
lottery = lottery_result.scalar_one()
# Re-check status under lock; may have changed since the router pre-checked
if lottery.status != LotteryStatus.ACTIVE:
raise ValueError("Lottery is no longer active")
# Mark as DRAWING immediately so any concurrent request sees the changed
# status and aborts before we even touch participants/prizes
lottery.status = LotteryStatus.DRAWING
await db.flush()
# Load participants with user info
result = await db.execute(
select(Participant, User)
.join(User, Participant.user_id == User.id)
.where(Participant.lottery_id == lottery_id)
)
rows = result.all()
if not rows:
# Roll back the DRAWING status so the lottery stays usable
lottery.status = LotteryStatus.ACTIVE
await db.commit()
raise ValueError("No participants in this lottery")
# Load prizes
prize_result = await db.execute(
select(Prize).where(Prize.lottery_id == lottery_id)
)
prizes = prize_result.scalars().all()
if not prizes:
lottery.status = LotteryStatus.ACTIVE
await db.commit()
raise ValueError("No prizes configured")
# Expand prizes by quantity: Prize(qty=3) → [Prize, Prize, Prize]
expanded_prizes: list[Prize] = []
for prize in prizes:
expanded_prizes.extend([prize] * prize.quantity)
random.shuffle(expanded_prizes)
now = datetime.utcnow()
winners_data = []
if lottery.allow_multiple_wins:
# Draw with replacement: all prize slots awarded, same participant can win multiple
for prize in expanded_prizes:
participant, user = random.choice(rows)
db.add(Winner(
lottery_id=lottery_id,
user_id=user.id,
prize_id=prize.id,
prize_name=prize.name,
drawn_at=now,
))
winners_data.append({
"user_id": user.id,
"username": user.username,
"first_name": user.first_name,
"last_name": user.last_name,
"prize_name": prize.name,
"drawn_at": now,
})
else:
# No repeat wins: shuffle participants and pair 1-to-1 with prizes
random.shuffle(rows)
n_winners = min(len(rows), len(expanded_prizes))
for i in range(n_winners):
participant, user = rows[i]
prize = expanded_prizes[i]
db.add(Winner(
lottery_id=lottery_id,
user_id=user.id,
prize_id=prize.id,
prize_name=prize.name,
drawn_at=now,
))
winners_data.append({
"user_id": user.id,
"username": user.username,
"first_name": user.first_name,
"last_name": user.last_name,
"prize_name": prize.name,
"drawn_at": now,
})
lottery.status = LotteryStatus.FINISHED
lottery.drawn_at = now
lottery.draw_trigger = trigger
await db.commit()
return winners_data
@@ -0,0 +1,53 @@
import logging
from aiogram.exceptions import TelegramAPIError, TelegramBadRequest, TelegramForbiddenError
logger = logging.getLogger(__name__)
# Errors that mean the user is definitively NOT in the chat
_NOT_MEMBER_PHRASES = (
"user not found",
"participant not found",
"user_not_participant",
"chat not found",
"bot was kicked",
"bot is not a member",
)
# Errors that mean we simply can't verify (privacy / anonymous mode) - allow through
_UNVERIFIABLE_PHRASES = (
"user_id_invalid",
"have no rights",
"not enough rights",
"administrators only",
)
async def check_membership(chat_id: int, user_id: int) -> bool:
"""Check if a user is an active member of a Telegram chat.
Returns True when membership is confirmed OR when the check cannot be
performed due to anonymous/privacy settings (bot has admin rights but
Telegram hides the member - treat as verified to avoid false rejections).
"""
from app.bot.router import bot
try:
member = await bot.get_chat_member(chat_id, user_id)
return member.status in ("member", "administrator", "creator", "restricted")
except TelegramBadRequest as e:
msg = str(e).lower()
if any(p in msg for p in _NOT_MEMBER_PHRASES):
return False
if any(p in msg for p in _UNVERIFIABLE_PHRASES):
logger.debug("Membership unverifiable for user %s in chat %s (%s) - allowing", user_id, chat_id, e)
return True
# Unknown bad request - conservative deny
logger.warning("getChatMember bad request for user %s in chat %s: %s", user_id, chat_id, e)
return False
except TelegramForbiddenError as e:
# Bot removed from chat or no rights at all
logger.warning("getChatMember forbidden for chat %s: %s", chat_id, e)
return False
except TelegramAPIError as e:
logger.warning("getChatMember error for user %s in chat %s: %s", user_id, chat_id, e)
return False
+134
View File
@@ -0,0 +1,134 @@
import asyncio
import html
import logging
import uuid
from datetime import datetime
from sqlalchemy import select
from app.core.database import AsyncSessionLocal
from app.models.lottery import Lottery, LotteryStatus
from app.services.draw_service import execute_draw
logger = logging.getLogger(__name__)
async def _announce_winners(lottery: Lottery, winners_data: list[dict]) -> None:
if not winners_data:
return
targets = lottery.announcement_targets or (
[{"chat_id": lottery.target_chat_id, "message_id": lottery.announcement_message_id}]
if lottery.target_chat_id else []
)
if not targets:
return
from app.bot.router import bot
from aiogram.exceptions import TelegramAPIError
lines = []
for w in winners_data:
full_name = html.escape(
w["first_name"] + (f" {w['last_name']}" if w.get("last_name") else "")
)
safe_name = f'<a href="tg://user?id={w["user_id"]}">{full_name}</a>'
lines.append(f"🏆 {safe_name} - {html.escape(w['prize_name'])}")
text = (
f"🎉 <b>Draw Results: {html.escape(lottery.title)}</b>\n\n"
+ "\n".join(lines)
+ "\n\nCongratulations to all winners! 🎊"
)
from aiogram.types import ReplyParameters
for t in targets:
try:
reply = (
ReplyParameters(message_id=t["message_id"], allow_sending_without_reply=True)
if t.get("message_id")
else None
)
await bot.send_message(
t["chat_id"],
text,
parse_mode="HTML",
reply_parameters=reply,
)
except TelegramAPIError as e:
logger.warning("Failed to announce auto-draw winners to %s: %s", t["chat_id"], e)
async def notify_winners(
lottery_title: str, winners_data: list[dict], contact_info: str | None = None,
lottery_id: uuid.UUID | None = None,
) -> None:
"""Send a private congratulations message to each winner via the bot."""
from app.bot.router import bot
from aiogram.exceptions import TelegramAPIError
from app.bot.keyboards.inline import lottery_detail_keyboard
from collections import defaultdict
user_wins: dict[int, list[dict]] = defaultdict(list)
for w in winners_data:
user_wins[w["user_id"]].append(w)
keyboard = lottery_detail_keyboard(str(lottery_id), text="🏆 View results") if lottery_id else None
for user_id, wins in user_wins.items():
if len(wins) == 1:
text = (
f"🎉 Congratulations! You won in <b>{html.escape(lottery_title)}</b>!\n"
f"🎁 Prize: <b>{html.escape(wins[0]['prize_name'])}</b>"
)
else:
prizes_lines = "\n".join(f"🎁 {html.escape(w['prize_name'])}" for w in wins)
text = (
f"🎉 Congratulations! You won {len(wins)} prizes in <b>{html.escape(lottery_title)}</b>!\n"
+ prizes_lines
)
if contact_info:
text += f"\n\n📬 Contact to claim your prize: {html.escape(contact_info)}"
else:
text += "\n\nPlease contact the lottery organizer to claim your prize."
try:
await bot.send_message(user_id, text, parse_mode="HTML", reply_markup=keyboard)
except TelegramAPIError:
pass
async def run_auto_draw(lottery_id: uuid.UUID, trigger: str = "scheduled") -> None:
async with AsyncSessionLocal() as db:
try:
winners_data = await execute_draw(db, lottery_id, trigger=trigger)
except ValueError as e:
logger.info("Auto-draw skipped for %s: %s", lottery_id, e)
return
except Exception as e:
logger.error("Auto-draw error for %s: %s", lottery_id, e)
return
result = await db.execute(select(Lottery).where(Lottery.id == lottery_id))
lottery = result.scalar_one_or_none()
if lottery:
await _announce_winners(lottery, winners_data)
await notify_winners(lottery.title, winners_data, lottery.contact_info, lottery_id=lottery.id)
async def auto_draw_scheduler() -> None:
"""Poll every 30 s for lotteries whose draw_at has passed."""
while True:
await asyncio.sleep(30)
try:
now = datetime.utcnow()
async with AsyncSessionLocal() as db:
result = await db.execute(
select(Lottery.id).where(
Lottery.status == LotteryStatus.ACTIVE,
Lottery.draw_at.isnot(None),
Lottery.draw_at <= now,
)
)
ids = result.scalars().all()
for lottery_id in ids:
asyncio.create_task(run_auto_draw(lottery_id))
except Exception as e:
logger.error("Scheduler error: %s", e)
+11
View File
@@ -0,0 +1,11 @@
fastapi>=0.111.0
uvicorn[standard]>=0.30.0
aiogram>=3.10.0
sqlalchemy[asyncio]>=2.0.30
asyncpg>=0.29.0
alembic>=1.13.0
pydantic>=2.7.0
pydantic-settings>=2.3.0
redis[hiredis]>=5.0.0
httpx>=0.27.0
python-multipart>=0.0.9
+36
View File
@@ -0,0 +1,36 @@
version: '3.9'
# Development overrides — applied automatically alongside docker-compose.yml.
# Backend mounts source and hot-reloads; frontend runs Vite dev server.
# Production deploy: docker compose -f docker-compose.yml up --build -d
services:
backend:
volumes:
- ./backend:/app
environment:
DEBUG: "true"
WEBHOOK_URL: ""
# Force polling so uvicorn --reload detects file changes on NAS filesystem
WATCHFILES_FORCE_POLLING: "1"
command: sh -c "alembic upgrade head && uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload"
frontend:
build:
context: ./frontend
dockerfile: Dockerfile.dev
volumes:
- ./frontend:/app
- frontend_node_modules:/app/node_modules
- frontend_dist:/app/dist
environment:
CHOKIDAR_USEPOLLING: "true"
nginx:
volumes:
- ./nginx/nginx.dev.conf:/etc/nginx/nginx.conf:ro
- frontend_dist:/usr/share/nginx/html
volumes:
frontend_node_modules:
frontend_dist:
+47
View File
@@ -0,0 +1,47 @@
version: '3.9'
services:
postgres:
image: postgres:16-alpine
environment:
POSTGRES_DB: tglotterybot
POSTGRES_USER: postgres
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres}
volumes:
- ./postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 5s
retries: 10
restart: unless-stopped
backend:
image: git.stdm.moe/stardream/tglotterybot-backend:latest
command: sh -c "alembic upgrade head && uvicorn app.main:app --host 0.0.0.0 --port 8000"
environment:
BOT_TOKEN: ${BOT_TOKEN}
WEBHOOK_URL: ${WEBHOOK_URL:-}
WEBHOOK_SECRET: ${WEBHOOK_SECRET:-}
DATABASE_URL: postgresql+asyncpg://postgres:${POSTGRES_PASSWORD:-postgres}@postgres:5432/tglotterybot
MINI_APP_URL: ${MINI_APP_URL:-}
DEBUG: ${DEBUG:-false}
depends_on:
postgres:
condition: service_healthy
restart: unless-stopped
frontend:
image: git.stdm.moe/stardream/tglotterybot-frontend:latest
restart: unless-stopped
nginx:
image: nginx:alpine
ports:
- "${PORT:-80}:80"
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
depends_on:
- backend
- frontend
restart: unless-stopped
+12
View File
@@ -0,0 +1,12 @@
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install --frozen-lockfile 2>/dev/null || npm install
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
+4
View File
@@ -0,0 +1,4 @@
FROM node:20-alpine
WORKDIR /app
# npm install runs at startup; then vite build --watch rebuilds on source changes
CMD ["sh", "-c", "npm install && npm run build -- --watch"]
+22
View File
@@ -0,0 +1,22 @@
<!doctype html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="theme-color" content="#ffffff" />
<title>TG Lottery Bot</title>
<script src="https://telegram.org/js/telegram-web-app.js"></script>
<script>
try {
if (window.Telegram && window.Telegram.WebApp) {
window.Telegram.WebApp.ready()
window.Telegram.WebApp.expand()
}
} catch (error) {}
</script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+22
View File
@@ -0,0 +1,22 @@
server {
listen 80;
root /usr/share/nginx/html;
index index.html;
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml text/javascript;
location = /index.html {
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate" always;
add_header Pragma "no-cache" always;
add_header Expires "0" always;
try_files /index.html =404;
}
location / {
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate" always;
add_header Pragma "no-cache" always;
add_header Expires "0" always;
try_files $uri $uri/ /index.html;
}
}
+4092
View File
File diff suppressed because it is too large Load Diff
+41
View File
@@ -0,0 +1,41 @@
{
"name": "tg-lottery-bot",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"@radix-ui/react-dialog": "^1.1.1",
"@radix-ui/react-label": "^2.1.0",
"@radix-ui/react-select": "^2.1.1",
"@radix-ui/react-separator": "^1.1.0",
"@radix-ui/react-switch": "^1.1.0",
"@radix-ui/react-tabs": "^1.1.0",
"@tanstack/react-query": "^5.56.2",
"axios": "^1.7.7",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"canvas-confetti": "^1.9.3",
"framer-motion": "^11.11.1",
"lucide-react": "^0.446.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.26.2",
"tailwind-merge": "^2.5.2"
},
"devDependencies": {
"@types/canvas-confetti": "^1.6.4",
"@types/react": "^18.3.10",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.2",
"autoprefixer": "^10.4.20",
"postcss": "^8.4.47",
"tailwindcss": "^3.4.13",
"typescript": "^5.5.3",
"vite": "^5.4.8"
}
}
+6
View File
@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
+41
View File
@@ -0,0 +1,41 @@
import { Component, type ReactNode } from 'react'
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom'
import Home from './pages/Home'
import CreateLottery from './pages/CreateLottery'
import LotteryDetail from './pages/LotteryDetail'
import EditLottery from './pages/EditLottery'
class ErrorBoundary extends Component<{ children: ReactNode }, { error: string | null }> {
state = { error: null }
static getDerivedStateFromError(e: Error) { return { error: e.message } }
render() {
if (this.state.error) {
return (
<div style={{ padding: 20, fontFamily: 'monospace', color: '#c00' }}>
<b>Render Error</b>
<pre style={{ whiteSpace: 'pre-wrap', fontSize: 12 }}>{this.state.error}</pre>
<p style={{ fontSize: 11, color: '#666' }}>
initData: {window.Telegram?.WebApp?.initData?.slice(0, 60) || '(empty)'}
</p>
</div>
)
}
return this.props.children
}
}
export default function App() {
return (
<ErrorBoundary>
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/create" element={<CreateLottery />} />
<Route path="/lottery/:id" element={<LotteryDetail />} />
<Route path="/lottery/:id/edit" element={<EditLottery />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</BrowserRouter>
</ErrorBoundary>
)
}
+98
View File
@@ -0,0 +1,98 @@
import { useNavigate } from 'react-router-dom'
import { Users, Gift, ChevronRight, Shuffle, Clock } from 'lucide-react'
import { motion } from 'framer-motion'
import { Badge } from './ui/Badge'
import { Card } from './ui/Card'
import type { Lottery } from '@/types'
import { STATUS_LABELS, formatDateShort } from '@/lib/utils'
function drawMethodLabel(lottery: Lottery): { icon: React.ReactNode; label: string } | null {
if (lottery.status === 'cancelled') return null
if (lottery.status === 'finished') {
const t = lottery.draw_trigger
if (t === 'scheduled') return { icon: <Clock className="h-3.5 w-3.5" />, label: 'Scheduled' }
if (t === 'auto_count') return { icon: <Users className="h-3.5 w-3.5" />, label: 'Auto draw' }
return { icon: <Shuffle className="h-3.5 w-3.5" />, label: 'Manual' }
}
if (lottery.draw_at) return { icon: <Clock className="h-3.5 w-3.5" />, label: 'Scheduled' }
if (lottery.auto_draw_count) return { icon: <Users className="h-3.5 w-3.5" />, label: 'Auto draw' }
return { icon: <Shuffle className="h-3.5 w-3.5" />, label: 'Manual' }
}
interface LotteryCardProps {
lottery: Lottery
currentUserId: number
showOwnerBadge?: boolean
fromTab?: string
}
export function LotteryCard({ lottery, currentUserId, showOwnerBadge = false, fromTab }: LotteryCardProps) {
const navigate = useNavigate()
const isOwner = lottery.creator_id === currentUserId
const drawMethod = drawMethodLabel(lottery)
return (
<motion.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.2 }}
>
<Card
className="cursor-pointer active:scale-[0.98] transition-transform"
onClick={() => navigate(`/lottery/${lottery.id}`, { state: { fromTab } })}
>
<div className="p-4 flex items-start justify-between gap-2">
<div className="flex-1 min-w-0">
<div className="flex flex-wrap items-center gap-x-1.5 gap-y-1 mb-1">
<Badge variant={lottery.status as any}>
{STATUS_LABELS[lottery.status] ?? lottery.status}
</Badge>
{lottery.status === 'finished' && lottery.is_winner === true && (
<Badge variant="default" className="bg-emerald-500/10 text-emerald-600">
🏆 Won
</Badge>
)}
{lottery.status === 'finished' && lottery.is_winner === false && (
<Badge variant="default" className="bg-tg-secondary-bg text-tg-hint">
😢 Missed
</Badge>
)}
{showOwnerBadge && isOwner && (
<Badge variant="default" className="bg-tg-btn/10 text-tg-btn">
Mine
</Badge>
)}
{lottery.require_membership && (
<Badge variant="default" className="bg-tg-btn/10 text-tg-btn">
🔒 Members only
</Badge>
)}
</div>
<h3 className="font-semibold text-tg-text truncate">{lottery.title}</h3>
{lottery.description && (
<p className="text-sm text-tg-hint truncate mt-0.5">{lottery.description}</p>
)}
<div className="flex items-center gap-2 mt-2 text-xs text-tg-hint">
<span className="flex items-center gap-1">
<Gift className="h-3.5 w-3.5" />
{lottery.total_prizes}
</span>
<span className="flex items-center gap-1">
<Users className="h-3.5 w-3.5" />
{lottery.participant_count}
</span>
{drawMethod && (
<span className="flex items-center gap-1">
{drawMethod.icon}
{drawMethod.label}
</span>
)}
<span className="ml-auto shrink-0">{formatDateShort(lottery.created_at)}</span>
</div>
</div>
<ChevronRight className="h-5 w-5 text-tg-hint shrink-0 mt-1" />
</div>
</Card>
</motion.div>
)
}
+137
View File
@@ -0,0 +1,137 @@
import { useState } from 'react'
import { Plus, Trash2, Pencil } from 'lucide-react'
import { Button } from './ui/Button'
import { Input } from './ui/Input'
import { Dialog, DialogContent, DialogTrigger } from './ui/Dialog'
import type { PrizeCreate } from '@/types'
interface LocalPrize extends PrizeCreate {
_id: string
}
interface PrizeEditorProps {
prizes: LocalPrize[]
onChange: (prizes: LocalPrize[]) => void
disabled?: boolean
}
let _counter = 0
export function PrizeEditor({ prizes, onChange, disabled }: PrizeEditorProps) {
const [open, setOpen] = useState(false)
const [editingId, setEditingId] = useState<string | null>(null)
const [name, setName] = useState('')
const [qty, setQty] = useState('1')
const [nameErr, setNameErr] = useState('')
function openAdd() {
setEditingId(null)
setName('')
setQty('1')
setNameErr('')
setOpen(true)
}
function openEdit(prize: LocalPrize) {
setEditingId(prize._id)
setName(prize.name)
setQty(String(prize.quantity))
setNameErr('')
setOpen(true)
}
function handleSave() {
if (!name.trim()) {
setNameErr('Enter a prize name')
return
}
const quantity = Math.max(1, parseInt(qty, 10) || 1)
if (editingId) {
onChange(prizes.map((p) => p._id === editingId ? { ...p, name: name.trim(), quantity } : p))
} else {
onChange([...prizes, { _id: String(++_counter), name: name.trim(), quantity }])
}
setOpen(false)
}
function handleRemove(id: string) {
onChange(prizes.filter((p) => p._id !== id))
}
return (
<div className="flex flex-col gap-2">
{prizes.length === 0 ? (
<p className="text-sm text-tg-hint text-center py-3">
No prizes yet. Add one below.
</p>
) : (
<div className="rounded-xl overflow-hidden bg-tg-bg divide-y divide-tg-secondary-bg">
{prizes.map((prize) => (
<div key={prize._id} className="flex items-center px-4 py-3 gap-3">
<div className="flex-1 min-w-0">
<p className="font-medium text-tg-text truncate">{prize.name}</p>
<p className="text-xs text-tg-hint">x{prize.quantity}</p>
</div>
{!disabled && (
<div className="flex items-center gap-1">
<button
onClick={() => openEdit(prize)}
className="text-tg-hint p-1.5 rounded-lg hover:bg-tg-secondary-bg transition-colors"
>
<Pencil className="h-4 w-4" />
</button>
<button
onClick={() => handleRemove(prize._id)}
className="text-red-400 p-1.5 rounded-lg hover:bg-red-50 transition-colors"
>
<Trash2 className="h-4 w-4" />
</button>
</div>
)}
</div>
))}
</div>
)}
{!disabled && (
<>
<Button variant="secondary" size="md" className="w-full" onClick={openAdd}>
<Plus className="h-4 w-4" />
Add prize
</Button>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent title={editingId ? 'Edit prize' : 'Add prize'}>
<div className="flex flex-col gap-4">
<Input
label="Prize name *"
placeholder="Example: iPhone 16 Pro"
value={name}
onChange={(e) => {
setName(e.target.value)
setNameErr('')
}}
error={nameErr}
autoFocus
/>
<Input
label="Quantity"
type="number"
min={1}
max={1000}
value={qty}
onChange={(e) => setQty(e.target.value)}
/>
<Button onClick={handleSave} size="lg">
{editingId ? 'Save' : 'Add'}
</Button>
</div>
</DialogContent>
</Dialog>
</>
)}
</div>
)
}
export type { LocalPrize }
+63
View File
@@ -0,0 +1,63 @@
import { useState } from 'react'
import { Trophy } from 'lucide-react'
import { motion } from 'framer-motion'
import type { Winner } from '@/types'
import { displayName } from '@/lib/utils'
function UserAvatar({ userId, name }: { userId: number; name: string }) {
const [failed, setFailed] = useState(false)
if (!failed) {
return (
<img
src={`/api/users/${userId}/avatar`}
alt={name}
className="h-9 w-9 rounded-full object-cover bg-tg-btn/10 shrink-0"
onError={() => setFailed(true)}
/>
)
}
return (
<div className="h-9 w-9 rounded-full bg-tg-btn/10 flex items-center justify-center text-sm font-bold text-tg-btn shrink-0">
{name[0]}
</div>
)
}
interface WinnerListProps {
winners: Winner[]
onUserClick?: (user: { user_id: number; username?: string | null }) => void
}
export function WinnerList({ winners, onUserClick }: WinnerListProps) {
if (winners.length === 0) {
return (
<div className="text-center py-8 text-tg-hint">
<Trophy className="h-10 w-10 mx-auto mb-2 opacity-30" />
<p>No winners yet</p>
</div>
)
}
return (
<div className="rounded-xl overflow-hidden bg-tg-bg divide-y divide-tg-secondary-bg">
{winners.map((winner, i) => (
<motion.div
key={`${winner.user_id}-${winner.prize_name}`}
initial={{ opacity: 0, x: -16 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: i * 0.06 }}
className={`flex items-center px-4 py-3 gap-3 ${onUserClick ? 'cursor-pointer active:bg-tg-secondary-bg transition-colors' : ''}`}
onClick={() => onUserClick?.(winner)}
>
<UserAvatar userId={winner.user_id} name={winner.first_name} />
<div className="flex-1 min-w-0">
<p className="font-semibold text-tg-text truncate">
{displayName(winner)}
</p>
<p className="text-sm text-tg-hint truncate">{winner.prize_name}</p>
</div>
</motion.div>
))}
</div>
)
}
+28
View File
@@ -0,0 +1,28 @@
import { type HTMLAttributes } from 'react'
import { cn } from '@/lib/utils'
interface BadgeProps extends HTMLAttributes<HTMLSpanElement> {
variant?: 'default' | 'draft' | 'active' | 'drawing' | 'finished' | 'cancelled'
}
const variantClasses: Record<string, string> = {
default: 'bg-gray-100 text-gray-600',
draft: 'bg-gray-100 text-gray-500',
active: 'bg-emerald-100 text-emerald-700',
drawing: 'bg-blue-100 text-blue-700',
finished: 'bg-purple-100 text-purple-700',
cancelled: 'bg-red-100 text-red-600',
}
export function Badge({ variant = 'default', className, ...props }: BadgeProps) {
return (
<span
className={cn(
'inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium',
variantClasses[variant],
className
)}
{...props}
/>
)
}
+53
View File
@@ -0,0 +1,53 @@
import { type ButtonHTMLAttributes, forwardRef } from 'react'
import { cva, type VariantProps } from 'class-variance-authority'
import { cn } from '@/lib/utils'
const buttonVariants = cva(
'inline-flex items-center justify-center gap-2 rounded-xl font-semibold transition-all active:scale-95 disabled:opacity-50 disabled:pointer-events-none select-none',
{
variants: {
variant: {
primary: 'bg-tg-btn text-tg-btn-text',
secondary: 'bg-tg-secondary-bg text-tg-text',
destructive: 'bg-red-500 text-white',
ghost: 'text-tg-link hover:bg-tg-secondary-bg',
outline: 'border border-tg-hint text-tg-text bg-transparent',
},
size: {
sm: 'h-8 px-3 text-sm',
md: 'h-11 px-5 text-base',
lg: 'h-12 px-6 text-base w-full',
icon: 'h-9 w-9',
},
},
defaultVariants: {
variant: 'primary',
size: 'md',
},
}
)
interface ButtonProps
extends ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
loading?: boolean
}
const Button = forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, loading, children, disabled, ...props }, ref) => (
<button
ref={ref}
className={cn(buttonVariants({ variant, size }), className)}
disabled={disabled || loading}
{...props}
>
{loading ? (
<span className="h-4 w-4 rounded-full border-2 border-current border-t-transparent animate-spin" />
) : null}
{children}
</button>
)
)
Button.displayName = 'Button'
export { Button, buttonVariants }
+32
View File
@@ -0,0 +1,32 @@
import { type HTMLAttributes, forwardRef } from 'react'
import { cn } from '@/lib/utils'
const Card = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('bg-tg-bg rounded-2xl shadow-sm overflow-hidden', className)} {...props} />
)
)
Card.displayName = 'Card'
const CardHeader = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('px-4 pt-4 pb-2', className)} {...props} />
)
)
CardHeader.displayName = 'CardHeader'
const CardContent = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('px-4 pb-4', className)} {...props} />
)
)
CardContent.displayName = 'CardContent'
const CardFooter = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('px-4 py-3 border-t border-tg-secondary-bg flex gap-2', className)} {...props} />
)
)
CardFooter.displayName = 'CardFooter'
export { Card, CardHeader, CardContent, CardFooter }
+45
View File
@@ -0,0 +1,45 @@
import type { ReactNode } from 'react'
import * as DialogPrimitive from '@radix-ui/react-dialog'
import { X } from 'lucide-react'
import { cn } from '@/lib/utils'
export const Dialog = DialogPrimitive.Root
export const DialogTrigger = DialogPrimitive.Trigger
export const DialogClose = DialogPrimitive.Close
export function DialogContent({
children,
className,
title,
}: {
children: ReactNode
className?: string
title?: string
}) {
return (
<DialogPrimitive.Portal>
<DialogPrimitive.Overlay className="fixed inset-0 z-40 bg-black/50 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0" />
<DialogPrimitive.Content
className={cn(
'fixed bottom-0 left-0 right-0 z-50 bg-tg-bg rounded-t-3xl p-6',
'data-[state=open]:animate-in data-[state=closed]:animate-out',
'data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom',
'max-h-[90dvh] overflow-y-auto',
className
)}
>
<div className="flex items-center justify-between mb-4">
{title && (
<DialogPrimitive.Title className="text-lg font-bold text-tg-text">
{title}
</DialogPrimitive.Title>
)}
<DialogPrimitive.Close className="ml-auto p-1 rounded-full hover:bg-tg-secondary-bg transition-colors">
<X className="h-5 w-5 text-tg-hint" />
</DialogPrimitive.Close>
</div>
{children}
</DialogPrimitive.Content>
</DialogPrimitive.Portal>
)
}
+59
View File
@@ -0,0 +1,59 @@
import { type InputHTMLAttributes, forwardRef } from 'react'
import { cn } from '@/lib/utils'
interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
label?: string
error?: string
hint?: string
}
const Input = forwardRef<HTMLInputElement, InputProps>(
({ className, label, error, hint, ...props }, ref) => (
<div className="flex flex-col gap-1 min-w-0">
{label && (
<label className="text-sm font-medium text-tg-hint">{label}</label>
)}
<input
ref={ref}
className={cn(
'h-11 w-full rounded-xl bg-tg-secondary-bg px-3 text-tg-text placeholder:text-tg-hint',
'outline-none focus:ring-2 focus:ring-tg-btn/40 transition-shadow',
error && 'ring-2 ring-red-400',
className
)}
{...props}
/>
{error && <p className="text-xs text-red-500">{error}</p>}
{hint && !error && <p className="text-xs text-tg-hint">{hint}</p>}
</div>
)
)
Input.displayName = 'Input'
interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
label?: string
error?: string
}
const Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>(
({ className, label, error, ...props }, ref) => (
<div className="flex flex-col gap-1">
{label && <label className="text-sm font-medium text-tg-hint">{label}</label>}
<textarea
ref={ref}
rows={3}
className={cn(
'w-full rounded-xl bg-tg-secondary-bg px-3 py-2.5 text-tg-text placeholder:text-tg-hint',
'outline-none focus:ring-2 focus:ring-tg-btn/40 transition-shadow resize-none',
error && 'ring-2 ring-red-400',
className
)}
{...props}
/>
{error && <p className="text-xs text-red-500">{error}</p>}
</div>
)
)
Textarea.displayName = 'Textarea'
export { Input, Textarea }
+70
View File
@@ -0,0 +1,70 @@
import * as SelectPrimitive from '@radix-ui/react-select'
import { ChevronDown, Check } from 'lucide-react'
import { cn } from '@/lib/utils'
interface SelectOption {
value: string
label: string
}
interface SelectProps {
value?: string
onValueChange: (value: string) => void
options: SelectOption[]
placeholder?: string
label?: string
disabled?: boolean
}
export function Select({ value, onValueChange, options, placeholder = '请选择', label, disabled }: SelectProps) {
return (
<div className="flex flex-col gap-1">
{label && <label className="text-sm font-medium text-tg-hint">{label}</label>}
<SelectPrimitive.Root value={value} onValueChange={onValueChange} disabled={disabled}>
<SelectPrimitive.Trigger
className={cn(
'flex h-11 w-full items-center justify-between rounded-xl',
'bg-tg-secondary-bg px-3 text-tg-text',
'outline-none focus:ring-2 focus:ring-tg-btn/40 transition-shadow',
'data-[placeholder]:text-tg-hint disabled:opacity-50'
)}
>
<SelectPrimitive.Value placeholder={placeholder} />
<ChevronDown className="h-4 w-4 text-tg-hint shrink-0" />
</SelectPrimitive.Trigger>
<SelectPrimitive.Portal>
<SelectPrimitive.Content
className={cn(
'z-50 min-w-[8rem] overflow-hidden rounded-xl bg-tg-bg shadow-xl border border-tg-secondary-bg',
'data-[state=open]:animate-in data-[state=closed]:animate-out',
'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95'
)}
position="popper"
sideOffset={4}
>
<SelectPrimitive.Viewport className="p-1">
{options.map((opt) => (
<SelectPrimitive.Item
key={opt.value}
value={opt.value}
className={cn(
'relative flex cursor-default select-none items-center rounded-lg px-3 py-2.5',
'text-sm text-tg-text outline-none',
'focus:bg-tg-secondary-bg data-[state=checked]:font-semibold'
)}
>
<SelectPrimitive.ItemText>{opt.label}</SelectPrimitive.ItemText>
<SelectPrimitive.ItemIndicator className="ml-auto">
<Check className="h-4 w-4 text-tg-btn" />
</SelectPrimitive.ItemIndicator>
</SelectPrimitive.Item>
))}
</SelectPrimitive.Viewport>
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
</SelectPrimitive.Root>
</div>
)
}
+40
View File
@@ -0,0 +1,40 @@
import * as SwitchPrimitive from '@radix-ui/react-switch'
import { cn } from '@/lib/utils'
interface SwitchProps {
checked: boolean
onCheckedChange: (checked: boolean) => void
label?: string
description?: string
disabled?: boolean
}
export function Switch({ checked, onCheckedChange, label, description, disabled }: SwitchProps) {
return (
<div className="flex items-center justify-between gap-3">
{(label || description) && (
<div className="flex-1 min-w-0">
{label && <p className="text-sm font-medium text-tg-text">{label}</p>}
{description && <p className="text-xs text-tg-hint mt-0.5">{description}</p>}
</div>
)}
<SwitchPrimitive.Root
checked={checked}
onCheckedChange={onCheckedChange}
disabled={disabled}
className={cn(
'relative h-6 w-11 rounded-full transition-colors focus-visible:outline-none',
'data-[state=checked]:bg-tg-btn data-[state=unchecked]:bg-gray-300',
'disabled:opacity-50 disabled:cursor-not-allowed'
)}
>
<SwitchPrimitive.Thumb
className={cn(
'block h-5 w-5 rounded-full bg-white shadow-md transition-transform',
'data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0.5'
)}
/>
</SwitchPrimitive.Root>
</div>
)
}
+22
View File
@@ -0,0 +1,22 @@
import { AnimatePresence, motion } from 'framer-motion'
interface ToastProps {
message: string | null
}
export function Toast({ message }: ToastProps) {
return (
<AnimatePresence>
{message && (
<motion.div
initial={{ opacity: 0, y: 40 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 40 }}
className="fixed bottom-24 left-4 right-4 z-[60] bg-gray-900 text-white text-sm px-4 py-3 rounded-2xl text-center shadow-lg"
>
{message}
</motion.div>
)}
</AnimatePresence>
)
}
+12
View File
@@ -0,0 +1,12 @@
import { useState } from 'react'
export function useToast(duration = 3000) {
const [toastMsg, setToastMsg] = useState<string | null>(null)
function showToast(msg: string) {
setToastMsg(msg)
window.setTimeout(() => setToastMsg(null), duration)
}
return { toastMsg, showToast }
}
+87
View File
@@ -0,0 +1,87 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer utilities {
.no-scrollbar::-webkit-scrollbar { display: none; }
.no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
}
:root {
--tg-bg-color: #ffffff;
--tg-text-color: #000000;
--tg-hint-color: #999999;
--tg-link-color: #2481cc;
--tg-button-color: #2481cc;
--tg-button-rgb: 36 129 204; /* RGB of #2481cc - needed for opacity variants */
--tg-button-text-color: #ffffff;
--tg-secondary-bg-color: #efeff3;
}
* {
box-sizing: border-box;
-webkit-tap-highlight-color: transparent;
}
html,
body {
margin: 0;
padding: 0;
background-color: var(--tg-secondary-bg-color);
color: var(--tg-text-color);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
min-height: 100dvh;
overscroll-behavior: none;
}
#root {
min-height: 100dvh;
}
/* Scrollbar - thin, blends into background, no layout impact on mobile */
::-webkit-scrollbar {
width: 3px;
background: transparent;
}
::-webkit-scrollbar-track {
background: var(--tg-secondary-bg-color);
}
::-webkit-scrollbar-thumb {
background: color-mix(in srgb, var(--tg-hint-color) 45%, transparent);
border-radius: 9999px;
}
::-webkit-scrollbar-thumb:hover {
background: color-mix(in srgb, var(--tg-button-color) 70%, transparent);
}
/* Firefox */
* {
scrollbar-width: thin;
scrollbar-color: color-mix(in srgb, var(--tg-hint-color) 45%, transparent) transparent;
}
/* Smooth scroll */
* {
scroll-behavior: smooth;
}
@layer components {
.card {
@apply bg-tg-bg rounded-2xl p-4 shadow-sm;
}
.section-header {
@apply text-xs font-semibold uppercase tracking-wide text-tg-hint px-4 pt-2 pb-1;
}
.list-item {
@apply bg-tg-bg px-4 py-3 flex items-center gap-3;
}
.list-item:not(:last-child) {
@apply border-b border-tg-secondary-bg;
}
}
+40
View File
@@ -0,0 +1,40 @@
import axios from 'axios'
import { getTelegramInitData } from './telegram'
const api = axios.create({
baseURL: '/api',
timeout: 15000,
})
async function waitForTelegramInitData(): Promise<string> {
const existing = getTelegramInitData()
if (existing) return existing
const hasTelegramWebApp = Boolean(window.Telegram?.WebApp)
if (!hasTelegramWebApp) return ''
const deadline = Date.now() + 2000
while (Date.now() < deadline) {
await new Promise((resolve) => window.setTimeout(resolve, 50))
const initData = getTelegramInitData()
if (initData) return initData
}
return ''
}
api.interceptors.request.use(async (config) => {
// Always send the header so the backend can return 401 instead of 422
config.headers['X-Telegram-Init-Data'] = await waitForTelegramInitData()
return config
})
api.interceptors.response.use(
(res) => res,
(err) => {
const msg = err.response?.data?.detail ?? err.message ?? 'Unknown error'
return Promise.reject(new Error(typeof msg === 'string' ? msg : JSON.stringify(msg)))
}
)
export default api
+121
View File
@@ -0,0 +1,121 @@
interface TelegramWebApp {
initData: string
initDataUnsafe: {
user?: {
id: number
username?: string
first_name: string
last_name?: string
}
start_param?: string
}
themeParams: {
bg_color?: string
text_color?: string
hint_color?: string
link_color?: string
button_color?: string
button_text_color?: string
secondary_bg_color?: string
}
colorScheme: 'light' | 'dark'
MainButton: {
text: string
color: string
textColor: string
isVisible: boolean
isActive: boolean
show(): void
hide(): void
enable(): void
disable(): void
showProgress(leaveActive?: boolean): void
hideProgress(): void
onClick(fn: () => void): void
offClick(fn: () => void): void
setParams(params: { text?: string; color?: string; text_color?: string; is_active?: boolean }): void
}
BackButton: {
isVisible: boolean
show(): void
hide(): void
onClick(fn: () => void): void
offClick(fn: () => void): void
}
HapticFeedback: {
impactOccurred(style: 'light' | 'medium' | 'heavy' | 'rigid' | 'soft'): void
notificationOccurred(type: 'error' | 'success' | 'warning'): void
selectionChanged(): void
}
openLink(url: string, options?: { try_instant_view?: boolean }): void
openTelegramLink(url: string): void
expand(): void
close(): void
ready(): void
showAlert(message: string, callback?: () => void): void
showConfirm(message: string, callback: (ok: boolean) => void): void
isExpanded: boolean
shareMessage(preparedMessageId: string, callback?: (sent: boolean) => void): void
}
declare global {
interface Window {
Telegram?: { WebApp: TelegramWebApp }
}
}
// Keep tg as a stable reference for non-auth uses (theme, haptic, BackButton, etc.)
// Do NOT use tg for initData reads - it may be captured before Telegram initializes.
export const tg: TelegramWebApp | undefined = window.Telegram?.WebApp
export function getTelegramInitData(): string {
// Read dynamically so we always get the value after Telegram has initialized
const initData = window.Telegram?.WebApp?.initData
if (initData) return initData
// Dev fallback: set VITE_DEV_INIT_DATA in .env.local for local testing
return import.meta.env.VITE_DEV_INIT_DATA ?? ''
}
export function getTelegramUser() {
return (
window.Telegram?.WebApp?.initDataUnsafe?.user ?? {
id: 0,
first_name: 'Dev',
username: 'devuser',
}
)
}
function hexToRgbTriplet(hex: string): string {
const h = hex.replace('#', '')
const r = parseInt(h.substring(0, 2), 16)
const g = parseInt(h.substring(2, 4), 16)
const b = parseInt(h.substring(4, 6), 16)
return `${r} ${g} ${b}`
}
export function applyTelegramTheme(): void {
if (!tg) return
const p = tg.themeParams
const root = document.documentElement
if (p.bg_color) root.style.setProperty('--tg-bg-color', p.bg_color)
if (p.text_color) root.style.setProperty('--tg-text-color', p.text_color)
if (p.hint_color) root.style.setProperty('--tg-hint-color', p.hint_color)
if (p.link_color) root.style.setProperty('--tg-link-color', p.link_color)
if (p.button_color) {
root.style.setProperty('--tg-button-color', p.button_color)
// Space-separated RGB for Tailwind opacity modifier support (bg-tg-btn/10)
root.style.setProperty('--tg-button-rgb', hexToRgbTriplet(p.button_color))
}
if (p.button_text_color) root.style.setProperty('--tg-button-text-color', p.button_text_color)
if (p.secondary_bg_color) root.style.setProperty('--tg-secondary-bg-color', p.secondary_bg_color)
}
export function haptic(type: 'light' | 'medium' | 'success' | 'error' = 'light'): void {
if (!tg) return
if (type === 'success' || type === 'error') {
tg.HapticFeedback.notificationOccurred(type)
} else {
tg.HapticFeedback.impactOccurred(type)
}
}
+49
View File
@@ -0,0 +1,49 @@
import { clsx, type ClassValue } from 'clsx'
import { twMerge } from 'tailwind-merge'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export function formatDate(iso: string): string {
const utc = iso.endsWith('Z') || iso.includes('+') ? iso : iso + 'Z'
return new Date(utc).toLocaleString(undefined, {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
})
}
export function formatDateShort(iso: string): string {
const utc = iso.endsWith('Z') || iso.includes('+') ? iso : iso + 'Z'
return new Date(utc).toLocaleString(undefined, {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
})
}
export function displayName(user: { first_name: string; last_name?: string | null; username?: string | null }): string {
const full = [user.first_name, user.last_name].filter(Boolean).join(' ')
return full || user.username || ''
}
export const STATUS_LABELS: Record<string, string> = {
draft: 'Draft',
active: 'Active',
drawing: 'Drawing',
finished: 'Finished',
cancelled: 'Cancelled',
}
export const STATUS_COLORS: Record<string, string> = {
draft: 'bg-gray-100 text-gray-600',
active: 'bg-emerald-100 text-emerald-700',
drawing: 'bg-blue-100 text-blue-700',
finished: 'bg-purple-100 text-purple-700',
cancelled: 'bg-red-100 text-red-600',
}
+27
View File
@@ -0,0 +1,27 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import App from './App'
import { applyTelegramTheme } from './lib/telegram'
import './index.css'
applyTelegramTheme()
window.Telegram?.WebApp?.ready()
window.Telegram?.WebApp?.expand()
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: 1,
staleTime: 30_000,
},
},
})
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</React.StrictMode>
)
+357
View File
@@ -0,0 +1,357 @@
import { useEffect, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { ArrowLeft, Link2, X } from 'lucide-react'
import { motion } from 'framer-motion'
import { Input, Textarea } from '@/components/ui/Input'
import { Button } from '@/components/ui/Button'
import { Select } from '@/components/ui/Select'
import { Switch } from '@/components/ui/Switch'
import { Toast } from '@/components/ui/Toast'
import { PrizeEditor, type LocalPrize } from '@/components/PrizeEditor'
import { useToast } from '@/hooks/useToast'
import api from '@/lib/api'
import { haptic, tg } from '@/lib/telegram'
import type { ChatInfo, Lottery } from '@/types'
function utcOffset(timezone: string): string {
const parts = new Intl.DateTimeFormat('en', {
timeZone: timezone,
timeZoneName: 'shortOffset',
}).formatToParts(new Date())
const offset = parts.find((p) => p.type === 'timeZoneName')?.value ?? ''
return offset.replace('GMT', 'UTC')
}
export default function CreateLottery() {
const navigate = useNavigate()
const location = useLocation()
const qc = useQueryClient()
const template = (location.state as any)?.template as import('@/types').Lottery | undefined
const [title, setTitle] = useState(() => template?.title ?? '')
const [description, setDescription] = useState(() => template?.description ?? '')
const [contactInfo, setContactInfo] = useState(() => template?.contact_info ?? '')
const [prizes, setPrizes] = useState<LocalPrize[]>(() =>
template?.prizes.map((p) => ({ _id: crypto.randomUUID(), name: p.name, description: p.description ?? '', quantity: p.quantity })) ?? []
)
const [requiredChatIds, setRequiredChatIds] = useState<string[]>(() =>
template?.required_chat_ids?.map(String) ?? []
)
const [chatPassphrases, setChatPassphrases] = useState<Record<string, string>>(() => {
if (!template?.required_chat_ids?.length) return {}
return Object.fromEntries(
template.required_chat_ids.map((id, i) => [String(id), (template.required_chat_passphrases ?? [])[i] ?? ''])
)
})
const [addChatKey, setAddChatKey] = useState(0)
const [maxParticipants, setMaxParticipants] = useState(() => template?.max_participants?.toString() ?? '')
const [drawDate, setDrawDate] = useState('')
const [drawTime, setDrawTime] = useState(() => {
const now = new Date()
return `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`
})
const creatorTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone
const [autoDrawCount, setAutoDrawCount] = useState(() => template?.auto_draw_count?.toString() ?? '')
const [allowMultipleWins, setAllowMultipleWins] = useState(() => template?.allow_multiple_wins ?? false)
const [inviteLinkChatIds, setInviteLinkChatIds] = useState<Set<string>>(() =>
new Set(template?.invite_link_chat_ids?.map(String) ?? [])
)
const [errors, setErrors] = useState<Record<string, string>>({})
const { toastMsg, showToast } = useToast()
useEffect(() => {
tg?.BackButton.show()
const back = () => navigate('/')
tg?.BackButton.onClick(back)
return () => {
tg?.BackButton.hide()
tg?.BackButton.offClick(back)
}
}, [navigate])
const { data: chats = [] } = useQuery<ChatInfo[]>({
queryKey: ['chats'],
queryFn: () => api.get('/chats').then((r) => r.data),
})
const createMutation = useMutation({
mutationFn: async () => {
const requiredChats = chats.filter((c) => requiredChatIds.includes(String(c.id)))
if (inviteLinkChatIds.size > 0) {
const failures: string[] = []
for (const cid of inviteLinkChatIds) {
const title = chats.find((c) => String(c.id) === cid)?.title ?? cid
try {
const { data } = await api.get(`/chats/${cid}/invite`)
if (!data.url) failures.push(`${title}${data.error ? ` (${data.error})` : ''}`)
} catch {
failures.push(title)
}
}
if (failures.length > 0)
throw new Error(`Cannot generate invite link for: ${failures.join('; ')}`)
}
const lottery: Lottery = await api
.post('/lotteries', {
title: title.trim(),
description: description.trim() || undefined,
contact_info: contactInfo.trim() || undefined,
require_membership: requiredChatIds.length > 0,
required_chat_ids: requiredChats.map((c) => c.id),
required_chat_titles: requiredChats.map((c) => c.title),
required_chat_types: requiredChats.map((c) => c.chat_type),
required_chat_usernames: requiredChats.map((c) => c.username ?? ''),
max_participants: maxParticipants ? parseInt(maxParticipants, 10) : undefined,
draw_at: drawDate ? new Date(`${drawDate}T${drawTime || '00:00'}`).toISOString() : undefined,
auto_draw_count: autoDrawCount ? parseInt(autoDrawCount, 10) : undefined,
creator_timezone: drawDate ? creatorTimezone : undefined,
allow_multiple_wins: allowMultipleWins,
invite_link_chat_ids: requiredChats.filter((c) => inviteLinkChatIds.has(String(c.id))).map((c) => c.id),
required_chat_passphrases: requiredChats.map((c) => chatPassphrases[String(c.id)] ?? ''),
})
.then((r) => r.data)
for (const prize of prizes) {
await api.post(`/lotteries/${lottery.id}/prizes`, {
name: prize.name,
description: prize.description,
quantity: prize.quantity,
})
}
return lottery
},
onSuccess: (lottery) => {
haptic('success')
qc.invalidateQueries({ queryKey: ['lotteries'] })
navigate(`/lottery/${lottery.id}`)
},
onError: (err: Error) => {
haptic('error')
showToast(err.message)
},
})
function validate(): boolean {
const errs: Record<string, string> = {}
if (!title.trim()) errs.title = 'Enter a title'
if (prizes.length === 0) errs.prizes = 'Add at least one prize'
if (drawDate) {
const drawDatetime = new Date(`${drawDate}T${drawTime || '00:00'}`)
if (drawDatetime <= new Date()) errs.drawAt = 'Draw time must be in the future'
}
setErrors(errs)
return Object.keys(errs).length === 0
}
function handleSubmit() {
if (!validate()) {
haptic('error')
return
}
createMutation.mutate()
}
return (
<div className="min-h-dvh bg-tg-secondary-bg pb-28">
<div className="bg-tg-bg px-4 pt-4 pb-4 sticky top-0 z-10 shadow-sm flex items-center gap-3">
<button
onClick={() => navigate('/')}
className="p-1.5 -ml-1.5 rounded-xl hover:bg-tg-secondary-bg transition-colors"
>
<ArrowLeft className="h-5 w-5 text-tg-text" />
</button>
<h1 className="text-lg font-bold text-tg-text">{template ? 'Copy lottery' : 'Create lottery'}</h1>
</div>
<div className="px-4 pt-4 flex flex-col gap-5">
<motion.div initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.05 }}>
<p className="section-header px-0">Basic info</p>
<div className="bg-tg-bg rounded-2xl p-4 flex flex-col gap-4">
<Input
label="Title *"
placeholder="Summer giveaway"
value={title}
onChange={(e) => {
setTitle(e.target.value)
setErrors((p) => ({ ...p, title: '' }))
}}
error={errors.title}
maxLength={255}
/>
<Textarea
label="Description"
placeholder="Add rules or notes."
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
<Input
label="Contact info (private)"
placeholder="e.g. @username or email"
value={contactInfo}
onChange={(e) => setContactInfo(e.target.value)}
hint="Only shown in winner notifications, not in public announcements."
/>
</div>
</motion.div>
<motion.div initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }}>
<p className="section-header px-0">
Prizes
{prizes.length > 0 && (
<span className="ml-1 text-tg-btn">({prizes.reduce((s, p) => s + p.quantity, 0)} total)</span>
)}
</p>
{errors.prizes && <p className="text-xs text-red-500 mb-2">{errors.prizes}</p>}
<PrizeEditor prizes={prizes} onChange={setPrizes} />
</motion.div>
<motion.div initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.15 }}>
<p className="section-header px-0">Group settings</p>
<div className="bg-tg-bg rounded-2xl p-4 flex flex-col gap-4">
<div className="flex flex-col gap-2">
<label className="text-sm font-medium text-tg-hint">Require membership</label>
{requiredChatIds.length > 0 && (
<div className="flex flex-col gap-2">
{requiredChatIds.map((cid) => {
const chat = chats.find((c) => String(c.id) === cid)
const isChannel = chat?.chat_type === 'channel'
const usingLink = inviteLinkChatIds.has(cid)
return (
<div key={cid} className="bg-tg-secondary-bg rounded-xl p-3 flex flex-col gap-2">
<div className="flex items-center gap-1.5">
<span className={`shrink-0 text-xs font-medium px-2 py-0.5 rounded-full ${isChannel ? 'bg-amber-500/10 text-amber-600' : 'bg-tg-btn/10 text-tg-btn'}`}>
{isChannel ? 'Channel' : 'Group'}
</span>
<span className="flex-1 text-sm text-tg-text truncate">{chat?.title ?? cid}</span>
<button
title={usingLink ? 'Disable invite link' : 'Use invite link'}
onClick={() => setInviteLinkChatIds((s) => { const n = new Set(s); usingLink ? n.delete(cid) : n.add(cid); return n })}
className={`p-1.5 rounded-lg transition-colors ${usingLink ? 'text-tg-btn' : 'text-tg-hint opacity-30'}`}
>
<Link2 className="h-4 w-4" />
</button>
<button
onClick={() => {
setRequiredChatIds((ids) => ids.filter((i) => i !== cid))
setInviteLinkChatIds((s) => { const n = new Set(s); n.delete(cid); return n })
setChatPassphrases((p) => { const n = { ...p }; delete n[cid]; return n })
}}
className="p-1.5 rounded-lg text-tg-hint opacity-30 hover:opacity-100 hover:text-red-500 transition-colors"
>
<X className="h-4 w-4" />
</button>
</div>
{!isChannel && (
<Input
placeholder="Passphrase (optional)"
value={chatPassphrases[cid] ?? ''}
onChange={(e) => setChatPassphrases((p) => ({ ...p, [cid]: e.target.value }))}
/>
)}
</div>
)
})}
</div>
)}
{requiredChatIds.length > 0 && (
<p className="text-xs text-tg-hint">Tap <Link2 className="inline h-3 w-3 -mt-0.5" /> to use invite link. Bot must be admin with invite link permission.</p>
)}
{(() => {
const available = chats.filter((c) => !requiredChatIds.includes(String(c.id)))
if (available.length === 0 && chats.length === 0) {
return <p className="text-xs text-tg-hint">Add the bot to a group first.</p>
}
if (available.length === 0) return null
return (
<Select
key={addChatKey}
placeholder="Add group / channel…"
value=""
onValueChange={(v) => {
setRequiredChatIds((ids) => [...ids, v])
setAddChatKey((k) => k + 1)
}}
options={available.map((c) => ({
value: String(c.id),
label: `${c.chat_type === 'channel' ? 'Channel' : 'Group'}: ${c.title}`,
}))}
/>
)
})()}
</div>
<Input
label="Max participants"
placeholder="Unlimited"
type="number"
min={1}
value={maxParticipants}
onChange={(e) => setMaxParticipants(e.target.value)}
hint="Leave empty for no limit."
/>
</div>
</motion.div>
<motion.div initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.2 }}>
<p className="section-header px-0">Draw settings</p>
<div className="bg-tg-bg rounded-2xl p-4 flex flex-col gap-4 overflow-hidden">
<Switch
label="Allow multiple wins"
description="The same participant may win more than one prize."
checked={allowMultipleWins}
onCheckedChange={setAllowMultipleWins}
/>
<div className="flex flex-col gap-1">
<label className="text-sm font-medium text-tg-hint">Draw at ({utcOffset(creatorTimezone)})</label>
<div className="flex gap-2">
<input
type="date"
value={drawDate}
onChange={(e) => setDrawDate(e.target.value)}
className="flex-1 min-w-0 h-11 rounded-xl bg-tg-secondary-bg px-3 text-tg-text outline-none focus:ring-2 focus:ring-tg-btn/40 transition-shadow"
/>
<input
type="time"
value={drawTime}
onChange={(e) => setDrawTime(e.target.value)}
disabled={!drawDate}
className="w-28 min-w-0 h-11 rounded-xl bg-tg-secondary-bg px-3 text-tg-text outline-none focus:ring-2 focus:ring-tg-btn/40 transition-shadow disabled:opacity-40"
/>
</div>
{errors.drawAt
? <p className="text-xs text-red-500">{errors.drawAt}</p>
: <p className="text-xs text-tg-hint">Leave empty to draw manually.</p>
}
</div>
<Input
label="Draw when participants reach"
placeholder="e.g. 100"
type="number"
min={1}
value={autoDrawCount}
onChange={(e) => setAutoDrawCount(e.target.value)}
hint="Independent from max participants."
/>
</div>
</motion.div>
</div>
<div className="fixed bottom-0 left-0 right-0 p-4 bg-tg-bg border-t border-tg-secondary-bg">
<Button
size="lg"
onClick={handleSubmit}
loading={createMutation.isPending}
disabled={createMutation.isPending}
>
Create lottery
</Button>
</div>
<Toast message={toastMsg} />
</div>
)
}
+444
View File
@@ -0,0 +1,444 @@
import { useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { ArrowLeft, Link2, Loader2, AlertCircle, X } from 'lucide-react'
import { motion } from 'framer-motion'
import { Input, Textarea } from '@/components/ui/Input'
import { Button } from '@/components/ui/Button'
import { Select } from '@/components/ui/Select'
import { Switch } from '@/components/ui/Switch'
import { Toast } from '@/components/ui/Toast'
import { PrizeEditor, type LocalPrize } from '@/components/PrizeEditor'
import { useToast } from '@/hooks/useToast'
import api from '@/lib/api'
import { haptic, tg } from '@/lib/telegram'
import type { ChatInfo, Lottery } from '@/types'
function utcOffset(timezone: string): string {
const parts = new Intl.DateTimeFormat('en', {
timeZone: timezone,
timeZoneName: 'shortOffset',
}).formatToParts(new Date())
const offset = parts.find((p) => p.type === 'timeZoneName')?.value ?? ''
return offset.replace('GMT', 'UTC')
}
type EditablePrize = LocalPrize & { existingId?: string }
function toDatetimeLocal(isoString: string): string {
const utc = isoString.endsWith('Z') || isoString.includes('+') ? isoString : isoString + 'Z'
const d = new Date(utc)
const offset = d.getTimezoneOffset() * 60000
return new Date(d.getTime() - offset).toISOString().slice(0, 16)
}
export default function EditLottery() {
const { id } = useParams<{ id: string }>()
const navigate = useNavigate()
const qc = useQueryClient()
const [title, setTitle] = useState('')
const [description, setDescription] = useState('')
const [contactInfo, setContactInfo] = useState('')
const [prizes, setPrizes] = useState<EditablePrize[]>([])
const [originalPrizeIds, setOriginalPrizeIds] = useState<Set<string>>(new Set())
const [requiredChatIds, setRequiredChatIds] = useState<string[]>([])
const [chatPassphrases, setChatPassphrases] = useState<Record<string, string>>({})
const [addChatKey, setAddChatKey] = useState(0)
const [maxParticipants, setMaxParticipants] = useState('')
const [drawDate, setDrawDate] = useState('')
const [drawTime, setDrawTime] = useState(() => {
const now = new Date()
return `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`
})
const creatorTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone
const [autoDrawCount, setAutoDrawCount] = useState('')
const [allowMultipleWins, setAllowMultipleWins] = useState(false)
const [inviteLinkChatIds, setInviteLinkChatIds] = useState<Set<string>>(new Set())
const [errors, setErrors] = useState<Record<string, string>>({})
const { toastMsg, showToast } = useToast()
const [initialized, setInitialized] = useState(false)
useEffect(() => {
tg?.BackButton.show()
const back = () => navigate(`/lottery/${id}`)
tg?.BackButton.onClick(back)
return () => {
tg?.BackButton.hide()
tg?.BackButton.offClick(back)
}
}, [navigate, id])
const { data: lottery, isLoading, error } = useQuery<Lottery>({
queryKey: ['lottery', id],
queryFn: () => api.get(`/lotteries/${id}`).then((r) => r.data),
enabled: !!id,
})
const canEditPrizes = lottery?.status === 'draft' || lottery?.status === 'active'
const { data: chats = [] } = useQuery<ChatInfo[]>({
queryKey: ['chats'],
queryFn: () => api.get('/chats').then((r) => r.data),
})
useEffect(() => {
if (!lottery || initialized) return
if (lottery.status === 'finished' || lottery.status === 'cancelled') {
navigate(`/lottery/${id}`, { replace: true })
return
}
setTitle(lottery.title)
setDescription(lottery.description ?? '')
setContactInfo(lottery.contact_info ?? '')
setMaxParticipants(lottery.max_participants ? String(lottery.max_participants) : '')
if (lottery.draw_at) {
const local = toDatetimeLocal(lottery.draw_at)
setDrawDate(local.slice(0, 10))
setDrawTime(local.slice(11, 16))
}
setAutoDrawCount(lottery.auto_draw_count ? String(lottery.auto_draw_count) : '')
setAllowMultipleWins(lottery.allow_multiple_wins ?? false)
setInviteLinkChatIds(new Set((lottery.invite_link_chat_ids ?? []).map(String)))
setRequiredChatIds((lottery.required_chat_ids ?? []).map(String))
setChatPassphrases(
Object.fromEntries(
(lottery.required_chat_ids ?? []).map((id, i) => [
String(id),
(lottery.required_chat_passphrases ?? [])[i] ?? '',
])
)
)
const existingPrizes: EditablePrize[] = lottery.prizes.map((p) => ({
_id: `existing_${p.id}`,
existingId: p.id,
name: p.name,
quantity: p.quantity,
}))
setPrizes(existingPrizes)
setOriginalPrizeIds(new Set(lottery.prizes.map((p) => p.id)))
setInitialized(true)
}, [lottery, initialized, navigate, id])
const saveMutation = useMutation({
mutationFn: async () => {
const requiredChats = chats.filter((c) => requiredChatIds.includes(String(c.id)))
if (inviteLinkChatIds.size > 0) {
const failures: string[] = []
for (const cid of inviteLinkChatIds) {
const title = chats.find((c) => String(c.id) === cid)?.title ?? cid
try {
const { data } = await api.get(`/chats/${cid}/invite`)
if (!data.url) failures.push(`${title}${data.error ? ` (${data.error})` : ''}`)
} catch {
failures.push(title)
}
}
if (failures.length > 0)
throw new Error(`Cannot generate invite link for: ${failures.join('; ')}`)
}
await api.put(`/lotteries/${id}`, {
title: title.trim(),
description: description.trim() || null,
contact_info: contactInfo.trim() || null,
require_membership: requiredChatIds.length > 0,
required_chat_ids: requiredChats.map((c) => c.id),
required_chat_titles: requiredChats.map((c) => c.title),
required_chat_types: requiredChats.map((c) => c.chat_type),
required_chat_usernames: requiredChats.map((c) => c.username ?? ''),
max_participants: maxParticipants ? parseInt(maxParticipants, 10) : null,
draw_at: drawDate ? new Date(`${drawDate}T${drawTime || '00:00'}`).toISOString() : null,
auto_draw_count: autoDrawCount ? parseInt(autoDrawCount, 10) : null,
creator_timezone: drawDate ? creatorTimezone : null,
allow_multiple_wins: allowMultipleWins,
invite_link_chat_ids: requiredChats.filter((c) => inviteLinkChatIds.has(String(c.id))).map((c) => c.id),
required_chat_passphrases: requiredChats.map((c) => chatPassphrases[String(c.id)] ?? ''),
})
if (lottery?.status === 'draft' || lottery?.status === 'active') {
const currentExistingIds = new Set(
prizes.filter((p) => p.existingId).map((p) => p.existingId as string)
)
const toDelete = [...originalPrizeIds].filter((pid) => !currentExistingIds.has(pid))
for (const pid of toDelete) {
await api.delete(`/prizes/${pid}`)
}
const originalByExistingId = Object.fromEntries(
lottery.prizes.map((p) => [p.id, p])
)
const existingPrizes = prizes.filter((p) => p.existingId)
for (const prize of existingPrizes) {
const orig = originalByExistingId[prize.existingId!]
if (orig && (orig.name !== prize.name || orig.quantity !== prize.quantity)) {
await api.put(`/prizes/${prize.existingId}`, {
name: prize.name,
quantity: prize.quantity,
})
}
}
const newPrizes = prizes.filter((p) => !p.existingId)
for (const prize of newPrizes) {
await api.post(`/lotteries/${id}/prizes`, {
name: prize.name,
description: prize.description,
quantity: prize.quantity,
})
}
}
},
onSuccess: () => {
haptic('success')
qc.invalidateQueries({ queryKey: ['lottery', id] })
qc.invalidateQueries({ queryKey: ['lotteries'] })
navigate(`/lottery/${id}`)
},
onError: (err: Error) => {
haptic('error')
showToast(err.message)
},
})
function validate(): boolean {
const errs: Record<string, string> = {}
if (!title.trim()) errs.title = 'Enter a title'
if (prizes.length === 0) errs.prizes = 'Add at least one prize'
if (drawDate) {
const drawDatetime = new Date(`${drawDate}T${drawTime || '00:00'}`)
if (drawDatetime <= new Date()) errs.drawAt = 'Draw time must be in the future'
}
setErrors(errs)
return Object.keys(errs).length === 0
}
function handleSubmit() {
if (!validate()) {
haptic('error')
return
}
saveMutation.mutate()
}
if (isLoading || !initialized) {
return (
<div className="min-h-dvh flex items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-tg-btn" />
</div>
)
}
if (error || !lottery) {
return (
<div className="min-h-dvh flex flex-col items-center justify-center p-6 text-center gap-3">
<AlertCircle className="h-10 w-10 text-red-500" />
<p className="font-semibold text-tg-text">Failed to load lottery</p>
<Button variant="secondary" onClick={() => navigate('/')}>Back</Button>
</div>
)
}
return (
<div className="min-h-dvh bg-tg-secondary-bg pb-28">
<div className="bg-tg-bg px-4 pt-4 pb-4 sticky top-0 z-10 shadow-sm flex items-center gap-3">
<button
onClick={() => navigate(`/lottery/${id}`)}
className="p-1.5 -ml-1.5 rounded-xl hover:bg-tg-secondary-bg transition-colors"
>
<ArrowLeft className="h-5 w-5 text-tg-text" />
</button>
<h1 className="text-lg font-bold text-tg-text">Edit lottery</h1>
</div>
<div className="px-4 pt-4 flex flex-col gap-5">
<motion.div initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.05 }}>
<p className="section-header px-0">Basic info</p>
<div className="bg-tg-bg rounded-2xl p-4 flex flex-col gap-4">
<Input
label="Title *"
placeholder="Summer giveaway"
value={title}
onChange={(e) => {
setTitle(e.target.value)
setErrors((p) => ({ ...p, title: '' }))
}}
error={errors.title}
maxLength={255}
/>
<Textarea
label="Description"
placeholder="Add rules or notes."
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
<Input
label="Contact info (private)"
placeholder="e.g. @username or email"
value={contactInfo}
onChange={(e) => setContactInfo(e.target.value)}
hint="Only shown in winner notifications, not in public announcements."
/>
</div>
</motion.div>
<motion.div initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }}>
<p className="section-header px-0">
Prizes
{prizes.length > 0 && (
<span className="ml-1 text-tg-btn">({prizes.reduce((s, p) => s + p.quantity, 0)} total)</span>
)}
</p>
{errors.prizes && <p className="text-xs text-red-500 mb-2">{errors.prizes}</p>}
<PrizeEditor prizes={prizes} onChange={(p) => setPrizes(p as EditablePrize[])} disabled={!canEditPrizes} />
</motion.div>
<motion.div initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.15 }}>
<p className="section-header px-0">Group settings</p>
<div className="bg-tg-bg rounded-2xl p-4 flex flex-col gap-4">
<div className="flex flex-col gap-2">
<label className="text-sm font-medium text-tg-hint">Require membership</label>
{requiredChatIds.length > 0 && (
<div className="flex flex-col gap-2">
{requiredChatIds.map((cid) => {
const chat = chats.find((c) => String(c.id) === cid)
const isChannel = chat?.chat_type === 'channel'
const usingLink = inviteLinkChatIds.has(cid)
return (
<div key={cid} className="bg-tg-secondary-bg rounded-xl p-3 flex flex-col gap-2">
<div className="flex items-center gap-1.5">
<span className={`shrink-0 text-xs font-medium px-2 py-0.5 rounded-full ${isChannel ? 'bg-amber-500/10 text-amber-600' : 'bg-tg-btn/10 text-tg-btn'}`}>
{isChannel ? 'Channel' : 'Group'}
</span>
<span className="flex-1 text-sm text-tg-text truncate">{chat?.title ?? cid}</span>
<button
title={usingLink ? 'Disable invite link' : 'Use invite link'}
onClick={() => setInviteLinkChatIds((s) => { const n = new Set(s); usingLink ? n.delete(cid) : n.add(cid); return n })}
className={`p-1.5 rounded-lg transition-colors ${usingLink ? 'text-tg-btn' : 'text-tg-hint opacity-30'}`}
>
<Link2 className="h-4 w-4" />
</button>
<button
onClick={() => {
setRequiredChatIds((ids) => ids.filter((i) => i !== cid))
setInviteLinkChatIds((s) => { const n = new Set(s); n.delete(cid); return n })
setChatPassphrases((p) => { const n = { ...p }; delete n[cid]; return n })
}}
className="p-1.5 rounded-lg text-tg-hint opacity-30 hover:opacity-100 hover:text-red-500 transition-colors"
>
<X className="h-4 w-4" />
</button>
</div>
{!isChannel && (
<Input
placeholder="Passphrase (optional)"
value={chatPassphrases[cid] ?? ''}
onChange={(e) => setChatPassphrases((p) => ({ ...p, [cid]: e.target.value }))}
/>
)}
</div>
)
})}
</div>
)}
{requiredChatIds.length > 0 && (
<p className="text-xs text-tg-hint">Tap <Link2 className="inline h-3 w-3 -mt-0.5" /> to use invite link. Bot must be admin with invite link permission.</p>
)}
{(() => {
const available = chats.filter((c) => !requiredChatIds.includes(String(c.id)))
if (available.length === 0 && chats.length === 0) {
return <p className="text-xs text-tg-hint">Add the bot to a group first.</p>
}
if (available.length === 0) return null
return (
<Select
key={addChatKey}
placeholder="Add group / channel…"
value=""
onValueChange={(v) => {
setRequiredChatIds((ids) => [...ids, v])
setAddChatKey((k) => k + 1)
}}
options={available.map((c) => ({
value: String(c.id),
label: `${c.chat_type === 'channel' ? 'Channel' : 'Group'}: ${c.title}`,
}))}
/>
)
})()}
</div>
<Input
label="Max participants"
placeholder="Unlimited"
type="number"
min={1}
value={maxParticipants}
onChange={(e) => setMaxParticipants(e.target.value)}
hint="Leave empty for no limit."
/>
</div>
</motion.div>
<motion.div initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.2 }}>
<p className="section-header px-0">Draw settings</p>
<div className="bg-tg-bg rounded-2xl p-4 flex flex-col gap-4 overflow-hidden">
<Switch
label="Allow multiple wins"
description="The same participant may win more than one prize."
checked={allowMultipleWins}
onCheckedChange={setAllowMultipleWins}
/>
<div className="flex flex-col gap-1">
<label className="text-sm font-medium text-tg-hint">Draw at ({utcOffset(creatorTimezone)})</label>
<div className="flex gap-2">
<input
type="date"
value={drawDate}
onChange={(e) => setDrawDate(e.target.value)}
className="flex-1 min-w-0 h-11 rounded-xl bg-tg-secondary-bg px-3 text-tg-text outline-none focus:ring-2 focus:ring-tg-btn/40 transition-shadow"
/>
<input
type="time"
value={drawTime}
onChange={(e) => setDrawTime(e.target.value)}
disabled={!drawDate}
className="w-28 min-w-0 h-11 rounded-xl bg-tg-secondary-bg px-3 text-tg-text outline-none focus:ring-2 focus:ring-tg-btn/40 transition-shadow disabled:opacity-40"
/>
</div>
{errors.drawAt
? <p className="text-xs text-red-500">{errors.drawAt}</p>
: <p className="text-xs text-tg-hint">Leave empty to draw manually.</p>
}
</div>
<Input
label="Draw when participants reach"
placeholder="e.g. 100"
type="number"
min={1}
value={autoDrawCount}
onChange={(e) => setAutoDrawCount(e.target.value)}
hint="Independent from max participants."
/>
</div>
</motion.div>
</div>
<div className="fixed bottom-0 left-0 right-0 p-4 bg-tg-bg border-t border-tg-secondary-bg">
<Button
size="lg"
onClick={handleSubmit}
loading={saveMutation.isPending}
disabled={saveMutation.isPending}
>
Save changes
</Button>
</div>
<Toast message={toastMsg} />
</div>
)
}
+325
View File
@@ -0,0 +1,325 @@
import { useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { Plus, Trophy, Loader2, AlertCircle, ChevronDown, Check } from 'lucide-react'
import * as TabsPrimitive from '@radix-ui/react-tabs'
import { motion, AnimatePresence } from 'framer-motion'
import { LotteryCard } from '@/components/LotteryCard'
import { Button } from '@/components/ui/Button'
import api from '@/lib/api'
import { getTelegramInitData, getTelegramUser } from '@/lib/telegram'
import type { Lottery } from '@/types'
import { cn, STATUS_LABELS } from '@/lib/utils'
export default function Home() {
const navigate = useNavigate()
const user = getTelegramUser()
const [tab, setTab] = useState<'mine' | 'joined'>(
() => (sessionStorage.getItem('homeTab') as 'mine' | 'joined') ?? 'mine'
)
const [direction, setDirection] = useState(0)
type FilterValue = 'all' | Lottery['status']
const [tabFilters, setTabFilters] = useState<Record<string, FilterValue>>(() => ({
mine: (sessionStorage.getItem('homeFilter_mine') as FilterValue) ?? 'all',
joined: (sessionStorage.getItem('homeFilter_joined') as FilterValue) ?? 'all',
}))
const filterStatus = tabFilters[tab] ?? 'all'
const [tabFinishedSub, setTabFinishedSub] = useState<Record<string, 'all' | 'won' | 'no_win'>>({ mine: 'all', joined: 'all' })
const finishedSub = tabFinishedSub[tab] ?? 'all'
const [finishedDropdownOpen, setFinishedDropdownOpen] = useState(false)
const [dropdownPos, setDropdownPos] = useState({ top: 0, left: 0 })
const finishedBtnRef = useRef<HTMLButtonElement>(null)
const tabOrder = { mine: 0, joined: 1 }
function handleTabChange(v: 'mine' | 'joined') {
setDirection(tabOrder[v] > tabOrder[tab] ? 1 : -1)
setTab(v)
sessionStorage.setItem('homeTab', v)
setFinishedDropdownOpen(false)
}
function handleFilterChange(status: FilterValue) {
setTabFilters((prev) => ({ ...prev, [tab]: status }))
sessionStorage.setItem(`homeFilter_${tab}`, status)
}
function openFinishedDropdown() {
handleFilterChange('finished')
const rect = finishedBtnRef.current?.getBoundingClientRect()
if (rect) setDropdownPos({ top: rect.bottom + 6, left: rect.left })
setFinishedDropdownOpen((v) => !v)
}
const {
data: myLotteries = [],
isLoading: myLoading,
error: myError,
} = useQuery<Lottery[]>({
queryKey: ['lotteries', 'mine'],
queryFn: () => api.get('/lotteries').then((r) => r.data),
})
const {
data: joinedLotteries = [],
isLoading: joinedLoading,
error: joinedError,
} = useQuery<Lottery[]>({
queryKey: ['lotteries', 'joined'],
queryFn: () => api.get('/lotteries/joined').then((r) => r.data),
enabled: tab === 'joined',
})
const isLoading = tab === 'mine' ? myLoading : joinedLoading
const error = tab === 'mine' ? myError : joinedError
const lotteries = tab === 'mine' ? myLotteries : joinedLotteries
const filteredLotteries =
filterStatus === 'all' ? lotteries
: filterStatus === 'finished' && finishedSub === 'won'
? lotteries.filter((l) => l.status === 'finished' && l.is_winner === true)
: filterStatus === 'finished' && finishedSub === 'no_win'
? lotteries.filter((l) => l.status === 'finished' && l.is_winner === false)
: lotteries.filter((l) => l.status === filterStatus)
const STATUS_ORDER: Lottery['status'][] = ['draft', 'active', 'drawing', 'finished', 'cancelled']
const uniqueStatuses = STATUS_ORDER.filter((s) => lotteries.some((l) => l.status === s))
const showWonSub = lotteries.some((l) => l.status === 'finished' && l.is_winner === true)
const showNoWinSub = lotteries.some((l) => l.status === 'finished' && l.is_winner === false)
return (
<div className="min-h-dvh bg-tg-secondary-bg pb-24">
<div className="sticky top-0 z-10">
<div className="bg-tg-bg px-4 pt-4 pb-4 shadow-sm">
<div className="flex items-center justify-between">
<div>
<h1 className="text-xl font-bold text-tg-text">Lottery Bot</h1>
<p className="text-sm text-tg-hint">
Hello, {user.first_name}
{user.username ? ` (@${user.username})` : ''}
</p>
</div>
<Trophy className="h-8 w-8 text-tg-btn opacity-80" />
</div>
<TabsPrimitive.Root value={tab} onValueChange={(v) => handleTabChange(v as 'mine' | 'joined')}>
<TabsPrimitive.List className="relative flex mt-3 gap-1 bg-tg-secondary-bg rounded-xl p-1">
{([
['mine', 'My lotteries'],
['joined', 'Joined'],
] as const).map(([value, label]) => (
<TabsPrimitive.Trigger
key={value}
value={value}
className={cn(
'relative flex-1 py-1.5 rounded-lg text-sm font-medium transition-colors z-10',
'data-[state=active]:text-tg-text',
'data-[state=inactive]:text-tg-hint'
)}
>
{tab === value && (
<motion.div
layoutId="tab-pill"
className="absolute inset-0 bg-tg-bg rounded-lg shadow-sm"
transition={{ type: 'spring', stiffness: 400, damping: 35 }}
/>
)}
<span className="relative z-10">
{label}
{value === 'joined' && joinedLotteries.length > 0 && (
<span className="ml-1.5 text-xs bg-tg-btn text-tg-btn-text px-1.5 py-0.5 rounded-full">
{joinedLotteries.length}
</span>
)}
</span>
</TabsPrimitive.Trigger>
))}
</TabsPrimitive.List>
</TabsPrimitive.Root>
</div>
<AnimatePresence>
{lotteries.length > 0 && uniqueStatuses.length > 1 && (
<motion.div
key={tab}
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
exit={{ opacity: 0, height: 0 }}
transition={{ duration: 0.18 }}
style={{ overflow: 'hidden' }}
>
<div className="flex gap-2 overflow-x-auto bg-tg-secondary-bg px-4 pt-3 pb-3 no-scrollbar">
<button
onClick={() => { handleFilterChange('all'); setFinishedDropdownOpen(false) }}
className={cn(
'shrink-0 flex items-center text-xs px-3 py-1 rounded-full font-medium transition-colors',
filterStatus === 'all' ? 'bg-tg-btn text-tg-btn-text' : 'bg-tg-secondary-bg text-tg-hint'
)}
>
All
</button>
{uniqueStatuses.map((s) => {
const isFinishedWithSub = s === 'finished' && (showWonSub || showNoWinSub)
const active = filterStatus === s
return (
<button
key={s}
ref={s === 'finished' ? finishedBtnRef : undefined}
onClick={() => isFinishedWithSub ? openFinishedDropdown() : handleFilterChange(s)}
className={cn(
'shrink-0 flex items-center gap-0.5 text-xs px-3 py-1 rounded-full font-medium transition-colors',
active ? 'bg-tg-btn text-tg-btn-text' : 'bg-tg-secondary-bg text-tg-hint'
)}
>
{STATUS_LABELS[s]}
{isFinishedWithSub && (
<ChevronDown className={cn('h-3 w-3 transition-transform', finishedDropdownOpen && active ? 'rotate-180' : '')} />
)}
</button>
)
})}
</div>
</motion.div>
)}
</AnimatePresence>
{/* Finished sub-filter dropdown */}
<AnimatePresence>
{finishedDropdownOpen && (
<>
<div className="fixed inset-0 z-[90]" onClick={() => setFinishedDropdownOpen(false)} />
<motion.div
initial={{ opacity: 0, scale: 0.95, y: -4 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.95, y: -4 }}
transition={{ duration: 0.12 }}
style={{ position: 'fixed', top: dropdownPos.top, left: dropdownPos.left, zIndex: 91 }}
className="bg-tg-bg rounded-xl shadow-lg overflow-hidden min-w-[130px]"
>
{([
['all', 'All finished'],
...(showWonSub ? [['won', '🏆 Won']] : []),
...(showNoWinSub ? [['no_win', '😢 Missed']] : []),
] as [string, string][]).map(([sub, label]) => (
<button
key={sub}
onClick={() => { setTabFinishedSub((p) => ({ ...p, [tab]: sub as 'all' | 'won' | 'no_win' })); setFinishedDropdownOpen(false) }}
className="flex items-center gap-2 w-full px-4 py-2.5 text-sm text-tg-text hover:bg-tg-secondary-bg transition-colors"
>
<span className="flex-1 text-left">{label}</span>
{finishedSub === sub && <Check className="h-3.5 w-3.5 text-tg-btn shrink-0" />}
</button>
))}
</motion.div>
</>
)}
</AnimatePresence>
</div>
<div className="px-4 pt-4 overflow-hidden">
<AnimatePresence mode="wait" custom={direction}>
<motion.div
key={tab}
custom={direction}
variants={{
enter: (d: number) => ({ x: d * 32, opacity: 0 }),
center: { x: 0, opacity: 1 },
exit: (d: number) => ({ x: d * -32, opacity: 0 }),
}}
initial="enter"
animate="center"
exit="exit"
transition={{ duration: 0.2, ease: 'easeInOut' }}
className="flex flex-col gap-3"
>
{error ? (
<ErrorState error={error} />
) : isLoading ? (
<div className="flex justify-center py-16">
<Loader2 className="h-8 w-8 animate-spin text-tg-btn" />
</div>
) : lotteries.length === 0 ? (
<EmptyState tab={tab} onCreateClick={() => navigate('/create')} />
) : filteredLotteries.length === 0 ? (
<p className="text-center text-sm text-tg-hint py-12">No lotteries match this filter.</p>
) : (
filteredLotteries.map((l) => (
<LotteryCard key={l.id} lottery={l} currentUserId={user.id} showOwnerBadge={tab === 'joined'} fromTab={tab} />
))
)}
</motion.div>
</AnimatePresence>
</div>
<motion.div
className="fixed bottom-6 right-4 z-20"
initial={{ scale: 0 }}
animate={{ scale: 1 }}
transition={{ type: 'spring', stiffness: 300, damping: 20 }}
>
<Button
size="md"
className="rounded-2xl shadow-lg gap-2 px-5"
onClick={() => navigate('/create')}
>
<Plus className="h-5 w-5" />
Create
</Button>
</motion.div>
</div>
)
}
function EmptyState({ tab, onCreateClick }: { tab: string; onCreateClick: () => void }) {
return (
<div className="flex flex-col items-center justify-center py-20 text-center">
<div className="text-5xl mb-4">-</div>
<p className="text-lg font-semibold text-tg-text mb-1">
{tab === 'mine' ? 'No lotteries yet' : 'No joined lotteries'}
</p>
<p className="text-sm text-tg-hint mb-6">
{tab === 'mine' ? 'Create your first lottery.' : 'Join a lottery to see it here.'}
</p>
{tab === 'mine' && (
<Button onClick={onCreateClick}>
<Plus className="h-4 w-4" />
Create
</Button>
)}
</div>
)
}
function ErrorState({ error }: { error: unknown }) {
const initData = getTelegramInitData()
const webApp = window.Telegram?.WebApp
const unsafeUser = webApp?.initDataUnsafe?.user
return (
<div
style={{
margin: 16,
padding: 16,
borderRadius: 12,
background: '#ffffff',
color: '#111111',
border: '1px solid #e5e7eb',
fontFamily: 'system-ui, -apple-system, Segoe UI, sans-serif',
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
<AlertCircle className="h-5 w-5 text-red-500" />
<strong>Failed to load Mini App</strong>
</div>
<p style={{ margin: '8px 0', color: '#374151', wordBreak: 'break-word' }}>
{String(error)}
</p>
<div style={{ margin: 0, fontSize: 12, lineHeight: 1.7, color: '#4b5563' }}>
<div>Telegram SDK: {webApp ? 'present' : 'missing'}</div>
<div>initData length: {initData.length}</div>
<div>initData has hash: {initData.includes('hash=') ? 'yes' : 'no'}</div>
<div>User: {unsafeUser?.id ? `${unsafeUser.id} ${unsafeUser.username ?? ''}` : 'missing'}</div>
<div>Platform: {(webApp as any)?.platform ?? 'unknown'}</div>
</div>
</div>
)
}
File diff suppressed because it is too large Load Diff
+78
View File
@@ -0,0 +1,78 @@
export interface Prize {
id: string
name: string
description?: string
quantity: number
sort_order: number
}
export interface Lottery {
id: string
creator_id: number
title: string
description?: string
contact_info?: string
status: 'draft' | 'active' | 'drawing' | 'finished' | 'cancelled'
target_chat_id?: number
target_chat_title?: string
require_membership: boolean
required_chat_ids: number[]
required_chat_titles: string[]
required_chat_types: string[]
required_chat_usernames: string[]
announcement_targets: { chat_id: number; chat_title: string; message_id?: number }[]
allow_multiple_wins: boolean
invite_link_chat_ids: number[]
required_chat_passphrases: string[]
max_participants?: number
draw_at?: string
auto_draw_count?: number
creator_timezone?: string
participant_count: number
prize_count: number
total_prizes: number
created_at: string
drawn_at?: string
draw_trigger?: 'manual' | 'scheduled' | 'auto_count'
prizes: Prize[]
is_winner?: boolean | null
}
export interface Participant {
user_id: number
username?: string
first_name: string
last_name?: string
joined_at: string
}
export interface Winner {
user_id: number
username?: string
first_name: string
last_name?: string
prize_name: string
drawn_at: string
}
export interface ChatInfo {
id: number
title: string
username?: string
chat_type: string
}
export interface PrizeCreate {
name: string
description?: string
quantity: number
}
export interface LotteryCreate {
title: string
description?: string
target_chat_id?: number
target_chat_title?: string
require_membership: boolean
max_participants?: number
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+25
View File
@@ -0,0 +1,25 @@
import type { Config } from 'tailwindcss'
export default {
content: ['./index.html', './src/**/*.{ts,tsx}'],
theme: {
extend: {
colors: {
tg: {
bg: 'var(--tg-bg-color)',
text: 'var(--tg-text-color)',
hint: 'var(--tg-hint-color)',
link: 'var(--tg-link-color)',
// Use RGB tuple format so opacity modifiers (bg-tg-btn/10) work
btn: 'rgb(var(--tg-button-rgb) / <alpha-value>)',
'btn-text': 'var(--tg-button-text-color)',
'secondary-bg': 'var(--tg-secondary-bg-color)',
},
},
fontFamily: {
sans: ['-apple-system', 'BlinkMacSystemFont', 'Segoe UI', 'sans-serif'],
},
},
},
plugins: [],
} satisfies Config
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["src"]
}
+24
View File
@@ -0,0 +1,24 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
export default defineConfig({
plugins: [react()],
build: {
target: 'es2018',
},
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
server: {
allowedHosts: true,
proxy: {
'/api': {
target: 'http://localhost:8000',
changeOrigin: true,
},
},
},
})
+46
View File
@@ -0,0 +1,46 @@
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml text/javascript;
gzip_min_length 1000;
upstream backend {
server backend:8000;
}
upstream frontend {
server frontend:80;
}
server {
listen 80;
client_max_body_size 10m;
# API and webhook → backend
location /api/ {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_read_timeout 60s;
}
location /webhook/ {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# Everything else → Mini App frontend
location / {
proxy_pass http://frontend;
proxy_set_header Host $host;
}
}
}
+38
View File
@@ -0,0 +1,38 @@
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
upstream backend {
server backend:8000;
}
server {
listen 80;
client_max_body_size 10m;
location /api/ {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_read_timeout 60s;
}
location /webhook/ {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# Serve built frontend files; no-cache so changes are picked up immediately
location / {
root /usr/share/nginx/html;
try_files $uri /index.html;
add_header Cache-Control "no-cache, no-store, must-revalidate";
}
}
}