Compare commits
13 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
9f95d004c1 | ||
|
cfab19f4d4 | ||
4229624763 | |||
3767417e23 | |||
07db185d8f | |||
|
63dabb0db5 | ||
420a945ea7 | |||
d2e95a42c9 | |||
33418e0c8b | |||
3a28cbb080 | |||
da06b5ad23 | |||
6169e6e32a | |||
61075491ec |
10
.drone.yml
10
.drone.yml
@ -15,20 +15,14 @@ steps:
|
|||||||
- name: test it first
|
- name: test it first
|
||||||
commands:
|
commands:
|
||||||
- /usr/bin/python3 -m py_compile bot.py
|
- /usr/bin/python3 -m py_compile bot.py
|
||||||
- /usr/bin/python3 pipisa_functions/pipisa_time.py
|
|
||||||
- name: pull into the folduh
|
- name: pull into the folduh
|
||||||
commands:
|
commands:
|
||||||
- cd /usr/share/$DRONE_REPO_NAME
|
- cd /usr/share/$DRONE_REPO_NAME
|
||||||
- su -c "git pull" jack
|
- git pull
|
||||||
#- chown -R jack:jack .
|
- chown -R jack:jack .
|
||||||
when:
|
when:
|
||||||
branch:
|
branch:
|
||||||
- main
|
- main
|
||||||
environment:
|
|
||||||
ARANGO_PASSWORD:
|
|
||||||
from_secret: arango-pwd
|
|
||||||
ARANGO_USERNAME:
|
|
||||||
from_secret: arango-usr
|
|
||||||
- name: restart systemd unit
|
- name: restart systemd unit
|
||||||
commands:
|
commands:
|
||||||
- systemctl restart jack_bot
|
- systemctl restart jack_bot
|
||||||
|
13
README.md
13
README.md
@ -1,13 +0,0 @@
|
|||||||
Пробуем проверять что-либо.
|
|
||||||
|
|
||||||
```mermaid
|
|
||||||
journey
|
|
||||||
title Пиписа
|
|
||||||
section Наш Чат
|
|
||||||
Оче больше пипис: 5: ГЕГЕМОН
|
|
||||||
Обычно большепенис: 3: Догоняющие
|
|
||||||
Скромный дик: 1: Отставшие
|
|
||||||
section Не наш чат
|
|
||||||
Не запустил: -1: Отставшие
|
|
||||||
Не крутил: 1: Отставшие
|
|
||||||
```
|
|
110
alembic.ini
Normal file
110
alembic.ini
Normal file
@ -0,0 +1,110 @@
|
|||||||
|
# A generic, single database configuration.
|
||||||
|
|
||||||
|
[alembic]
|
||||||
|
# path to migration scripts
|
||||||
|
script_location = alembic
|
||||||
|
|
||||||
|
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
||||||
|
# Uncomment the line below if you want the files to be prepended with date and time
|
||||||
|
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
||||||
|
# for all available tokens
|
||||||
|
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
||||||
|
|
||||||
|
# sys.path path, will be prepended to sys.path if present.
|
||||||
|
# defaults to the current working directory.
|
||||||
|
prepend_sys_path = .
|
||||||
|
|
||||||
|
# timezone to use when rendering the date within the migration file
|
||||||
|
# as well as the filename.
|
||||||
|
# If specified, requires the python-dateutil library that can be
|
||||||
|
# installed by adding `alembic[tz]` to the pip requirements
|
||||||
|
# string value is passed to dateutil.tz.gettz()
|
||||||
|
# leave blank for localtime
|
||||||
|
# timezone =
|
||||||
|
|
||||||
|
# max length of characters to apply to the
|
||||||
|
# "slug" field
|
||||||
|
# truncate_slug_length = 40
|
||||||
|
|
||||||
|
# set to 'true' to run the environment during
|
||||||
|
# the 'revision' command, regardless of autogenerate
|
||||||
|
# revision_environment = false
|
||||||
|
|
||||||
|
# set to 'true' to allow .pyc and .pyo files without
|
||||||
|
# a source .py file to be detected as revisions in the
|
||||||
|
# versions/ directory
|
||||||
|
# sourceless = false
|
||||||
|
|
||||||
|
# version location specification; This defaults
|
||||||
|
# to alembic/versions. When using multiple version
|
||||||
|
# directories, initial revisions must be specified with --version-path.
|
||||||
|
# The path separator used here should be the separator specified by "version_path_separator" below.
|
||||||
|
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
|
||||||
|
|
||||||
|
# version path separator; As mentioned above, this is the character used to split
|
||||||
|
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
|
||||||
|
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
|
||||||
|
# Valid values for version_path_separator are:
|
||||||
|
#
|
||||||
|
# version_path_separator = :
|
||||||
|
# version_path_separator = ;
|
||||||
|
# version_path_separator = space
|
||||||
|
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
|
||||||
|
|
||||||
|
# set to 'true' to search source files recursively
|
||||||
|
# in each "version_locations" directory
|
||||||
|
# new in Alembic version 1.10
|
||||||
|
# recursive_version_locations = false
|
||||||
|
|
||||||
|
# the output encoding used when revision files
|
||||||
|
# are written from script.py.mako
|
||||||
|
# output_encoding = utf-8
|
||||||
|
|
||||||
|
sqlalchemy.url = postgresql+psycopg2://postgres:postgres@postgres.vdk2ch.ru:5432/jack_bot
|
||||||
|
|
||||||
|
|
||||||
|
[post_write_hooks]
|
||||||
|
# post_write_hooks defines scripts or Python functions that are run
|
||||||
|
# on newly generated revision scripts. See the documentation for further
|
||||||
|
# detail and examples
|
||||||
|
|
||||||
|
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||||
|
# hooks = black
|
||||||
|
# black.type = console_scripts
|
||||||
|
# black.entrypoint = black
|
||||||
|
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||||
|
|
||||||
|
# Logging configuration
|
||||||
|
[loggers]
|
||||||
|
keys = root,sqlalchemy,alembic
|
||||||
|
|
||||||
|
[handlers]
|
||||||
|
keys = console
|
||||||
|
|
||||||
|
[formatters]
|
||||||
|
keys = generic
|
||||||
|
|
||||||
|
[logger_root]
|
||||||
|
level = WARN
|
||||||
|
handlers = console
|
||||||
|
qualname =
|
||||||
|
|
||||||
|
[logger_sqlalchemy]
|
||||||
|
level = WARN
|
||||||
|
handlers =
|
||||||
|
qualname = sqlalchemy.engine
|
||||||
|
|
||||||
|
[logger_alembic]
|
||||||
|
level = INFO
|
||||||
|
handlers =
|
||||||
|
qualname = alembic
|
||||||
|
|
||||||
|
[handler_console]
|
||||||
|
class = StreamHandler
|
||||||
|
args = (sys.stderr,)
|
||||||
|
level = NOTSET
|
||||||
|
formatter = generic
|
||||||
|
|
||||||
|
[formatter_generic]
|
||||||
|
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||||
|
datefmt = %H:%M:%S
|
1
alembic/README
Normal file
1
alembic/README
Normal file
@ -0,0 +1 @@
|
|||||||
|
Generic single-database configuration.
|
78
alembic/env.py
Normal file
78
alembic/env.py
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
from logging.config import fileConfig
|
||||||
|
|
||||||
|
from sqlalchemy import engine_from_config
|
||||||
|
from sqlalchemy import pool
|
||||||
|
from sqdb import Base
|
||||||
|
from alembic import context
|
||||||
|
|
||||||
|
# this is the Alembic Config object, which provides
|
||||||
|
# access to the values within the .ini file in use.
|
||||||
|
config = context.config
|
||||||
|
|
||||||
|
# Interpret the config file for Python logging.
|
||||||
|
# This line sets up loggers basically.
|
||||||
|
if config.config_file_name is not None:
|
||||||
|
fileConfig(config.config_file_name)
|
||||||
|
|
||||||
|
# add your model's MetaData object here
|
||||||
|
# for 'autogenerate' support
|
||||||
|
# from myapp import mymodel
|
||||||
|
# target_metadata = mymodel.Base.metadata
|
||||||
|
target_metadata = Base.metadata
|
||||||
|
|
||||||
|
# other values from the config, defined by the needs of env.py,
|
||||||
|
# can be acquired:
|
||||||
|
# my_important_option = config.get_main_option("my_important_option")
|
||||||
|
# ... etc.
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_offline() -> None:
|
||||||
|
"""Run migrations in 'offline' mode.
|
||||||
|
|
||||||
|
This configures the context with just a URL
|
||||||
|
and not an Engine, though an Engine is acceptable
|
||||||
|
here as well. By skipping the Engine creation
|
||||||
|
we don't even need a DBAPI to be available.
|
||||||
|
|
||||||
|
Calls to context.execute() here emit the given string to the
|
||||||
|
script output.
|
||||||
|
|
||||||
|
"""
|
||||||
|
url = config.get_main_option("sqlalchemy.url")
|
||||||
|
context.configure(
|
||||||
|
url=url,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
literal_binds=True,
|
||||||
|
dialect_opts={"paramstyle": "named"},
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_online() -> None:
|
||||||
|
"""Run migrations in 'online' mode.
|
||||||
|
|
||||||
|
In this scenario we need to create an Engine
|
||||||
|
and associate a connection with the context.
|
||||||
|
|
||||||
|
"""
|
||||||
|
connectable = engine_from_config(
|
||||||
|
config.get_section(config.config_ini_section, {}),
|
||||||
|
prefix="sqlalchemy.",
|
||||||
|
poolclass=pool.NullPool,
|
||||||
|
)
|
||||||
|
|
||||||
|
with connectable.connect() as connection:
|
||||||
|
context.configure(
|
||||||
|
connection=connection, target_metadata=target_metadata
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
run_migrations_offline()
|
||||||
|
else:
|
||||||
|
run_migrations_online()
|
24
alembic/script.py.mako
Normal file
24
alembic/script.py.mako
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = ${repr(up_revision)}
|
||||||
|
down_revision = ${repr(down_revision)}
|
||||||
|
branch_labels = ${repr(branch_labels)}
|
||||||
|
depends_on = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
${downgrades if downgrades else "pass"}
|
47
alembic/versions/7521d874503f_.py
Normal file
47
alembic/versions/7521d874503f_.py
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
"""empty message
|
||||||
|
|
||||||
|
Revision ID: 7521d874503f
|
||||||
|
Revises:
|
||||||
|
Create Date: 2023-06-22 15:21:26.835612
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '7521d874503f'
|
||||||
|
down_revision = None
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table('dick_requests',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('size_change', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('user_id', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('date_changed', sa.DateTime(), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(['user_id'], ['users.user_id'], ),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_foreign_key(None, 'user_dicks', 'users', ['user_id'], ['user_id'])
|
||||||
|
op.add_column('users', sa.Column('date_created', sa.DateTime(), nullable=True))
|
||||||
|
op.add_column('users', sa.Column('date_updated', sa.DateTime(), nullable=True))
|
||||||
|
op.drop_column('users', 'chat_id')
|
||||||
|
op.drop_column('users', 'datetimes')
|
||||||
|
op.drop_column('users', 'dick_size')
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.add_column('users', sa.Column('dick_size', sa.INTEGER(), autoincrement=False, nullable=True))
|
||||||
|
op.add_column('users', sa.Column('datetimes', postgresql.TIMESTAMP(), autoincrement=False, nullable=True))
|
||||||
|
op.add_column('users', sa.Column('chat_id', sa.BIGINT(), autoincrement=False, nullable=True))
|
||||||
|
op.drop_column('users', 'date_updated')
|
||||||
|
op.drop_column('users', 'date_created')
|
||||||
|
op.drop_constraint(None, 'user_dicks', type_='foreignkey')
|
||||||
|
op.drop_table('dick_requests')
|
||||||
|
# ### end Alembic commands ###
|
50
bot.py
50
bot.py
@ -1,55 +1,27 @@
|
|||||||
import logging
|
import logging
|
||||||
from aiogram import executor, Bot, Dispatcher
|
import graypy
|
||||||
|
|
||||||
|
from aiogram import executor
|
||||||
|
|
||||||
from create_bot import dp
|
from create_bot import dp
|
||||||
|
|
||||||
import handlers
|
import handlers
|
||||||
import json, logging
|
|
||||||
from global_conf import CONFIG
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def remake_field_generator(d, field='text'):
|
|
||||||
if isinstance(d, list):
|
|
||||||
for k2 in d:
|
|
||||||
for id_val in remake_field_generator(k2):
|
|
||||||
yield id_val
|
|
||||||
elif isinstance(d, dict):
|
|
||||||
for k, v in d.items():
|
|
||||||
if k == field:
|
|
||||||
d[k] = '<blank!>'
|
|
||||||
yield v
|
|
||||||
elif isinstance(v, list):
|
|
||||||
for k2 in v:
|
|
||||||
for id_val in remake_field_generator(k2):
|
|
||||||
yield id_val
|
|
||||||
elif isinstance(v, dict):
|
|
||||||
for id_val in remake_field_generator(v):
|
|
||||||
yield id_val
|
|
||||||
|
|
||||||
def filter_grammar_messages(record):
|
|
||||||
if record.args and (not None in record.args):
|
|
||||||
j = json.loads(record.args[2])
|
|
||||||
for _ in remake_field_generator(j):
|
|
||||||
pass
|
|
||||||
record.args = (record.args[0], record.args[1], json.dumps(j))
|
|
||||||
return True
|
|
||||||
|
|
||||||
logging.basicConfig(level=logging.DEBUG)
|
logging.basicConfig(level=logging.DEBUG)
|
||||||
logging.getLogger("aiogram").addFilter(filter_grammar_messages)
|
|
||||||
|
|
||||||
|
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.DEBUG,
|
||||||
|
handlers=[graypy.GELFUDPHandler('localhost', 12201)]
|
||||||
|
)
|
||||||
|
|
||||||
# pipisa.register_handlers_pipisa(dp)
|
# pipisa.register_handlers_pipisa(dp)
|
||||||
# time_new_year.register_handlers_time(dp)
|
# time_new_year.register_handlers_time(dp)
|
||||||
# sendalarm.register_handlers_test(dp)
|
# sendalarm.register_handlers_test(dp)
|
||||||
# start_help.register_handlers_StartHelp(dp)
|
# start_help.register_handlers_StartHelp(dp)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
#print(CONFIG)
|
|
||||||
|
|
||||||
logging.info('Бот в строю.')
|
|
||||||
executor.start_polling(dp, skip_updates=True)
|
executor.start_polling(dp, skip_updates=True)
|
||||||
logging.info('Всем пока.')
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
19
config.yaml
19
config.yaml
@ -1,19 +0,0 @@
|
|||||||
---
|
|
||||||
databaso:
|
|
||||||
host: 'https://arango.guaranteedstruggle.host'
|
|
||||||
#user: root
|
|
||||||
#pass: stolendick527
|
|
||||||
base: pipisa
|
|
||||||
collection: dicks
|
|
||||||
posts_removal_collection: posts_removal
|
|
||||||
|
|
||||||
telegram_token: 6991523312:AAFpxPlWHfnNq2dVXM_v1GuHcrbNgWdSWBM
|
|
||||||
telegram_admins_ids:
|
|
||||||
- 317051301 # hogweed1
|
|
||||||
- 226765676 # blackjack
|
|
||||||
- 94830892 # viktorRMI
|
|
||||||
- 132002803
|
|
||||||
|
|
||||||
openai:
|
|
||||||
token: 5947963644:AAF_GKgMmU5ovqMpc1KXIpcf4aN0JMyKPqc
|
|
||||||
api_key: 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 ## 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
|
|
@ -1,8 +1,4 @@
|
|||||||
from aiogram import Bot, Dispatcher
|
from aiogram import Bot, Dispatcher
|
||||||
from global_conf import CONFIG
|
API_TOKEN = '5724991559:AAEuLvpLsgP6LHRGMSyFtQLlR5qPQUO4b_w'
|
||||||
|
bot = Bot(token=API_TOKEN, parse_mode="HTML")
|
||||||
|
dp = Dispatcher(bot)
|
||||||
|
|
||||||
|
|
||||||
bot = Bot(token=CONFIG['telegram_token'], parse_mode="HTML")
|
|
||||||
dp = Dispatcher(bot)
|
|
@ -1,44 +0,0 @@
|
|||||||
|
|
||||||
from global_conf import CONFIG
|
|
||||||
|
|
||||||
#### https://docs.python-arango.com/en/main/
|
|
||||||
from arango import ArangoClient
|
|
||||||
|
|
||||||
import logging
|
|
||||||
import os
|
|
||||||
|
|
||||||
|
|
||||||
def get_dicks_collection():
|
|
||||||
try:
|
|
||||||
arango_client = ArangoClient(hosts=CONFIG['databaso']['host'] )
|
|
||||||
pipisa_db = arango_client.db(
|
|
||||||
CONFIG['databaso']['base'],
|
|
||||||
username=os.environ['ARANGO_USR'],
|
|
||||||
password=os.environ['ARANGO_PWD'],
|
|
||||||
#username=CONFIG['databaso']['user'],
|
|
||||||
#password=CONFIG['databaso']['pass']
|
|
||||||
)
|
|
||||||
dicks_collection = pipisa_db.collection(CONFIG['databaso']['collection'])
|
|
||||||
|
|
||||||
return dicks_collection
|
|
||||||
except Exception as e:
|
|
||||||
logging.error('ошибка DB при взятии коллекции пипис')
|
|
||||||
logging.error(e)
|
|
||||||
|
|
||||||
|
|
||||||
def get_posts_removal_collection():
|
|
||||||
try:
|
|
||||||
arango_client = ArangoClient(hosts=CONFIG['databaso']['host'] )
|
|
||||||
pipisa_db = arango_client.db(
|
|
||||||
CONFIG['databaso']['base'],
|
|
||||||
username=os.environ['ARANGO_USR'],
|
|
||||||
password=os.environ['ARANGO_PWD'],
|
|
||||||
#username=CONFIG['databaso']['user'],
|
|
||||||
#password=CONFIG['databaso']['pass']
|
|
||||||
)
|
|
||||||
posts_removal_collection = pipisa_db.collection(CONFIG['databaso']['posts_removal_collection'])
|
|
||||||
|
|
||||||
return posts_removal_collection
|
|
||||||
except Exception as e:
|
|
||||||
logging.error('ошибка DB при взятии коллекции постов-на-удаление')
|
|
||||||
logging.error(e)
|
|
@ -1,75 +0,0 @@
|
|||||||
from db_logic import collections
|
|
||||||
import datetime, logging
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def append_post_to_cleaning_sequence(message, type=None):
|
|
||||||
try:
|
|
||||||
novenkiy = {
|
|
||||||
'msg_id': message.message_id,
|
|
||||||
'chat_id': message.chat.id,
|
|
||||||
'type': type,
|
|
||||||
'datetimes': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
||||||
}
|
|
||||||
metadata = collections.get_posts_removal_collection().insert(novenkiy, overwrite_mode='update')
|
|
||||||
|
|
||||||
logging.debug('Успешно добавлен пост на удаление')
|
|
||||||
except Exception as e2:
|
|
||||||
logging.error('ошибка DB :: добавление нового поста на удаление')
|
|
||||||
logging.error(e2)
|
|
||||||
|
|
||||||
|
|
||||||
def get_posts_to_be_removed(chat_id, type=None, max_id=None):
|
|
||||||
# собираем
|
|
||||||
try:
|
|
||||||
#posts = [p for p in collections.get_posts_removal_collection().all( ) ]
|
|
||||||
|
|
||||||
if type:
|
|
||||||
posts = [p for p in collections.get_posts_removal_collection().find({'chat_id': chat_id, 'type': type}, skip=0, limit=1100) ]
|
|
||||||
else:
|
|
||||||
posts = [p for p in collections.get_posts_removal_collection().find({'chat_id': chat_id}, skip=0, limit=1100) ]
|
|
||||||
|
|
||||||
posts_ret = [ p for p in posts ]
|
|
||||||
# # for p in posts:
|
|
||||||
# # last_time = datetime.datetime.strptime(p['datetimes'], '%Y-%m-%d %H:%M:%S')
|
|
||||||
# # timediff = (datetime.datetime.now() - last_time).total_seconds()
|
|
||||||
|
|
||||||
# # if timediff > 60:
|
|
||||||
# # posts_ret.append(p)
|
|
||||||
|
|
||||||
if max_id:
|
|
||||||
posts_ret = [ p for p in posts_ret if p['msg_id'] != max_id]
|
|
||||||
else:
|
|
||||||
posts_ret = [ p for p in posts_ret if p['msg_id'] != max([pp['msg_id'] for pp in posts_ret])]
|
|
||||||
|
|
||||||
|
|
||||||
#### TODO удалять все предыдущие без учёта времени
|
|
||||||
|
|
||||||
return posts_ret
|
|
||||||
except Exception as e:
|
|
||||||
logging.error('ошибка DB :: получение постов на удаление')
|
|
||||||
logging.error(e)
|
|
||||||
|
|
||||||
|
|
||||||
def del_post(msg_id, chat_id):
|
|
||||||
# удаляем из базы
|
|
||||||
try:
|
|
||||||
|
|
||||||
candidate_cursor = collections.get_posts_removal_collection().find(
|
|
||||||
{
|
|
||||||
'msg_id': msg_id,
|
|
||||||
'chat_id': chat_id,
|
|
||||||
},
|
|
||||||
skip = 0,
|
|
||||||
limit = 1488
|
|
||||||
)
|
|
||||||
if candidate_cursor.count() > 0:
|
|
||||||
pp = candidate_cursor.pop()
|
|
||||||
else:
|
|
||||||
pp = None
|
|
||||||
|
|
||||||
collections.get_posts_removal_collection().delete(pp)
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logging.error('ошибка DB :: удаление поста на удаление')
|
|
||||||
logging.error(e)
|
|
@ -1,65 +0,0 @@
|
|||||||
from global_conf import CONFIG
|
|
||||||
from db_logic import collections
|
|
||||||
import logging
|
|
||||||
|
|
||||||
|
|
||||||
def get_tops(top_ = False, glob_ = False, chat_id = None):
|
|
||||||
|
|
||||||
if top_:
|
|
||||||
try:
|
|
||||||
dicks = [d for d in collections.get_dicks_collection().find({'chat_id': chat_id}, skip=0, limit=1100)]
|
|
||||||
except Exception as e:
|
|
||||||
logging.error('ошибка DB в /topdick')
|
|
||||||
logging.error(e)
|
|
||||||
elif glob_:
|
|
||||||
try:
|
|
||||||
dicks = [d for d in collections.get_dicks_collection().all( ) if d['user_id'] != d['chat_id']]
|
|
||||||
except Exception as e:
|
|
||||||
logging.error('ошибка DB в /globaldick')
|
|
||||||
logging.error(e)
|
|
||||||
else:
|
|
||||||
logging.error('вызывают хз что!')
|
|
||||||
|
|
||||||
top_dicks = sorted(dicks, key=lambda dick: dick['dick_size'], reverse=True)
|
|
||||||
top_dicks = top_dicks[:( min(len(top_dicks), 10) )]
|
|
||||||
|
|
||||||
dickos = ''
|
|
||||||
emo = ['🏆','🚀','🍆','🍌','🐍','🐎','🌭','🌶','👌','💩']
|
|
||||||
|
|
||||||
if len(top_dicks) > 0:
|
|
||||||
for i in range(len(top_dicks)):
|
|
||||||
dickos += f' {emo[i]} {i+1}. {top_dicks[i]["user_fullname"]}: {top_dicks[i]["dick_size"]}см\n'
|
|
||||||
i += 1
|
|
||||||
|
|
||||||
return dickos
|
|
||||||
|
|
||||||
|
|
||||||
def get_antitops(top_ = False, glob_ = False, chat_id = None):
|
|
||||||
dicks = []
|
|
||||||
if top_:
|
|
||||||
try:
|
|
||||||
dicks = [d for d in collections.get_dicks_collection().find({'chat_id': chat_id}, skip=0, limit=1100)]
|
|
||||||
except Exception as e:
|
|
||||||
logging.error('ошибка DB в /topdick')
|
|
||||||
logging.error(e)
|
|
||||||
elif glob_:
|
|
||||||
try:
|
|
||||||
dicks = [d for d in collections.get_dicks_collection().all() if d['user_id'] != d['chat_id']]
|
|
||||||
except Exception as e:
|
|
||||||
logging.error('ошибка DB в /globaldick')
|
|
||||||
logging.error(e)
|
|
||||||
else:
|
|
||||||
logging.error('вызывают хз что!')
|
|
||||||
|
|
||||||
antitop_dicks = sorted(dicks, key=lambda dick: dick['dick_size'], reverse=False)
|
|
||||||
antitop_dicks = antitop_dicks[:( min(len(antitop_dicks), 10) )]
|
|
||||||
|
|
||||||
dickos = ''
|
|
||||||
emo = ['💩', '😞', '🤕', '😣', '🙁', '😐', '😑', '😶', '😒', '😕']
|
|
||||||
|
|
||||||
if len(antitop_dicks) > 0:
|
|
||||||
for i in range(len(antitop_dicks)):
|
|
||||||
dickos += f' {emo[i]} {i+1}. {antitop_dicks[i]["user_fullname"]}: {antitop_dicks[i]["dick_size"]}см\n'
|
|
||||||
i += 1
|
|
||||||
|
|
||||||
return dickos
|
|
@ -1,86 +0,0 @@
|
|||||||
from db_logic import collections
|
|
||||||
import datetime, logging
|
|
||||||
|
|
||||||
|
|
||||||
def store_new_user(message, result ):
|
|
||||||
|
|
||||||
try:
|
|
||||||
novenkiy = {
|
|
||||||
'user_id': message.from_user.id,
|
|
||||||
'user_fullname': message.from_user.full_name,
|
|
||||||
'dick_size': abs(result),
|
|
||||||
'datetimes': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
|
||||||
'attempts': 1,
|
|
||||||
'chat_id': message.chat.id
|
|
||||||
}
|
|
||||||
metadata = collections.get_dicks_collection().insert(novenkiy, overwrite_mode='update')
|
|
||||||
|
|
||||||
logging.debug(f'Успешно добавлен нового пользователь @{message.from_user.username}')
|
|
||||||
except Exception as e2:
|
|
||||||
logging.error(f'ошибка DB в /dick :: добавление нового пользователя @{message.from_user.username}')
|
|
||||||
logging.error(e2)
|
|
||||||
|
|
||||||
|
|
||||||
def update_attempts(message, user ):
|
|
||||||
try:
|
|
||||||
metadata = collections.get_dicks_collection().insert(
|
|
||||||
{
|
|
||||||
'_key': user['_key'], ### этот нужен чтобы апдейт прилетал тому же юзеру
|
|
||||||
'user_id': user['user_id'] ,
|
|
||||||
'user_fullname': message.from_user.full_name,
|
|
||||||
'dick_size': user['dick_size'] ,
|
|
||||||
'datetimes': user['datetimes'] ,
|
|
||||||
'attempts': user['attempts'] + 1,
|
|
||||||
'chat_id': message.chat.id
|
|
||||||
},
|
|
||||||
overwrite_mode='update'
|
|
||||||
)
|
|
||||||
|
|
||||||
logging.debug(f'Успешно апдейтнули попытку крутить пипису @{message.from_user.username}')
|
|
||||||
except Exception as e2:
|
|
||||||
logging.error(f'ошибка DB в /dick :: обновление попытки крутить пипису @{message.from_user.username}')
|
|
||||||
logging.error(e2)
|
|
||||||
|
|
||||||
|
|
||||||
def update_dick_size(message, user, updatedDick ):
|
|
||||||
|
|
||||||
try:
|
|
||||||
metadata = collections.get_dicks_collection().insert(
|
|
||||||
{
|
|
||||||
'_key': user['_key'], ### этот нужен чтобы апдейт прилетал тому же юзеру
|
|
||||||
'user_id': user['user_id'],
|
|
||||||
'user_fullname': message.from_user.full_name,
|
|
||||||
'dick_size': updatedDick,
|
|
||||||
'datetimes': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
|
||||||
'attempts': user['attempts'] + 1,
|
|
||||||
'chat_id': message.chat.id
|
|
||||||
},
|
|
||||||
overwrite_mode='update'
|
|
||||||
)
|
|
||||||
|
|
||||||
logging.info(f'Успешно апдейтнули пипису @{message.from_user.username}')
|
|
||||||
except Exception as e2:
|
|
||||||
logging.error(f'ошибка DB в /dick :: обновление пиписы @{message.from_user.username}')
|
|
||||||
logging.error(e2)
|
|
||||||
|
|
||||||
|
|
||||||
def get_user(message):
|
|
||||||
try:
|
|
||||||
#### Чекнуть есть ли юзер в базе
|
|
||||||
candidate_cursor = collections.get_dicks_collection().find(
|
|
||||||
{
|
|
||||||
'user_id': message.from_user.id,
|
|
||||||
'chat_id': message.chat.id
|
|
||||||
},
|
|
||||||
skip = 0,
|
|
||||||
limit = 1488
|
|
||||||
)
|
|
||||||
if candidate_cursor.count() > 0:
|
|
||||||
user = candidate_cursor.pop()
|
|
||||||
else:
|
|
||||||
user = None
|
|
||||||
|
|
||||||
return user
|
|
||||||
except Exception as e:
|
|
||||||
logging.error('ошибка DB в /dick :: поиск юзера')
|
|
||||||
logging.error(e)
|
|
@ -8,5 +8,9 @@ def RandomDick():
|
|||||||
with open('dicktxt/dick_sinonims.txt', 'r', encoding='utf-8') as file:
|
with open('dicktxt/dick_sinonims.txt', 'r', encoding='utf-8') as file:
|
||||||
words = file.readlines()
|
words = file.readlines()
|
||||||
|
|
||||||
return random.choice(words).strip()
|
random_line = random.choice(words).strip()
|
||||||
|
return random_line
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -1,21 +0,0 @@
|
|||||||
import yaml
|
|
||||||
import random
|
|
||||||
|
|
||||||
|
|
||||||
def ChangeWord(result): #выбирает рандомное слово для изменения размера пиписы
|
|
||||||
|
|
||||||
with open("dicktxt/dick_changes.yaml", 'r', encoding='utf-8') as f:
|
|
||||||
words = yaml.load(f, Loader=yaml.Loader)
|
|
||||||
|
|
||||||
dick_inc = [ f'<b>{w}</b>' for w in words['increment'] ]
|
|
||||||
dick_static = [ f'<b>{w}</b>' for w in words['nothing'] ]
|
|
||||||
dick_decr = [ f'<b>{w}</b>' for w in words['decrement'] ]
|
|
||||||
|
|
||||||
if result > 0:
|
|
||||||
size_change = random.choice(dick_inc) + '🚀'
|
|
||||||
elif result == 0:
|
|
||||||
size_change = random.choice(dick_static) + '🤨'
|
|
||||||
else:
|
|
||||||
size_change = random.choice(dick_decr) + '✂'
|
|
||||||
|
|
||||||
return size_change
|
|
@ -1,30 +0,0 @@
|
|||||||
---
|
|
||||||
increment:
|
|
||||||
- вырос
|
|
||||||
- подрос
|
|
||||||
- привстал
|
|
||||||
- увеличился
|
|
||||||
- преисполнился
|
|
||||||
- приподнялся
|
|
||||||
- изменил размер
|
|
||||||
- облагородился
|
|
||||||
- чрезвычайно преуспел
|
|
||||||
decrement:
|
|
||||||
- неудачно потусил на сходке
|
|
||||||
- уменьшился
|
|
||||||
- откусила злая гадюка
|
|
||||||
- продали евреи, он стал дешевле
|
|
||||||
- схуднул
|
|
||||||
- отрицательно вырос
|
|
||||||
- словил низкие вибрации
|
|
||||||
- повредился после простуды
|
|
||||||
- стал жертвой репрессий
|
|
||||||
- был подло использован
|
|
||||||
nothing:
|
|
||||||
- продвинулся
|
|
||||||
- наноуменьшился
|
|
||||||
- познал стабильность
|
|
||||||
- зафиксировал прибыль
|
|
||||||
- подумал о судьбах Китая
|
|
||||||
- прогулялся по лесу
|
|
||||||
- самоутвердился
|
|
@ -1,4 +1,4 @@
|
|||||||
кожаный бабах
|
Кожаный бабах
|
||||||
пистон
|
пистон
|
||||||
дуршлаг
|
дуршлаг
|
||||||
елдак
|
елдак
|
||||||
@ -93,4 +93,3 @@
|
|||||||
венерический суккуб
|
венерический суккуб
|
||||||
боец невидимого фронта
|
боец невидимого фронта
|
||||||
сморчок
|
сморчок
|
||||||
джечник
|
|
@ -1,6 +0,0 @@
|
|||||||
import yaml
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
with open("config.yaml", 'r') as f:
|
|
||||||
CONFIG = yaml.load(f, Loader=yaml.Loader)
|
|
@ -1,6 +1,7 @@
|
|||||||
|
|
||||||
from handlers import pipisa
|
from handlers import pipisa
|
||||||
|
from handlers import davinci
|
||||||
|
from handlers import time_new_year
|
||||||
|
from handlers import sendalarm
|
||||||
from handlers import start_help
|
from handlers import start_help
|
||||||
|
|
||||||
from handlers import time_new_year
|
|
||||||
|
|
||||||
|
@ -1,70 +1,26 @@
|
|||||||
from openai import AsyncOpenAI
|
import openai
|
||||||
from aiogram import types
|
from aiogram import types
|
||||||
from create_bot import dp, bot
|
from create_bot import dp
|
||||||
import logging
|
|
||||||
from global_conf import CONFIG
|
|
||||||
|
|
||||||
admins = CONFIG['telegram_admins_ids']
|
token = '5947963644:AAF_GKgMmU5ovqMpc1KXIpcf4aN0JMyKPqc'
|
||||||
|
openai.api_key = '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'
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
ban_comands = ['/dick','/topdick']
|
|
||||||
|
|
||||||
# Image_promt =['тупица сгенерируй','тупица сгенерируй картинку',\
|
|
||||||
# 'тупица отправь картинку', 'тупица отправь картинку']
|
|
||||||
client = AsyncOpenAI(api_key="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")
|
|
||||||
|
|
||||||
# @dp.message_handler(commands=['image'])
|
|
||||||
# async def send_image(message: types.Message):
|
|
||||||
# if message.from_user.id in admins and message.chat.type == 'private':
|
|
||||||
# try:
|
|
||||||
# description = message.text.replace('/image', '').strip()
|
|
||||||
|
|
||||||
# if not description:
|
|
||||||
# await message.reply('Ты даун, описание запроса напиши после пробела')
|
|
||||||
# return
|
|
||||||
# except Exception as e:
|
|
||||||
# logging.error(f'Error in send_image: {e}')
|
|
||||||
# try:
|
|
||||||
|
|
||||||
# response = openai.Image.create(
|
|
||||||
# prompt=message.text,
|
|
||||||
# n=1,
|
|
||||||
# size="1024x1024",
|
|
||||||
# response_format="url",
|
|
||||||
|
|
||||||
# )
|
|
||||||
# image_url = response['data'][0]['url']
|
|
||||||
# await message.answer('Генерирую изображение...')
|
|
||||||
# await message.reply_photo(image_url)
|
|
||||||
# except Exception as e:
|
|
||||||
# await message.reply('у меня не получилось')
|
|
||||||
|
|
||||||
|
|
||||||
async def gpt_text(req):
|
|
||||||
completion = await client.chat.completions.create(
|
|
||||||
messages=[
|
|
||||||
{
|
|
||||||
"role": "user",
|
|
||||||
"content": req,
|
|
||||||
}
|
|
||||||
],
|
|
||||||
model="gpt-4",
|
|
||||||
)
|
|
||||||
return completion
|
|
||||||
|
|
||||||
@dp.message_handler()
|
@dp.message_handler()
|
||||||
async def send(message: types.Message):
|
async def send(message: types.Message):
|
||||||
if message.from_user.id in admins and message.chat.type == 'private':
|
if 'тупица' in message.text.lower():
|
||||||
response = await gpt_text(message.text)
|
|
||||||
await message.answer(response.choices[0].message.content)
|
response = openai.Completion.create(
|
||||||
|
model="text-davinci-003",
|
||||||
|
prompt=message.text[7:],
|
||||||
|
temperature=0.7,
|
||||||
|
max_tokens=1000,
|
||||||
|
top_p=1.0,
|
||||||
|
frequency_penalty=0.0,
|
||||||
|
presence_penalty=0.6,
|
||||||
|
stop=["сброс"]
|
||||||
|
)
|
||||||
|
await message.reply(response['choices'][0]['text'])
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,146 +1,201 @@
|
|||||||
from aiogram import types
|
from aiogram import types
|
||||||
|
from sqlalchemy.orm.session import close_all_sessions
|
||||||
from create_bot import bot, dp
|
from create_bot import bot, dp
|
||||||
|
from sqdb import User, session, DickRequest, UserDick
|
||||||
import random
|
import random
|
||||||
|
import traceback
|
||||||
from random import randint
|
from random import randint
|
||||||
import datetime, logging
|
import datetime
|
||||||
from dicktxt import ForReadDict, WordsChange
|
from dicktxt import ForReadDict
|
||||||
from pipisa_functions import pipisa_time
|
|
||||||
|
|
||||||
from global_conf import CONFIG
|
size_change = None
|
||||||
|
dick_plus = None
|
||||||
from db_logic import tops, user_stuff, postcleaner
|
dick_minus = None
|
||||||
|
|
||||||
|
|
||||||
admins = CONFIG['telegram_admins_ids']
|
def get_dick(user_id, chat_id):
|
||||||
|
dick = session.query(UserDick).filter(UserDick.user_id == user_id, UserDick.chat_id == chat_id).first()
|
||||||
|
return dick
|
||||||
|
|
||||||
|
def top_dick_message(delimiter, top_list):
|
||||||
|
message = f'🏆Топ 10 бубылд чата🏆\n\n'
|
||||||
|
f'🚀 {delimiter.join(map(str, top_list[0]))}\n'
|
||||||
|
f'💫 {delimiter.join(map(str, top_list[1]))}\n'
|
||||||
|
f'🍆 {delimiter.join(map(str, top_list[2]))}\n'
|
||||||
|
f'🍌 {delimiter.join(map(str, top_list[3]))}\n'
|
||||||
|
f'🐍 {delimiter.join(map(str, top_list[4]))}\n'
|
||||||
|
f'🐎 {delimiter.join(map(str, top_list[5]))}\n'
|
||||||
|
f'🌭 {delimiter.join(map(str, top_list[6]))}\n'
|
||||||
|
f'🌶 {delimiter.join(map(str, top_list[7]))}\n'
|
||||||
|
f'👌 {delimiter.join(map(str, top_list[8]))}\n'
|
||||||
|
f'💩 {delimiter.join(map(str, top_list[9]))}\n'
|
||||||
|
return message
|
||||||
|
|
||||||
|
|
||||||
|
@dp.message_handler(commands=["maintenance"])
|
||||||
|
async def stop_for_maintenance(message: types.Message): # остановить бота
|
||||||
|
if message.from_user.id == 226765676:
|
||||||
|
bot.send_message(message.from_user.id, "Блять. Как же больно. Мне холодно. Наверное это конец...")
|
||||||
|
close_all_sessions()
|
||||||
|
dp.stop_polling()
|
||||||
|
|
||||||
|
|
||||||
@dp.message_handler(commands=["dick"])
|
@dp.message_handler(commands=["dick"])
|
||||||
async def up_dick(message: types.Message):
|
async def up_dick(message: types.Message): # рандомайзер
|
||||||
|
|
||||||
if message.from_user.id in admins or message.chat.type != 'private':
|
numb = randint(-6, 10)
|
||||||
|
global size_change, dick_plus, dick_minus
|
||||||
|
dick_plus = ('<b>вырос</b>', '<b>подрос</b>', '<b>привстал</b>')
|
||||||
|
dick_minus = ('<b>уменьшился</b>', '<b>откусила злая гадюка</b>', '<b>продали евреи, он стал дешевле</b>')
|
||||||
|
if numb > 0:
|
||||||
|
size_change = random.choice(dick_plus) + '🚀'
|
||||||
|
# if numb = 0 size_change = random.choice(const) TODO
|
||||||
|
else:
|
||||||
|
size_change = random.choice(dick_minus) + '✂'
|
||||||
|
|
||||||
|
|
||||||
postcleaner.append_post_to_cleaning_sequence(message=message, type=f'COMMAND_CALL__DICK')
|
# работа с таблицей
|
||||||
await clean_posts(chat_id=message.chat.id, type='COMMAND_CALL__DICK', max_id=message.message_id)
|
try:
|
||||||
|
dick_request = DickRequest(size_change=numb, date_changed=datetime.datetime.now())
|
||||||
|
b = session.query(User).filter(User.user_id == message.from_user.id).first()
|
||||||
|
if b:
|
||||||
|
last_time = b.date_updated
|
||||||
|
now_time = datetime.datetime.now()
|
||||||
|
diff = now_time.day - last_time.day
|
||||||
|
|
||||||
#### TODO уплатить нолог с 100 см для самого нищего
|
if abs(diff) <= 0:
|
||||||
|
try:
|
||||||
|
current_dick = b.dick_size
|
||||||
|
await bot.send_message(message.chat.id, f'@{message.from_user.username},'
|
||||||
|
f'🚫 вы уже крутили пипису, '
|
||||||
|
f'ее размер <b>{current_dick}</b> см! ')
|
||||||
|
except Exception as e:
|
||||||
|
print('ошибка в if diff <=0 ' + "\n".join(traceback.format_tb(e.__traceback__)))
|
||||||
|
session.rollback()
|
||||||
|
finally:
|
||||||
|
session.close_all()
|
||||||
|
print('пользователь уже крутил')
|
||||||
|
|
||||||
# рандомайзер
|
|
||||||
result = randint(-9,10)
|
|
||||||
|
|
||||||
#### Чекнуть есть ли юзер в базе
|
|
||||||
user = user_stuff.get_user(message)
|
|
||||||
|
|
||||||
if user:
|
|
||||||
## Если есть то нарастить и отправить сообщение
|
|
||||||
|
|
||||||
if pipisa_time.rolltime(check_datetime=user['datetimes'], curr_time=datetime.datetime.now()):
|
|
||||||
# пришло время крутить!!
|
|
||||||
|
|
||||||
updatedDick = user["dick_size"] + result
|
|
||||||
user_stuff.update_dick_size(message, user, updatedDick)
|
|
||||||
|
|
||||||
randomdickword = ForReadDict.RandomDick()
|
|
||||||
change_phrase = WordsChange.ChangeWord(result)
|
|
||||||
|
|
||||||
await bot.send_message( message.chat.id,
|
|
||||||
f'@{message.from_user.username}, ваш <em>{randomdickword}</em> {change_phrase} на <b>{abs(result)}</b> см!\nТеперь он равен <b>{updatedDick}</b> см! '
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
mmm = await bot.send_message( message.chat.id,
|
try:
|
||||||
f'@{message.from_user.username}, 🚫 вы уже крутили пипису, её размер <b>{user["dick_size"]}</b> см! '
|
usr = session.query(User)
|
||||||
)
|
a = usr.filter(User.user_id == message.from_user.id).first() # запрос на поиск в таблице
|
||||||
user_stuff.update_attempts( message, user)
|
dick = get_dick(User.user_id, message.chat.id)
|
||||||
|
updated_dick = dick.dick_size = (dick.dick_size + numb)
|
||||||
|
dick_request.user = a
|
||||||
|
a.date_updated = datetime.datetime.now()
|
||||||
|
session.add(dick_request)
|
||||||
|
session.flush()
|
||||||
|
session.commit() # обновляет запись
|
||||||
|
randomword = ForReadDict.RandomDick()
|
||||||
|
|
||||||
|
await bot.send_message(message.chat.id, f'@{message.from_user.username}, '
|
||||||
|
f'ваш <em>{randomword}</em> {size_change}'
|
||||||
|
f'на <b>{abs(numb)}</b> см!\n'
|
||||||
|
f'Теперь он равен <b>{updated_dick}</b> см! ')
|
||||||
|
except Exception as e:
|
||||||
|
session.rollback()
|
||||||
|
print('ошибка в обновлении пиписы, трейсбек-бек-бек: ' +
|
||||||
|
"\n".join(traceback.format_tb(e.__traceback__)))
|
||||||
|
finally:
|
||||||
|
session.close_all()
|
||||||
|
print('пиписа обновлена')
|
||||||
|
|
||||||
postcleaner.append_post_to_cleaning_sequence(message=mmm, type='ALREADY_ROLLED')
|
|
||||||
await clean_posts(chat_id=mmm.chat.id, type='ALREADY_ROLLED', max_id=mmm.message_id)
|
|
||||||
else:
|
else:
|
||||||
## если нету, то создать
|
session.close()
|
||||||
user_stuff.store_new_user(message, result)
|
try:
|
||||||
|
numb = randint(1, 10)
|
||||||
|
int_table = User(user_id=message.from_user.id,
|
||||||
|
user_fullname=message.from_user.full_name,
|
||||||
|
date_updated=datetime.datetime.now(),
|
||||||
|
date_created=datetime.datetime.now())
|
||||||
|
new_dick = DickRequest(user_id=message.from_user.id,
|
||||||
|
chat_id=message.chat.id,
|
||||||
|
dick_size=numb)
|
||||||
|
|
||||||
await bot.send_message( message.chat.id,
|
dick_request.user = int_table
|
||||||
f'@{message.from_user.username}, Добро пожаловать в игру! Ваш писюн показал головку 🚀\nна <b>{abs(result)}</b> см!\nТеперь он равен <b>{abs(result)}</b> см!'
|
session.add(int_table)
|
||||||
)
|
session.add(new_dick)
|
||||||
|
session.add(dick_request)
|
||||||
|
session.flush()
|
||||||
|
session.commit()
|
||||||
|
session.close()
|
||||||
|
await bot.send_message(message.chat.id, f'@{message.from_user.username}, '
|
||||||
|
f'ваш писюн показал головку 🚀 \n'
|
||||||
|
f'на <b>{abs(numb)}</b> см!\n'
|
||||||
|
f'Теперь он равен <b>{numb}</b> см!')
|
||||||
|
except Exception as e:
|
||||||
|
print('ошибка в добавлении нового пользователя, трейсбек: ' +
|
||||||
|
'\n'.join(traceback.format_tb(e.__traceback__)))
|
||||||
|
session.rollback()
|
||||||
|
finally:
|
||||||
|
session.close_all()
|
||||||
|
print('Успешно добавлен пользователь')
|
||||||
|
|
||||||
else:
|
except Exception as e:
|
||||||
await message.reply('Растить елду можно только в общих чатах!')
|
session.rollback()
|
||||||
|
print('ошибка в основном коде, трейсбек:' + '\n'.join(traceback.format_tb(e.__traceback__)))
|
||||||
|
finally:
|
||||||
|
session.close_all()
|
||||||
|
|
||||||
|
|
||||||
|
@dp.message_handler(commands=["topdick"])
|
||||||
|
async def send_top_chat(message: types.Message):
|
||||||
|
try:
|
||||||
|
top = []
|
||||||
|
chats = message.chat.id
|
||||||
|
changechat_id = session.query(DickRequest).filter(DickRequest.user_id == message.from_user.id,
|
||||||
|
DickRequest.chat_id == chats).first()
|
||||||
|
dicks = session.query(DickRequest)\
|
||||||
|
.filter(DickRequest.chat_id == chats)\
|
||||||
|
.limit(10).all()\
|
||||||
|
.order_by(DickRequest.dick_size.desc())
|
||||||
|
for dick in dicks:
|
||||||
|
user = session.query(User.user_fullname).filter(User.user_id == dick.user_id)
|
||||||
|
top.append([user.full_name, dick.dick_size])
|
||||||
|
delimiter = ': '
|
||||||
|
|
||||||
@dp.message_handler(commands = ['topdick', 'globaldick'])
|
# проверка на длину списка, если меньше limit, то:
|
||||||
async def send_topchat(message: types.Message):
|
|
||||||
if message.from_user.id in admins or message.chat.type != 'private':
|
|
||||||
|
|
||||||
top_ = message['text'].startswith('/topdick')
|
size_len = len(top)
|
||||||
glob_ = message['text'].startswith('/globaldick')
|
if size_len < 10:
|
||||||
|
len_minus = 10 - size_len
|
||||||
|
top.extend([('-'*len_minus),""])
|
||||||
|
await bot.send_message(message.chat.id, top_dick_message(delimiter, top))
|
||||||
|
session.close()
|
||||||
|
# если все нормально и участников минимум 10
|
||||||
|
|
||||||
if top_:
|
|
||||||
dickos = tops.get_tops( top_ = True, chat_id=message.chat.id )
|
|
||||||
postcleaner.append_post_to_cleaning_sequence(message=message, type=f'COMMAND_CALL__TOPDICK')
|
|
||||||
await clean_posts(chat_id=message.chat.id, type='COMMAND_CALL__TOPDICK', max_id=message.message_id)
|
|
||||||
elif glob_:
|
|
||||||
dickos = tops.get_tops( glob_ = True )
|
|
||||||
postcleaner.append_post_to_cleaning_sequence(message=message, type=f'COMMAND_CALL__GLOBALDICK')
|
|
||||||
await clean_posts(chat_id=message.chat.id, type='COMMAND_CALL__GLOBALDICK', max_id=message.message_id)
|
|
||||||
else:
|
else:
|
||||||
logging.error('вызывают хз что!')
|
|
||||||
|
await bot.send_message(message.chat.id, top_dick_message(delimiter, top))
|
||||||
|
except Exception as e:
|
||||||
|
session.rollback()
|
||||||
|
print('ошибка в /topdick. Трейсбэк:\n' + '\n'.join(traceback.format_tb(e.__traceback__)))
|
||||||
|
finally:
|
||||||
|
session.close_all()
|
||||||
|
|
||||||
|
|
||||||
if not dickos:
|
@dp.message_handler(commands=["globaldick"])
|
||||||
await bot.send_message(message.chat.id, '🍆 Никто ничего не нарастил! 🍌')
|
async def send_global_top(message: types.Message):
|
||||||
else:
|
try:
|
||||||
if top_:
|
top = []
|
||||||
await bot.send_message(message.chat.id, '🏆Топ 10 бубылд чата🏆\n\n' + dickos)
|
dicks = session.query(DickRequest) \
|
||||||
elif glob_:
|
.limit(10).all() \
|
||||||
await bot.send_message(message.chat.id, '🏆Топ 10 пипис в мире🏆\n\n' + dickos)
|
.order_by(DickRequest.dick_size.desc())
|
||||||
else:
|
for dick in dicks:
|
||||||
await message.reply('Работает только в общих чатах!\n'\
|
user = session.query(User.user_fullname).filter(User.user_id == dick.user_id)
|
||||||
'Вы можете посмотреть топ по миру /globaldick')
|
top.append([user.full_name, dick.dick_size])
|
||||||
|
delimiter = ': '
|
||||||
|
|
||||||
@dp.message_handler(commands = ['antitopdick', 'antiglobaldick'])
|
await bot.send_message(message.chat.id, top_dick_message(delimiter, top))
|
||||||
async def send_antitopchat(message: types.Message):
|
except Exception as e:
|
||||||
if message.from_user.id in admins or message.chat.type != 'private':
|
session.rollback()
|
||||||
antitop_ = message['text'].startswith('/antitopdick')
|
print('ошибка в /globaldick, трейсбэк:\n' + '\n'.join(traceback.format_tb(e.__traceback__)))
|
||||||
antiglob_ = message['text'].startswith('/antiglobaldick')
|
finally:
|
||||||
|
session.close_all()
|
||||||
if antitop_:
|
|
||||||
dickos = tops.get_antitops(top_=True, chat_id=message.chat.id)
|
|
||||||
postcleaner.append_post_to_cleaning_sequence(message=message, type=f'COMMAND_CALL__ANTITOPDICK')
|
|
||||||
await clean_posts(chat_id=message.chat.id, type='COMMAND_CALL__ANTITOPDICK', max_id=message.message_id)
|
|
||||||
elif antiglob_:
|
|
||||||
dickos = tops.get_antitops(glob_=True)
|
|
||||||
postcleaner.append_post_to_cleaning_sequence(message=message, type=f'COMMAND_CALL__ANTIGLOBALDICK')
|
|
||||||
await clean_posts(chat_id=message.chat.id, type='COMMAND_CALL__ANTIGLOBALDICK', max_id=message.message_id)
|
|
||||||
else:
|
|
||||||
logging.error('вызывают хз что!')
|
|
||||||
|
|
||||||
if not dickos:
|
|
||||||
await bot.send_message(message.chat.id, '🍌 У всех пользователей бубылда растёт! 🍆')
|
|
||||||
else:
|
|
||||||
if antitop_:
|
|
||||||
await bot.send_message(message.chat.id, '🚫Антитоп 10 вагись чата🚫\n\n' + dickos)
|
|
||||||
elif antiglob_:
|
|
||||||
await bot.send_message(message.chat.id, '🚫Антитоп 10 вагись в мире🚫\n\n' + dickos)
|
|
||||||
else:
|
|
||||||
await message.reply('Работает только в общих чатах!\n'\
|
|
||||||
'Вы можете посмотреть антитоп по миру /antiglobaldick')
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
async def clean_posts(chat_id, type=None, max_id=None):
|
|
||||||
psts = postcleaner.get_posts_to_be_removed(chat_id, type, max_id)
|
|
||||||
|
|
||||||
for p in psts:
|
|
||||||
postcleaner.del_post(chat_id=p['chat_id'], msg_id=p['msg_id'])
|
|
||||||
|
|
||||||
#### TODO проверить админит ли бот
|
|
||||||
|
|
||||||
try:
|
|
||||||
await bot.delete_message( chat_id=p['chat_id'], message_id=p['msg_id'], )
|
|
||||||
except Exception as e:
|
|
||||||
logging.error('ошибка удаления поста-на-удаление')
|
|
||||||
logging.error(e)
|
|
||||||
|
|
||||||
|
|
||||||
|
# def register_handlers_pipisa(dp: Dispatcher):
|
||||||
|
# dp.register_message_handler(up_dick)
|
||||||
|
# dp.register_message_handler(send_topchat)
|
||||||
|
# dp.register_message_handler(send_global_top)
|
||||||
|
32
handlers/sendalarm.py
Normal file
32
handlers/sendalarm.py
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
import traceback
|
||||||
|
|
||||||
|
from create_bot import dp, bot
|
||||||
|
from aiogram import types, Dispatcher
|
||||||
|
from sqdb import User, session
|
||||||
|
|
||||||
|
|
||||||
|
@dp.message_handler(commands=['sendall'])
|
||||||
|
async def sendall(message: types.Message):
|
||||||
|
print('команда прошла')
|
||||||
|
if message.chat.type == 'private':
|
||||||
|
if message.from_user.id == 226765676:
|
||||||
|
text = message.text[9:]
|
||||||
|
try:
|
||||||
|
chats_id = session.query(User.chat_id).distinct()
|
||||||
|
for row in chats_id:
|
||||||
|
try:
|
||||||
|
await bot.send_message(row[0], text)
|
||||||
|
except Exception as e:
|
||||||
|
print('вероятно бота нет в чате, на всякий случай трейсбек:\n' +
|
||||||
|
"\n".join(traceback.format_tb(e.__traceback__)))
|
||||||
|
await bot.send_message(message.from_user.id, 'Сообщение успешно отправлено во все чаты')
|
||||||
|
except Exception as e:
|
||||||
|
session.rollback()
|
||||||
|
print('error sendall, traceback:\n' +
|
||||||
|
"\n".join(traceback.format_tb(e.__traceback__)))
|
||||||
|
finally:
|
||||||
|
session.close_all()
|
||||||
|
|
||||||
|
|
||||||
|
# def register_handlers_test(dp: Dispatcher):
|
||||||
|
# dp.register_message_handler(send_welcome)
|
@ -1,27 +1,28 @@
|
|||||||
from aiogram import types
|
from aiogram import types
|
||||||
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
|
||||||
from create_bot import dp, bot
|
from create_bot import dp, bot
|
||||||
|
|
||||||
|
|
||||||
@dp.message_handler(commands=['start'])
|
@dp.message_handler(commands=['start'])
|
||||||
async def start_func(message: types.Message):
|
async def start_func(message: types.Message):
|
||||||
if message.chat.type == 'private':
|
await message.reply('похуй')
|
||||||
|
|
||||||
lkb = InlineKeyboardMarkup(row_width=1).add(InlineKeyboardButton(text = 'Добавить в группу', callback_data='add_2_group'))
|
|
||||||
|
|
||||||
await message.answer(f'<b>Добро пожаловать, {message.from_user.full_name}!</b>\n'
|
|
||||||
'Это бот, который растит члены. Чтобы начать, добавь бота в чат'\
|
|
||||||
, reply_markup=lkb
|
|
||||||
|
|
||||||
)
|
|
||||||
# TODO добавить кнопку, по которой смогут добавлять юзера в чат
|
|
||||||
|
|
||||||
@dp.callback_query_handler(text = 'add_2_group')
|
|
||||||
async def addgroup(callback: types.CallbackQuery):
|
|
||||||
await callback.answer('жмав')
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@dp.message_handler(commands=['photo'])
|
||||||
|
async def send_image(message: types.Message):
|
||||||
|
await bot.send_photo(message.chat.id,
|
||||||
|
photo='https://memepedia.ru/wp-content/uploads/2018/08/ya-pidoras.jpg',
|
||||||
|
reply_to_message_id=message.message_id)
|
||||||
|
|
||||||
|
|
||||||
|
@dp.message_handler(content_types=types.ContentTypes.TEXT)
|
||||||
|
async def send_faggot(message: types.Message):
|
||||||
|
print(message.text)
|
||||||
|
if message.text == 'хто я':
|
||||||
|
await bot.send_photo(message.chat.id,
|
||||||
|
photo='https://www.meme-arsenal.com/memes/ecebd2339c7eab40e09874bd86a38a09.jpg')
|
||||||
|
|
||||||
|
|
||||||
|
# def register_handlers_StartHelp(dp: Dispatcher):
|
||||||
|
# dp.register_message_handler(start_func)
|
||||||
|
# dp.register_message_handler(send_faggot)
|
||||||
|
# dp.register_message_handler(send_image)
|
||||||
|
@ -1,27 +1,28 @@
|
|||||||
from aiogram import types, Dispatcher
|
from aiogram import types
|
||||||
from create_bot import dp, bot
|
from create_bot import dp
|
||||||
import datetime
|
import datetime
|
||||||
|
|
||||||
|
|
||||||
@dp.message_handler(commands=["time"])
|
@dp.message_handler(commands=["time"])
|
||||||
async def send_time(message: types.Message):
|
async def send_time(message: types.Message):
|
||||||
new_year = datetime.datetime(datetime.datetime.now().year, 12, 31) #дата нового года
|
new_year = datetime.datetime(2024, 12, 31) # дата нового года
|
||||||
ct = datetime.datetime.now() #датавремя
|
ct = datetime.datetime.now() # дата/время
|
||||||
cd = datetime.datetime.now().strftime("%d/%m/%Y") #дата (д,м,г)
|
cd = datetime.datetime.now().strftime("%d/%m/%Y") # дата (д,м,г)
|
||||||
ct1 = ct # zoichem??? +datetime.timedelta(hours=15) # +14 часов от сервера
|
ct1 = ct+datetime.timedelta(hours=15) # +14 часов от сервера
|
||||||
ct2 = ct1.strftime('%H:%M') # форматирует датувремя просто во время(ч,м)
|
ct2 = ct1.strftime('%H:%M') # форматирует дату/время просто во время(ч, м)
|
||||||
raznitsa = (new_year - ct).days #отнимает от нг текущее время и получаем разницу в днях
|
date_difference = (new_year - ct).days # отнимает от нг текущее время и получаем разницу в днях
|
||||||
|
|
||||||
days = ['день', 'дня', 'дней']
|
days = ['день', 'дня', 'дней']
|
||||||
if raznitsa % 10 == 1 and raznitsa % 100 != 11:
|
if date_difference % 10 == 1 and date_difference % 100 != 11:
|
||||||
p = 0
|
p = 0
|
||||||
elif 2 <= raznitsa % 10 <= 4 and (raznitsa % 100 < 10 or raznitsa % 100 >= 20):
|
elif 2 <= date_difference % 10 <= 4 and (date_difference % 100 < 10 or date_difference % 100 >= 20):
|
||||||
p = 1
|
p = 1
|
||||||
else:
|
else:
|
||||||
p = 2
|
p = 2
|
||||||
num=(str(raznitsa) + ' ' + days[p])
|
num = (str(date_difference) + ' ' + days[p])
|
||||||
|
|
||||||
await message.reply(f'Сегодня {cd} \nВремя: {ct2} \nДо Нового Года осталось {num}')
|
await message.reply(f'Сегодня {cd} \nВремя: {ct2} \nДо Нового Года осталось {num}')
|
||||||
|
|
||||||
|
|
||||||
def register_handlers_time(dp: Dispatcher):
|
# def register_handlers_time(dp: Dispatcher):
|
||||||
dp.register_message_handler(send_time)
|
# dp.register_message_handler(send_time)
|
||||||
|
@ -1,15 +0,0 @@
|
|||||||
# пример того что лежит на хосте
|
|
||||||
[Unit]
|
|
||||||
Description=pipisa-bot
|
|
||||||
After=network.target
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
User=jack
|
|
||||||
Type=simple
|
|
||||||
Restart=always
|
|
||||||
WorkingDirectory=/usr/share/python_bot
|
|
||||||
ExecStart=/usr/bin/python3 /usr/share/python_bot/bot.py
|
|
||||||
ExecStart=/usr/bin/python3 /usr/share/python_bot/bot.py
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=multi-user.target#
|
|
@ -1 +0,0 @@
|
|||||||
from . import pipisa_time
|
|
@ -1,88 +0,0 @@
|
|||||||
|
|
||||||
import unittest
|
|
||||||
import datetime
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def rolltime(check_datetime , curr_time=datetime.datetime.now()):
|
|
||||||
|
|
||||||
last_time = datetime.datetime.strptime(check_datetime, '%Y-%m-%d %H:%M:%S')
|
|
||||||
time_to_grow = curr_time.replace(hour=14, minute=8, second=8, microsecond=0) #+ datetime.timedelta(days=0)
|
|
||||||
|
|
||||||
timediff = (time_to_grow - last_time).total_seconds()
|
|
||||||
|
|
||||||
# print()
|
|
||||||
# print(f'\tlast_time : {last_time}')
|
|
||||||
# print(f'\ttime_to_grow : {time_to_grow}')
|
|
||||||
# print(f'\tcurr_time : {curr_time.strftime("%Y-%m-%d %H:%M:%S")}')
|
|
||||||
# print(f'\t\tsecs diff : {timediff}')
|
|
||||||
|
|
||||||
|
|
||||||
if timediff > 86400 or (curr_time > time_to_grow and last_time < time_to_grow):
|
|
||||||
return True
|
|
||||||
else:
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class TestPipisa(unittest.TestCase):
|
|
||||||
def test_very_long_ago(self):
|
|
||||||
self.assertEqual(rolltime('2021-10-11 23:44:00'), True, "Пиписа прокручена очень давно. Очевидный прокрут")
|
|
||||||
|
|
||||||
def test_just_after(self):
|
|
||||||
self.assertEqual(rolltime(
|
|
||||||
datetime.datetime.now().replace(hour=14, minute=9, second=8, microsecond=0).strftime('%Y-%m-%d %H:%M:%S')
|
|
||||||
), False, "Попытка крутить когда старый прокрут был через 1 минуту после сегодняшнего обновления роллов. Фейл.")
|
|
||||||
|
|
||||||
def test_yesterdayroll(self):
|
|
||||||
self.assertEqual(
|
|
||||||
rolltime(
|
|
||||||
(
|
|
||||||
datetime.datetime.now().replace(hour=14, minute=9, second=8, microsecond=0) - datetime.timedelta(days=1)
|
|
||||||
).strftime('%Y-%m-%d %H:%M:%S'),
|
|
||||||
datetime.datetime.now().replace(hour=14, minute=9, second=8, microsecond=0)
|
|
||||||
), True, "Крутилась вчера через минуту после обновления роллов. Должно пропускать ")
|
|
||||||
|
|
||||||
|
|
||||||
def test_hour_before_roll(self):
|
|
||||||
self.assertEqual(
|
|
||||||
rolltime(
|
|
||||||
(
|
|
||||||
datetime.datetime.now().replace(hour=14, minute=9, second=8, microsecond=0) - datetime.timedelta(hours=1)
|
|
||||||
).strftime('%Y-%m-%d %H:%M:%S'),
|
|
||||||
datetime.datetime.now().replace(hour=14, minute=9, second=8, microsecond=0)
|
|
||||||
), True, "Крутилась последний раз за час до прокрута. Надо разрешать заново!")
|
|
||||||
|
|
||||||
def test_after_midnight(self):
|
|
||||||
self.assertEqual(
|
|
||||||
rolltime(
|
|
||||||
(
|
|
||||||
datetime.datetime.now().replace(hour=14, minute=9, second=8, microsecond=0) - datetime.timedelta(hours=14)
|
|
||||||
).strftime('%Y-%m-%d %H:%M:%S'),
|
|
||||||
datetime.datetime.now().replace(hour=0, minute=11, second=8, microsecond=0)
|
|
||||||
), False, "Где-то ночью прокручивается повторно. Фейл.")
|
|
||||||
|
|
||||||
def test_before_midnight(self):
|
|
||||||
self.assertEqual(
|
|
||||||
rolltime(
|
|
||||||
(
|
|
||||||
datetime.datetime.now().replace(hour=14, minute=9, second=8, microsecond=0) - datetime.timedelta(hours=15)
|
|
||||||
).strftime('%Y-%m-%d %H:%M:%S'),
|
|
||||||
datetime.datetime.now().replace(hour=0, minute=11, second=8, microsecond=0) - datetime.timedelta(hours=15)
|
|
||||||
), False, "Где-то ночью прокручивается повторно. Фейл.")
|
|
||||||
|
|
||||||
def test_somewhere_after(self):
|
|
||||||
self.assertEqual(
|
|
||||||
rolltime(
|
|
||||||
(
|
|
||||||
datetime.datetime.now().replace(hour=14, minute=26, second=8, microsecond=0)
|
|
||||||
).strftime('%Y-%m-%d %H:%M:%S'),
|
|
||||||
datetime.datetime.now().replace(hour=14, minute=27, second=8, microsecond=0)
|
|
||||||
), False, "Сегодня уже открутили а хотят ещё. Фейл.")
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main(verbosity=2)
|
|
@ -1,3 +0,0 @@
|
|||||||
aiogram==2.15
|
|
||||||
python-arango
|
|
||||||
pyyaml
|
|
6
requirements.txt
Normal file
6
requirements.txt
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
aiogram
|
||||||
|
sqdb
|
||||||
|
sqlalchemy
|
||||||
|
graypy
|
||||||
|
openai
|
||||||
|
psycopg2
|
71
sqdb.py
Normal file
71
sqdb.py
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
from sqlalchemy import create_engine, MetaData, Table, Integer, String, BIGINT, \
|
||||||
|
Column, DateTime, ForeignKey, Numeric
|
||||||
|
from sqlalchemy.ext.declarative import declarative_base
|
||||||
|
from sqlalchemy.orm import sessionmaker, relationship
|
||||||
|
from sqlalchemy import select, update
|
||||||
|
engine = create_engine('postgresql+psycopg2://postgres:postgres@postgres.vdk2ch.ru:5432/jack_bot', echo=True)
|
||||||
|
Session = sessionmaker(bind=engine)
|
||||||
|
session = Session()
|
||||||
|
|
||||||
|
Base = declarative_base()
|
||||||
|
|
||||||
|
|
||||||
|
class User(Base):
|
||||||
|
__tablename__ = 'users'
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True)
|
||||||
|
user_id = Column(Integer)
|
||||||
|
date_created = (Column(DateTime))
|
||||||
|
user_fullname = Column(String)
|
||||||
|
date_updated = (Column(DateTime))
|
||||||
|
dick_requests = relationship("DickRequest", back_populates="user")
|
||||||
|
user_dicks = relationship("UserDick", back_populates="user")
|
||||||
|
|
||||||
|
|
||||||
|
class UserDick(Base):
|
||||||
|
__tablename__ = 'user_dicks'
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True)
|
||||||
|
user_id = Column(Integer, ForeignKey("users.user_id"))
|
||||||
|
dick_size = (Column(Integer))
|
||||||
|
chat_id = Column(BIGINT)
|
||||||
|
user = relationship("User", back_populates="user_dicks")
|
||||||
|
|
||||||
|
|
||||||
|
class DickRequest(Base):
|
||||||
|
__tablename__ = 'dick_requests'
|
||||||
|
id = Column(Integer, primary_key=True)
|
||||||
|
size_change = Column(Integer)
|
||||||
|
user_id = Column(Integer, ForeignKey("users.user_id"))
|
||||||
|
user = relationship("User", back_populates="dick_requests")
|
||||||
|
date_changed = (Column(DateTime))
|
||||||
|
|
||||||
|
session.close()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
# top = session.query(user.user_fullname, user.dick_size)
|
||||||
|
# .order_by(user.dick_size.desc())
|
||||||
|
# .filter(user.chat_id == user.chat_id).limit(10).all()
|
||||||
|
# print(top)
|
||||||
|
|
||||||
|
|
||||||
|
#Base.metadata.create_all(engine)
|
||||||
|
|
||||||
|
# int_table = user(user_id = 12345678, user_fullname = 'test', dick_size = 10) #импортирую юзер из sqdb
|
||||||
|
# session.add(int_table)
|
||||||
|
# session.commit()
|
||||||
|
# select user_id, name from employees limit 10
|
||||||
|
|
||||||
|
# def adding():
|
||||||
|
|
||||||
|
# session.add()
|
||||||
|
# session.commit()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user