🗃️ Add basic database support using SQLAlchemy and Alembic
Some checks failed
ci / docker (push) Successful in 4m54s
Python formatting PEP8 / Python-PEP8 (push) Failing after 13s

This commit is contained in:
Finn Christiansen 2024-06-16 20:57:18 +02:00
parent d6792c91a8
commit 9a2a18172c
13 changed files with 325 additions and 13 deletions

View file

@ -1,3 +1,4 @@
HOMESERVER="https://example.org" HOMESERVER="https://example.org"
USERNAME="PrayingTimesBotUsername" USERNAME="PrayingTimesBotUsername"
PASSWORD="supersecret" PASSWORD="supersecret"
DB_URI="sqlite:///data/database.db"

1
.gitignore vendored
View file

@ -1,6 +1,7 @@
# created by virtualenv automatically # created by virtualenv automatically
bin/ bin/
lib/ lib/
include/
__pycache__ __pycache__
pyvenv.cfg pyvenv.cfg
.env .env

116
alembic.ini Normal file
View file

@ -0,0 +1,116 @@
# 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>=3.9 or backports.zoneinfo library.
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
# string value is passed to ZoneInfo()
# 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 migrations/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:migrations/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 = driver://user:pass@localhost/dbname
[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
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
# hooks = ruff
# ruff.type = exec
# ruff.executable = %(here)s/.venv/bin/ruff
# ruff.options = --fix 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
View file

@ -0,0 +1 @@
Generic single-database configuration.

83
alembic/env.py Normal file
View file

@ -0,0 +1,83 @@
import os
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
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
config.set_main_option("sqlalchemy.url", os.getenv("DB_URI"))
# 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 = None
from matrix_bot_praying_times.db import Base
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()

26
alembic/script.py.mako Normal file
View file

@ -0,0 +1,26 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}

View file

@ -0,0 +1,37 @@
"""Initial migration
Revision ID: 12669d9a145b
Revises:
Create Date: 2024-06-16 20:53:32.463819
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '12669d9a145b'
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(), nullable=True),
sa.Column('location', sa.String(), nullable=True),
sa.Column('room_id', sa.String(), nullable=True),
sa.Column('reminder_time_in_minutes', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('user')
# ### end Alembic commands ###

View file

@ -0,0 +1 @@
from .models.user import User

View file

@ -6,6 +6,11 @@ import pytz
from typing import Dict from typing import Dict
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from .models.user import User
from sqlalchemy import create_engine
from sqlalchemy.sql import select
from sqlalchemy.orm import sessionmaker
load_dotenv() load_dotenv()
@ -20,9 +25,10 @@ bot = botlib.Bot(creds)
PREFIX = '!' PREFIX = '!'
utc = pytz.UTC utc = pytz.UTC
user_locations: dict = {} engine = create_engine(os.getenv("DB_URI"))
user_reminders: dict = {} Session = sessionmaker(bind=engine)
user_room_ids: dict = {} session = Session()
@bot.listener.on_message_event @bot.listener.on_message_event
@ -42,13 +48,15 @@ async def times(room, message) -> None:
username = str(message).split(': ')[0] username = str(message).split(': ')[0]
response = "" response = ""
user = session.query(User).filter(User.username == username, User.location != "").one_or_none()
if match.is_not_from_this_bot() and match.prefix() and match.command("times"): if match.is_not_from_this_bot() and match.prefix() and match.command("times"):
if username not in user_locations: if not user:
response = "Please set your location first using *!set-location City, Country*" response = "Please set your location first using *!set-location City, Country*"
else: else:
times = get_praying_times(datetime.datetime.today(), username) times = get_praying_times(datetime.datetime.today(), username)
response = "Today's praying times for {}:\n\n".format(user_locations[username]) response = "Today's praying times for {}:\n\n".format(user.location)
response += "\n".join("{}: {}".format(key, value) for key, value in times.items()) response += "\n".join("{}: {}".format(key, value) for key, value in times.items())
await bot.api.send_markdown_message(room.room_id, response) await bot.api.send_markdown_message(room.room_id, response)
@ -77,7 +85,15 @@ async def set_location(room, message) -> None:
if match.is_not_from_this_bot() and match.prefix() and match.command("set-location"): if match.is_not_from_this_bot() and match.prefix() and match.command("set-location"):
location = " ".join(arg for arg in match.args()) location = " ".join(arg for arg in match.args())
username = str(message).split(': ')[0] username = str(message).split(': ')[0]
user_locations[username] = location
user = session.query(User).filter_by(username=username).one_or_none()
if not user:
# create new user
user = User(username=username, location=location)
session.add(user)
user.location = location
session.commit()
response = "Your location was set to: {}".format(location) response = "Your location was set to: {}".format(location)
await bot.api.send_markdown_message(room.room_id, response) await bot.api.send_markdown_message(room.room_id, response)
@ -91,13 +107,14 @@ async def set_reminder(room, message) -> None:
if match.is_not_from_this_bot() and match.prefix() and match.command("set-reminder"): if match.is_not_from_this_bot() and match.prefix() and match.command("set-reminder"):
minutes = int(match.args()[0]) minutes = int(match.args()[0])
username = str(message).split(': ')[0] username = str(message).split(': ')[0]
user = session.query(User).filter(User.username == username, User.location != "").one_or_none()
if username not in user_locations: if not user:
response = "You did not set your location yet." response = "You did not set your location yet."
await bot.api.send_markdown_message(room.room_id, response) await bot.api.send_markdown_message(room.room_id, response)
else: else:
user_reminders[username] = minutes user.reminder_time_in_minues = minutes
user_room_ids[username] = room.room_id user.room_id = room.room_id
response = "Your reminder was set to {} minutes before praying.".format(minutes) response = "Your reminder was set to {} minutes before praying.".format(minutes)
schedule_reminder(username) schedule_reminder(username)
await bot.api.send_markdown_message(room.room_id, response) await bot.api.send_markdown_message(room.room_id, response)
@ -107,15 +124,16 @@ def get_praying_times(date: datetime.date, username) -> Dict[str, str]:
day = date.day day = date.day
month = date.month month = date.month
year = date.year year = date.year
times_api_url = 'http://api.aladhan.com/v1/timingsByAddress/{}-{}-{}?address={}&method=7&iso8601=true'.format(day, month, year, user_locations[username]) user = session.query(User).filter_by(username=username).one_or_none()
times_api_url = 'http://api.aladhan.com/v1/timingsByAddress/{}-{}-{}?address={}&method=7&iso8601=true'.format(day, month, year, user.location)
times = requests.get(times_api_url) times = requests.get(times_api_url)
times = times.json()['data']['timings'] times = times.json()['data']['timings']
return times return times
def schedule_reminder(username) -> None: def schedule_reminder(username) -> None:
# TODO: add peristence for reminders
now = datetime.datetime.now(datetime.UTC) now = datetime.datetime.now(datetime.UTC)
user = session.query(User).filter_by(username=username).one_or_none()
# as a workaround until it's finished schedule the next 7 days # as a workaround until it's finished schedule the next 7 days
for i in range(7): for i in range(7):
times = get_praying_times(datetime.date.today() + datetime.timedelta(days=i), username) times = get_praying_times(datetime.date.today() + datetime.timedelta(days=i), username)
@ -124,12 +142,13 @@ def schedule_reminder(username) -> None:
if praying_time > now: if praying_time > now:
seconds = int((praying_time - now).total_seconds()) seconds = int((praying_time - now).total_seconds())
message = "{} is at {}".format(prayer, praying_time.strftime("%H:%M")) message = "{} is at {}".format(prayer, praying_time.strftime("%H:%M"))
asyncio.ensure_future(remind(username, message, seconds - user_reminders[username] * 60)) asyncio.ensure_future(remind(username, message, seconds - user.reminder_time_in_minues * 60))
async def remind(username, message, seconds) -> None: async def remind(username, message, seconds) -> None:
await asyncio.sleep(seconds) await asyncio.sleep(seconds)
await bot.api.send_markdown_message(user_room_ids[username], message) user = session.query(User).filter_by(username=username).one_or_none()
await bot.api.send_markdown_message(user.room_id, message)
bot.run() bot.run()

View file

@ -0,0 +1,7 @@
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()

View file

@ -0,0 +1,13 @@
from sqlalchemy import Column, String, Integer
from ..db import Base
class User(Base):
__tablename__ = "user"
id = Column(Integer, primary_key=True)
username = Column(String)
location = Column(String)
room_id = Column(String)
reminder_time_in_minutes = Column(Integer)

View file

@ -1,7 +1,9 @@
adhanpy==1.0.5
aiofiles==23.2.1 aiofiles==23.2.1
aiohttp==3.9.5 aiohttp==3.9.5
aiohttp-socks==0.8.4 aiohttp-socks==0.8.4
aiosignal==1.3.1 aiosignal==1.3.1
alembic==1.13.1
async-timeout==4.0.3 async-timeout==4.0.3
attrs==23.2.0 attrs==23.2.0
certifi==2024.6.2 certifi==2024.6.2
@ -9,6 +11,7 @@ cffi==1.16.0
charset-normalizer==3.3.2 charset-normalizer==3.3.2
cryptography==42.0.8 cryptography==42.0.8
frozenlist==1.4.1 frozenlist==1.4.1
greenlet==3.0.3
h11==0.14.0 h11==0.14.0
h2==4.1.0 h2==4.1.0
hpack==4.0.0 hpack==4.0.0
@ -16,7 +19,9 @@ hyperframe==6.0.1
idna==3.7 idna==3.7
jsonschema==4.22.0 jsonschema==4.22.0
jsonschema-specifications==2023.12.1 jsonschema-specifications==2023.12.1
Mako==1.3.5
Markdown==3.6 Markdown==3.6
MarkupSafe==2.1.5
matrix-nio==0.24.0 matrix-nio==0.24.0
multidict==6.0.5 multidict==6.0.5
pillow==10.3.0 pillow==10.3.0
@ -30,7 +35,9 @@ referencing==0.35.1
requests==2.32.3 requests==2.32.3
rpds-py==0.18.1 rpds-py==0.18.1
simplematrixbotlib==2.11.0 simplematrixbotlib==2.11.0
SQLAlchemy==2.0.30
toml==0.10.2 toml==0.10.2
typing_extensions==4.12.2
unpaddedbase64==2.1.0 unpaddedbase64==2.1.0
urllib3==2.2.1 urllib3==2.2.1
yarl==1.9.4 yarl==1.9.4