Skip to content

Commit

Permalink
Merge pull request #72 from ajstewart/discordv2
Browse files Browse the repository at this point in the history
Update for discord.py v2.0
  • Loading branch information
ajstewart authored Jun 23, 2022
2 parents 457a6da + 1eb8094 commit 269650c
Show file tree
Hide file tree
Showing 26 changed files with 2,052 additions and 1,053 deletions.
7 changes: 5 additions & 2 deletions .env_template
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ DISCORD_TOKEN="Insert token here"
# Full path to the database created with `initdb.py`
DATABASE="/full/path/to/database.db"

DEFAULT_OPEN_MESSAGE="Used the Poké Flute and Snorlax woke up! Channel open! Will close at {} {}."
DEFAULT_CLOSE_MESSAGE="Snorlax is blocking the path! Channel closed! Will reopen at {} {}."
DEFAULT_OPEN_MESSAGE="**Used the Poké Flute and Snorlax woke up!**"
DEFAULT_CLOSE_MESSAGE="**Snorlax is blocking the path!**"
DEFAULT_TZ="Australia/Sydney"

# Time before warning.
Expand All @@ -22,3 +22,6 @@ BAN_NAMES=

# Default prefix
DEFAULT_PREFIX=!

# ID of the test server if developing (loads cogs and registers slash commands only to this server)
TEST_GUILD=
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
*.pyc
.env
*.db
*.db.bk
*.log
.DS_Store
alembic.ini
59 changes: 40 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,18 @@ It seems to do the job but undoubtedly could be done much better!
It is for this reason that I am not yet generally using an invite link for a hosted instance, and rather made the code public for people to self-host if they wish.
But if you are interested in using a hosted instance please find me on the Sydney Pokemon Go server.

This is yet to be updated to use discord.py >= 2.0, so threads and slash commands are not supported.
This version supports `discord.py` v2.0 however it only contains all the features that were present in Snorlax v0.2.0. Slash commands are coming!

## Requirements

* Python 3.5.3+ (tested on 3.8.5)
* discord.py > 1.6.0, < 2.0
* Python 3.9+
* discord.py >= 2.0
* pandas > 1.1.0
* python-dotenv == 0.20.0
* alembic == 1.8.0
* aiosqlite == 0.17.0

There is a requirements.txt file to install the dependancies from:
There is a requirements.txt file to install the dependencies from:
```
pip install -r requirements.txt
```
Expand All @@ -33,22 +36,30 @@ pip install -r requirements.txt

3. Checkout the `main` branch.

```
git checkout main
```
```
git checkout main
```

4. Initialise the sqlite3 database using the initdb.py script:
```
python initdb.py
```
this will create `database.db`.
4. Copy the `alembic.ini.template` file to `alembic.ini` and edit line `58` by replacing "ENTER DATABASE HERE!" with your intended database name, e.g.

```
sqlalchemy.url = sqlite:///database.db
```

and then run:

```
alembic upgrade head
```

which will create the database.

5. Copy the `.env_template` to `.env` and proceed to enter your settings.

6. Run the bot with:
```
python bot.py
```
```
python bot.py
```

## Permissions Required

Expand Down Expand Up @@ -155,15 +166,17 @@ To set this up:
1. Create a voice channel and make sure the permissions are so that no one can connect to it.
2. Copy the ID of the voice channel created.
3. Enter the following command in Discord in the Snorlax admin channel, replacing ID with the channel ID copied (the `<#>` is needed in this case):
```
@Officer Snorlax setTimeChannel <#ID>
```
```
@Officer Snorlax setTimeChannel <#ID>
```

The voice channel name will now be updated every 10 minutes and will look like the example below.

![setTimeChannel](/screenshots/setTimeChannel.png)
![Time Example](/screenshots/time_display_example.png)

Note that Snorlax should take care of the permissions of the voice channel.

## Schedule Behaviour

To add an open and close schedule you mention the bot and use the `createSchedule` command in the following format:
Expand All @@ -186,8 +199,16 @@ A summary of all created schedules can be
It works by toggling the `@everyone` role on the channel to `deny` for closure and `neutral` for open.
The bot will check if the channel is already closed or opening before applying the change, so it won't attempt to close a channel already closed for example.

When creating the schedule Snorlax will check that it has the correct permissions on the respective channel to implement the schedule.

![CloseAndOpen](/screenshots/CloseAndOpen.png)

### Roles Not Affected By Schedule

When creating the schedule, Snorlax will check if any roles have an explicit send message permission. This would mean that the schedule will have no effect for these roles. These will be communicated via a warning message upon creation like that shown below.

![ScheduleRolesWarning](/screenshots/SchedulesRolesWarning.png)

### Warning Option

If selected, then if the channel has seen activity in the past `X` minutes, where `X` is determined by the setting `INACTIVE_TIME`, then `Y` minutes before the scheduled closeure, where `Y` is determined by the setting `WARNING_TIME`, the bot will post a warning that the channel is scheduled to close soon.
Expand Down Expand Up @@ -308,7 +329,7 @@ The `removeAllSchedules` command will ask for confirmation before processing req

![removeAllSchedules](/screenshots/remove_all_confirmation.png)

Click on the green tick emoji to confirm the deletion, or the red cross to cancel.
Click on the `Confirm` to confirm the deletion, or the `Cancel` button to cancel. The command will timeout after 1 minute.

### Manual Open and Closing

Expand Down
105 changes: 105 additions & 0 deletions alembic.ini.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# 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.

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8

sqlalchemy.url = sqlite:///ENTER DATABASE HERE!


[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 change: 1 addition & 0 deletions alembic/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generic single-database configuration.
78 changes: 78 additions & 0 deletions alembic/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
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

# 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

# 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 changes: 24 additions & 0 deletions alembic/script.py.mako
Original file line number Diff line number Diff line change
@@ -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"}
Loading

0 comments on commit 269650c

Please sign in to comment.