Skip to content

Commit

Permalink
merge: Merge branch 'dev' into feat/highlight
Browse files Browse the repository at this point in the history
  • Loading branch information
null2264 committed Mar 16, 2023
2 parents 109a920 + 7784781 commit 27e63d4
Show file tree
Hide file tree
Showing 25 changed files with 257 additions and 264 deletions.
11 changes: 9 additions & 2 deletions .github/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
# v3.6 (Structure Refactor)

> **Info**
> **Note**
>
> Version 3.6.x is mostly about refactoring the project structure since
> previously functions and constants are all over the place that it's starting
> to get harder to find what I'm looking for.
## 3.6.0 (Project Structure Refactor)
## 3.6.1 (Project Structure Refactor - Part 1.5 A.K.A Hotfix)

- [**Fixed**] Fixed issues related to `import tse`
- [**Fixed**] Aerich caused the bot to crash in production environment

## 3.6.0 (Project Structure Refactor - Part 1)

### Bugfixes
- [**Fixed**] Fixed potential error related to user without avatar
Expand Down Expand Up @@ -36,6 +41,8 @@
- [**Improved**] Moved JSON (and Blacklist) and Cache (and its properties) into `core.data`
- [**Changed**] Removed `CMDName`
- [**Added**] Initial ZeroMQ support for Dashboard
- [**Improved**] `ccModeCheck` is now an actual check (`hasCCPriviledge`)
- [**Improved**] CustomCommand is now a converter

# v3.5 (Overhaul an Overhaul?)

Expand Down
6 changes: 5 additions & 1 deletion .github/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@

## About

> **Note**
>
> `dev` branch is used mostly for development and generally considered as unstable, to host the bot it's recommended to use `overhaul` branch or release tags instead!
**`Z3R0`** (codename **`ziBot`**) is a **free** and **open-source** multi-purpose discord bot, created for fun in the middle of quarantine. Used to be fork of [Steve-Bot](https://github.com/MCBE-Speedrunning/Steve-Bot) by MCBE Speedrunning Moderators.

### Features
Expand Down Expand Up @@ -104,7 +108,7 @@ More feature coming soon!
> Python 3.10+ (3.10.9 is recommended) is required to host this bot!

- Download this repository by executing `git clone https://github.com/ZiRO-Bot/Z3R0.git`
or click "Code" -> "Download ZIP"
or click "Code" -> "Download ZIP" (be sure to choose `overhaul` branch first!)
- Install poetry by executing this command,

```zsh
Expand Down
34 changes: 32 additions & 2 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
name: Nightly Build
name: Build

on:
push:
branches:
- dev
- overhaul
tags:
- 3.*

permissions:
contents: read
Expand Down Expand Up @@ -31,10 +34,37 @@ jobs:
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}

- name: Build and push
- name: Get tag name
if: startsWith(github.ref, 'refs/tags/') && github.repository == 'ziro-bot/z3r0'
run: |
set -x
echo "VERSION_TAG=${GITHUB_REF/refs\/tags\//}" >> $GITHUB_ENV
- name: Build and push (Nightly)
uses: docker/build-push-action@v4
if: ${{ !startsWith(github.ref, 'refs/tags/') && github.ref_name == 'dev' && github.repository == 'ziro-bot/z3r0' }}
with:
context: .
file: ./docker/Dockerfile
push: true
tags: ghcr.io/ziro-bot/z3r0:nightly

- name: Build and push (Canary)
uses: docker/build-push-action@v4
if: ${{ !startsWith(github.ref, 'refs/tags/') && github.ref_name == 'overhaul' && github.repository == 'ziro-bot/z3r0' }}
with:
context: .
file: ./docker/Dockerfile
push: true
tags: ghcr.io/ziro-bot/z3r0:canary

- name: Build and push (Release)
uses: docker/build-push-action@v4
if: startsWith(github.ref, 'refs/tags/') && github.repository == 'ziro-bot/z3r0'
with:
context: .
file: ./docker/Dockerfile
push: true
tags: |
ghcr.io/ziro-bot/z3r0:latest
ghcr.io/ziro-bot/z3r0:${{ env.VERSION_TAG }}
4 changes: 0 additions & 4 deletions aerich.ini

This file was deleted.

3 changes: 2 additions & 1 deletion aerichConfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@
except ImportError:
dbUrl = os.environ["ZIBOT_DB_URL"]

cfg = Config("", dbUrl)
cfg = Config("", dbUrl, useAerich=True)
t = cfg.tortoiseConfig
1 change: 1 addition & 0 deletions docker/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ ENV PATH="/venv/bin:${PATH}" \
VIRTUAL_ENV="/venv"

COPY --from=builder /venv /venv
COPY --from=builder /app/pyproject.toml /app/
COPY --from=builder /app/src/ /app/src
COPY assets/ /app/assets
COPY docker/__main__.py ./
Expand Down
14 changes: 7 additions & 7 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 5 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "Z3R0"
version = "3.6.0"
version = "3.6.1"
description = "A multi-purpose open source discord bot"
authors = ["null2264"]
license = "MPL-2.0"
Expand Down Expand Up @@ -43,7 +43,7 @@ black = "^22.10.0"
isort = "^5.10.1"
pre-commit = "^2.13.0"
pyproject-flake8 = "^0.0.1-alpha.2"
aerich = "^0.6.2"
aerich = "0.7.1"

[tool.poetry.group.test]

Expand Down Expand Up @@ -84,9 +84,9 @@ multi_line_output = 3
lines_after_imports = 2

[tool.aerich]
tortoise_orm = "config.TORTOISE_ORM"
location = "./migrations"
tortoise_orm = "aerichConfig.t"
location = "./src/main/migrations"
src_folder = "./."

[tool.pytest.ini_options]
pythonpath = ["src"]
pythonpath = ["."]
11 changes: 8 additions & 3 deletions src/main/core/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,20 +232,25 @@ async def on_ready(self) -> None:
self.logger.warning("Ready: {0} (ID: {0.id})".format(self.user))

async def zmqBind(self):
context = zmq.asyncio.Context.instance()
pubPort = self.config.zmqPorts.get("PUB")
subPort = self.config.zmqPorts.get("SUB")
repPort = self.config.zmqPorts.get("REP")

if not pubPort and not subPort and not repPort:
return

context = zmq.asyncio.Context.instance()

if pubPort:
self.pubSocket = context.socket(zmq.PUB)
self.pubSocket.bind(f"tcp://*:{pubPort}")

subPort = self.config.zmqPorts.get("SUB")
if subPort:
self.subSocket = context.socket(zmq.SUB)
self.subSocket.setsockopt(zmq.SUBSCRIBE, b"")
self.subSocket.bind(f"tcp://*:{subPort}")
self.socketTasks.append(asyncio.create_task(self.onZMQReceivePUBMessage()))

repPort = self.config.zmqPorts.get("REP")
if repPort:
self.repSocket = context.socket(zmq.REP)
self.repSocket.bind(f"tcp://*:{repPort}")
Expand Down
9 changes: 8 additions & 1 deletion src/main/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class Config:
"internalApiHost",
"test",
"zmqPorts",
"useAerich",
)

def __init__(
Expand All @@ -41,6 +42,7 @@ def __init__(
internalApiHost: str | None = None,
test: bool = False,
zmqPorts: dict[str, int] | None = None,
useAerich: bool = False,
):
self.token = token
self.defaultPrefix = defaultPrefix or ">"
Expand All @@ -54,18 +56,23 @@ def __init__(
self.internalApiHost = internalApiHost or "127.0.0.1:2264"
self.test = test
self.zmqPorts = zmqPorts or {}
self.useAerich = useAerich

@property
def tortoiseConfig(self):
mainModel = "main.core.db"
if not self.test:
mainModel = "src." + mainModel

models = [mainModel]
if self.useAerich:
models.append("aerich.models")

return self._tortoiseConfig or {
"connections": {"default": self.databaseUrl},
"apps": {
"models": {
"models": [mainModel, "aerich.models"],
"models": models,
"default_connection": "default",
},
},
Expand Down
31 changes: 24 additions & 7 deletions src/main/core/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""

from __future__ import annotations

import io
from contextlib import asynccontextmanager
from typing import Union
Expand All @@ -24,10 +26,6 @@ def __init__(self, **kwargs) -> None:
def session(self) -> aiohttp.ClientSession:
return self.bot.session

# @property
# def db(self):
# return self.bot.db

@property
def cache(self):
return self.bot.cache
Expand Down Expand Up @@ -62,12 +60,20 @@ async def safe_send_reply(self, content, *, escape_mentions=True, type="send", *
kwargs["content"] = content
return await action(**kwargs)

async def safe_send(self, content, *, escape_mentions=True, **kwargs):
async def safe_send(self, content, *, escape_mentions: bool = True, **kwargs):
# TODO: Deprecate
return await self.safe_send_reply(content, escape_mentions=escape_mentions, type="send", **kwargs)

async def safe_reply(self, content, *, escape_mentions=True, **kwargs):
async def safeSend(self, content, *, escapeMentions: bool = True, **kwargs):
return await self.safe_send(content, escape_mentions=escapeMentions, **kwargs)

async def safe_reply(self, content, *, escape_mentions: bool = True, **kwargs):
# TODO: Deprecate
return await self.safe_send_reply(content, escape_mentions=escape_mentions, type="reply", **kwargs)

async def safeReply(self, content, *, escapeMentions: bool = True, **kwargs):
return await self.safe_reply(content, escape_mentions=escapeMentions, **kwargs)

async def error(self, error_message: str = None, title: str = "Something went wrong!"):
e = ZEmbed.error(title="ERROR" + (f": {title}" if title else ""))
if error_message is not None:
Expand Down Expand Up @@ -119,8 +125,19 @@ def replied_reference(self):
return None

@discord.utils.cached_property
def guild(self):
def guild(self) -> GuildWrapper | None:
g = self.message.guild
if g:
return GuildWrapper(g, self.bot)
return None

def requireGuild(self) -> GuildWrapper:
"""
Inspired by Android's requireActivity()
Should only be used if the command has guild only check
"""
g = self.guild
if not g:
raise commands.NoPrivateMessage
return g
2 changes: 1 addition & 1 deletion src/main/core/menus.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def __init__(
timeout: float = 180.0,
ownerOnly: bool = True,
) -> None:
owner: Union[discord.User, discord.Member] = ctx.author
owner: discord.User | discord.Member = ctx.author
super().__init__(owner, timeout=timeout)
self.context = ctx
self._message: Optional[discord.Message] = None
Expand Down
2 changes: 1 addition & 1 deletion src/main/exts/events/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from discord.app_commands import AppCommandError
from discord.ext import commands

import tse
from src import tse

from ...core import errors
from ...core.embed import ZEmbed
Expand Down
12 changes: 9 additions & 3 deletions src/main/exts/fun/fun.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,9 +185,15 @@ async def findseed(self, ctx, *, args: FindseedFlags = None):
"Ping random member\n" 'Also known as "Discord\'s mistake"\n' "**Note**: Only available on April Fools (UTC)!"
),
)
@commands.cooldown(1, 5, commands.BucketType.user)
@commands.guild_only()
@checks.isAprilFool()
async def someone(self, ctx):
await ctx.send(choice(ctx.guild.members).mention)
async def someone(self, ctx: Context):
allowPingGuilds = (793642143243173888,)
allowedMentions = discord.AllowedMentions.none()
if ctx.requireGuild().id in allowPingGuilds:
allowedMentions = discord.AllowedMentions(users=True)
await ctx.send(choice(ctx.requireGuild().members).mention, allowed_mentions=allowedMentions)

@commands.hybrid_command(
usage="(status code)",
Expand Down Expand Up @@ -317,7 +323,7 @@ async def flip(self, ctx):
"**Support optional size**: d4, d8, d10, d00, d12, d20"
),
usage="[dice size] (number of dice)",
extras=dict(example=("roll 5", "roll d20", "role d00 4")),
extras=dict(example=("roll 5", "roll d20", "roll d00 4")),
)
@commands.cooldown(1, 5, type=commands.BucketType.user)
async def roll(self, ctx, *args):
Expand Down
1 change: 0 additions & 1 deletion src/main/exts/info/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
from ...utils import pillow
from ...utils.api.openweather import CityNotFound, OpenWeatherAPI
from ...utils.format import formatDiscordDT, renderBar
from ...utils.infoQuote import * # noqa: F403
from ...utils.other import authorOrReferenced, utcnow


Expand Down
Loading

0 comments on commit 27e63d4

Please sign in to comment.