├── .dockerignore ├── .github ├── CODE_OF_CONDUCT.md ├── dependabot.yml └── workflows │ ├── docker_build.yml │ └── python-lint-test.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── blackjack ├── __init__.py ├── errors │ ├── __init__.py │ ├── gamealreadyrunningexception.py │ ├── gamenotrunningexception.py │ ├── insufficientpermissionsexception.py │ ├── maxplayersreachedexception.py │ ├── nextplayerisdealerexception.py │ ├── noplayersleftexception.py │ ├── notenoughplayersexception.py │ ├── playeralreadyexistingexception.py │ ├── playerbustedexception.py │ └── playergot21exception.py └── game │ ├── README.md │ ├── __init__.py │ ├── blackjackgame.py │ ├── card.py │ ├── dealer.py │ ├── deck.py │ ├── player.py │ ├── shoe.py │ └── tests │ ├── __init__.py │ ├── blackjackgame_test.py │ ├── card_test.py │ ├── deck_test.py │ ├── player_test.py │ └── shoe_test.py ├── blackjackbot ├── __init__.py ├── commands │ ├── __init__.py │ ├── admin │ │ ├── __init__.py │ │ ├── commands.py │ │ └── functions.py │ ├── game │ │ ├── __init__.py │ │ ├── commands.py │ │ ├── functions.py │ │ └── tests │ │ │ ├── __init__.py │ │ │ └── functions_test.py │ ├── settings │ │ ├── __init__.py │ │ └── commands.py │ └── util │ │ ├── __init__.py │ │ ├── commands.py │ │ ├── decorators.py │ │ └── functions.py ├── errors │ ├── __init__.py │ ├── errorhandler.py │ └── noactivegameexception.py ├── gamestore.py ├── lang │ ├── __init__.py │ ├── custom_strings │ │ └── README.md │ ├── language.py │ ├── strings │ │ ├── translations_de.json │ │ ├── translations_en.json │ │ ├── translations_eo.json │ │ ├── translations_es.json │ │ ├── translations_nl.json │ │ ├── translations_pl.json │ │ ├── translations_pt-br.json │ │ └── translations_ru.json │ └── tests │ │ ├── __init__.py │ │ └── language_test.py └── util │ ├── __init__.py │ ├── misc.py │ ├── tests │ ├── __init__.py │ ├── misc_test.py │ └── textutils_test.py │ ├── textutils.py │ └── userstate.py ├── bot.py ├── config.sample.py ├── database ├── __init__.py ├── database.py ├── statistics.py └── tests │ ├── __init__.py │ └── statistics_test.py ├── docker-compose.yml ├── gamehandler.py ├── logs └── .keep ├── requirements.txt ├── setup.cfg └── util ├── __init__.py ├── bannedusercallback.py ├── banneduserhandler.py └── cache.py /.dockerignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | .venv 85 | 86 | # Spyder project settings 87 | .spyderproject 88 | 89 | # Rope project settings 90 | .ropeproject 91 | 92 | 93 | .idea 94 | .svn 95 | .git 96 | __pycache__ 97 | *.db 98 | .vs 99 | .github 100 | 101 | # Keep logrotated files out of git 102 | logs/*.log* 103 | config.py 104 | 105 | *.md 106 | LICENSE 107 | .travis.yml 108 | *_test.py 109 | -------------------------------------------------------------------------------- /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team on [Telegram](https://t.me/d_Rickyy_b). The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: pip 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: "04:00" 8 | open-pull-requests-limit: 10 9 | target-branch: dev 10 | ignore: 11 | - dependency-name: python-telegram-bot 12 | versions: 13 | - "13.2" 14 | - "13.3" 15 | -------------------------------------------------------------------------------- /.github/workflows/docker_build.yml: -------------------------------------------------------------------------------- 1 | name: Docker Image CI 2 | 3 | on: 4 | push: 5 | tags: 6 | - "v*.*.*" 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - name: Check out code into the Go module directory 14 | uses: actions/checkout@v3 15 | 16 | - name: Set build tag as env var 17 | run: echo "TAG=${GITHUB_REF#refs/*/v}" >> $GITHUB_ENV 18 | 19 | - name: Docker login 20 | run: docker login -u ${{ secrets.DOCKERHUB_USERNAME }} -p ${{ secrets.DOCKERHUB_TOKEN }} 21 | 22 | - name: Build the Docker image 23 | run: docker build . --file Dockerfile --tag ${{ secrets.DOCKERHUB_USERNAME }}/blackjackbot:latest --tag ${{ secrets.DOCKERHUB_USERNAME }}/blackjackbot:${{ env.TAG }} 24 | 25 | - name: Push the Docker image 26 | run: docker push ${{ secrets.DOCKERHUB_USERNAME }}/blackjackbot --all-tags 27 | -------------------------------------------------------------------------------- /.github/workflows/python-lint-test.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions 3 | 4 | name: Run tests and lint 5 | 6 | on: 7 | push: 8 | branches: [ master, dev ] 9 | pull_request: 10 | branches: [ master ] 11 | 12 | jobs: 13 | test-and-lint: 14 | 15 | runs-on: ubuntu-latest 16 | strategy: 17 | matrix: 18 | python-version: [ '3.9', '3.10', '3.11'] 19 | 20 | steps: 21 | - uses: actions/checkout@v3 22 | - name: Set up Python ${{ matrix.python-version }} 23 | uses: actions/setup-python@v4 24 | with: 25 | python-version: ${{ matrix.python-version }} 26 | - name: Install dependencies 27 | run: | 28 | python -m pip install --upgrade pip 29 | python -m pip install flake8 pytest coveralls 30 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 31 | - name: Lint with flake8 32 | run: | 33 | # stop the build if there are Python syntax errors or undefined names 34 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 35 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 36 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 37 | - name: Test with pytest 38 | run: | 39 | coverage run --omit='*/virtualenv/*,*/site-packages/*' -m pytest 40 | - name: Publish coverage 41 | env: 42 | COVERALLS_REPO_TOKEN: ${{ secrets.COVERALLS_REPO_TOKEN }} 43 | run: | 44 | coveralls 45 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | .venv 85 | 86 | # Spyder project settings 87 | .spyderproject 88 | 89 | # Rope project settings 90 | .ropeproject 91 | 92 | 93 | .idea 94 | .svn 95 | .git 96 | __pycache__ 97 | *.db 98 | .vs 99 | 100 | # Keep logrotated files out of git 101 | logs/*.log* 102 | config.py 103 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3-slim 2 | 3 | LABEL maintainer="d-Rickyy-b " 4 | LABEL site="https://github.com/d-Rickyy-b/Python-BlackJackBot" 5 | 6 | RUN mkdir -p /blackjackbot/logs 7 | COPY . /blackjackbot 8 | WORKDIR /blackjackbot 9 | RUN pip install --no-cache-dir -r /blackjackbot/requirements.txt 10 | 11 | CMD ["python", "/blackjackbot/bot.py"] 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://github.com/d-Rickyy-b/Python-BlackJackBot/actions/workflows/python-lint-test.yml/badge.svg)](https://github.com/d-Rickyy-b/Python-BlackJackBot/actions/workflows/python-lint-test.yml) 2 | [![Docker Image Version (latest semver)](https://img.shields.io/docker/v/0rickyy0/blackjackbot?label=docker&sort=semver)](https://hub.docker.com/repository/docker/0rickyy0/blackjackbot) 3 | [![Coverage Status](https://coveralls.io/repos/github/d-Rickyy-b/Python-BlackJackBot/badge.svg?branch=rebuild)](https://coveralls.io/github/d-Rickyy-b/Python-BlackJackBot?branch=rebuild) 4 | [![Codacy Badge](https://app.codacy.com/project/badge/Grade/12996d68fc0f436085221ac6b1f525f9)](https://www.codacy.com/manual/d-Rickyy-b/Python-BlackJackBot?utm_source=github.com&utm_medium=referral&utm_content=d-Rickyy-b/Python-BlackJackBot&utm_campaign=Badge_Grade) 5 | 6 | # Python-BlackJackBot 7 | 8 | This is the code for my Telegram Bot with which you can play the game Black Jack. 9 | You can find the hosted version of it here: https://telegram.me/BlackJackBot 10 | 11 | ## Setup 12 | This project is really easy to set up. No matter which of the following ways you'll use, you'll always need a config file. 13 | To create one, simply copy the existing `config.sample.py` file and name it `config.py`. Enter your bot token and make your changes accordingly. 14 | 15 | Then you're left with several ways to run this bot. 16 | 17 | ### 1.) Cloning the repo 18 | If you want to run this code from source, you can just `git clone` this repo. 19 | It's recommended to create a new virtual environment (`python3 -m venv /path/to/venv`). 20 | This bot uses the [python-telegram-bot](https://python-telegram-bot.org/) framework to make Telegram API calls. 21 | You can install it (and potential other requlrements) like that: 22 | 23 | ``pip install -r requirements.txt`` 24 | 25 | Afterwards just run `python3 bot.py` and if done right, you'll be left with a working bot. 26 | 27 | ### 2.) Docker 28 | This project also contains a `Dockerfile` as well as a pre-built [Docker image](https://hub.docker.com/repository/docker/0rickyy0/blackjackbot) hosted on the official Docker Hub. 29 | 30 | You will also find the `docker-compose.yml` file with which you can easily set up your own instance of the bot. 31 | Just specify the path to your config etc. in said docker-compose file. 32 | -------------------------------------------------------------------------------- /blackjack/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | -------------------------------------------------------------------------------- /blackjack/errors/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from .playerbustedexception import PlayerBustedException 4 | from .gamealreadyrunningexception import GameAlreadyRunningException 5 | from .playeralreadyexistingexception import PlayerAlreadyExistingException 6 | from .gamenotrunningexception import GameNotRunningException 7 | from .maxplayersreachedexception import MaxPlayersReachedException 8 | from .notenoughplayersexception import NotEnoughPlayersException 9 | from .nextplayerisdealerexception import NextPlayerIsDealerException 10 | from .insufficientpermissionsexception import InsufficientPermissionsException 11 | from .noplayersleftexception import NoPlayersLeftException 12 | from .playergot21exception import PlayerGot21Exception 13 | 14 | __all__ = ['PlayerBustedException', 'GameAlreadyRunningException', 'PlayerAlreadyExistingException', 'MaxPlayersReachedException', 'GameNotRunningException', 15 | 'NotEnoughPlayersException', 'NextPlayerIsDealerException', 'InsufficientPermissionsException', 'NoPlayersLeftException', 'PlayerGot21Exception'] 16 | -------------------------------------------------------------------------------- /blackjack/errors/gamealreadyrunningexception.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | class GameAlreadyRunningException(Exception): 5 | pass 6 | -------------------------------------------------------------------------------- /blackjack/errors/gamenotrunningexception.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | class GameNotRunningException(Exception): 5 | pass 6 | -------------------------------------------------------------------------------- /blackjack/errors/insufficientpermissionsexception.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | class InsufficientPermissionsException(Exception): 5 | pass 6 | -------------------------------------------------------------------------------- /blackjack/errors/maxplayersreachedexception.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | class MaxPlayersReachedException(Exception): 5 | pass 6 | -------------------------------------------------------------------------------- /blackjack/errors/nextplayerisdealerexception.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | class NextPlayerIsDealerException(Exception): 5 | pass 6 | -------------------------------------------------------------------------------- /blackjack/errors/noplayersleftexception.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | class NoPlayersLeftException(Exception): 5 | pass 6 | -------------------------------------------------------------------------------- /blackjack/errors/notenoughplayersexception.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | class NotEnoughPlayersException(Exception): 5 | pass 6 | -------------------------------------------------------------------------------- /blackjack/errors/playeralreadyexistingexception.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | class PlayerAlreadyExistingException(Exception): 5 | pass 6 | -------------------------------------------------------------------------------- /blackjack/errors/playerbustedexception.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | class PlayerBustedException(Exception): 5 | pass 6 | -------------------------------------------------------------------------------- /blackjack/errors/playergot21exception.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | class PlayerGot21Exception(Exception): 5 | pass 6 | -------------------------------------------------------------------------------- /blackjack/game/README.md: -------------------------------------------------------------------------------- 1 | # BlackJack 2 | This package contains all the code needed for 3 | 4 | # Errors 5 | All errors or exceptions are stored in the /blackjack/errors/ directory. 6 | 7 | # Flow 8 | A user first needs to create an instance of a BlackJackGame: `game = BlackJackGame()` 9 | 10 | 11 | -------------------------------------------------------------------------------- /blackjack/game/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from .card import Card 4 | from .deck import Deck 5 | from .shoe import Shoe 6 | from .player import Player 7 | from .dealer import Dealer 8 | from .blackjackgame import BlackJackGame 9 | 10 | __all__ = ['BlackJackGame', 'Player', 'Dealer', 'Card', 'Deck', 'Shoe'] 11 | -------------------------------------------------------------------------------- /blackjack/game/blackjackgame.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import logging 3 | from datetime import datetime 4 | from enum import Enum 5 | 6 | import blackjack.errors as errors 7 | from blackjack.game import Player, Dealer, Deck 8 | 9 | 10 | class BlackJackGame(object): 11 | """Representation of a game of Black Jack - The equivalent of a Black Jack casino table.""" 12 | MAX_PLAYERS = 5 13 | 14 | def __init__(self, gametype=None, game_id=None, lang_id="en"): 15 | self.logger = logging.getLogger(__name__) 16 | self.__on_start_handlers = [] 17 | self.__on_stop_handlers = [] 18 | self.list_won = [] 19 | self.list_tie = [] 20 | self.list_lost = [] 21 | self.datetime_started = datetime.now() 22 | self.bets_active = True 23 | self._current_player = 0 24 | self.players = [] 25 | self.running = False 26 | self.deck = Deck(lang_id) 27 | self.dealer = Dealer("Dealer") 28 | 29 | self.type = gametype or BlackJackGame.Type.SINGLEPLAYER 30 | self.id = game_id 31 | self.lang_id = lang_id 32 | 33 | class Type(Enum): 34 | """Enum describing the type of a game""" 35 | SINGLEPLAYER = 1 36 | MULTIPLAYER_GROUP = 2 37 | MULTIPLAYER_DIRECT = 3 38 | 39 | def register_on_start_handler(self, func): 40 | """ 41 | Registers a callback function as on_start_handler. 42 | :param func: Function reference that will be called when the game is starting. It receives a reference to the game as parameter. 43 | :return: 44 | """ 45 | self.__on_start_handlers.append(func) 46 | 47 | def register_on_stop_handler(self, func): 48 | """ 49 | Registers a callback function as on_stop_handler. 50 | :param func: Function reference that will be called when the game is stopping. It receives a reference to the game as parameter. 51 | :return: 52 | """ 53 | self.__on_stop_handlers.append(func) 54 | 55 | # noinspection PyBroadException 56 | def _run_handlers(self, handlers): 57 | """ 58 | Call all handlers of the passed 'handlers' list 59 | :param handlers: List of handlers (e.g. __on_start_handlers, __on_stop_handlers) 60 | :return: 61 | """ 62 | for handler in handlers: 63 | try: 64 | handler(self) 65 | except Exception as e: 66 | self.logger.error("Couldn't run handler '{0}' - The following exception occurred: '{1}'".format(handler, e)) 67 | 68 | def start(self, user_id): 69 | """ 70 | Sets up the players' and the dealer's hands 71 | :return: 72 | """ 73 | if self.running: 74 | raise errors.GameAlreadyRunningException 75 | 76 | if (self.type == BlackJackGame.Type.SINGLEPLAYER and len(self.players) < 1) or \ 77 | (self.type in [BlackJackGame.Type.MULTIPLAYER_DIRECT, BlackJackGame.Type.MULTIPLAYER_GROUP] and len(self.players) < 2): 78 | raise errors.NotEnoughPlayersException 79 | 80 | if user_id != self.players[0].user_id: 81 | raise errors.InsufficientPermissionsException 82 | 83 | self.running = True 84 | 85 | # Give every player and the dealer 2 cards 86 | for player in (self.players + [self.dealer]) * 2: 87 | card = self.deck.pick_one_card() 88 | player.give_card(card) 89 | 90 | self._run_handlers(self.__on_start_handlers) 91 | 92 | def stop(self, user_id): 93 | """ 94 | Stops the game, if the user has sufficient permissions 95 | :param user_id: The user_id of the user requesting to stop the game 96 | :return: 97 | """ 98 | if user_id != -1 and user_id != self.players[0].user_id: 99 | raise errors.InsufficientPermissionsException 100 | self.running = False 101 | self._run_handlers(self.__on_stop_handlers) 102 | 103 | def get_current_player(self): 104 | return self.players[self._current_player] 105 | 106 | def add_player(self, user_id, first_name): 107 | """ 108 | Add a new player to the game as long as it didn't start yet 109 | :param user_id: The user_id of the player 110 | :param first_name: The player's first_name 111 | :return: 112 | """ 113 | if self.running: 114 | raise errors.GameAlreadyRunningException("Not adding player, the game is already on!") 115 | 116 | if user_id in [player.user_id for player in self.players]: 117 | raise errors.PlayerAlreadyExistingException 118 | 119 | if len(self.players) >= self.MAX_PLAYERS: 120 | raise errors.MaxPlayersReachedException 121 | 122 | player = Player(user_id, first_name) 123 | self.logger.debug("Adding new player: {}!".format(player)) 124 | self.players.append(player) 125 | 126 | if self.type == BlackJackGame.Type.SINGLEPLAYER: 127 | self.logger.debug("Starting game now, because it's a singleplayer game") 128 | self.start(user_id) 129 | 130 | def draw_card(self): 131 | """ 132 | Draw one card and add it to the player's hand 133 | :return: 134 | """ 135 | if not self.running: 136 | raise errors.GameNotRunningException("The game must be started before you can draw cards") 137 | 138 | player = self.get_current_player() 139 | card = self.deck.pick_one_card() 140 | 141 | player.give_card(card) 142 | 143 | if player.cardvalue > 21: 144 | self.logger.debug("While giving user {} the card {}, they busted.".format(player.first_name, card)) 145 | raise errors.PlayerBustedException 146 | if player.cardvalue == 21: 147 | raise errors.PlayerGot21Exception 148 | 149 | def next_player(self): 150 | """ 151 | Marks the next player as active player. If all players are finished, go to dealer's turn 152 | :return: 153 | """ 154 | if not self.running: 155 | raise errors.GameNotRunningException("The game must be started before it's the next player's turn") 156 | 157 | if self._current_player >= len(self.players) - 1: 158 | self.logger.debug("Next player is dealer!") 159 | self._current_player = -1 160 | self.dealers_turn() 161 | raise errors.NoPlayersLeftException 162 | 163 | self.get_current_player().turn_over = True 164 | self._current_player += 1 165 | 166 | def dealers_turn(self): 167 | if not self.running: 168 | raise errors.GameNotRunningException("The game must be started before it's the dealer's turn") 169 | 170 | while self.dealer.cardvalue <= 16: 171 | card = self.deck.pick_one_card() 172 | self.dealer.give_card(card) 173 | 174 | self.dealer.turn_over = True 175 | self.running = False 176 | 177 | def evaluation(self): 178 | """ 179 | Check which player won and which lost. Also calculate profits if applicable 180 | :return: 181 | """ 182 | list_busted = [player for player in self.players if player.busted] 183 | list_not_busted = [player for player in self.players if not player.busted] 184 | 185 | list_won = [] 186 | list_tie = [] 187 | list_lost = [] 188 | 189 | if self.dealer.busted: 190 | for player in list_not_busted: 191 | if player.has_blackjack(): 192 | # BlackJack pays 3:2 -> return bet + 1.5 x bet 193 | player.pay(factor=2.5) 194 | else: 195 | player.pay(factor=2) 196 | list_won.append(player) 197 | 198 | elif self.dealer.has_blackjack(): 199 | for player in list_not_busted: 200 | if player.has_blackjack(): 201 | player.pay(1) 202 | list_tie.append(player) 203 | else: 204 | list_lost.append(player) 205 | elif self.dealer.cardvalue <= 21: 206 | for player in list_not_busted: 207 | if player.cardvalue > self.dealer.cardvalue: 208 | player.pay(2) 209 | list_won.append(player) 210 | elif player.cardvalue == self.dealer.cardvalue: 211 | player.pay(1) 212 | list_tie.append(player) 213 | elif player.cardvalue < self.dealer.cardvalue: 214 | list_lost.append(player) 215 | 216 | list_lost.extend(list_busted) 217 | 218 | self.list_won = sorted(list_won, key=lambda player: player.cardvalue, reverse=True) 219 | self.list_tie = sorted(list_tie, key=lambda player: player.cardvalue, reverse=True) 220 | self.list_lost = sorted(list_lost, key=lambda player: player.cardvalue, reverse=True) 221 | 222 | return self.list_won, self.list_tie, self.list_lost 223 | 224 | def get_player_list(self): 225 | return "\n".join(["👤{}".format(p.first_name) for p in self.players]) 226 | -------------------------------------------------------------------------------- /blackjack/game/card.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from enum import Enum 3 | 4 | 5 | class Card(object): 6 | 7 | class Type(Enum): 8 | NUMBER = "card_number" 9 | JACK = "card_jack" 10 | QUEEN = "card_queen" 11 | KING = "card_king" 12 | ACE = "card_ace" 13 | 14 | symbols = ["♥", "♦", "♣", "♠"] 15 | value_str = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"] 16 | 17 | def __init__(self, card_id): 18 | self.card_id = card_id 19 | 20 | def is_ace(self): 21 | return self.value == 11 22 | 23 | @property 24 | def symbol(self): 25 | return self.symbols[self.card_id // 13] 26 | 27 | @property 28 | def value(self): 29 | values = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11] 30 | return values[self.card_id % 13] 31 | 32 | @property 33 | def face(self): 34 | return self.value_str[self.card_id % 13] 35 | 36 | @property 37 | def type(self): 38 | if (self.card_id % 13) in range(0, 9): 39 | return Card.Type.NUMBER 40 | elif (self.card_id % 13) == 9: 41 | return Card.Type.JACK 42 | elif (self.card_id % 13) == 10: 43 | return Card.Type.QUEEN 44 | elif (self.card_id % 13) == 11: 45 | return Card.Type.KING 46 | elif (self.card_id % 13) == 12: 47 | return Card.Type.ACE 48 | else: 49 | raise ValueError("card_id '{}' can't be mapped to card type!".format(self.card_id)) 50 | 51 | @property 52 | def str_id(self): 53 | str_ids = ["card_2", "card_3", "card_4", "card_5", "card_6", 54 | "card_7", "card_8", "card_9", "card_10", 55 | "card_jack", "card_queen", "card_king", "card_ace"] 56 | return str_ids[self.card_id % 13] 57 | 58 | def __str__(self): 59 | return "{} {}".format(self.symbol, self.face) 60 | 61 | def __repr__(self): 62 | return self.__str__() 63 | -------------------------------------------------------------------------------- /blackjack/game/dealer.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from .player import Player 4 | 5 | 6 | class Dealer(Player): 7 | credits = 0 8 | 9 | def __init__(self, first_name): 10 | super().__init__(user_id=-1, first_name=first_name) 11 | self.is_dealer = True 12 | -------------------------------------------------------------------------------- /blackjack/game/deck.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from random import shuffle 4 | 5 | from .card import Card 6 | 7 | __author__ = 'Rico' 8 | 9 | 10 | class Deck(object): 11 | 12 | def __init__(self, lang_id="en"): 13 | self.lang_id = lang_id 14 | self._cards = [] 15 | self._set_up_deck() 16 | self._shuffle() 17 | 18 | def _set_up_deck(self): 19 | self._cards = [] 20 | 21 | for card_id in range(52): 22 | card = Card(card_id) 23 | self._cards.append(card) 24 | 25 | def _shuffle(self): 26 | shuffle(self._cards) 27 | 28 | @property 29 | def cards(self): 30 | return self._cards 31 | 32 | def pick_one_card(self): 33 | # TODO if len(self._cards) <= 0, then raise error 34 | return self._cards.pop(0) 35 | 36 | def __repr__(self): 37 | return str(self._cards) 38 | -------------------------------------------------------------------------------- /blackjack/game/player.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from .card import Card 4 | 5 | 6 | class Player(object): 7 | 8 | def __init__(self, user_id, first_name, lang_id="en"): 9 | """ 10 | Player representation 11 | :param user_id: A unique ID for the player 12 | :param first_name: The name of the player 13 | :param lang_id: The ID of the language of the player. Defaults to "en" 14 | """ 15 | self.is_dealer = False 16 | self._cards = [] 17 | self.bet = 0 18 | self.win = 0 19 | self.turn_over = False 20 | 21 | self.user_id = user_id 22 | self.first_name = first_name 23 | self.lang_id = lang_id 24 | 25 | def give_card(self, card: Card): 26 | self._cards.append(card) 27 | 28 | @property 29 | def busted(self): 30 | return self.cardvalue > 21 31 | 32 | @property 33 | def cardvalue(self): 34 | """ 35 | Calculate the current value of the cards on the hand 36 | :return: Current value of the cards on the hand 37 | """ 38 | value = 0 39 | ace_counter = 0 40 | 41 | for card in self._cards: 42 | if card.is_ace(): 43 | # if we encounter an ace, we don't calculate it yet 44 | ace_counter += 1 45 | else: 46 | # If no ace we simply add the value to the total 47 | value += card.value 48 | 49 | if ace_counter == 0: 50 | return value 51 | 52 | possible_values = set() 53 | 54 | # We now calculate all the possible values combinations of the cards + aces 55 | for i in range(ace_counter + 1): 56 | possible_values.add(value + (i * 11) + ((ace_counter - i) * 1)) 57 | 58 | possible_values_list = list(possible_values) 59 | # Sort the list so that we can later on work with returning the first/last element of a list without checking actual values again 60 | possible_values_list.sort() 61 | 62 | # Split up the results into two list for easier handling 63 | lower_21 = [i for i in possible_values_list if i <= 21] 64 | bigger_21 = [i for i in possible_values_list if i > 21] 65 | 66 | # If we have an ace, we want to return the biggest value below 21 (is possible). 67 | if len(lower_21) >= 1: 68 | return lower_21[-1] 69 | 70 | # If there is no such value we want to return the lowest value above 21 71 | if len(bigger_21) >= 1: 72 | return bigger_21[0] 73 | 74 | raise ValueError("Can't calculate a value from those cards: {}".format(self._cards)) 75 | 76 | @property 77 | def cards(self): 78 | return self._cards 79 | 80 | @property 81 | def amount_of_cards(self): 82 | return len(self._cards) 83 | 84 | def has_blackjack(self): 85 | return self.cardvalue == 21 and self.amount_of_cards == 2 86 | 87 | def has_21(self): 88 | return self.cardvalue == 21 89 | 90 | def pay(self, factor): 91 | self.win = self.bet * factor 92 | 93 | def __repr__(self): 94 | return "Player: {}, '{}'".format(self.user_id, self.first_name) 95 | -------------------------------------------------------------------------------- /blackjack/game/shoe.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Reference: https://en.wikipedia.org/wiki/Shoe_(cards) 3 | from random import shuffle 4 | from math import floor 5 | 6 | from .deck import Deck 7 | 8 | 9 | class Shoe(object): 10 | # Represents a dealing shoe (holder of several decks) 11 | 12 | def __init__(self, decks=4): 13 | self._cards = [] 14 | self.deck_amount = decks 15 | for _ in range(decks): 16 | deck = Deck() 17 | self._cards.extend(deck.cards) 18 | # Shuffle the full shoe again 19 | shuffle(self._cards) 20 | 21 | cut_amount = floor(len(self._cards) * 0.1) 22 | cut_card = len(self._cards) - cut_amount 23 | self._cards = self._cards[:cut_card] 24 | 25 | def draw(self): 26 | """ 27 | Draw a card from the shoe 28 | :return: 29 | """ 30 | try: 31 | card = self._cards.pop() 32 | return card 33 | except IndexError: 34 | # TODO implement custom error 35 | raise 36 | -------------------------------------------------------------------------------- /blackjack/game/tests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | -------------------------------------------------------------------------------- /blackjack/game/tests/blackjackgame_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import unittest 3 | from unittest.mock import Mock 4 | 5 | from blackjack.errors import GameAlreadyRunningException, PlayerAlreadyExistingException, MaxPlayersReachedException, NotEnoughPlayersException, \ 6 | GameNotRunningException, PlayerBustedException, NoPlayersLeftException 7 | from blackjack.game import BlackJackGame 8 | 9 | 10 | class BlackJackGameTest(unittest.TestCase): 11 | 12 | def setUp(self): 13 | self.game = BlackJackGame(gametype=BlackJackGame.Type.MULTIPLAYER_GROUP) 14 | 15 | @staticmethod 16 | def _generate_mock_deck(value=1): 17 | deck = Mock() 18 | card = Mock() 19 | card.value = value 20 | card.is_ace.return_value = (value == 11) 21 | deck.pick_one_card.return_value = card 22 | return deck 23 | 24 | def test_creation(self): 25 | """ 26 | Check if creating an instance holds all necessary values 27 | :return: 28 | """ 29 | self.assertFalse(self.game.running) 30 | self.assertEqual([], self.game.players) 31 | self.assertEqual(0, self.game._current_player) 32 | 33 | def test_start(self): 34 | """ 35 | Check if starting the game changes the state and initializes the values of certain variables 36 | :return: 37 | """ 38 | self.game.add_player(user_id=111, first_name="Player 111") 39 | self.assertFalse(self.game.running) 40 | self.game.add_player(user_id=222, first_name="Player 222") 41 | self.assertFalse(self.game.running) 42 | self.game.start(111) 43 | self.assertTrue(self.game.running) 44 | 45 | # Assert that each player has 2 cards 46 | self.assertEqual(2, len(self.game.players[0]._cards)) 47 | self.assertEqual(2, len(self.game.dealer._cards)) 48 | self.assertEqual(2, len(self.game.players)) 49 | 50 | def test_start_twice(self): 51 | """ 52 | Check that starting twice doesn't work and raises an exception 53 | :return: 54 | """ 55 | self.game.type = BlackJackGame.Type.SINGLEPLAYER 56 | self.assertFalse(self.game.running) 57 | self.game.add_player(user_id=111, first_name="Player 111") 58 | self.assertTrue(self.game.running) 59 | 60 | with self.assertRaises(GameAlreadyRunningException): 61 | self.game.start(111) 62 | 63 | self.assertTrue(self.game.running) 64 | 65 | def test_start_not_enough_players(self): 66 | """ 67 | Check that starting without players doesn't work and raises an exception 68 | :return: 69 | """ 70 | self.assertFalse(self.game.running) 71 | 72 | with self.assertRaises(NotEnoughPlayersException): 73 | self.game.start(111) 74 | 75 | self.assertFalse(self.game.running) 76 | 77 | def test_add_player(self): 78 | """ 79 | Check if adding new players works 80 | :return: 81 | """ 82 | self.assertEqual(0, len(self.game.players)) 83 | self.game.add_player(user_id=15, first_name="Player 15") 84 | self.assertEqual(15, self.game.players[0].user_id) 85 | self.assertEqual("Player 15", self.game.players[0].first_name) 86 | 87 | self.assertEqual(1, len(self.game.players)) 88 | self.game.add_player(user_id=125, first_name="Player 125") 89 | self.assertEqual(2, len(self.game.players)) 90 | 91 | # Make sure that inserting players with the same name works just fine 92 | self.game.add_player(user_id=126, first_name="Player 125") 93 | self.assertEqual(3, len(self.game.players)) 94 | 95 | def test_add_player_existing(self): 96 | """ 97 | Check if adding existing players works as intended 98 | :return: 99 | """ 100 | self.assertEqual(0, len(self.game.players)) 101 | 102 | self.game.add_player(user_id=15, first_name="Player " + str(15)) 103 | self.assertEqual(1, len(self.game.players)) 104 | 105 | with self.assertRaises(PlayerAlreadyExistingException): 106 | self.game.add_player(user_id=15, first_name="Player " + str(15)) 107 | 108 | self.assertEqual(1, len(self.game.players)) 109 | 110 | def test_add_player_max(self): 111 | """ 112 | Check if adding players when MAX_PLAYERS is reached raises an exception 113 | :return: 114 | """ 115 | for i in range(self.game.MAX_PLAYERS): 116 | self.game.add_player(user_id=i, first_name="Player " + str(i)) 117 | self.assertEqual(self.game.MAX_PLAYERS, len(self.game.players)) 118 | 119 | with self.assertRaises(MaxPlayersReachedException): 120 | self.game.add_player(user_id=9999, first_name="Player 9999") 121 | 122 | self.assertEqual(self.game.MAX_PLAYERS, len(self.game.players)) 123 | 124 | def test_add_player_game_started(self): 125 | """ 126 | Check that it's no longer possible to add players as soon as the game is running 127 | :return: 128 | """ 129 | self.assertEqual(0, len(self.game.players)) 130 | 131 | self.game.add_player(user_id=15, first_name="Player " + str(15)) 132 | self.assertEqual(1, len(self.game.players)) 133 | 134 | self.game.add_player(user_id=125, first_name="Player 125") 135 | self.assertEqual(2, len(self.game.players)) 136 | 137 | self.game.start(15) 138 | 139 | self.assertEqual(2, len(self.game.players)) 140 | 141 | with self.assertRaises(GameAlreadyRunningException): 142 | self.game.add_player(user_id=111, first_name="Player 111") 143 | 144 | self.assertEqual(2, len(self.game.players)) 145 | 146 | def test_next_player(self): 147 | """ 148 | Check if using the next_player function leads to the player counter being increased 149 | :return: 150 | """ 151 | self.game.add_player(user_id=111, first_name="Player 111") 152 | self.game.add_player(user_id=222, first_name="Player 222") 153 | 154 | self.game.start(111) 155 | 156 | self.assertEqual(0, self.game._current_player) 157 | self.game.next_player() 158 | self.assertEqual(1, self.game._current_player) 159 | 160 | def test_next_player_game_not_running(self): 161 | """ 162 | Check if one can move to the next player although the game is not running yet 163 | :return: 164 | """ 165 | self.game.add_player(user_id=111, first_name="Player 111") 166 | self.game.add_player(user_id=222, first_name="Player 222") 167 | 168 | self.assertEqual(0, self.game._current_player) 169 | with self.assertRaises(GameNotRunningException): 170 | self.game.next_player() 171 | 172 | self.assertEqual(0, self.game._current_player) 173 | 174 | def test_next_player_dealer(self): 175 | """ 176 | Check if using the next_player function while there are no more players leads to the dealer's turn 177 | :return: 178 | """ 179 | self.game.add_player(user_id=111, first_name="Player 111") 180 | self.game.add_player(user_id=222, first_name="Player 222") 181 | 182 | dealers_turn = Mock() 183 | self.game.dealers_turn = dealers_turn 184 | 185 | self.game.start(111) 186 | 187 | self.assertEqual(0, self.game._current_player) 188 | self.game.next_player() 189 | self.assertEqual(1, self.game._current_player) 190 | with self.assertRaises(NoPlayersLeftException): 191 | self.game.next_player() 192 | self.assertEqual(-1, self.game._current_player) 193 | dealers_turn.assert_called() 194 | 195 | def test_get_current_player(self): 196 | """ 197 | Check if we receive the correct player from get_current_player() 198 | :return: 199 | """ 200 | self.game.add_player(user_id=111, first_name="Player 111") 201 | self.game.add_player(user_id=222, first_name="Player 222") 202 | 203 | self.game.start(111) 204 | 205 | self.assertEqual(0, self.game._current_player) 206 | self.assertEqual(111, self.game.get_current_player().user_id) 207 | self.game.next_player() 208 | self.assertEqual(1, self.game._current_player) 209 | self.assertEqual(222, self.game.get_current_player().user_id) 210 | 211 | def test_draw_card(self): 212 | """ 213 | Check if drawing cards works as intended 214 | :return: 215 | """ 216 | self.game.deck = self._generate_mock_deck() 217 | self.game.add_player(user_id=111, first_name="Player 111") 218 | self.game.add_player(user_id=222, first_name="Player 222") 219 | 220 | self.game.start(111) 221 | 222 | # We have 2 cards from the init 223 | self.assertEqual(2, len(self.game.players[0]._cards)) 224 | self.game.draw_card() 225 | 226 | # Now we should have 3 cards after drawing one 227 | self.assertEqual(3, len(self.game.players[0]._cards)) 228 | 229 | # And it should have a value of 1 230 | self.assertEqual(1, self.game.players[0]._cards[2].value) 231 | 232 | def test_draw_card_game_not_running(self): 233 | """ 234 | Check if it's possible to draw cards even though the game did not start yet 235 | :return: 236 | """ 237 | self.assertFalse(self.game.running) 238 | with self.assertRaises(GameNotRunningException): 239 | self.game.draw_card() 240 | 241 | def test_draw_card_player_busted(self): 242 | """ 243 | Check if we receive an exception when a player busted while drawing a card 244 | :return: 245 | """ 246 | self.game.deck = self._generate_mock_deck(value=10) 247 | self.game.add_player(user_id=111, first_name="Player 111") 248 | self.game.add_player(user_id=222, first_name="Player 222") 249 | 250 | self.game.start(111) 251 | 252 | # We have 2 cards from the init 253 | self.assertEqual(2, len(self.game.players[0]._cards)) 254 | self.assertEqual(20, self.game.players[0].cardvalue) 255 | 256 | with self.assertRaises(PlayerBustedException): 257 | self.game.draw_card() 258 | 259 | # Now we should have 3 cards after drawing one 260 | self.assertEqual(3, len(self.game.players[0]._cards)) 261 | 262 | # And it should have a value of 10 263 | self.assertEqual(10, self.game.players[0]._cards[2].value) 264 | self.assertEqual(30, self.game.players[0].cardvalue) 265 | 266 | def test_dealers_turn(self): 267 | """ 268 | Check that the dealer always draws cards until the card value > 16 269 | """ 270 | self.game.type = BlackJackGame.Type.SINGLEPLAYER 271 | 272 | # TODO generate specific Card Deck for a better test 273 | self.game.add_player(user_id=111, first_name="Player 111") 274 | 275 | self.assertEqual(2, len(self.game.dealer._cards)) 276 | self.game.dealers_turn() 277 | self.assertGreater(self.game.dealer.cardvalue, 16) 278 | 279 | def test_dealers_turn_random(self): 280 | """ 281 | Check that the dealer always draws cards until the card value > 16 282 | """ 283 | self.game.type = BlackJackGame.Type.SINGLEPLAYER 284 | self.game.add_player(user_id=111, first_name="Player 111") 285 | 286 | self.assertEqual(2, len(self.game.dealer._cards)) 287 | self.game.dealers_turn() 288 | self.assertGreater(self.game.dealer.cardvalue, 16) 289 | 290 | def test_dealers_turn_game_not_running(self): 291 | """ 292 | Check that the dealer can't take turn when the game is not running yet 293 | """ 294 | self.game.add_player(user_id=111, first_name="Player 111") 295 | 296 | with self.assertRaises(GameNotRunningException): 297 | self.game.dealers_turn() 298 | 299 | self.assertEqual(0, self.game.dealer.cardvalue) 300 | 301 | 302 | if __name__ == '__main__': 303 | unittest.main() 304 | -------------------------------------------------------------------------------- /blackjack/game/tests/card_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import unittest 3 | 4 | from blackjack.game.card import Card 5 | 6 | 7 | class CardTest(unittest.TestCase): 8 | 9 | @staticmethod 10 | def _generate_card(value): 11 | card = Card(value) 12 | return card 13 | 14 | def test_creation(self): 15 | """ 16 | Check that the card is properly created 17 | :return: 18 | """ 19 | for multiplier in range(4): 20 | offset = multiplier * 13 21 | # Numbers 22 | for i in range(offset, offset + 9): 23 | card = self._generate_card(i) 24 | self.assertEqual(i + 2 - offset, card.value) 25 | self.assertEqual(i, card.card_id) 26 | 27 | # Jack, Queen, King 28 | for i in range(offset + 9, offset + 12): 29 | card = self._generate_card(i) 30 | self.assertEqual(10, card.value) 31 | self.assertEqual(i, card.card_id) 32 | 33 | # Ace 34 | card = self._generate_card(offset + 12) 35 | self.assertEqual(11, card.value) 36 | self.assertEqual(offset + 12, card.card_id) 37 | 38 | def test_is_ace(self): 39 | """ 40 | Check if cards return correct values when they are aces 41 | :return: 42 | """ 43 | for i in range(52): 44 | card = self._generate_card(i) 45 | if card.value == 11: 46 | self.assertTrue(card.is_ace()) 47 | else: 48 | self.assertFalse(card.is_ace()) 49 | 50 | 51 | if __name__ == '__main__': 52 | unittest.main() 53 | -------------------------------------------------------------------------------- /blackjack/game/tests/deck_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from blackjack.game.card import Card 4 | from blackjack.game.deck import Deck 5 | 6 | 7 | class DeckTest(unittest.TestCase): 8 | 9 | def test_creation(self): 10 | """ 11 | Check that the deck is properly created 12 | :return: 13 | """ 14 | self.deck = Deck() 15 | self.assertEqual("en", self.deck.lang_id) 16 | self.assertEqual(52, len(self.deck._cards)) 17 | 18 | def test_shuffle(self): 19 | """ 20 | Check that shuffeling actually changes order of cards 21 | :return: 22 | """ 23 | self.deck = Deck() 24 | d1 = self.deck._cards.copy() 25 | 26 | d2 = self.deck._cards.copy() 27 | # We check that our two decks we copied are the same 28 | # This is to proof that the assertNotEqual later on works correctly 29 | self.assertEqual(d1, d2) 30 | 31 | self.deck._shuffle() 32 | d3 = self.deck._cards.copy() 33 | 34 | # Just check that we did not lose any cards through shuffeling 35 | self.assertEqual(52, len(d1)) 36 | self.assertEqual(52, len(d2)) 37 | self.assertEqual(52, len(d3)) 38 | 39 | # Our first and third deck should now differ 40 | # There is a veeeeeery tiny rest probability that after shuffeling the deck is exactly the same as before 41 | # But we are ignoring that here! 42 | self.assertNotEqual(d1, d3) 43 | 44 | def test_set_up_deck(self): 45 | """ 46 | Check if the set up method creates a new sorted deck of cards 47 | :return: 48 | """ 49 | self.deck = Deck() 50 | self.deck._set_up_deck() 51 | 52 | # Check if the deck is sorted (linear ascending numbers) 53 | for counter in range(52): 54 | self.assertEqual(counter, self.deck._cards[counter].card_id) 55 | 56 | def test_draw(self): 57 | """ 58 | Check if drawing cards works as intended 59 | :return: 60 | """ 61 | self.deck = Deck() 62 | self.assertEqual(52, len(self.deck._cards)) 63 | 64 | card = self.deck.pick_one_card() 65 | 66 | self.assertEqual(51, len(self.deck._cards)) 67 | self.assertEqual(Card, type(card)) 68 | 69 | def test_draw_empty(self): 70 | """ 71 | Check if drawing works as intended when the deck is empty 72 | :return: 73 | """ 74 | pass 75 | 76 | 77 | if __name__ == '__main__': 78 | unittest.main() 79 | -------------------------------------------------------------------------------- /blackjack/game/tests/player_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from unittest.mock import Mock 3 | 4 | from blackjack.game import Player 5 | 6 | 7 | class PlayerTest(unittest.TestCase): 8 | 9 | def setUp(self): 10 | self.player = Player(1, "Test") 11 | 12 | @staticmethod 13 | def _generate_mock_card(value): 14 | mock_card = Mock() 15 | mock_card.value = value 16 | mock_card.is_ace.return_value = (value == 11) 17 | return mock_card 18 | 19 | def test_player_init(self): 20 | self.assertEqual(0, self.player.cardvalue) 21 | self.assertEqual(1, self.player.user_id) 22 | self.assertEqual("Test", self.player.first_name) 23 | self.assertEqual("en", self.player.lang_id) 24 | 25 | def test_give_card(self): 26 | """ 27 | Check if giving a player a card will store the card in the player object 28 | :return: 29 | """ 30 | self.player.give_card(self._generate_mock_card(10)) 31 | self.assertEqual(1, len(self.player._cards)) 32 | 33 | self.player.give_card(self._generate_mock_card(11)) 34 | self.assertEqual(2, len(self.player._cards)) 35 | 36 | self.player.give_card(self._generate_mock_card(10)) 37 | self.assertEqual(3, len(self.player._cards)) 38 | 39 | def test_set_cardvalue(self): 40 | """ 41 | Check if trying to set the cardvalue will raise an AttributeError 42 | :return: 43 | """ 44 | with self.assertRaises(AttributeError): 45 | self.player.cardvalue = 2 46 | 47 | def test_cardvalue(self): 48 | """ 49 | Check if the cardvalue method returns a correct results for regular (non ace/K/Q/J) card values 50 | :return: 51 | """ 52 | self.player.give_card(self._generate_mock_card(10)) 53 | self.assertEqual(10, self.player.cardvalue) 54 | 55 | self.player.give_card(self._generate_mock_card(9)) 56 | self.assertEqual(19, self.player.cardvalue) 57 | 58 | def test_cardvalue_ace(self): 59 | """ 60 | Check if several aces will be calculated correctly (A+A+A+A+5+2 = 21) 61 | :return: 62 | """ 63 | self.player.give_card(self._generate_mock_card(11)) 64 | self.assertEqual(11, self.player.cardvalue) 65 | 66 | self.player.give_card(self._generate_mock_card(11)) 67 | self.assertEqual(12, self.player.cardvalue) 68 | 69 | self.player.give_card(self._generate_mock_card(11)) 70 | self.assertEqual(13, self.player.cardvalue) 71 | 72 | self.player.give_card(self._generate_mock_card(11)) 73 | self.assertEqual(14, self.player.cardvalue) 74 | 75 | self.player.give_card(self._generate_mock_card(5)) 76 | self.assertEqual(19, self.player.cardvalue) 77 | 78 | self.player.give_card(self._generate_mock_card(2)) 79 | self.assertEqual(21, self.player.cardvalue) 80 | 81 | def test_cardvalue_ace2(self): 82 | """ 83 | Check if several aces will be calculated correctly (A+A+A+5 = 18) 84 | :return: 85 | """ 86 | self.player.give_card(self._generate_mock_card(11)) 87 | self.assertEqual(11, self.player.cardvalue) 88 | 89 | self.player.give_card(self._generate_mock_card(11)) 90 | self.assertEqual(12, self.player.cardvalue) 91 | 92 | self.player.give_card(self._generate_mock_card(11)) 93 | self.assertEqual(13, self.player.cardvalue) 94 | 95 | self.player.give_card(self._generate_mock_card(5)) 96 | self.assertEqual(18, self.player.cardvalue) 97 | 98 | def test_cardvalue_soft_hand(self): 99 | """ 100 | Check if aces are correctly calculated in soft hands (5+A+3 = 19) 101 | :return: 102 | """ 103 | self.player.give_card(self._generate_mock_card(5)) 104 | self.assertEqual(5, self.player.cardvalue) 105 | 106 | self.player.give_card(self._generate_mock_card(11)) 107 | self.assertEqual(16, self.player.cardvalue) 108 | 109 | self.player.give_card(self._generate_mock_card(3)) 110 | self.assertEqual(19, self.player.cardvalue) 111 | 112 | def test_cardvalue_soft_hand_bj(self): 113 | """ 114 | Check if black jacks are calculated correctly (10+A = 21/BJ) 115 | :return: 116 | """ 117 | self.player.give_card(self._generate_mock_card(10)) 118 | self.assertEqual(10, self.player.cardvalue) 119 | 120 | self.player.give_card(self._generate_mock_card(11)) 121 | self.assertEqual(21, self.player.cardvalue) 122 | 123 | def test_cardvalue_hard_hand(self): 124 | """ 125 | Check if a hard hand gets calculated correctly (8+A+2 == 21 hard hand) 126 | :return: 127 | """ 128 | self.player.give_card(self._generate_mock_card(8)) 129 | self.assertEqual(8, self.player.cardvalue) 130 | 131 | self.player.give_card(self._generate_mock_card(11)) 132 | self.assertEqual(19, self.player.cardvalue) 133 | 134 | self.player.give_card(self._generate_mock_card(2)) 135 | self.assertEqual(21, self.player.cardvalue) 136 | 137 | def test_cardvalue_hard_hand2(self): 138 | """ 139 | Check if a hard hand gets calculated correctly (8+5+A == 14 hard hand) 140 | :return: 141 | """ 142 | self.player.give_card(self._generate_mock_card(8)) 143 | self.assertEqual(8, self.player.cardvalue) 144 | 145 | self.player.give_card(self._generate_mock_card(5)) 146 | self.assertEqual(13, self.player.cardvalue) 147 | 148 | self.player.give_card(self._generate_mock_card(11)) 149 | self.assertEqual(14, self.player.cardvalue) 150 | 151 | def test_cardvalue_busted_wo_ace(self): 152 | """ 153 | Check if a correct value will be returned if the player busted without an ace 154 | :return: 155 | """ 156 | self.player.give_card(self._generate_mock_card(8)) 157 | self.assertEqual(8, self.player.cardvalue) 158 | 159 | self.player.give_card(self._generate_mock_card(5)) 160 | self.assertEqual(13, self.player.cardvalue) 161 | 162 | self.player.give_card(self._generate_mock_card(10)) 163 | self.assertEqual(23, self.player.cardvalue) 164 | 165 | def test_cardvalue_busted_w_ace(self): 166 | """ 167 | Check if a correct value will be returned if the player busted with an ace 168 | :return: 169 | """ 170 | self.player.give_card(self._generate_mock_card(8)) 171 | self.assertEqual(8, self.player.cardvalue) 172 | 173 | self.player.give_card(self._generate_mock_card(11)) 174 | self.assertEqual(19, self.player.cardvalue) 175 | 176 | self.player.give_card(self._generate_mock_card(10)) 177 | self.assertEqual(19, self.player.cardvalue) 178 | 179 | self.player.give_card(self._generate_mock_card(5)) 180 | self.assertEqual(24, self.player.cardvalue) 181 | 182 | def test_amount_of_cards(self): 183 | """ 184 | Check if the number of cards is calculated correctly 185 | :return: 186 | """ 187 | self.assertEqual(0, self.player.amount_of_cards) 188 | 189 | self.player.give_card(self._generate_mock_card(10)) 190 | 191 | self.assertEqual(1, self.player.amount_of_cards) 192 | 193 | self.player.give_card(self._generate_mock_card(9)) 194 | 195 | self.assertEqual(2, self.player.amount_of_cards) 196 | 197 | def test_amount_of_cards_write(self): 198 | """ 199 | Assure that we can't write to the variable 200 | :return: 201 | """ 202 | with self.assertRaises(AttributeError): 203 | self.player.amount_of_cards = 2 204 | 205 | 206 | if __name__ == '__main__': 207 | unittest.main() 208 | -------------------------------------------------------------------------------- /blackjack/game/tests/shoe_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from math import ceil 3 | from unittest.mock import Mock 4 | 5 | from blackjack.game import Shoe 6 | 7 | 8 | class ShoeTest(unittest.TestCase): 9 | 10 | def setUp(self): 11 | self.shoe = Shoe() 12 | 13 | def test_init(self): 14 | # test explicit 15 | shoe = Shoe(decks=4) 16 | expected_amount = 4 * 52 - 20 17 | self.assertEqual(expected_amount, len(shoe._cards)) 18 | 19 | # test generic 20 | for i in range(2, 9): 21 | shoe = Shoe(decks=i) 22 | expected_amount = ceil((i * 52) * 0.9) 23 | self.assertEqual(expected_amount, len(shoe._cards)) 24 | 25 | def test_draw(self): 26 | mock_card = Mock() 27 | self.shoe._cards = [mock_card] 28 | card = self.shoe.draw() 29 | 30 | self.assertEqual(mock_card, card) 31 | 32 | def test_draw_empty(self): 33 | self.shoe._cards = [] 34 | 35 | with self.assertRaises(IndexError): 36 | _ = self.shoe.draw() 37 | 38 | 39 | if __name__ == '__main__': 40 | unittest.main() 41 | -------------------------------------------------------------------------------- /blackjackbot/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from telegram import Update 3 | from telegram.ext import CommandHandler, CallbackQueryHandler, MessageHandler, Filters 4 | 5 | from blackjackbot.commands import game, admin, settings, util 6 | from blackjackbot.errors import error_handler 7 | from util import BannedUserHandler, banned_user_callback 8 | 9 | # Banned users 10 | banned_user_handler = BannedUserHandler(callback=banned_user_callback, type=Update) 11 | 12 | # User commands 13 | start_command_handler = CommandHandler("start", game.start_cmd) 14 | stop_command_handler = CommandHandler("stop", game.stop_cmd) 15 | language_command_handler = CommandHandler("language", settings.language_cmd) 16 | stats_command_handler = CommandHandler("stats", util.stats_cmd) 17 | resetstats_command_handler = CommandHandler("resetstats", util.reset_stats_cmd) 18 | comment_command_handler = CommandHandler("comment", util.comment_cmd) 19 | comment_text_command_handler = MessageHandler(Filters.text & ~(Filters.forwarded | Filters.command), util.comment_text) 20 | 21 | # Admin methods 22 | reload_lang_command_handler = CommandHandler("reload_lang", admin.reload_languages_cmd) 23 | users_command_handler = CommandHandler("users", admin.users_cmd) 24 | answer_command_handler = CommandHandler("answer", admin.answer_comment_cmd, Filters.reply) 25 | kill_command_handler = CommandHandler("kill", admin.kill_game_cmd, Filters.text) 26 | ban_command_handler = CommandHandler("ban", admin.ban_user_cmd, pass_args=True) 27 | unban_command_handler = CommandHandler("unban", admin.unban_user_cmd, pass_args=True) 28 | bans_command_handler = CommandHandler("bans", admin.bans_cmd) 29 | 30 | # Callback handlers 31 | hit_callback_handler = CallbackQueryHandler(game.hit_callback, pattern=r"^hit_[0-9]{7}$") 32 | stand_callback_handler = CallbackQueryHandler(game.stand_callback, pattern=r"^stand_[0-9]{7}$") 33 | join_callback_handler = CallbackQueryHandler(game.join_callback, pattern=r"^join_[0-9]{7}$") 34 | start_callback_handler = CallbackQueryHandler(game.start_callback, pattern=r"^start_[0-9]{7}$") 35 | newgame_callback_handler = CallbackQueryHandler(game.newgame_callback, pattern=r"^newgame$") 36 | language_callback_handler = CallbackQueryHandler(settings.language_callback, pattern=r"^lang_([a-z]{2}(?:-[a-z]{2})?)$") 37 | reset_stats_callback_handler = CallbackQueryHandler(util.reset_stats_callback, pattern=r"^reset_stats_(confirm|cancel)$") 38 | 39 | handlers = [banned_user_handler, 40 | start_command_handler, stop_command_handler, join_callback_handler, hit_callback_handler, 41 | stand_callback_handler, start_callback_handler, language_command_handler, stats_command_handler, 42 | newgame_callback_handler, reload_lang_command_handler, language_callback_handler, users_command_handler, 43 | comment_command_handler, comment_text_command_handler, answer_command_handler, ban_command_handler, 44 | unban_command_handler, bans_command_handler, resetstats_command_handler, reset_stats_callback_handler] 45 | 46 | __all__ = ['handlers', 'error_handler'] 47 | -------------------------------------------------------------------------------- /blackjackbot/commands/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from .admin import reload_languages_cmd, users_cmd 4 | from .game import start_cmd, rules_cmd, stop_cmd, start_callback, stand_callback, hit_callback, join_callback, newgame_callback, create_game, next_player, \ 5 | players_turn 6 | from .settings import language_cmd, language_callback 7 | from .util import stats_cmd, comment_cmd, comment_text 8 | 9 | __all__ = ['start_cmd', 'stop_cmd', 'stats_cmd', 'language_cmd', 'rules_cmd', 'hit_callback', 'stand_callback', 'join_callback', 'start_callback', 10 | 'newgame_callback', 'language_callback', 'reload_languages_cmd', 'users_cmd', 'comment_cmd', 'comment_text'] 11 | -------------------------------------------------------------------------------- /blackjackbot/commands/admin/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from .functions import notify_admins 3 | from .commands import answer_comment_cmd, reload_languages_cmd, users_cmd, kill_game_cmd, ban_user_cmd, \ 4 | unban_user_cmd, bans_cmd 5 | 6 | __all__ = ["answer_comment_cmd", "reload_languages_cmd", "users_cmd", "notify_admins", "kill_game_cmd", "ban_user_cmd", 7 | "unban_user_cmd", "bans_cmd"] 8 | -------------------------------------------------------------------------------- /blackjackbot/commands/admin/commands.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import logging 4 | import re 5 | 6 | from telegram import ParseMode 7 | 8 | from blackjackbot.commands.admin import notify_admins 9 | from blackjackbot.commands.util.decorators import admin_method 10 | from blackjackbot.errors import NoActiveGameException 11 | from blackjackbot.gamestore import GameStore 12 | from blackjackbot.lang import reload_strings, Translator 13 | from database import Database 14 | 15 | logger = logging.getLogger(__name__) 16 | 17 | 18 | @admin_method 19 | def ban_user_cmd(update, context): 20 | """Bans a user from using the bot""" 21 | usage_message = r"Please provide a valid userid\. Usage: `/ban `" 22 | # Try to get user_id from command 23 | if len(context.args) != 1: 24 | update.effective_message.reply_text(usage_message, parse_mode=ParseMode.MARKDOWN_V2) 25 | return 26 | 27 | match = re.search(r"^\d+$", context.args[0]) 28 | if not match: 29 | logger.error(f"The user_id did not match. Args: {context.args}") 30 | update.effective_message.reply_text(usage_message, parse_mode=ParseMode.MARKDOWN_V2) 31 | return 32 | user_id = match.group(0) 33 | 34 | db = Database() 35 | db.ban_user(user_id=user_id) 36 | 37 | logger.info(f"Admin '{update.effective_user.id}' banned user '{user_id}'!") 38 | notify_admins(f"Admin '{update.effective_user.id}' banned user '{user_id}'!", context) 39 | 40 | 41 | @admin_method 42 | def unban_user_cmd(update, context): 43 | """Unbans a user from using the bot""" 44 | usage_message = r"Please provide a valid userid\. Usage: `/unban `" 45 | 46 | # Try to get user_id from command 47 | if len(context.args) != 1: 48 | update.message.reply_text(usage_message, parse_mode=ParseMode.MARKDOWN_V2) 49 | return 50 | 51 | match = re.search(r"^\d+$", context.args[0]) 52 | if not match: 53 | logger.error(f"The user_id did not match. Args: {context.args}") 54 | update.effective_message.reply_text(usage_message, parse_mode=ParseMode.MARKDOWN_V2) 55 | return 56 | user_id = match.group(0) 57 | 58 | db = Database() 59 | db.unban_user(user_id=user_id) 60 | 61 | logger.info(f"Admin '{update.effective_user.id}' unbanned user '{user_id}'!") 62 | notify_admins(f"Admin '{update.effective_user.id}' unbanned user '{user_id}'!", context) 63 | 64 | 65 | @admin_method 66 | def kill_game_cmd(update, context): 67 | """Kills the game for a certain chat/group""" 68 | if len(context.args) == 0: 69 | update.message.reply_text("Please provide a chat_id!") 70 | 71 | chat_id = context.args[0] 72 | # Input validation for chat_id 73 | if not re.match(r"^-?[0-9]+$", chat_id): 74 | update.message.reply_text("Sorry, the chat_id is invalid!") 75 | return 76 | 77 | chat_id = int(chat_id) 78 | 79 | try: 80 | _ = GameStore().get_game(chat_id=chat_id) 81 | except NoActiveGameException: 82 | update.message.reply_text("Sorry, there is no running game in a chat with that ID!") 83 | return 84 | 85 | logger.info("Admin '{0}' removed game in chat '{1}'".format(update.effective_user.id, chat_id)) 86 | GameStore().remove_game(chat_id=chat_id) 87 | update.message.reply_text("Alright, I killed the running game in '{0}'!".format(chat_id)) 88 | context.bot.send_message(chat_id=chat_id, text="The creator of this bot stopped your current game of BlackJack.") 89 | 90 | 91 | @admin_method 92 | def reload_languages_cmd(update, context): 93 | reload_strings() 94 | update.message.reply_text("Reloaded languages & strings!") 95 | 96 | 97 | @admin_method 98 | def answer_comment_cmd(update, context): 99 | # Answer to admins only in English, because we don't save admin languages yet 100 | text = update.effective_message.text 101 | reply_to_message = update.message.reply_to_message 102 | text = text.replace("/answer ", "") 103 | 104 | # Error handling 105 | if reply_to_message is None or update.message.reply_to_message.from_user.id != context.bot.id: 106 | update.message.reply_text("⚠ You need to reply to the user's comment!") 107 | return 108 | if update.message.reply_to_message.text is None: 109 | update.message.reply_text("⚠ You replied to a non text message!") 110 | return 111 | 112 | try: 113 | # Parse user data from the message 114 | user_info = reply_to_message.text.split("\n")[-1] 115 | except Exception as e: 116 | update.message.reply_text("⚠ An unexpected error occurred!") 117 | logger.error("While parsing user data, the following exception occurred: {}".format(e)) 118 | return 119 | 120 | user = user_info.split(" | ") 121 | 122 | if type(user) != list or len(user) != 6: 123 | update.message.reply_text("⚠ Can't parse user data from the message you replied to! Please reply to a comment!") 124 | logger.warning("Can't parse user data from message: {}".format(reply_to_message.text)) 125 | return 126 | 127 | chat_id = user[0] 128 | 129 | if not re.match(r"^-?\d+$", chat_id): 130 | update.message.reply_text("⚠ Malformed chat_id!") 131 | logger.error("Malformed chat_id: {}".format(chat_id)) 132 | return 133 | 134 | translator = Translator(chat_id) 135 | user_reply = translator("reply_from_maintainer").format(text) 136 | 137 | # The following errors can easily happen here: 138 | # Have no rights to send a message -> Missing permissions 139 | # Forbidden: bot was blocked by the user -> User blocked the bot 140 | context.bot.send_message(chat_id=chat_id, text=user_reply) 141 | update.message.reply_text(text="I sent your comment to the user!") 142 | 143 | notify_admins("An admin replied to the comment by\n\n{}\n\nwith:\n\n{}".format(user_info, text), context) 144 | 145 | 146 | @admin_method 147 | def users_cmd(update, context): 148 | """Returns the amount of players in the last 24 hours""" 149 | db = Database() 150 | players = db.get_recent_players() 151 | 152 | text = "Last 24 hours: {}".format(len(players)) 153 | 154 | update.message.reply_text(text=text) 155 | 156 | 157 | @admin_method 158 | def bans_cmd(update, context): 159 | """Returns the amount of players in the last 24 hours""" 160 | db = Database() 161 | banned_users = db.get_banned_users() 162 | 163 | text = f"Banned user count: {len(banned_users)}" 164 | 165 | update.message.reply_text(text=text) 166 | -------------------------------------------------------------------------------- /blackjackbot/commands/admin/functions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from database import Database 3 | 4 | 5 | def notify_admins(text, context): 6 | """ 7 | Sends a message to all stored admins 8 | :param text: The text that is sent 9 | :param context: python-telegram-bot context object 10 | :return: 11 | """ 12 | db = Database() 13 | for admin_id in db.get_admins(): 14 | context.bot.sendMessage(admin_id, text=text) 15 | -------------------------------------------------------------------------------- /blackjackbot/commands/game/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from .commands import start_cmd, rules_cmd, stop_cmd 4 | from .commands import start_callback, stand_callback, hit_callback, join_callback, newgame_callback 5 | from .functions import create_game, next_player, players_turn 6 | 7 | __all__ = ['start_cmd', 'rules_cmd', 'stop_cmd', 'start_callback', 'stand_callback', 'hit_callback', 'join_callback', 'newgame_callback', 8 | 'create_game', 'next_player', 'players_turn'] 9 | -------------------------------------------------------------------------------- /blackjackbot/commands/game/commands.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from telegram.parsemode import ParseMode 4 | 5 | import blackjack.errors as errors 6 | from blackjack.game import BlackJackGame 7 | from blackjackbot.commands.util import html_mention, get_game_keyboard, get_join_keyboard, get_start_keyboard, remove_inline_keyboard 8 | from blackjackbot.commands.util.decorators import needs_active_game 9 | from blackjackbot.errors import NoActiveGameException 10 | from blackjackbot.gamestore import GameStore 11 | from blackjackbot.lang import Translator 12 | from blackjackbot.util import get_cards_string 13 | from database import Database 14 | from .functions import create_game, players_turn, next_player, is_button_affiliated 15 | 16 | 17 | def start_cmd(update, context): 18 | """Handles messages contianing the /start command. Starts a game for a specific user""" 19 | user = update.effective_user 20 | chat = update.effective_chat 21 | lang_id = Database().get_lang_id(chat.id) 22 | translator = Translator(lang_id=lang_id) 23 | 24 | Database().add_user(user.id, user.language_code, user.first_name, user.last_name, user.username) 25 | 26 | try: 27 | GameStore().get_game(update.effective_chat.id) 28 | # TODO notify user that there is a running game already? 29 | except NoActiveGameException: 30 | # If there is no game, we create one 31 | create_game(update, context) 32 | 33 | 34 | def start_callback(update, context): 35 | """Starts a game that has been created already""" 36 | user = update.effective_user 37 | chat = update.effective_chat 38 | lang_id = Database().get_lang_id(chat.id) 39 | translator = Translator(lang_id=lang_id) 40 | 41 | try: 42 | game = GameStore().get_game(update.effective_chat.id) 43 | 44 | if not is_button_affiliated(update, context, game, lang_id): 45 | return 46 | except NoActiveGameException: 47 | update.callback_query.answer(translator("mp_no_created_game_callback")) 48 | remove_inline_keyboard(update, context) 49 | return 50 | 51 | try: 52 | game.start(user.id) 53 | update.callback_query.answer(translator("mp_starting_game_callback")) 54 | except errors.GameAlreadyRunningException: 55 | update.callback_query.answer(translator("mp_game_already_begun_callback")) 56 | return 57 | except errors.NotEnoughPlayersException: 58 | update.callback_query.answer(translator("mp_not_enough_players_callback")) 59 | return 60 | except errors.InsufficientPermissionsException: 61 | update.callback_query.answer(translator("mp_only_creator_start_callback").format(user.first_name)) 62 | return 63 | 64 | if game.type != BlackJackGame.Type.SINGLEPLAYER: 65 | players_are = translator("mp_players_are") 66 | for player in game.players: 67 | players_are += "👤{}\n".format(player.first_name) 68 | players_are += "\n" 69 | else: 70 | players_are = "" 71 | 72 | update.effective_message.edit_text(translator("game_starts_now").format(players_are, get_cards_string(game.dealer, lang_id))) 73 | players_turn(update, context) 74 | 75 | 76 | @needs_active_game 77 | def stop_cmd(update, context): 78 | """Stops a game for a specific user""" 79 | user = update.effective_user 80 | chat = update.effective_chat 81 | lang_id = Database().get_lang_id(chat.id) 82 | translator = Translator(lang_id=lang_id) 83 | 84 | game = GameStore().get_game(chat.id) 85 | 86 | user_id = user.id 87 | try: 88 | if chat.type == "group" or chat.type == "supergroup": 89 | # If yes, get the chat admins 90 | admins = context.bot.get_chat_administrators(chat_id=chat.id) 91 | # if user.id in chat admin IDs, let them end the game with admin powers 92 | if user.id in [x.user.id for x in admins]: 93 | user_id = -1 94 | 95 | game.stop(user_id) 96 | update.effective_message.reply_text(translator("game_ended")) 97 | except errors.InsufficientPermissionsException: 98 | update.effective_message.reply_text(translator("mp_only_creator_can_end")) 99 | 100 | 101 | @needs_active_game 102 | def join_callback(update, context): 103 | """ 104 | CallbackQueryHandler callback for the 'join' inline button. Adds the executing player to the game of the specific chat 105 | """ 106 | user = update.effective_user 107 | chat = update.effective_chat 108 | lang_id = Database().get_lang_id(chat.id) 109 | translator = Translator(lang_id=lang_id) 110 | 111 | game = GameStore().get_game(chat.id) 112 | 113 | if not is_button_affiliated(update, context, game, lang_id): 114 | return 115 | 116 | try: 117 | game.add_player(user.id, user.first_name) 118 | update.effective_message.edit_text(text=translator("mp_request_join").format(game.get_player_list()), 119 | reply_markup=get_join_keyboard(game.id, lang_id)) 120 | update.callback_query.answer(translator("mp_join_callback").format(user.first_name)) 121 | 122 | # If players are full, replace join keyboard with start keyboard 123 | if len(game.players) >= game.MAX_PLAYERS: 124 | update.effective_message.edit_reply_markup(reply_markup=get_start_keyboard(lang_id)) 125 | except errors.GameAlreadyRunningException: 126 | remove_inline_keyboard(update, context) 127 | update.callback_query.answer(translator("mp_game_already_begun_callback")) 128 | except errors.MaxPlayersReachedException: 129 | update.effective_message.edit_reply_markup(reply_markup=get_start_keyboard(lang_id)) 130 | update.callback_query.answer(translator("mp_max_players_callback")) 131 | except errors.PlayerAlreadyExistingException: 132 | update.callback_query.answer(translator("mp_already_joined_callback")) 133 | 134 | 135 | @needs_active_game 136 | def hit_callback(update, context): 137 | """ 138 | CallbackQueryHandler callback for the 'hit' inline button. Draws a card for you. 139 | """ 140 | user = update.effective_user 141 | chat = update.effective_chat 142 | lang_id = Database().get_lang_id(chat.id) 143 | translator = Translator(lang_id=lang_id) 144 | 145 | game = GameStore().get_game(chat.id) 146 | 147 | if not is_button_affiliated(update, context, game, lang_id): 148 | return 149 | 150 | player = game.get_current_player() 151 | user_mention = html_mention(user_id=player.user_id, first_name=player.first_name) 152 | 153 | try: 154 | if user.id != player.user_id: 155 | update.callback_query.answer(translator("mp_not_your_turn_callback").format(user.first_name)) 156 | return 157 | 158 | game.draw_card() 159 | player_cards = get_cards_string(player, lang_id) 160 | text = translator("your_cards_are").format(user_mention, player.cardvalue, player_cards) 161 | update.effective_message.edit_text(text=text, parse_mode=ParseMode.HTML, reply_markup=get_game_keyboard(game.id, lang_id)) 162 | except errors.PlayerBustedException: 163 | player_cards = get_cards_string(player, lang_id) 164 | text = (translator("your_cards_are") + "\n\n" + translator("you_busted")).format(user_mention, player.cardvalue, player_cards) 165 | update.effective_message.edit_text(text=text, parse_mode=ParseMode.HTML, reply_markup=None) 166 | next_player(update, context) 167 | except errors.PlayerGot21Exception: 168 | player_cards = get_cards_string(player, lang_id) 169 | if player.has_blackjack(): 170 | text = (translator("your_cards_are") + "\n\n" + translator("got_blackjack")).format(user_mention, player.cardvalue, player_cards) 171 | else: 172 | text = (translator("your_cards_are") + "\n\n" + translator("got_21")).format(user_mention, player.cardvalue, player_cards) 173 | 174 | update.effective_message.edit_text(text=text, parse_mode=ParseMode.HTML, reply_markup=None) 175 | next_player(update, context) 176 | 177 | 178 | @needs_active_game 179 | def stand_callback(update, context): 180 | """ 181 | CallbackQueryHandler callback for the 'stand' inline button. Prepares round for the next player. 182 | """ 183 | chat = update.effective_chat 184 | lang_id = Database().get_lang_id(chat.id) 185 | game = GameStore().get_game(update.effective_chat.id) 186 | 187 | if not is_button_affiliated(update, context, game, lang_id): 188 | return 189 | 190 | next_player(update, context) 191 | 192 | 193 | def newgame_callback(update, context): 194 | remove_inline_keyboard(update, context) 195 | start_cmd(update, context) 196 | 197 | 198 | def rules_cmd(update, context): 199 | update.effective_message.reply_text("Rules:\n\n- Black Jack pays 3 to 2\n- Dealer must stand on 17 and must draw to 16\n- Insurance pays 2 to 1") 200 | -------------------------------------------------------------------------------- /blackjackbot/commands/game/functions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import logging 3 | 4 | from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ParseMode 5 | 6 | from blackjack.errors import NoPlayersLeftException 7 | from blackjack.game import BlackJackGame 8 | from blackjackbot.commands.util.decorators import needs_active_game 9 | from blackjackbot.commands.util import html_mention, get_game_keyboard, get_join_keyboard, generate_evaluation_string, remove_inline_keyboard 10 | from blackjackbot.gamestore import GameStore 11 | from blackjackbot.lang import Translator 12 | from blackjackbot.util import get_cards_string 13 | from database import Database 14 | 15 | logger = logging.getLogger(__name__) 16 | 17 | 18 | def is_button_affiliated(update, context, game, lang_id): 19 | try: 20 | game_id = int(update.callback_query.data.split("_")[1]) 21 | if game.id != game_id: 22 | update.callback_query.answer("Sorry, the button you pressed is not for your current game!") 23 | remove_inline_keyboard(update, context) 24 | return False 25 | return True 26 | except Exception as e: 27 | logger.error("Something unexpected happened while checking button affiliation: {} - {}".format(update.callback_query.data, e)) 28 | return False 29 | 30 | 31 | def players_turn(update, context): 32 | """Execute a player's turn""" 33 | chat = update.effective_chat 34 | game = GameStore().get_game(chat.id) 35 | player = game.get_current_player() 36 | user_mention = html_mention(user_id=player.user_id, first_name=player.first_name) 37 | 38 | lang_id = Database().get_lang_id(chat.id) 39 | translator = Translator(lang_id=lang_id) 40 | 41 | logger.info("Player's turn: {}".format(player)) 42 | player_cards = get_cards_string(player, lang_id) 43 | 44 | # Check if player already has 21 or a BlackJack before their move. If so, automatically jump to the next player. 45 | # We need reply_text here, because we must send a new message (this is the first message for the player)! 46 | if player.has_blackjack(): 47 | text = (translator("your_cards_are") + "\n\n" + translator("got_blackjack")).format(user_mention, player.cardvalue, player_cards) 48 | update.effective_message.reply_text(text=text, parse_mode=ParseMode.HTML, reply_markup=None) 49 | next_player(update, context) 50 | elif player.cardvalue == 21: 51 | text = (translator("your_cards_are") + "\n\n" + translator("got_21")).format(user_mention, player.cardvalue, player_cards) 52 | update.effective_message.reply_text(text=text, parse_mode=ParseMode.HTML, reply_markup=None) 53 | next_player(update, context) 54 | else: 55 | text = translator("your_cards_are").format(user_mention, player.cardvalue, player_cards) 56 | update.effective_message.reply_text(text=text, parse_mode=ParseMode.HTML, reply_markup=get_game_keyboard(game.id, lang_id)) 57 | 58 | 59 | @needs_active_game 60 | def next_player(update, context): 61 | chat = update.effective_chat 62 | user = update.effective_user 63 | lang_id = Database().get_lang_id(chat.id) 64 | translator = Translator(lang_id=lang_id) 65 | 66 | game = GameStore().get_game(chat.id) 67 | 68 | try: 69 | if user.id != game.get_current_player().user_id: 70 | update.callback_query.answer(translator("mp_not_your_turn_callback").format(user.first_name)) 71 | return 72 | 73 | remove_inline_keyboard(update, context) 74 | game.next_player() 75 | except NoPlayersLeftException: 76 | # TODO merge messages 77 | update.effective_message.reply_text(translator("dealers_cards_are").format(game.dealer.cardvalue, 78 | get_cards_string(game.dealer, lang_id)), 79 | parse_mode=ParseMode.HTML) 80 | evaluation_string = generate_evaluation_string(game, lang_id) 81 | 82 | newgame_button = InlineKeyboardButton(text=translator("inline_keyboard_newgame"), callback_data="newgame") 83 | keyboard = InlineKeyboardMarkup(inline_keyboard=[[newgame_button]]) 84 | update.effective_message.reply_text(evaluation_string, reply_markup=keyboard) 85 | game.stop(-1) 86 | return 87 | 88 | players_turn(update, context) 89 | 90 | 91 | def create_game(update, context): 92 | """Create a new game instance for the chat of the user""" 93 | user = update.effective_user 94 | chat = update.effective_chat 95 | lang_id = Database().get_lang_id(chat.id) 96 | translator = Translator(lang_id=lang_id) 97 | 98 | # Create either a singleplayer or multiplayer game 99 | if chat.type == "private": 100 | game_type = BlackJackGame.Type.SINGLEPLAYER 101 | elif chat.type == "group" or chat.type == "supergroup": 102 | game_type = BlackJackGame.Type.MULTIPLAYER_GROUP 103 | else: 104 | logger.error("Chat type '{}' not supported!".format(chat.type)) 105 | return 106 | 107 | game = BlackJackGame(gametype=game_type) 108 | game.add_player(user_id=user.id, first_name=user.first_name) 109 | GameStore().add_game(chat.id, game) 110 | 111 | # TODO currently the game starts instantly - this should change with multiplayer rooms 112 | if game.type == BlackJackGame.Type.SINGLEPLAYER: 113 | update.effective_message.reply_text(translator("game_starts_now").format("", get_cards_string(game.dealer, lang_id))) 114 | players_turn(update, context) 115 | else: 116 | text = translator("mp_request_join").format(game.get_player_list()) 117 | update.effective_message.reply_text(text=text, reply_markup=get_join_keyboard(game.id, lang_id)) 118 | -------------------------------------------------------------------------------- /blackjackbot/commands/game/tests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | -------------------------------------------------------------------------------- /blackjackbot/commands/game/tests/functions_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import unittest 3 | from unittest.mock import Mock 4 | 5 | from blackjackbot.commands.game.functions import is_button_affiliated 6 | 7 | 8 | class GameCommandsFunctionsTest(unittest.TestCase): 9 | 10 | def test_is_button_affiliated_positive(self): 11 | """Check if button assignment is calculated correctly - game.id and data.id are equal""" 12 | game = Mock() 13 | game.id = 133769420 14 | update = Mock() 15 | update.callback_query = Mock() 16 | update.callback_query.answer = Mock() 17 | update.callback_query.data = "start_{}".format(game.id) 18 | 19 | result = is_button_affiliated(update, Mock(), game, "en") 20 | self.assertTrue(result) 21 | 22 | def test_is_button_affiliated_negative(self): 23 | """Check if button assignment is calculated correctly - game.id and data.id differ""" 24 | game = Mock() 25 | game.id = 420133769 26 | update = Mock() 27 | update.callback_query = Mock() 28 | update.callback_query.answer = Mock() 29 | update.callback_query.data = "start_133769420" 30 | 31 | result = is_button_affiliated(update, Mock(), game, "en") 32 | self.assertFalse(result) 33 | update.callback_query.answer.assert_called_once() 34 | 35 | 36 | if __name__ == '__main__': 37 | unittest.main() 38 | -------------------------------------------------------------------------------- /blackjackbot/commands/settings/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from .commands import language_cmd 3 | from .commands import language_callback 4 | 5 | __all__ = ['language_cmd', 'language_callback'] 6 | -------------------------------------------------------------------------------- /blackjackbot/commands/settings/commands.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import logging 3 | import re 4 | 5 | from telegram import InlineKeyboardButton, InlineKeyboardMarkup 6 | 7 | from blackjackbot.lang import translate, get_available_languages, get_language_info 8 | from blackjackbot.util import build_menu 9 | from database import Database 10 | 11 | logger = logging.getLogger(__name__) 12 | 13 | 14 | def language_cmd(update, context): 15 | """ 16 | Handler for /language commands 17 | """ 18 | buttons = [] 19 | 20 | for lang in get_available_languages(): 21 | display_name = lang.get("display_name") 22 | lang_code = lang.get("lang_code") 23 | buttons.append(InlineKeyboardButton(text=display_name, callback_data="lang_{}".format(lang_code))) 24 | 25 | lang_keyboard = InlineKeyboardMarkup(build_menu(buttons, n_cols=3)) 26 | 27 | lang_id = Database().get_lang_id(update.effective_chat.id) 28 | update.message.reply_text(text=translate("select_lang", lang_id), reply_markup=lang_keyboard) 29 | 30 | 31 | def language_callback(update, context): 32 | """ 33 | Callback function to handle inline buttons of the /language menu for changing the language 34 | """ 35 | query_data = update.callback_query.data 36 | lang_id = re.search(r"^lang_([a-z]{2}(?:-[a-z]{2})?)$", query_data).group(1) 37 | 38 | # Inform user about language change 39 | lang = get_language_info(lang_id) 40 | lang_changed_text = translate("lang_changed", lang_id).format(lang.get("display_name")) 41 | update.effective_message.edit_text(text=lang_changed_text, reply_markup=None) 42 | 43 | Database().set_lang_id(lang_id=lang_id, chat_id=update.effective_chat.id) 44 | logger.debug("Language changed to '{}' for user {}".format(lang_id, update.effective_user.id)) 45 | -------------------------------------------------------------------------------- /blackjackbot/commands/util/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from .functions import remove_inline_keyboard, get_start_keyboard, generate_evaluation_string, html_mention, get_game_keyboard, get_join_keyboard 3 | from .decorators import admin_method, needs_active_game 4 | from .commands import stats_cmd, comment_cmd, comment_text, reset_stats_cmd, reset_stats_callback 5 | 6 | __all__ = ['remove_inline_keyboard', 'get_start_keyboard', 'generate_evaluation_string', 'html_mention', 'get_game_keyboard', 'get_join_keyboard', 7 | 'stats_cmd', 'comment_cmd', 'comment_text', 'admin_method', 'needs_active_game', 'reset_stats_cmd', 'reset_stats_callback'] 8 | -------------------------------------------------------------------------------- /blackjackbot/commands/util/commands.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from telegram import ForceReply, ParseMode, InlineKeyboardButton, InlineKeyboardMarkup 4 | 5 | from blackjackbot.commands.admin.functions import notify_admins 6 | from blackjackbot.lang import translate 7 | from blackjackbot.util.userstate import UserState 8 | from database import Database 9 | from database.statistics import get_user_stats 10 | 11 | 12 | def stats_cmd(update, context): 13 | update.message.reply_text(get_user_stats(update.effective_user.id), parse_mode=ParseMode.HTML) 14 | 15 | 16 | def reset_stats_cmd(update, context): 17 | """Asks the user if they want to reset their statistics""" 18 | user_id = update.effective_user.id 19 | chat_id = update.effective_chat.id 20 | 21 | _modify_old_reset_message(context) 22 | 23 | db = Database() 24 | lang_id = db.get_lang_id(user_id) 25 | 26 | keyboard = [[ 27 | InlineKeyboardButton(translate("reset_stats_confirm_button"), callback_data='reset_stats_confirm'), 28 | InlineKeyboardButton(translate("reset_stats_cancel_button"), callback_data='reset_stats_cancel'), 29 | ]] 30 | reply_markup = InlineKeyboardMarkup(keyboard) 31 | 32 | sent_message = update.message.reply_text(translate("reset_stats_confirm", lang_id), reply_markup=reply_markup) 33 | reset_message = {"message_id": sent_message.message_id, "chat_id": chat_id} 34 | context.user_data["reset_messages"] = reset_message 35 | 36 | 37 | def _modify_old_reset_message(context): 38 | """Removes the last saved reset confirmation messages from the chat history""" 39 | reset_message = context.user_data.get("reset_message", None) 40 | if reset_message is None: 41 | return 42 | 43 | try: 44 | context.bot.edit_message_reply_markup(chat_id=reset_message.get("chat_id"), message_id=reset_message.get("message_id")) 45 | except: 46 | pass 47 | 48 | context.user_data["reset_messages"] = None 49 | 50 | 51 | def reset_stats_callback(update, context): 52 | """Handler for confirmation of statistics reset""" 53 | query = update.callback_query 54 | query.answer() 55 | 56 | user_id = update.effective_user.id 57 | db = Database() 58 | lang_id = db.get_lang_id(user_id) 59 | 60 | if query.data == "reset_stats_confirm": 61 | db.reset_stats(user_id=user_id) 62 | query.edit_message_text(translate("reset_stats_executed", lang_id)) 63 | 64 | elif query.data == "reset_stats_cancel": 65 | query.edit_message_text(translate("reset_stats_cancelled", lang_id)) 66 | 67 | 68 | def comment_cmd(update, context): 69 | """MessageHandler callback for the /comment command""" 70 | if context.user_data.get("state", UserState.IDLE) != UserState.IDLE: 71 | return 72 | 73 | chat = update.effective_chat 74 | lang_id = Database().get_lang_id(chat.id) 75 | update.message.reply_text(translate("send_comment", lang_id), reply_markup=ForceReply()) 76 | context.user_data["state"] = UserState.COMMENTING 77 | 78 | 79 | def comment_text(update, context): 80 | """ 81 | MessageHandler callback for processing comments sent by a user. 82 | Notifies the admins of the bot about the comment 83 | """ 84 | # Only handle the message, if the user is currently in the "commenting" state 85 | if context.user_data.get("state", None) != UserState.COMMENTING: 86 | return 87 | 88 | user = update.effective_user 89 | chat = update.effective_chat 90 | lang_id = Database().get_lang_id(chat.id) 91 | 92 | # username can be None, so we need to use str() 93 | data = [chat.id, user.id, user.first_name, user.last_name, "@" + str(user.username), user.language_code] 94 | 95 | userdata = " | ".join([str(item) for item in data]) 96 | userdata = userdata.replace("\r", "").replace("\n", "") 97 | 98 | text = update.effective_message.text 99 | 100 | notify_admins("New comment from a user:\n\n{}\n\n{}".format(text, userdata), context) 101 | update.message.reply_text(translate("received_comment", lang_id)) 102 | 103 | context.user_data["state"] = UserState.IDLE 104 | -------------------------------------------------------------------------------- /blackjackbot/commands/util/decorators.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import functools 3 | import logging 4 | 5 | from blackjackbot.commands.util import remove_inline_keyboard 6 | from blackjackbot.errors import NoActiveGameException 7 | from blackjackbot.gamestore import GameStore 8 | from blackjackbot.lang import Translator 9 | from database import Database 10 | 11 | 12 | def admin_method(func): 13 | """Decorator for marking methods as admin-only methods, so that strangers can't use them""" 14 | 15 | def admin_check(update, context): 16 | user = update.effective_user 17 | chat = update.effective_chat 18 | lang_id = Database().get_lang_id(chat.id) 19 | translator = Translator(lang_id=lang_id) 20 | 21 | if user.id in Database().get_admins(): 22 | return func(update, context) 23 | else: 24 | update.message.reply_text(translator("no_permission")) 25 | logging.warning("User {} ({}, @{}) tried to use admin function '{}'!".format(user.id, user.first_name, user.username, func.__name__)) 26 | 27 | return admin_check 28 | 29 | 30 | def needs_active_game(func): 31 | """Decorator for making sure a game exists for a certain chat""" 32 | 33 | @functools.wraps(func) 34 | def wrapper(update, context, *args, **kwargs): 35 | chat = update.effective_chat 36 | lang_id = Database().get_lang_id(chat.id) 37 | translator = Translator(lang_id=lang_id) 38 | 39 | try: 40 | game = GameStore().get_game(chat.id) 41 | except NoActiveGameException: 42 | remove_inline_keyboard(update, context) 43 | update.effective_message.reply_text(translator("mp_no_created_game_callback")) 44 | return 45 | 46 | return func(update, context) 47 | 48 | return wrapper 49 | -------------------------------------------------------------------------------- /blackjackbot/commands/util/functions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """Utility functions for performing chat related tasks""" 3 | import html 4 | 5 | from telegram import InlineKeyboardButton, InlineKeyboardMarkup 6 | 7 | from blackjack.game import BlackJackGame 8 | from blackjackbot.lang import Translator 9 | 10 | 11 | def remove_inline_keyboard(update, context): 12 | """ 13 | Removes the inline keyboard for a given message 14 | :param update: PTB update object 15 | :param context: PTB context object 16 | :return: 17 | """ 18 | if update.effective_message.from_user.id == context.bot.id: 19 | try: 20 | update.effective_message.edit_reply_markup(reply_markup=None) 21 | except Exception: 22 | # When the message already has no reply markup, simply ignore the exception 23 | # We can't check for message.reply_markup, because it might have been removed earlier 24 | pass 25 | 26 | 27 | def html_mention(user_id, first_name): 28 | """Generate HTML code that will mention a user in a group""" 29 | first_name = html.escape(first_name) 30 | return '{}'.format(user_id, first_name) 31 | 32 | 33 | def _get_player_list_string(player_list, dealer_name): 34 | """ 35 | Generate a string containing a newline separated list of players in the passed list 36 | :param player_list: A list of players 37 | :param dealer_name: The localized name of the dealer 38 | :return: 39 | """ 40 | players = [] 41 | name_value_template = "{} - {}" 42 | 43 | for player in player_list: 44 | if player.is_dealer: 45 | players.append(name_value_template.format(dealer_name, player.cardvalue)) 46 | else: 47 | players.append(name_value_template.format(player.first_name, player.cardvalue)) 48 | 49 | return "\n".join(players) 50 | 51 | 52 | def _generate_evaluation_string_mp(game, lang_id): 53 | list_won, list_tie, list_losses = game.evaluation() 54 | message = "" 55 | translator = Translator(lang_id) 56 | dealer_name = translator("dealer_name") 57 | 58 | if len(list_won) > 0: 59 | message += translator("eval_heading_wins") + "\n" 60 | message += _get_player_list_string(list_won, dealer_name) 61 | 62 | # 🔃 63 | if len(list_tie) > 0: 64 | message += "\n\n{}\n".format(translator("eval_heading_ties")) 65 | message += _get_player_list_string(list_tie, dealer_name) 66 | 67 | if len(list_losses) > 0: 68 | message += "\n\n{}\n".format(translator("eval_heading_losses")) 69 | message += _get_player_list_string(list_losses, dealer_name) 70 | 71 | return message 72 | 73 | 74 | def _generate_evaluation_string_sp(game, lang_id): 75 | list_won, list_tie, list_losses = game.evaluation() 76 | message = "" 77 | join_str = "\n{} - {}" 78 | player = game.players[0] 79 | translator = Translator(lang_id) 80 | 81 | if len(list_won) == 1: 82 | if game.dealer.busted: 83 | # Dealer busted, you won 84 | message += translator("dealer_busted") 85 | else: 86 | # Closer to 21 87 | message += translator("closer_to_21") 88 | 89 | message += "\n" 90 | message += join_str.format(player.first_name, player.cardvalue) 91 | message += join_str.format(translator("dealer_name"), game.dealer.cardvalue) 92 | elif len(list_tie) == 1: 93 | # Same value as dealer 94 | message += translator("tied_with_dealer") 95 | message += "\n" 96 | message += join_str.format(player.first_name, player.cardvalue) 97 | message += join_str.format(translator("dealer_name"), game.dealer.cardvalue) 98 | elif len(list_losses) == 1: 99 | if player.busted: 100 | # busted 101 | message += translator("you_busted") 102 | elif game.dealer.has_blackjack(): 103 | message += translator("dealer_got_blackjack") 104 | else: 105 | message += translator("dealer_got_21") 106 | 107 | message += "\n" 108 | message += join_str.format(translator("dealer_name"), game.dealer.cardvalue) 109 | message += join_str.format(player.first_name, player.cardvalue) 110 | 111 | return message 112 | 113 | 114 | def generate_evaluation_string(game, lang_id): 115 | if game.type == BlackJackGame.Type.SINGLEPLAYER: 116 | return _generate_evaluation_string_sp(game, lang_id) 117 | else: 118 | return _generate_evaluation_string_mp(game, lang_id) 119 | 120 | 121 | def get_game_keyboard(game_id, lang_id): 122 | """Generates a game keyboard translated into the given language 123 | :param game_id: A unique identifier for each game 124 | :param lang_id: The language identifier for a specific chat 125 | :return: 126 | """ 127 | translator = Translator(lang_id) 128 | one_more_button = InlineKeyboardButton(text=translator("inline_keyboard_hit"), callback_data="hit_{}".format(game_id)) 129 | no_more_button = InlineKeyboardButton(text=translator("inline_keyboard_stand"), callback_data="stand_{}".format(game_id)) 130 | stop_button = InlineKeyboardButton(text="Stop", callback_data="stop_{}".format(game_id)) 131 | return InlineKeyboardMarkup(inline_keyboard=[[one_more_button, no_more_button]]) 132 | 133 | 134 | def get_join_keyboard(game_id, lang_id): 135 | """ 136 | Generates a join keyboard translated into the given language 137 | :param game_id: A unique identifier for each game 138 | :param lang_id: The language identifier for a specific chat 139 | :return: 140 | """ 141 | translator = Translator(lang_id) 142 | join_button = InlineKeyboardButton(text=translator("inline_keyboard_join"), callback_data="join_{}".format(game_id)) 143 | start_button = InlineKeyboardButton(text=translator("inline_keyboard_start"), callback_data="start_{}".format(game_id)) 144 | return InlineKeyboardMarkup(inline_keyboard=[[join_button, start_button]]) 145 | 146 | 147 | def get_start_keyboard(lang_id): 148 | translator = Translator(lang_id) 149 | start_button = InlineKeyboardButton(text=translator("inline_keyboard_start"), callback_data="start") 150 | return InlineKeyboardMarkup(inline_keyboard=[[start_button]]) 151 | -------------------------------------------------------------------------------- /blackjackbot/errors/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from .noactivegameexception import NoActiveGameException 3 | from .errorhandler import error_handler 4 | 5 | __all__ = ['NoActiveGameException', 'error_handler'] 6 | -------------------------------------------------------------------------------- /blackjackbot/errors/errorhandler.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import logging 3 | 4 | from telegram.error import Unauthorized, BadRequest, TimedOut, NetworkError, ChatMigrated, TelegramError 5 | from blackjackbot.gamestore import GameStore 6 | 7 | logger = logging.getLogger(__name__) 8 | 9 | 10 | def error_handler(update, context): 11 | try: 12 | raise context.error 13 | except Unauthorized as e: 14 | # remove update.message.chat_id from conversation list 15 | logger.error("The update {} raised the following 'Unauthorized' exception: {}".format(update, e)) 16 | if e.message == "Forbidden: bot was blocked by the user": 17 | GameStore().remove_game(update.effective_chat.id) 18 | elif e.message == "Forbidden: bot was kicked from the supergroup chat" or e.message == "Forbidden: bot was kicked from the group chat": 19 | GameStore().remove_game(update.effective_chat.id) 20 | 21 | except BadRequest as e: 22 | # handle malformed requests - read more below! 23 | logger.error("The update {} raised the following 'BadRequest' exception: {}".format(update, e)) 24 | except TimedOut as e: 25 | logger.warning("The update {} timed out: {}".format(update, e)) 26 | # handle slow connection problems 27 | except NetworkError as e: 28 | # handle other connection problems 29 | logger.warning("The update {} raised the following 'NetworkError' exception: {}".format(update, e)) 30 | except ChatMigrated as e: 31 | # the chat_id of a group has changed, use e.new_chat_id instead 32 | logger.warning("The update {} raised the following 'ChatMigrated' exception: {}".format(update, e)) 33 | except TelegramError as e: 34 | # handle all other telegram related errors 35 | logger.error("The update {} caused the following TelegramError: {}".format(update, e)) 36 | -------------------------------------------------------------------------------- /blackjackbot/errors/noactivegameexception.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | class NoActiveGameException(Exception): 5 | pass 6 | -------------------------------------------------------------------------------- /blackjackbot/gamestore.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import logging 3 | from datetime import datetime, timedelta 4 | from random import randint 5 | 6 | from .errors.noactivegameexception import NoActiveGameException 7 | import database.statistics 8 | 9 | 10 | class GameStore(object): 11 | _instance = None 12 | _initialized = False 13 | 14 | def __new__(cls): 15 | if GameStore._instance is None: 16 | GameStore._instance = super(GameStore, cls).__new__(cls) 17 | return GameStore._instance 18 | 19 | def __init__(self): 20 | if not self._initialized: 21 | self._chat_dict = {} 22 | self._game_dict = {} 23 | self.logger = logging.getLogger(__name__) 24 | self._initialized = True 25 | 26 | @staticmethod 27 | def _generate_id(): 28 | return randint(1000000, 9999999) 29 | 30 | def add_game(self, chat_id, game): 31 | if self.has_game(chat_id): 32 | raise Exception 33 | 34 | game.id = self._generate_id() 35 | while self._game_dict.get(game.id, None): 36 | game.id = self._generate_id() 37 | 38 | self.logger.info("Adding game with id {}".format(game.id)) 39 | game.register_on_stop_handler(self._game_stopped_callback) 40 | self._chat_dict[chat_id] = game 41 | self._game_dict[game.id] = chat_id 42 | 43 | def get_game(self, chat_id): 44 | """ 45 | 46 | :param chat_id: 47 | :return: 48 | """ 49 | game = self._chat_dict.get(chat_id) 50 | if game is None: 51 | raise NoActiveGameException 52 | return game 53 | 54 | def has_game(self, chat_id): 55 | return chat_id in self._chat_dict 56 | 57 | def remove_game(self, chat_id): 58 | """ 59 | Removes the game of a specific chat from the store 60 | :param chat_id: 61 | :return: 62 | """ 63 | if chat_id == -1: 64 | return 65 | 66 | try: 67 | game = self._chat_dict.pop(chat_id) 68 | self._game_dict.pop(game.id) 69 | self.logger.debug("Removing game for {} ({})".format(chat_id, game.id)) 70 | except KeyError: 71 | self.logger.error("Can't remove game for {}, because there is no such game!".format(chat_id)) 72 | 73 | def _game_stopped_callback(self, game): 74 | """ 75 | Callback to remove game from the GameStore 76 | :param game: 77 | :return: 78 | """ 79 | for player in game.players: 80 | database.statistics.add_game_played(player.user_id) 81 | if player in game.list_won: 82 | database.statistics.set_game_won(player.user_id) 83 | self.remove_game(self._game_dict[game.id]) 84 | 85 | self.logger.debug("Current games: {}".format(len(self._chat_dict))) 86 | 87 | def cleanup_stale_games(self): 88 | stale_timeout_min = 10 89 | now = datetime.now() 90 | remove_chat_ids = [] 91 | 92 | for game_id, chat_id in self._game_dict.items(): 93 | game = self.get_game(chat_id) 94 | 95 | game_older_than_10_mins = game.datetime_started < (now - timedelta(minutes=stale_timeout_min)) 96 | if game_older_than_10_mins: 97 | logging.info("Killing game with id {} because it's stale for > {} mins".format(game.id, stale_timeout_min)) 98 | # TODO notify chat 99 | remove_chat_ids.append(chat_id) 100 | 101 | for chat_id in remove_chat_ids: 102 | self.remove_game(chat_id) 103 | -------------------------------------------------------------------------------- /blackjackbot/lang/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from .language import translate, reload_strings, get_available_languages, Translator, get_language_info 4 | 5 | __all__ = ['translate', 'reload_strings', 'get_available_languages', 'Translator', 'get_language_info'] 6 | -------------------------------------------------------------------------------- /blackjackbot/lang/custom_strings/README.md: -------------------------------------------------------------------------------- 1 | ## custom_strings directory 2 | 3 | This directory was created to add translations on the fly, when the bot runs inside a docker container. 4 | 5 | ``` 6 | └───lang 7 | ├───custom_strings // custom translations 8 | └───strings // translations provided by the package maintainer 9 | ``` 10 | -------------------------------------------------------------------------------- /blackjackbot/lang/language.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import json 4 | import os 5 | import pathlib 6 | import re 7 | import logging 8 | 9 | logger = logging.getLogger(__name__) 10 | 11 | lang_path = pathlib.Path(__file__).parent.absolute() 12 | maintainer_strings_path = lang_path / "strings" 13 | custom_strings_path = lang_path / "custom_strings" 14 | 15 | language_paths = [maintainer_strings_path, custom_strings_path] 16 | languages = {} 17 | 18 | 19 | class Translator(object): 20 | 21 | def __init__(self, lang_id): 22 | self.lang_id = lang_id or "en" 23 | 24 | def translate(self, string): 25 | return translate(string, self.lang_id) 26 | 27 | def __call__(self, string): 28 | """ 29 | Wrapper for the translate method. Calling the object directly 30 | instead of the translate method will leave you with more tidy code 31 | """ 32 | return self.translate(string) 33 | 34 | 35 | def load_strings_from_dir(directory): 36 | """Reads the translation files into a dict. Overwrites the dict if already present""" 37 | with os.scandir(directory) as entries: 38 | for entry in entries: 39 | match = re.search(r"^translations_([a-z]{2}(-[a-z]{2})?)\.json$", entry.name) 40 | 41 | if not match: 42 | continue 43 | 44 | with open(entry.path, encoding="utf-8") as json_file: 45 | try: 46 | data = json.load(json_file) 47 | except json.JSONDecodeError: 48 | logger.error("Can't open translation file '{}'".format(entry.path)) 49 | continue 50 | 51 | file_lang_code = match.group(1) 52 | 53 | # Make sure the language file got a lang_code specified 54 | lang_code = data.get("lang_code", None) 55 | if not lang_code: 56 | logger.error("No lang_code specified in translation file '{0}'".format(entry.path)) 57 | return 58 | 59 | if languages.get(lang_code, None): 60 | logger.warning("Overwriting translations for lang_code: {0}".format(lang_code)) 61 | 62 | logger.info("Loaded translation file {0} - language code: {1}".format(entry.name, lang_code)) 63 | languages[lang_code] = data 64 | 65 | 66 | def reload_strings(): 67 | for path in language_paths: 68 | if not path.exists(): 69 | logger.warning("The path for translations does not exist: {0}".format(path.name)) 70 | continue 71 | load_strings_from_dir(path) 72 | 73 | if len(languages) == 0: 74 | logger.error("Coudln't load translations!") 75 | 76 | 77 | def get_available_languages(): 78 | """Return a list of available languages""" 79 | if len(languages) == 0: 80 | reload_strings() 81 | langs = [] 82 | 83 | for key, value in languages.items(): 84 | langs.append(get_language_info(key)) 85 | 86 | return langs 87 | 88 | 89 | def get_language_info(lang_code): 90 | """Returns information such as the lang_code, the language's name and the display name (with flag) for a certain language""" 91 | lang = get_language(lang_code) 92 | lang_name = lang.get("language_name", "N/A") 93 | lang_flag = lang.get("language_flag", "N/A") 94 | display_name = "{} {}".format(lang_name, lang_flag) 95 | 96 | return {"lang_code": lang.get("lang_code", "N/A"), "name": lang.get("language_name", "N/A"), "display_name": display_name} 97 | 98 | 99 | def get_language(lang_code): 100 | """Returns the translation dict for a certain language if it exists. If not, return the English translations""" 101 | if len(languages) == 0: 102 | reload_strings() 103 | 104 | lang = languages.get(lang_code, None) 105 | if lang is None: 106 | if "-" in lang_code: 107 | return get_language(lang_code.split("-")[0]) 108 | 109 | return languages["en"] 110 | return lang 111 | 112 | 113 | def translate(string, lang_code="en"): 114 | """Returns the translation in a specific language for a specific string""" 115 | lang = get_language(lang_code) 116 | 117 | translated_string = lang.get(string, None) 118 | 119 | if translated_string is None: 120 | # We want to give at least an english string as a fallback if there is none available in the selected language 121 | 122 | if lang_code != "en": 123 | return translate(string, "en") 124 | logger.warning("Missing string '{}'!".format(string)) 125 | return "STRING_NOT_AVAILABLE ('{}')".format(string) 126 | 127 | return translated_string 128 | -------------------------------------------------------------------------------- /blackjackbot/lang/strings/translations_de.json: -------------------------------------------------------------------------------- 1 | { 2 | "lang_code": "de", 3 | "language_name": "Deutsch", 4 | "language_flag": "\uD83C\uDDE9\uD83C\uDDEA", 5 | "you_busted": "\u274C Du hast überkauft!", 6 | "your_cards_are": "{} - Wert: {}\n\n{}", 7 | "dealers_cards_are": "Dealer: {}\n\n{}", 8 | "inline_keyboard_hit": "Hit", 9 | "inline_keyboard_stand": "Stand", 10 | "inline_keyboard_join": "Beitreten", 11 | "inline_keyboard_start": "Start", 12 | "inline_keyboard_newgame": "Neues Spiel", 13 | "card_ace": "Ass", 14 | "card_jack": "Bube", 15 | "card_queen": "Dame", 16 | "card_king": "König", 17 | "cancel": "Abbrechen", 18 | "mp_request_join": "Spiel erstellt, bitte beitreten. Spieler sind:\n\n{}", 19 | "mp_join_callback": "Willkommen, {}", 20 | "mp_game_already_begun_callback": "Das Spiel hat schon begonnen.", 21 | "mp_max_players_callback": "Die maximale Anzahl an Spielern wurde schon erreicht!", 22 | "mp_already_joined_callback": "Du bist dem Spiel schon beigetreten!", 23 | "mp_no_created_game_callback": "Es existiert kein erstelltes Spiel!", 24 | "mp_starting_game_callback": "Spiel wird gestartet!", 25 | "mp_not_enough_players_callback": "Noch nicht genügend Spieler!", 26 | "mp_only_creator_start_callback": "Entschuldige {}, nur der Ersteller kann das Spiel starten!", 27 | "mp_not_your_turn_callback": "Du bist nicht am Zug, {}!", 28 | "game_starts_now": "Das Spiel startet jetzt. \uD83C\uDFB2\n\n{}Karten des Dealers:\n\n{}", 29 | "game_ended": "Das Spiel wurde beendet! \uD83D\uDE09 Mit /start kannst du ein neues starten!", 30 | "mp_only_creator_can_end": "Nur der Ersteller kann das Spiel beenden!", 31 | "mp_players_are": "Spieler sind:\n", 32 | "no_permission": "Du hast dafür keine Berechtigungen!", 33 | "select_lang": "Bitte wähle deine Sprache.", 34 | "lang_changed": "Ich habe deine Sprache zu {} geändert!", 35 | "got_blackjack": "\u2705 Glückwunsch, du hast einen BlackJack!", 36 | "got_21": "\u2705 Glückwunsch, du hast exakt 21!", 37 | "dealer_got_blackjack": "\u274C Der Dealer hat einen BlackJack. Du verlierst.", 38 | "dealer_got_21": "\u274C Der Dealer kam näher an 21. Du verlierst.", 39 | "tied_with_dealer": "\uD83D\uDC4C Gleichstand mit dem Dealer.", 40 | "dealer_busted": "\uD83C\uDFC6 Glückwunsch! Der Dealer hat überkauft, daher gewinnst du diese Runde.", 41 | "closer_to_21": "\uD83C\uDFC6 Glückwunsch! Du bist näher an 21, daher gewinnst du diese Runde.", 42 | "eval_heading_wins": "\uD83D\uDD30 Gewinner:", 43 | "eval_heading_ties": "\uD83D\uDC4C Gleichstand:", 44 | "eval_heading_losses": "\u274C Verlierer:", 45 | "send_comment": "Bitte sende deinen Kommentar (nur Text) als Antwort auf diese Nachricht. Ich leite sie dann an den Betreiber des Bots weiter.", 46 | "received_comment": "Vielen Dank, dein Kommentar wurde an den Betreiber weitergeleitet.", 47 | "admin_reply": "⚠ Du musst auf den Kommentar des Nutzers antworten!", 48 | "reply_from_maintainer": "Der Betreiber des Bots hat dir eine Antwort geschickt:\n\n{}", 49 | "statistic_template": "Hier sind deine Statistiken 📊:\n\nGespielte Runden: {}\nGewonnene Runden: {}\nZuletzt gespielt: {} UTC\n\n{}\n\nGewinnrate: {:.2%}", 50 | "dealer_name": "Dealer" 51 | } 52 | -------------------------------------------------------------------------------- /blackjackbot/lang/strings/translations_en.json: -------------------------------------------------------------------------------- 1 | { 2 | "lang_code": "en", 3 | "language_name": "English", 4 | "language_flag": "\uD83C\uDDFA\uD83C\uDDF8", 5 | "you_busted": "\u274C You busted!", 6 | "your_cards_are": "{} - Value: {}\n\n{}", 7 | "dealers_cards_are": "Dealer: {}\n\n{}", 8 | "inline_keyboard_hit": "Hit", 9 | "inline_keyboard_stand": "Stand", 10 | "inline_keyboard_join": "Join", 11 | "inline_keyboard_start": "Start", 12 | "inline_keyboard_newgame": "New game", 13 | "card_ace": "Ace", 14 | "card_jack": "Jack", 15 | "card_queen": "Queen", 16 | "card_king": "King", 17 | "cancel": "Cancel", 18 | "mp_request_join": "Game created, please join. Players are:\n\n{}", 19 | "mp_join_callback": "Welcome {}", 20 | "mp_game_already_begun_callback": "The game has already begun.", 21 | "mp_max_players_callback": "The max amount of players has been reached!", 22 | "mp_already_joined_callback": "You already joined the game!", 23 | "mp_no_created_game_callback": "There is no created game!", 24 | "mp_starting_game_callback": "Starting game!", 25 | "mp_not_enough_players_callback": "There are not enough players yet!", 26 | "mp_only_creator_start_callback": "Sorry {}, only the creator can start the game!", 27 | "mp_not_your_turn_callback": "It's not your turn, {}!", 28 | "game_starts_now": "The game starts now. \uD83C\uDFB2\n\n{}Dealer's cards:\n\n{}", 29 | "game_ended": "The game has been ended. \uD83D\uDE09 You can /start another one if you like to.", 30 | "mp_only_creator_can_end": "Only the creator can end the game!", 31 | "mp_players_are": "Players are:\n", 32 | "no_permission": "You don't have the required permissions to do that!", 33 | "select_lang": "Please select your language.", 34 | "lang_changed": "I changed your language to {}!", 35 | "got_blackjack": "\u2705 Congratulations, you got a BlackJack!", 36 | "got_21": "\u2705 Congratulations, you got exactly 21!", 37 | "dealer_got_blackjack": "\u274C The dealer got a BlackJack. You lost.", 38 | "dealer_got_21": "\u274C The dealer got closer to 21. You lost.", 39 | "tied_with_dealer": "\uD83D\uDC4C You tied with the dealer.", 40 | "dealer_busted": "\uD83C\uDFC6 Congrats! The dealer busted, hence you win this round.", 41 | "closer_to_21": "\uD83C\uDFC6 Congrats! You are closer to 21 and win this round.", 42 | "eval_heading_wins": "\uD83D\uDD30 Wins:", 43 | "eval_heading_ties": "\uD83D\uDC4C Ties:", 44 | "eval_heading_losses": "\u274C Losses:", 45 | "send_comment": "Please send your comment (text only) as a reply to this message now. We'll forward it to the maintainer.", 46 | "received_comment": "Thank you, your comment was forwarded to the maintainer.", 47 | "admin_reply": "⚠ You need to reply to the user's comment!", 48 | "reply_from_maintainer": "The maintainer of this bot sent you a reply:\n\n{}", 49 | "statistic_template": "Here are your statistics 📊:\n\nPlayed Games: {}\nWon Games: {}\nLast Played: {} UTC\n\n{}\n\nWinning rate: {:.2%}", 50 | "dealer_name": "Dealer", 51 | "reset_stats_confirm": "Do you really want to reset your statistics?", 52 | "reset_stats_confirm_button": "Reset", 53 | "reset_stats_cancel_button": "Cancel", 54 | "reset_stats_executed": "Alright, I reset your statistics!", 55 | "reset_stats_cancelled": "Okay, I did not reset your statistics!", 56 | "no_stats": "You haven't played yet, there are no statistics for you." 57 | } 58 | -------------------------------------------------------------------------------- /blackjackbot/lang/strings/translations_eo.json: -------------------------------------------------------------------------------- 1 | { 2 | "lang_code": "eo", 3 | "language_name": "Esperanto", 4 | "language_flag": "💚", 5 | "you_busted": "❌ Vi malvenkis!", 6 | "your_cards_are": "{} - Valoro: {}\n\n{}", 7 | "dealers_cards_are": "Krupiero: {}\n\n{}", 8 | "inline_keyboard_hit": "Plia karto", 9 | "inline_keyboard_stand": "Ne pli", 10 | "inline_keyboard_join": "Aliĝi", 11 | "inline_keyboard_start": "Komenci", 12 | "inline_keyboard_newgame": "Nova ludo", 13 | "card_ace": "Aso", 14 | "card_jack": "Fanto", 15 | "card_queen": "Reĝino", 16 | "card_king": "Reĝo", 17 | "cancel": "Nuligi", 18 | "mp_request_join": "La ludo estas kreita, aliĝu. La ludantoj estas:\n\n{}", 19 | "mp_join_callback": "Bonvenon {}", 20 | "mp_game_already_begun_callback": "La ludo jam komenciĝis.", 21 | "mp_max_players_callback": "La maksimuma kvanto da ludantoj estas atingita!", 22 | "mp_already_joined_callback": "Vi jam aliĝis al la ludo!", 23 | "mp_no_created_game_callback": "Ne estas kreita ludo!", 24 | "mp_starting_game_callback": "La ludo komenciĝas!", 25 | "mp_not_enough_players_callback": "Ankoraŭ ne estas sufiĉe da ludantoj!", 26 | "mp_only_creator_start_callback": "Pardonon {}, nur la kreinto povas komenci la ludon!", 27 | "mp_not_your_turn_callback": "Ne estas via vico, {}!", 28 | "game_starts_now": "La ludo nun komenciĝas. 🎲\n\n{}La kartoj de la krupiero:\n\n{}", 29 | "game_ended": "La ludo estas finita. 😉 Vi povas komenci alian per /start, se vi ŝatus.", 30 | "mp_only_creator_can_end": "Nur la kreinto povas fini la ludon!", 31 | "mp_players_are": "La ludantoj estas:\n", 32 | "no_permission": "Vi ne havas la necesajn permesojn por fari tion!", 33 | "select_lang": "Elektu vian lingvon.", 34 | "lang_changed": "Mi ŝanĝis vian lingvon al {}!", 35 | "got_blackjack": "✅ Gratulon, vi havas Blackjack!", 36 | "got_21": "✅ Gratulon, vi havas ekzakte 21!", 37 | "dealer_got_blackjack": "❌ La krupiero havas Blackjack. Vi malvenkis.", 38 | "dealer_got_21": "❌ La krupiero pli proksimas al 21. Vi malvenkis.", 39 | "tied_with_dealer": "👌 Vi kaj la krupiero egalvenkis.", 40 | "dealer_busted": "🏆 Gratulon! La krupiero malvenkis, tial vi venkas ĉi tiun raŭndon.", 41 | "closer_to_21": "🏆 Gratulon! Vi pli proksimas al 21 kaj venkas ĉi tiun raŭndon.", 42 | "eval_heading_wins": "🔰 Venkoj:", 43 | "eval_heading_ties": "👌 Egalvenkoj:", 44 | "eval_heading_losses": "❌ Malvenkoj:", 45 | "send_comment": "Nun sendu vian komenton (nurtekstan) kiel respondon al ĉi tiu mesaĝo. Ni plusendos ĝin al la prizorganto.", 46 | "received_comment": "Dankon, via komento estas plusendita al la prizorganto.", 47 | "admin_reply": "⚠ Vi devas respondi al la komento de la uzanto!", 48 | "reply_from_maintainer": "La prizorganto de ĉi tiu roboto sendis al vi respondon:\n\n{}", 49 | "statistic_template": "Jen viaj statistikoj 📊:\n\nLuditaj ludoj: {}\nVenkitaj ludoj: {}\nLasta ludo: {} UTC\n\n{}\n\nVenko-elcento: {:.2%}", 50 | "dealer_name": "Krupiero" 51 | } 52 | -------------------------------------------------------------------------------- /blackjackbot/lang/strings/translations_es.json: -------------------------------------------------------------------------------- 1 | { 2 | "lang_code": "es", 3 | "language_name": "Español", 4 | "language_flag": "🇪🇸", 5 | "you_busted": "❌ ¡Te pasaste!", 6 | "your_cards_are": "{} - Valor: {}\n\n{}", 7 | "dealers_cards_are": "Crupier: {}\n\n{}", 8 | "inline_keyboard_hit": "Pedir", 9 | "inline_keyboard_stand": "Plantarse", 10 | "inline_keyboard_join": "Unirse", 11 | "inline_keyboard_start": "Comenzar", 12 | "inline_keyboard_newgame": "Nueva partida", 13 | "card_ace": "As", 14 | "card_jack": "Jota", 15 | "card_queen": "Reina", 16 | "card_king": "Rey", 17 | "cancel": "Cancelar", 18 | "mp_request_join": "El juego ha empezado, por favor únete. Los jugadores son:\n\n{}", 19 | "mp_join_callback": "Bienvenid {}", 20 | "mp_game_already_begun_callback": "La partida ya ha empezado.", 21 | "mp_max_players_callback": "¡Ya no hay espacio para más jugadores!", 22 | "mp_already_joined_callback": "¡Ya te has unido a la partida!", 23 | "mp_no_created_game_callback": "¡No hay ninguna partida en curso!", 24 | "mp_starting_game_callback": "¡Comenzando la partida!", 25 | "mp_not_enough_players_callback": "¡Aún no hay suficientes jugadores!", 26 | "mp_only_creator_start_callback": "Lo siento {}, sólo el creador puede empezar la partida.", 27 | "mp_not_your_turn_callback": "¡No es tu turno, {}!", 28 | "game_starts_now": "La partida comienza ahora. 🎲\n\n{}Cartas del crupier:\n\n{}", 29 | "game_ended": "La partida ha terminado. 😉 Puedes comenzar otra con /start si lo deseas.", 30 | "mp_only_creator_can_end": "¡Sólo el creador puede finalizar la partida!", 31 | "mp_players_are": "Los jugadores son:\n", 32 | "no_permission": "¡No tienes permisos para hacer eso!", 33 | "select_lang": "Por favor elige tu idioma.", 34 | "lang_changed": "¡Hemos cambiado tu idioma a {}!", 35 | "got_blackjack": "✅ ¡Felicidades, has conseguido un BlackJack!", 36 | "got_21": "✅ ¡Felicidades, tienes exactamente 21!", 37 | "dealer_got_blackjack": "❌ El crupier tiene un BlackJack. Has perdido.", 38 | "dealer_got_21": "❌ El crupier está más cerca de 21. Has perdido.", 39 | "tied_with_dealer": "👌 Has empatado con el crupier.", 40 | "dealer_busted": "🏆 ¡Felicidades! El crupier se ha pasado, así que ganas esta ronda.", 41 | "closer_to_21": "🏆 ¡Felicidades! Ganas esta ronda por estar más cerca de 21.", 42 | "eval_heading_wins": "🔰 Victorias:", 43 | "eval_heading_ties": "👌 Empate:", 44 | "eval_heading_losses": "❌ Derrotas:", 45 | "send_comment": "Por favor envía un comentario (sólo texto) como respuesta a este mensaje. Se lo haremos llegar al creador.", 46 | "received_comment": "Gracias, tu comentario se ha enviado al creador.", 47 | "admin_reply": "⚠ ¡Necesitas responder al comentario del usuario!", 48 | "reply_from_maintainer": "El creador del bot te ha respondido:\n\n{}", 49 | "statistic_template": "Estas son tus estadísticas 📊:\n\nPartidas jugadas: {}\nPartidas ganadas: {}\nÚltima partida: {} UTC\n\n{}\n\nPorcentaje de victorias: {:.2%}", 50 | "dealer_name": "Crupier" 51 | } 52 | -------------------------------------------------------------------------------- /blackjackbot/lang/strings/translations_nl.json: -------------------------------------------------------------------------------- 1 | { 2 | "lang_code": "nl", 3 | "language_name": "Nederlands", 4 | "language_flag": "🇳🇱", 5 | "you_busted": "❌ Je hebt verloren!", 6 | "your_cards_are": "{} - Waarde: {}\n\n{}", 7 | "dealers_cards_are": "Dealer: {}\n\n{}", 8 | "inline_keyboard_hit": "Extra kaart", 9 | "inline_keyboard_stand": "Passen", 10 | "inline_keyboard_join": "Deelnemen", 11 | "inline_keyboard_start": "Beginnen", 12 | "inline_keyboard_newgame": "Nieuw spel", 13 | "card_ace": "Aas", 14 | "card_jack": "Boer", 15 | "card_queen": "Koningin", 16 | "card_king": "Koning", 17 | "cancel": "Annuleren", 18 | "mp_request_join": "Het spel is gemaakt, doe mee. De spelers zijn:\n\n{}", 19 | "mp_join_callback": "Welkom {}", 20 | "mp_game_already_begun_callback": "Het spel is al begonnen.", 21 | "mp_max_players_callback": "Het maximale aantal spelers is bereikt!", 22 | "mp_already_joined_callback": "Je neemt al deel aan het spel!", 23 | "mp_no_created_game_callback": "Er is nog geen spel gemaakt!", 24 | "mp_starting_game_callback": "Het spel begint!", 25 | "mp_not_enough_players_callback": "Er zijn nog niet genoeg spelers!", 26 | "mp_only_creator_start_callback": "Sorry {}, alleen de maker kan het spel starten!", 27 | "mp_not_your_turn_callback": "Je bent niet aan de beurt, {}!", 28 | "game_starts_now": "Het spel begint nu. 🎲\n\n{}De kaarten van de dealer:\n\n{}", 29 | "game_ended": "Het spel is gestopt. 😉 Je kan een nieuwe beginnen met /start, als je dat wilt.", 30 | "mp_only_creator_can_end": "Alleen de maker kan het spel stoppen!", 31 | "mp_players_are": "De spelers zijn:\n", 32 | "no_permission": "Je hebt niet de vereiste permissies om dat te doen!", 33 | "select_lang": "Kies je taal.", 34 | "lang_changed": "Ik heb je taal verandert naar het {}!", 35 | "got_blackjack": "✅ Gefeliciteerd, je hebt een blackjack!", 36 | "got_21": "✅ Gefeliciteerd, je hebt precies 21!", 37 | "dealer_got_blackjack": "❌ De dealer heeft een blackjack. Je hebt verloren.", 38 | "dealer_got_21": "❌ De dealer kwam dichter bij 21. Je hebt verloren.", 39 | "tied_with_dealer": "👌 Je hebt gelijkgespeeld met de dealer.", 40 | "dealer_busted": "🏆 Gefeliciteerd! De dealer verloor, waardoor je deze ronde wint.", 41 | "closer_to_21": "🏆 Gefeliciteerd! Je kwam dichter bij 21 en wint deze ronde.", 42 | "eval_heading_wins": "🔰 Overwinningen:", 43 | "eval_heading_ties": "👌 Gelijkspellen:", 44 | "eval_heading_losses": "❌ Nederlagen:", 45 | "send_comment": "Stuur nu je opmerking (alleen tekst) als een reactie op dit bericht. We zullen het doorsturen naar de beheerder.", 46 | "received_comment": "Bedankt, je opmerking is doorgestuurd naar de beheerder.", 47 | "admin_reply": "⚠ Je moet reageren op de opermking van de gebruiker!", 48 | "reply_from_maintainer": "De beheerder van deze bot heeft je een reactie gestuurd:\n\n{}", 49 | "statistic_template": "Hier zijn je statistieken 📊:\n\nGespeelde spellen: {}\nGewonnen spellen: {}\nLaatst gespeeld: {} UTC\n\n{}\n\nWinpercentage: {:.2%}", 50 | "dealer_name": "Dealer" 51 | } 52 | -------------------------------------------------------------------------------- /blackjackbot/lang/strings/translations_pl.json: -------------------------------------------------------------------------------- 1 | { 2 | "lang_code": "pl", 3 | "language_name": "Polski", 4 | "language_flag": "🇵🇱", 5 | "you_busted": "❌ Masz więcej niż 21 punktów, odpadasz.", 6 | "your_cards_are": "{} - Wartość: {}\n\n{}", 7 | "dealers_cards_are": "Kupier: {}\n\n{}", 8 | "inline_keyboard_hit": "Dobierz", 9 | "inline_keyboard_stand": "Nie dobieraj", 10 | "inline_keyboard_join": "Dołącz", 11 | "inline_keyboard_start": "Rozpocznij", 12 | "inline_keyboard_newgame": "Nowa gra", 13 | "card_ace": "As", 14 | "card_jack": "Walet", 15 | "card_queen": "Dama", 16 | "card_king": "Król", 17 | "cancel": "Anuluj", 18 | "mp_request_join": "Gra stworzona, proszę dołączyć. Obecni gracze:\n\n{}", 19 | "mp_join_callback": "Witaj {}", 20 | "mp_game_already_begun_callback": "Gra już się rozpoczęła.", 21 | "mp_max_players_callback": "Maksymalna liczba graczy została osiągnięta!", 22 | "mp_already_joined_callback": "Jesteś już w grze!", 23 | "mp_no_created_game_callback": "Nie ma w tej chwili żadnej gry!", 24 | "mp_starting_game_callback": "Gra się rozpoczyna!", 25 | "mp_not_enough_players_callback": "Brak wystarczającej ilości graczy!", 26 | "mp_only_creator_start_callback": "Wybacz {}, ale tylko host może rozpocząć grę!", 27 | "mp_not_your_turn_callback": "Poczekaj na swoją turę, {}!", 28 | "game_starts_now": "Gra się rozpoczęła. \uD83C\uDFB2\n\n{}Karty Krupiera:\n\n{}", 29 | "game_ended": "Gra się zakończyła. \uD83D\uDE09 Naciśnij /start by rozpocząć nową.", 30 | "mp_only_creator_can_end": "Tylko host może zakończyć grę!", 31 | "mp_players_are": "Gracze:\n", 32 | "no_permission": "Nie posiadasz odpowiednich uprawnień!", 33 | "select_lang": "Proszę wybierz swój język.", 34 | "lang_changed": "Twój język został zmieniony na {}!", 35 | "got_blackjack": "\u2705 Brawo, to BlackJack!", 36 | "got_21": "\u2705 Brawo, masz dokładnie 21 punktów!", 37 | "dealer_got_blackjack": "\u274C Krupier ma BlackJacka. Przegrywasz grę.", 38 | "dealer_got_21": "\u274C Krupier jest bliżej 21 punktów. Przegrywasz grę.", 39 | "tied_with_dealer": "\uD83D\uDC4C Remis!", 40 | "dealer_busted": "\uD83C\uDFC6 Brawo! Krupier odpadł więc wygrywasz grę.", 41 | "closer_to_21": "\uD83C\uDFC6 Brawo! Jesteś bliżej 21 punktów więc wygrywasz grę.", 42 | "eval_heading_wins": "\uD83D\uDD30 Zwycięstw:", 43 | "eval_heading_ties": "\uD83D\uDC4C Remisy:", 44 | "eval_heading_losses": "\u274C Przegrane:", 45 | "send_comment": "Wyślij swoją wiadomość tekstową jako odpowiedź do tej. Wiadomość ta zostanie przekazana bezpośrednio do właściciela tego bota.", 46 | "received_comment": "Dzięki, Twoja wiadomość została przekazana.", 47 | "admin_reply": "⚠ Musisz bezpośrednio odpowiedzieć na komentarz użytkownika!", 48 | "reply_from_maintainer": "Właściciel tego bota odpowiedział na Twój komentarz:\n\n{}", 49 | "statistic_template": "Twoje statystyki wyglądają następująco 📊:\n\nRozegrane gry: {}\nZwyciężone gry: {}\nOstatnio grano: {} UTC\n\n{}\n\nWspółczynnik zwycięstw: {:.2%}", 50 | "dealer_name": "Kupier" 51 | } 52 | -------------------------------------------------------------------------------- /blackjackbot/lang/strings/translations_pt-br.json: -------------------------------------------------------------------------------- 1 | { 2 | "lang_code": "pt-br", 3 | "language_name": "Português (Brasil)", 4 | "language_flag": "🇧🇷", 5 | "you_busted": "❌ Você estourou!", 6 | "your_cards_are": "{} - Valor: {}\n\n{}", 7 | "dealers_cards_are": "Dealer: {}\n\n{}", 8 | "inline_keyboard_hit": "Mais uma", 9 | "inline_keyboard_stand": "Parar", 10 | "inline_keyboard_join": "Entrar", 11 | "inline_keyboard_start": "Iniciar", 12 | "inline_keyboard_newgame": "Novo jogo", 13 | "card_ace": "Ás", 14 | "card_jack": "Valete", 15 | "card_queen": "Rainha", 16 | "card_king": "Rei", 17 | "cancel": "Cancelar", 18 | "mp_request_join": "Jogo criado, entre. Os jogadores são:\n\n{}", 19 | "mp_join_callback": "Bem-vindo {}", 20 | "mp_game_already_begun_callback": "O jogo já começou.", 21 | "mp_max_players_callback": "Limite máximo de jogadores atingido.", 22 | "mp_already_joined_callback": "Você já entrou nesse jogo!", 23 | "mp_no_created_game_callback": "Não existe um jogo criado!", 24 | "mp_starting_game_callback": "Iniciando o jogo!", 25 | "mp_not_enough_players_callback": "Ainda não há jogadores suficientes!", 26 | "mp_only_creator_start_callback": "Desculpe {}, apenas o criador pode iniciar o jogo!", 27 | "mp_not_your_turn_callback": "Não é a sua vez, {}!", 28 | "game_starts_now": "O jogo começa agora. 🎲\n\n{}Cartas do Dealer:\n\n{}", 29 | "game_ended": "O jogo foi encerrado. 😉 Você pode iniciar outro jogo com /start, caso queira.", 30 | "mp_only_creator_can_end": "Apenas o criador pode encerrar o jogo!", 31 | "mp_players_are": "Os jogadores são:\n", 32 | "no_permission": "Você não tem as permissões necessárias para fazer isso!", 33 | "select_lang": "Por favor, selecione seu idioma.", 34 | "lang_changed": "Eu alterei seu idioma para {}!", 35 | "got_blackjack": "✅ Parabéns, você pegou um BlackJack!", 36 | "got_21": "✅ Parabéns, você tirou exatamente 21!", 37 | "dealer_got_blackjack": "❌ O dealer pegou um BlackJack. Você perdeu.", 38 | "dealer_got_21": "❌ O dealer está mais próximo de 21. Você perdeu.", 39 | "tied_with_dealer": "👌 Você empatou com o dealer.", 40 | "dealer_busted": "🏆 Parabéns! O dealer estourou, então você ganhou essa rodada.", 41 | "closer_to_21": "🏆 Parabéns! Você está mais próximo de 21 e ganhou essa rodada.", 42 | "eval_heading_wins": "🔰 Vitórias:", 43 | "eval_heading_ties": "👌 Empates:", 44 | "eval_heading_losses": "❌ Derrotas:", 45 | "send_comment": "Por favor, envie seu comentário (somente texto) como resposta à essa mensagem agora. Encaminharemos isso para o desenvolvedor.", 46 | "received_comment": "Obrigado, seu comentário será encaminhado para o desenvolvedor.", 47 | "admin_reply": "⚠ Você precisa responder ao comentário do usuário!", 48 | "reply_from_maintainer": "O desenvolvedor desse bot te enviou uma resposta:\n\n{}", 49 | "statistic_template": "Aqui estão suas estatísticas 📊:\n\nJogos: {}\nVitórias: {}\nÚltimo jogo: {} UTC\n\n{}\n\nPorcentagem de vitórias: {:.2%}", 50 | "dealer_name": "Dealer" 51 | } 52 | -------------------------------------------------------------------------------- /blackjackbot/lang/strings/translations_ru.json: -------------------------------------------------------------------------------- 1 | { 2 | "lang_code": "ru", 3 | "language_name": "Pусский", 4 | "language_flag": "🇷🇺", 5 | "you_busted": "❌ Вы проиграли!", 6 | "your_cards_are": "{} - Значение: {}\n\n{}", 7 | "dealers_cards_are": "Дилер: {}\n\n{}", 8 | "inline_keyboard_hit": "Ставка", 9 | "inline_keyboard_stand": "Хватит", 10 | "inline_keyboard_join": "Войти", 11 | "inline_keyboard_start": "Начать", 12 | "inline_keyboard_newgame": "Новая игра", 13 | "card_ace": "Туз", 14 | "card_jack": "Валет", 15 | "card_queen": "Дама", 16 | "card_king": "Король", 17 | "cancel": "Отмена", 18 | "mp_request_join": "Игра создана, присоединяйтесь. Игроки:\n\n{}", 19 | "mp_join_callback": "Добро пожаловать {}", 20 | "mp_game_already_begun_callback": "Игра уже началась.", 21 | "mp_max_players_callback": "Достигнуто максимальное количество игроков!", 22 | "mp_already_joined_callback": "Вы уже в игре!", 23 | "mp_no_created_game_callback": "Созданной игры не существует!", 24 | "mp_starting_game_callback": "Запускаем игру!", 25 | "mp_not_enough_players_callback": "Игроков недостаточно!", 26 | "mp_only_creator_start_callback": "Извините {}, только создатель может начать игру!", 27 | "mp_not_your_turn_callback": "Не Ваш ход, {}!", 28 | "game_starts_now": "Игра начинается. 🎲\n\n{}Карты дилера:\n\n{}", 29 | "game_ended": "Игра закончена. 😉 Вы можете начать новую игру, прописав /start", 30 | "mp_only_creator_can_end": "Только создатель может закончить игру!", 31 | "mp_players_are": "Игроки:\n", 32 | "no_permission": "У Вас недостаточно прав для этого действия!", 33 | "select_lang": "Пожалуйста, выберите Ваш язык.", 34 | "lang_changed": "Язык успешно сменен на {}!", 35 | "got_blackjack": "✅ Успех, у Вас БлекДжек!", 36 | "got_21": "✅ Поздравляем, Вы набрали ровно 21!", 37 | "dealer_got_blackjack": "❌ У дилера БлекДжек. Вы проиграли.", 38 | "dealer_got_21": "❌ Дилер набрал 21. Вы проиграли.", 39 | "tied_with_dealer": "👌 Вы сыграли в ничью с дилером.", 40 | "dealer_busted": "🏆 Поздравляем! Дилер проиграл, победа Ваша!", 41 | "closer_to_21": "🏆 Поздравляем! Вы приблизились к 21 и одержали победу.", 42 | "eval_heading_wins": "🔰 Победы:", 43 | "eval_heading_ties": "👌 Ничьи:", 44 | "eval_heading_losses": "❌ Проигрыши:", 45 | "send_comment": "Пожалуйста, оставьте Ваш комментарий (только текст) в качестве ответа к этому сообщению. Мы отправим его обслуживающему персоналу.", 46 | "received_comment": "Спасибо, Ваш комментарий был передан обслуживающему персоналу.", 47 | "admin_reply": "⚠ Вам необходимо ответить на комментарий пользователя!", 48 | "reply_from_maintainer": "Обслуживающий персонал прислал Вам ответ:\n\n{}", 49 | "statistic_template": "Ваша статистика 📊:\n\nКоличество игр:{}\nПобеды:{}\nПоследняя игра: {} UTC\n\n{}\n\nПроцент побед:{:.2%}" 50 | } 51 | -------------------------------------------------------------------------------- /blackjackbot/lang/tests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | -------------------------------------------------------------------------------- /blackjackbot/lang/tests/language_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | class LanguageTest(unittest.TestCase): 5 | 6 | def setUp(self): 7 | pass 8 | 9 | def test_translate(self): 10 | pass 11 | 12 | 13 | if __name__ == '__main__': 14 | unittest.main() 15 | -------------------------------------------------------------------------------- /blackjackbot/util/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from .textutils import build_menu 4 | from .misc import get_cards_string 5 | from .userstate import UserState 6 | 7 | __all__ = ['build_menu', 'get_cards_string', 'UserState'] 8 | -------------------------------------------------------------------------------- /blackjackbot/util/misc.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from blackjack.game import Card 4 | from blackjackbot.lang import translate 5 | 6 | 7 | def get_cards_string(player, lang_id): 8 | """Returns the translated string representation of a player's hand""" 9 | if player.is_dealer and not player.turn_over: 10 | # We need to check, if we are allowed to display all of the dealer's cards already 11 | # Only the dealer's first card is shown until the dealer finished their turn 12 | return "{} • [❔]".format(get_card_string(player.cards[0], lang_id)) 13 | else: 14 | return ' • '.join(get_card_string(card, lang_id) for card in player.cards) 15 | 16 | 17 | def get_card_string(card, lang_id): 18 | """Returns the translated string representation of a card object""" 19 | if card.type == Card.Type.NUMBER: 20 | face = card.value 21 | else: 22 | face = translate(card.str_id, lang_code=lang_id) 23 | 24 | return "{} {}".format(card.symbol, face) 25 | -------------------------------------------------------------------------------- /blackjackbot/util/tests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | -------------------------------------------------------------------------------- /blackjackbot/util/tests/misc_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from unittest.mock import Mock 3 | from blackjack.game import Card 4 | from blackjackbot.util import get_cards_string 5 | 6 | 7 | class MiscTest(unittest.TestCase): 8 | 9 | def test_get_cards_string_dealer(self): 10 | player = Mock() 11 | player.is_dealer = True 12 | player.turn_over = False 13 | card = Card(12) # Heart Ace 14 | card2 = Card(6) # Heart eight 15 | player.cards = [card, card2] 16 | 17 | self.assertEqual("♥ Ace • [❔]", get_cards_string(player, "en")) 18 | self.assertEqual("♥ Ass • [❔]", get_cards_string(player, "de")) 19 | 20 | player.cards = [card2, card] 21 | 22 | self.assertEqual("♥ 8 • [❔]", get_cards_string(player, "en")) 23 | self.assertEqual("♥ 8 • [❔]", get_cards_string(player, "de")) 24 | 25 | def test_get_cards_string_dealer_turn_over(self): 26 | player = Mock() 27 | player.is_dealer = True 28 | player.turn_over = True 29 | card = Card(12) # Heart Ace 30 | card2 = Card(6) # Heart eight 31 | player.cards = [card, card2] 32 | 33 | self.assertEqual("♥ Ace • ♥ 8", get_cards_string(player, "en")) 34 | self.assertEqual("♥ Ass • ♥ 8", get_cards_string(player, "de")) 35 | 36 | player.cards = [card2, card] 37 | 38 | self.assertEqual("♥ 8 • ♥ Ace", get_cards_string(player, "en")) 39 | self.assertEqual("♥ 8 • ♥ Ass", get_cards_string(player, "de")) 40 | 41 | def test_get_cards_string_player(self): 42 | player = Mock() 43 | player.is_dealer = False 44 | player.turn_over = False 45 | card = Card(11) # Heart King 46 | card2 = Card(6) # Heart eight 47 | player.cards = [card, card2] 48 | 49 | self.assertEqual("♥ King • ♥ 8", get_cards_string(player, "en")) 50 | self.assertEqual("♥ König • ♥ 8", get_cards_string(player, "de")) 51 | 52 | # Changing the turn_over value shouldn't have any effect 53 | player.turn_over = True 54 | self.assertEqual("♥ King • ♥ 8", get_cards_string(player, "en")) 55 | self.assertEqual("♥ König • ♥ 8", get_cards_string(player, "de")) 56 | 57 | def test_get_cards_string_player_multiple(self): 58 | player = Mock() 59 | player.is_dealer = False 60 | player.turn_over = False 61 | card = Card(10) # Heart Queen 62 | card2 = Card(6) # Heart eight 63 | card3 = Card(22) # Diamond Jack 64 | player.cards = [card, card2, card3] 65 | 66 | self.assertEqual("♥ Queen • ♥ 8 • ♦ Jack", get_cards_string(player, "en")) 67 | self.assertEqual("♥ Dame • ♥ 8 • ♦ Bube", get_cards_string(player, "de")) 68 | 69 | def test_get_card_string(self): 70 | pass 71 | 72 | 73 | if __name__ == '__main__': 74 | unittest.main() 75 | -------------------------------------------------------------------------------- /blackjackbot/util/tests/textutils_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import unittest 3 | from unittest.mock import Mock 4 | 5 | from blackjackbot.util import build_menu 6 | 7 | 8 | class TextutilsTest(unittest.TestCase): 9 | 10 | def test_build_menu_1b_1c(self): 11 | """Test if splitting up one buttons in one column works as intended""" 12 | button1 = Mock() 13 | b = [button1] 14 | m = build_menu(b, 1) 15 | 16 | # Assert there is a single row 17 | self.assertEqual(1, len(m)) 18 | 19 | # Assert that there is only a single button 20 | self.assertEqual(1, len(m[0])) 21 | 22 | def test_build_menu_2b_1c(self): 23 | """Test if splitting up two buttons in one column works as intended""" 24 | button1 = Mock() 25 | b = [button1, button1] 26 | m = build_menu(b, 1) # Menu has 1 column => 2 rows 27 | 28 | # We have two rows (one button per row) 29 | self.assertEqual(2, len(m)) 30 | 31 | def test_build_menu_2b_2c(self): 32 | """Test if splitting up two buttons in two columns works as intended""" 33 | button1 = Mock() 34 | b = [button1, button1] 35 | m = build_menu(b, 2) 36 | 37 | # Assert that there is only one row 38 | self.assertEqual(1, len(m)) 39 | 40 | # Assert that first row has 2 buttons 41 | self.assertEqual(2, len(m[0])) 42 | 43 | def test_build_menu_2b_3c(self): 44 | """Test if splitting up two buttons in three columns works as intended""" 45 | button1 = Mock() 46 | b = [button1, button1] 47 | m = build_menu(b, 3) # Menu has 3 columns => 2 rows 48 | 49 | # We have two rows (one button per row) 50 | self.assertEqual(1, len(m)) 51 | 52 | # Assert that first row has 2 buttons 53 | self.assertEqual(2, len(m[0])) 54 | 55 | def test_build_menu_3(self): 56 | """Test if splitting up the buttons in several rows works as intended""" 57 | button1 = Mock() 58 | b = [button1, button1, button1, button1, button1] 59 | m = build_menu(b, 2) 60 | 61 | # We have 3 rows 62 | self.assertEqual(3, len(m)) 63 | 64 | # First row has 2 buttons 65 | self.assertEqual(2, len(m[0])) 66 | # Second row has 2 buttons 67 | self.assertEqual(2, len(m[1])) 68 | # Third row has one button 69 | self.assertEqual(1, len(m[2])) 70 | 71 | def test_header(self): 72 | """Test if adding a header button works as intended""" 73 | button1 = Mock() 74 | button2 = Mock() 75 | b = [button1, button1, button1, button1, button1] 76 | 77 | header = button2 78 | m = build_menu(b, 2, header_buttons=header) 79 | 80 | # Make sure there is only a single header button 81 | self.assertEqual(1, len(m[0])) 82 | 83 | # Check that this header button is actually the first button of the menu 84 | self.assertEqual(button2, m[0][0]) 85 | 86 | def test_footer(self): 87 | button1 = Mock() 88 | button2 = Mock() 89 | b = [button1, button1, button1, button1, button1] 90 | 91 | footer = button2 92 | m = build_menu(b, 2, footer_buttons=footer) 93 | 94 | # Make sure there is only a single footer button 95 | self.assertEqual(1, len(m[-1])) 96 | 97 | # Check that this footer button is actually the last button of the menu 98 | self.assertEqual(button2, m[-1][0]) 99 | 100 | 101 | if __name__ == '__main__': 102 | unittest.main() 103 | -------------------------------------------------------------------------------- /blackjackbot/util/textutils.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | def build_menu(buttons, n_cols, header_buttons=None, footer_buttons=None): 5 | menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)] 6 | if header_buttons: 7 | menu.insert(0, [header_buttons]) 8 | if footer_buttons: 9 | menu.append([footer_buttons]) 10 | return menu 11 | -------------------------------------------------------------------------------- /blackjackbot/util/userstate.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from enum import Enum 3 | 4 | 5 | class UserState(Enum): 6 | COMMENTING = 0 7 | IDLE = 1 8 | -------------------------------------------------------------------------------- /bot.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import logging 4 | import logging.handlers 5 | import pathlib 6 | 7 | from telegram.ext import Updater, JobQueue 8 | 9 | import config 10 | from blackjackbot import handlers, error_handler 11 | from blackjackbot.gamestore import GameStore 12 | 13 | logdir_path = pathlib.Path(__file__).parent.joinpath("logs").absolute() 14 | logfile_path = logdir_path.joinpath("bot.log") 15 | 16 | if not logdir_path.exists(): 17 | logdir_path.mkdir() 18 | 19 | logfile_handler = logging.handlers.WatchedFileHandler(logfile_path, "a", "utf-8") 20 | 21 | loglevels = {"debug": logging.DEBUG, "error": logging.DEBUG, "fatal": logging.FATAL, "info": logging.INFO} 22 | loglevel = loglevels.get(config.LOGLEVEL, logging.INFO) 23 | 24 | logger = logging.getLogger(__name__) 25 | logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=loglevel, handlers=[logfile_handler, logging.StreamHandler()]) 26 | logging.getLogger("telegram").setLevel(logging.ERROR) 27 | logging.getLogger("apscheduler").setLevel(logging.ERROR) 28 | 29 | updater = Updater(token=config.BOT_TOKEN, use_context=True) 30 | 31 | for handler in handlers: 32 | updater.dispatcher.add_handler(handler) 33 | 34 | updater.dispatcher.add_error_handler(error_handler) 35 | 36 | 37 | # Set up jobs 38 | def stale_game_cleaner(context): 39 | gs = GameStore() 40 | gs.cleanup_stale_games() 41 | 42 | 43 | updater.job_queue.run_repeating(callback=stale_game_cleaner, interval=300, first=300) 44 | 45 | 46 | if config.USE_WEBHOOK: 47 | updater.start_webhook(listen=config.WEBHOOK_IP, port=config.WEBHOOK_PORT, url_path=config.BOT_TOKEN, cert=config.CERTPATH, webhook_url=config.WEBHOOK_URL) 48 | updater.bot.set_webhook(config.WEBHOOK_URL) 49 | logger.info("Started webhook server!") 50 | else: 51 | updater.start_polling() 52 | logger.info("Started polling!") 53 | 54 | logger.info("Bot started as @{}".format(updater.bot.username)) 55 | updater.idle() 56 | -------------------------------------------------------------------------------- /config.sample.py: -------------------------------------------------------------------------------- 1 | BOT_TOKEN = "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11" 2 | USE_WEBHOOK = False 3 | WEBHOOK_IP = "127.0.0.1" 4 | WEBHOOK_PORT = 9001 5 | WEBHOOK_URL = "https://domain.example.com/" + BOT_TOKEN 6 | CERTPATH = "/etc/certs/example.com/fullchain.cer" 7 | LOGLEVEL = "INFO" 8 | -------------------------------------------------------------------------------- /database/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from .database import Database 3 | 4 | __all__ = ['Database'] 5 | -------------------------------------------------------------------------------- /database/database.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import logging 3 | import os 4 | import sqlite3 5 | from time import time 6 | 7 | from util import Cache 8 | 9 | 10 | class Database(object): 11 | dir_path = os.path.dirname(os.path.abspath(__file__)) 12 | 13 | _instance = None 14 | _initialized = False 15 | _banned_users = set() 16 | 17 | def __new__(cls): 18 | if not Database._instance: 19 | Database._instance = super(Database, cls).__new__(cls) 20 | return Database._instance 21 | 22 | def __init__(self): 23 | if self._initialized: 24 | return 25 | 26 | database_path = os.path.join(self.dir_path, "users.db") 27 | self.logger = logging.getLogger(__name__) 28 | 29 | if not os.path.exists(database_path): 30 | self.logger.debug("File '{}' does not exist! Trying to create one.".format(database_path)) 31 | try: 32 | self.create_database(database_path) 33 | except Exception: 34 | self.logger.error("An error has occurred while creating the database!") 35 | 36 | self.connection = sqlite3.connect(database_path) 37 | self.connection.row_factory = sqlite3.Row 38 | self.connection.text_factory = lambda x: str(x, 'utf-8', "ignore") 39 | self.cursor = self.connection.cursor() 40 | 41 | self.load_banned_users() 42 | 43 | self._initialized = True 44 | 45 | @staticmethod 46 | def create_database(database_path): 47 | """ 48 | Create database file and add admin and users table to the database 49 | :param database_path: 50 | :return: 51 | """ 52 | open(database_path, 'a').close() 53 | 54 | connection = sqlite3.connect(database_path) 55 | connection.text_factory = lambda x: str(x, 'utf-8', "ignore") 56 | cursor = connection.cursor() 57 | 58 | cursor.execute("CREATE TABLE IF NOT EXISTS 'admins' " 59 | "('user_id' INTEGER NOT NULL," 60 | "'first_name' TEXT," 61 | "'username' TEXT," 62 | "PRIMARY KEY('user_id'));") 63 | 64 | cursor.execute("CREATE TABLE IF NOT EXISTS 'users'" 65 | "('user_id' INTEGER NOT NULL," 66 | "'first_name' TEXT," 67 | "'last_name' TEXT," 68 | "'username' TEXT," 69 | "'games_played' INTEGER DEFAULT 0," 70 | "'games_won' INTEGER DEFAULT 0," 71 | "'games_tie' INTEGER DEFAULT 0," 72 | "'last_played' INTEGER DEFAULT 0," 73 | "'banned' INTEGER DEFAULT 0," 74 | "PRIMARY KEY('user_id'));") 75 | 76 | cursor.execute("CREATE TABLE IF NOT EXISTS 'chats'" 77 | "('chat_id' INTEGER NOT NULL," 78 | "'lang_id' TEXT NOT NULL DEFAULT 'en'," 79 | "PRIMARY KEY('chat_id'));") 80 | connection.commit() 81 | connection.close() 82 | 83 | def load_banned_users(self): 84 | """Loads all banned users from the database into a list""" 85 | self.cursor.execute("SELECT user_id FROM users WHERE banned=1;") 86 | result = self.cursor.fetchall() 87 | 88 | if not result: 89 | return 90 | 91 | for row in result: 92 | self._banned_users.add(int(row["user_id"])) 93 | 94 | def get_banned_users(self): 95 | """Returns a list of all banned user_ids""" 96 | return self._banned_users 97 | 98 | def get_user(self, user_id): 99 | self.cursor.execute("SELECT user_id, first_name, last_name, username, games_played, games_won, games_tie, last_played, banned" 100 | " FROM users WHERE user_id=?;", [str(user_id)]) 101 | 102 | result = self.cursor.fetchone() 103 | if not result or len(result) == 0: 104 | return None 105 | return result 106 | 107 | def is_user_banned(self, user_id): 108 | """Checks if a user was banned by the admin of the bot from using it""" 109 | # user = self.get_user(user_id) 110 | # return user is not None and user[8] == 1 111 | return int(user_id) in self._banned_users 112 | 113 | def ban_user(self, user_id): 114 | """Bans a user from using a the bot""" 115 | self.cursor.execute("UPDATE users SET banned=1 WHERE user_id=?;", [str(user_id)]) 116 | self.connection.commit() 117 | self._banned_users.add(int(user_id)) 118 | 119 | def unban_user(self, user_id): 120 | """Unbans a user from using a the bot""" 121 | self.cursor.execute("UPDATE users SET banned=0 WHERE user_id=?;", [str(user_id)]) 122 | self.connection.commit() 123 | self._banned_users.remove(int(user_id)) 124 | 125 | def get_recent_players(self): 126 | one_day_in_secs = 60 * 60 * 24 127 | current_time = int(time()) 128 | self.cursor.execute("SELECT user_id FROM users WHERE last_played>=?;", [current_time - one_day_in_secs]) 129 | 130 | return self.cursor.fetchall() 131 | 132 | def get_played_games(self, user_id): 133 | self.cursor.execute("SELECT games_played FROM users WHERE user_id=?;", [str(user_id)]) 134 | result = self.cursor.fetchone() 135 | 136 | if not result or len(result) <= 0: 137 | return 0 138 | 139 | return int(result["games_played"]) 140 | 141 | @Cache(timeout=60) 142 | def get_admins(self): 143 | self.cursor.execute("SELECT user_id from admins;") 144 | admins = self.cursor.fetchall() 145 | admin_list = [] 146 | for admin in admins: 147 | admin_list.append(admin["user_id"]) 148 | return admin_list 149 | 150 | @Cache(timeout=120) 151 | def get_lang_id(self, chat_id): 152 | self.cursor.execute("SELECT lang_id FROM chats WHERE chat_id=?;", [str(chat_id)]) 153 | result = self.cursor.fetchone() 154 | 155 | if not result or not result["lang_id"]: 156 | # Make sure that the database stored an actual value and not "None" 157 | return "en" 158 | 159 | return result["lang_id"] 160 | 161 | def set_lang_id(self, chat_id, lang_id): 162 | if lang_id is None: 163 | lang_id = "en" 164 | Cache().invalidate_lang_cache(chat_id) 165 | try: 166 | self.cursor.execute("INSERT INTO chats (chat_id, lang_id) VALUES(?, ?);", [chat_id, lang_id]) 167 | except sqlite3.IntegrityError: 168 | self.cursor.execute("UPDATE chats SET lang_id = ? WHERE chat_id = ?;", [lang_id, chat_id]) 169 | self.connection.commit() 170 | 171 | def add_user(self, user_id, lang_id, first_name, last_name, username): 172 | if self.is_user_saved(user_id): 173 | return 174 | self._add_user(user_id, lang_id, first_name, last_name, username) 175 | 176 | def _add_user(self, user_id, lang_id, first_name, last_name, username): 177 | try: 178 | self.cursor.execute("INSERT INTO users VALUES (?, ?, ?, ?, 0, 0, 0, 0, 0);", [str(user_id), first_name, last_name, username]) 179 | self.cursor.execute("INSERT INTO chats VALUES (?, ?);", [str(user_id), lang_id]) 180 | self.connection.commit() 181 | except sqlite3.IntegrityError: 182 | return 183 | 184 | def set_games_won(self, games_won, user_id): 185 | self.cursor.execute("UPDATE users SET games_won = ? WHERE user_id = ?;", [games_won, str(user_id)]) 186 | self.connection.commit() 187 | 188 | def set_games_played(self, games_played, user_id): 189 | self.cursor.execute("UPDATE users SET games_played = ? WHERE user_id = ?;", [games_played, str(user_id)]) 190 | self.connection.commit() 191 | 192 | def set_last_played(self, last_played, user_id): 193 | self.cursor.execute("UPDATE users SET last_played = ? WHERE user_id = ?;", [last_played, str(user_id)]) 194 | self.connection.commit() 195 | 196 | def is_user_saved(self, user_id): 197 | self.cursor.execute("SELECT rowid, * FROM users WHERE user_id=?;", [str(user_id)]) 198 | 199 | result = self.cursor.fetchall() 200 | if len(result) > 0: 201 | return True 202 | else: 203 | return False 204 | 205 | def user_data_changed(self, user_id, first_name, last_name, username): 206 | self.cursor.execute("SELECT * FROM users WHERE user_id=?;", [str(user_id)]) 207 | result = self.cursor.fetchone() 208 | 209 | # check if user is saved 210 | if not result: 211 | return True 212 | 213 | if result["first_name"] == first_name and result["last_name"] == last_name and result["username"] == username: 214 | return False 215 | 216 | return True 217 | 218 | def update_user_data(self, user_id, first_name, last_name, username): 219 | self.cursor.execute("UPDATE users SET first_name=?, last_name=?, username=? WHERE user_id=?;", [first_name, last_name, username, str(user_id)]) 220 | self.connection.commit() 221 | 222 | def reset_stats(self, user_id): 223 | self.cursor.execute("UPDATE users SET games_played='0', games_won='0', games_tie='0', last_played='0' WHERE user_id=?;", [str(user_id)]) 224 | self.connection.commit() 225 | 226 | def close_conn(self): 227 | self.connection.close() 228 | -------------------------------------------------------------------------------- /database/statistics.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import logging 3 | from datetime import datetime 4 | from time import time 5 | 6 | from blackjackbot.lang import translate 7 | from database import Database 8 | 9 | logger = logging.getLogger(__name__) 10 | 11 | 12 | def set_game_won(user_id): 13 | if user_id > 0: 14 | db = Database() 15 | user = db.get_user(user_id) 16 | if user is None: 17 | logger.warning("User '{}' is None - can't set won games!".format(user)) 18 | return 19 | games_won = int(user[5]) + 1 20 | logger.debug("Add game won for user: {}".format(user_id)) 21 | db.set_games_won(games_won, user_id) 22 | 23 | 24 | def add_game_played(user_id): 25 | db = Database() 26 | games_played = db.get_played_games(user_id) 27 | games_played = games_played + 1 28 | logger.debug("Add game played for user: {}".format(user_id)) 29 | db.set_games_played(games_played, user_id) 30 | db.set_last_played(str(int(time())), user_id) 31 | 32 | 33 | def generate_bar_chart(win_percentage): 34 | """ 35 | Generate a string of emojis representing a bar (10 chars) that indicates wins vs. losses 36 | :param win_percentage: The percentage of wins 37 | :return: Example (55.0%-64.9%) '🏆🏆🏆🏆🏆🏆🔴🔴🔴🔴' 38 | """ 39 | win_portion = round(win_percentage / 10) 40 | loss_portion = 10 - win_portion 41 | return "🏆" * win_portion + "🔴" * loss_portion 42 | 43 | 44 | def get_user_stats(user_id): 45 | """ 46 | Generates and returns a string displaying the statistics of a user 47 | :param user_id: The user_id of a specific user 48 | :return: 49 | """ 50 | user = Database().get_user(user_id) 51 | 52 | if user is None: 53 | logger.warning("User '{}' is not stored in the database!".format(user_id)) 54 | return "No statistics found!" 55 | 56 | lang_id = Database().get_lang_id(user_id) 57 | 58 | try: 59 | played_games, won_games, _, last_played = user[4:8] 60 | except ValueError as e: 61 | logger.warning("Cannot unpack user - {}".format(e)) 62 | raise 63 | 64 | if played_games == 0: 65 | # prevent division by zero errors 66 | return translate("no_stats") 67 | 68 | last_played_formatted = datetime.utcfromtimestamp(last_played).strftime('%d.%m.%y %H:%M') 69 | win_percentage = round(float(won_games) / float(played_games), 4) 70 | bar = generate_bar_chart(win_percentage * 100) 71 | template = translate("statistic_template", lang_id) 72 | statistics_string = template.format(played_games, won_games, last_played_formatted, bar, win_percentage) 73 | return statistics_string 74 | -------------------------------------------------------------------------------- /database/tests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | -------------------------------------------------------------------------------- /database/tests/statistics_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import unittest 3 | 4 | import database.statistics 5 | from database import Database 6 | 7 | 8 | class StatisticsTest(unittest.TestCase): 9 | pass 10 | 11 | def setUp(self): 12 | pass 13 | 14 | def test_generate_bar_chart(self): 15 | """Test generation of bar charts""" 16 | bar_0_wins = "🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴" 17 | bar_1_wins = "🏆🔴🔴🔴🔴🔴🔴🔴🔴🔴" 18 | bar_2_wins = "🏆🏆🔴🔴🔴🔴🔴🔴🔴🔴" 19 | bar_3_wins = "🏆🏆🏆🔴🔴🔴🔴🔴🔴🔴" 20 | bar_9_wins = "🏆🏆🏆🏆🏆🏆🏆🏆🏆🔴" 21 | bar_10_wins = "🏆🏆🏆🏆🏆🏆🏆🏆🏆🏆" 22 | 23 | bar1 = database.statistics.generate_bar_chart(0) 24 | self.assertEqual(bar_0_wins, bar1) 25 | bar2 = database.statistics.generate_bar_chart(0.5) 26 | self.assertEqual(bar_0_wins, bar2) 27 | bar3 = database.statistics.generate_bar_chart(5.0) 28 | self.assertEqual(bar_0_wins, bar3) 29 | 30 | bar4 = database.statistics.generate_bar_chart(5.1) 31 | self.assertEqual(bar_1_wins, bar4) 32 | 33 | bar5 = database.statistics.generate_bar_chart(11) 34 | self.assertEqual(bar_1_wins, bar5) 35 | 36 | bar6 = database.statistics.generate_bar_chart(16) 37 | self.assertEqual(bar_2_wins, bar6) 38 | 39 | bar7 = database.statistics.generate_bar_chart(29) 40 | self.assertEqual(bar_3_wins, bar7) 41 | 42 | bar8 = database.statistics.generate_bar_chart(91) 43 | self.assertEqual(bar_9_wins, bar8) 44 | 45 | bar9 = database.statistics.generate_bar_chart(100) 46 | self.assertEqual(bar_10_wins, bar9) 47 | 48 | def test_set_game_won(self): 49 | user_id = 123 50 | db = Database() 51 | db.add_user(user_id, "en", "test", "test2", "test3") 52 | 53 | user = db.get_user(user_id) 54 | self.assertEqual(user[5], 0) 55 | 56 | database.statistics.set_game_won(user_id) 57 | 58 | user = db.get_user(user_id) 59 | self.assertEqual(user[5], 1) 60 | 61 | database.statistics.set_game_won(user_id) 62 | 63 | user = db.get_user(user_id) 64 | self.assertEqual(user[5], 2) 65 | 66 | if __name__ == '__main__': 67 | unittest.main() 68 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | services: 3 | bot: 4 | restart: always 5 | image: 0rickyy0/blackjackbot 6 | volumes: 7 | # Speficy the paths to the log directory, user.db and config.py 8 | # Only modify the path on the left side of the colon 9 | - /path/to/logs:/blackjackbot/logs 10 | - /path/to/users.db:/blackjackbot/database/users.db 11 | - /path/to/config.py:/blackjackbot/config.py 12 | ports: 13 | # Ports for the webhook server - not needed if you use long polling 14 | - 127.0.0.1:8080:80 15 | -------------------------------------------------------------------------------- /gamehandler.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import random 4 | import string 5 | from typing import Optional 6 | 7 | from game.blackJackGame_old import BlackJackGame 8 | 9 | __author__ = 'Rico' 10 | 11 | 12 | # game_handler handles the blackJack-game-objects. When a new game is created, it is saved in the "game_list" 13 | class GameHandler(object): 14 | class __GameHandler(object): 15 | def __init__(self): 16 | self.game_list = [] # List, where the running Games are stored in 17 | pass 18 | 19 | def gl_create(self) -> None: 20 | self.game_list = [] 21 | 22 | def gl_remove(self, chat_id: int) -> None: 23 | index = self.get_index_by_chatid(chat_id) 24 | if index is None: 25 | return 26 | if not index < 0: 27 | self.game_list.pop(index) 28 | 29 | def get_index_by_chatid(self, chat_id: int) -> Optional[int]: 30 | for index, game in enumerate(self.game_list): 31 | if game.chat_id == chat_id: 32 | return index 33 | else: 34 | for player in game.players: 35 | if player.user_id == chat_id: 36 | return index 37 | 38 | return None 39 | 40 | def add_game(self, blackjackgame: BlackJackGame) -> None: 41 | self.game_list.append(blackjackgame) 42 | 43 | def get_game_by_chatid(self, chat_id: int) -> Optional[BlackJackGame]: 44 | index = self.get_index_by_chatid(chat_id) 45 | if index is None: 46 | return None 47 | return self.game_list[index] 48 | 49 | def get_game_by_index(self, index: int) -> BlackJackGame: 50 | return self.game_list[index] 51 | 52 | def get_game_by_id(self, game_id: int) -> Optional[BlackJackGame]: 53 | if game_id is None: 54 | return None 55 | for game in self.game_list: 56 | if game.game_id == game_id: 57 | return game 58 | return None 59 | 60 | def generate_id(self) -> str: 61 | """Generates a random ID for a game""" 62 | game_id = ''.join(random.choice(string.digits + string.ascii_letters) for _ in range(8)) 63 | 64 | while self.id_already_existing(game_id): 65 | print("ID already existing: " + str(game_id)) 66 | game_id = ''.join(random.choice(string.digits + string.ascii_letters) for _ in range(8)) 67 | 68 | return game_id 69 | 70 | def id_already_existing(self, game_id: str) -> bool: 71 | """Checks if an ID is already existing in the list of games""" 72 | for game in self.game_list: 73 | if game.game_id == game_id: 74 | return True 75 | 76 | return False 77 | 78 | instance = None 79 | 80 | def __init__(self): 81 | if not GameHandler.instance: 82 | GameHandler.instance = GameHandler.__GameHandler() 83 | 84 | @staticmethod 85 | def get_instance() -> __GameHandler: 86 | if not GameHandler.instance: 87 | GameHandler.instance = GameHandler.__GameHandler() 88 | 89 | return GameHandler.instance 90 | -------------------------------------------------------------------------------- /logs/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/d-Rickyy-b/Python-BlackJackBot/3d93215a5027ff611e56c6889d3394aefacb4d6e/logs/.keep -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | python-telegram-bot>=13.5, <20 2 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [flake8] 2 | exclude = .git,__pycache__,build,dist,.env,.venv,venv 3 | max-line-length = 160 4 | ignore = E501 -------------------------------------------------------------------------------- /util/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from .bannedusercallback import banned_user_callback 3 | from .banneduserhandler import BannedUserHandler 4 | from .cache import Cache 5 | 6 | __all__ = ["Cache", "BannedUserHandler", "banned_user_callback"] 7 | -------------------------------------------------------------------------------- /util/bannedusercallback.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | def banned_user_callback(update, context): 4 | """Gets called by the dispatcher when it's found that the user sending the update was banned from using the bot""" 5 | banned_text = "You have been banned from using this bot!" 6 | 7 | if update.callback_query: 8 | update.callback_query.answer(banned_text) 9 | else: 10 | update.effective_message.reply_text(banned_text) 11 | -------------------------------------------------------------------------------- /util/banneduserhandler.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import logging 3 | 4 | from telegram.ext import TypeHandler 5 | 6 | import database 7 | 8 | 9 | class BannedUserHandler(TypeHandler): 10 | logger = logging.getLogger() 11 | 12 | def check_update(self, update): 13 | db = database.Database() 14 | user = update.effective_user 15 | 16 | if user is None: 17 | self.logger.warning(f"User is None! Update: {update}") 18 | return False 19 | 20 | if db.is_user_banned(user.id): 21 | return True 22 | 23 | return False 24 | -------------------------------------------------------------------------------- /util/cache.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Reference: https://code.activestate.com/recipes/325905-memoize-decorator-with-timeout/#c1 3 | import time 4 | 5 | 6 | class Cache(object): 7 | """Cache class decorator for caching method results for a certain input""" 8 | _caches = {} 9 | _timeouts = {} 10 | 11 | def __init__(self, timeout=2): 12 | self.timeout = timeout 13 | 14 | def collect(self): 15 | """Clear cache of results which have timed out""" 16 | for func in self._caches: 17 | cache = {} 18 | for key in self._caches[func]: 19 | if (time.time() - self._caches[func][key][1]) < self._timeouts[func]: 20 | cache[key] = self._caches[func][key] 21 | self._caches[func] = cache 22 | 23 | def invalidate_lang_cache(self, chat_id): 24 | """ 25 | Invalidate language cache for certain chat_id, e.g. after changing languages 26 | :param chat_id: The chat_id of a certain Telegram chat 27 | :return: 28 | """ 29 | for func in self._caches: 30 | # Sadly I haven't been able to find a better way to access the correct cache 31 | # So we are using string comparison for now 32 | if "Database.get_lang_id" not in str(func): 33 | continue 34 | 35 | for key in self._caches[func]: 36 | try: 37 | if int(chat_id) == key[0][1]: 38 | new_tuple = (self._caches[func][key][0], 0) 39 | self._caches[func][key] = new_tuple 40 | except Exception as e: 41 | print(e) 42 | 43 | def __call__(self, f): 44 | self.cache = self._caches[f] = {} 45 | self._timeouts[f] = self.timeout 46 | 47 | def func(*args, **kwargs): 48 | kw = sorted(kwargs.items()) 49 | key = (args, tuple(kw)) 50 | # The cache depends on the function being called, the args and the kwargs. 51 | # Only if all of them match, we return the stored value for that exact combination 52 | try: 53 | # if there is no cached value yet OR the value has timed out, a KeyError is being raised 54 | v = self.cache[key] 55 | if (time.time() - v[1]) > self.timeout: 56 | raise KeyError 57 | except KeyError: 58 | # When a KeyError is raised, we'll actually call the wrapped method and store the value 59 | v = self.cache[key] = f(*args, **kwargs), time.time() 60 | return v[0] 61 | 62 | func.func_name = f.__name__ 63 | 64 | return func 65 | --------------------------------------------------------------------------------