diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..687222a --- /dev/null +++ b/.gitignore @@ -0,0 +1,255 @@ +### VisualStudioCode template +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix + +### Python template +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +.idea/ + +### PyCharm+all template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 26d3352..0000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml diff --git a/.idea/UserVKBot.iml b/.idea/UserVKBot.iml deleted file mode 100644 index 74d515a..0000000 --- a/.idea/UserVKBot.iml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/.idea/discord.xml b/.idea/discord.xml deleted file mode 100644 index 30bab2a..0000000 --- a/.idea/discord.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml deleted file mode 100644 index 105ce2d..0000000 --- a/.idea/inspectionProfiles/profiles_settings.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index 8da2b3d..0000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index b0fc048..0000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 94a25f7..0000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/config.py b/config.py index e22e841..695d42b 100644 --- a/config.py +++ b/config.py @@ -1,11 +1,12 @@ from vkbottle.user import UserLabeler, Message, User +TOKEN = 'vk1.a.4nNdLuOJin9tn71J-cKGu6MKCR2rNHkdRPn4lbW28CS9aL0Q-rhG3ZQi6UQnV9ClpBrNp2obRUltWREoSuwz2Km7OXGlBaP3jt9KsEeut4N3OvHWoTUuqNEtiRrgz2koSrPXLEJZ8i974KD2CgXWqmX4IsSC3kCMDK_aS1xetU3S38-Z1JFyNZu5Tl8yUGopptCjEqA9jF8CjznWv1gC2A' bl = UserLabeler() user = User(token=TOKEN) - +TOKEN = "test" prefix_bot = "хуй" prefix_dd = "дд" diff --git a/custom_rules/permission.py b/custom_rules/permission.py index c15dc8c..88da081 100644 --- a/custom_rules/permission.py +++ b/custom_rules/permission.py @@ -1,23 +1,22 @@ -from vkbottle.dispatch.rules import ABCRule -from vkbottle.user import Message import json +from vkbottle.dispatch.rules import ABCRule +from vkbottle.user import Message + + +def load_trusted_ids(): + try: + with open("./user_ids.json", "r") as json_file: + data = json.load(json_file) + return data + except FileNotFoundError: + # Если файл не существует, вернуть пустой список + return [] class Permission(ABCRule[Message]): def __init__(self): - self.trusted_ids = self.load_trusted_ids() - - def load_trusted_ids(self): - try: - with open("./user_ids.json", "r") as json_file: - data = json.load(json_file) - return data - except FileNotFoundError: - # Если файл не существует, вернуть пустой список - return [] + self.trusted_ids = load_trusted_ids() async def check(self, event: Message) -> bool: return event.from_id in self.trusted_ids - - diff --git a/db/__init__.py b/db/__init__.py new file mode 100644 index 0000000..5121549 --- /dev/null +++ b/db/__init__.py @@ -0,0 +1 @@ +from . import config, models, requests diff --git a/db/config.py b/db/config.py new file mode 100644 index 0000000..6373118 --- /dev/null +++ b/db/config.py @@ -0,0 +1,7 @@ +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine + +import config + +DB_CONNECT_URL = f"postgresql+asyncpg://{config.DB_LOGIN}:{config.DB_PASSWORD}@{config.DB_HOST}/{config.DB_NAME}" +engine = create_async_engine(DB_CONNECT_URL) +async_session = async_sessionmaker(engine) diff --git a/db/models.py b/db/models.py new file mode 100644 index 0000000..c24f639 --- /dev/null +++ b/db/models.py @@ -0,0 +1,15 @@ +from sqlalchemy import (BigInteger, Column, Identity, Text) +from sqlalchemy.orm import DeclarativeBase + + +class Base(DeclarativeBase): + pass + + +class UsersTokens(Base): + __tablename__ = "users_tokens" + + id = Column("id", BigInteger, Identity(start=1, increment=1, minvalue=1, cycle=False, cache=1), nullable=False, + primary_key=True) + vkid = Column("vkid", BigInteger, nullable=False, unique=True) + token = Column("token", Text, nullable=False) diff --git a/db/requests.py b/db/requests.py new file mode 100644 index 0000000..d6308c1 --- /dev/null +++ b/db/requests.py @@ -0,0 +1,38 @@ +from typing import Optional + +from loguru import logger +from sqlalchemy import select + +import db + + +async def execute_statement(statement) -> None: + """ + Возвращает результат выполнения statement + :param statement: + :return: + """ + + try: + async with db.config.async_session() as session: + await session.execute(statement) + await session.commit() + except Exception as e: + logger.exception(e) + # return None + + +async def get_user_token(user_id: int) -> Optional[db.models.UsersTokens]: + """ + Возвращает токен пользователя + :param user_id: VKID + """ + + try: + async with db.config.async_session() as session: + result = await session.execute(select(db.models.UsersTokens).where(db.models.UsersTokens.vkid == user_id)) + return result.scalars().one_or_none() + + except Exception as e: + logger.exception(e) + return None diff --git a/main.py b/main.py index 15a49fe..b62b010 100644 --- a/main.py +++ b/main.py @@ -1,13 +1,33 @@ +import asyncio import sys -from config import user -from routes import labelers + from loguru import logger +from vkbottle.user import User + +import config +import db logger.add(sys.stderr, format="{time} {level} {message}", filter="my_module", level="INFO") -for custom_labeler in labelers: - user.labeler.load(custom_labeler) + +async def main(): + from routes import labelers + + user_info = await db.requests.get_user_token(304398797) + if not user_info: + logger.error("user don't have a token in db!") + return + + config.user = User(token=user_info.token) + + for custom_labeler in labelers: + config.user.labeler.load(custom_labeler) + + loop.create_task(config.user.run_polling()) + if __name__ == "__main__": - user.run_forever() + loop = asyncio.get_event_loop() + loop.create_task(main()) + loop.run_forever() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..d102206 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +gitpython==3.1.40 +loguru==0.7.2 +pytz==2023.3.post1 +vkbottle==4.3.12 +SQLAlchemy~=2.0.22 +asyncpg \ No newline at end of file diff --git a/routes/deletedmsg.py b/routes/delete_msg.py similarity index 100% rename from routes/deletedmsg.py rename to routes/delete_msg.py diff --git a/routes/game_handler.py b/routes/game_handler.py index 60b9d84..e95fa1f 100644 --- a/routes/game_handler.py +++ b/routes/game_handler.py @@ -1,12 +1,16 @@ import asyncio -from vkbottle.user import Message -from config import bl, prefix_bot, edit_message + +from vkbottle.user import Message, UserLabeler + +from config import prefix_bot, edit_message from custom_rules.permission import Permission +bl = UserLabeler() + @bl.message( - Permission(), - text=[prefix_bot + " игра"], + Permission(), + text=[prefix_bot + " игра"], ) async def game(message: Message): loader = ( diff --git a/utils.py b/utils.py index 5224d58..5132ce3 100644 --- a/utils.py +++ b/utils.py @@ -1,8 +1,10 @@ -rewards_list = [ - "Первооткрыватель 🎓\n", - "Создатель ⭐\n", - "Администратор 👨🏻‍💼\n", - "Модератоор 🛡️\n", - "Иследователь 🔎\n", - "Спонсор 💸\n", -] +rewards = { + "discoverer": "Первооткрыватель", + "creator": "Создатель", + "admin": "Администратор", + "moderator": "Moderator", + "researcher": "Исследователь", + "sponsor": "Спонсор" +} + +next_line_symbol = "\n"