Skip to content

Commit

Permalink
modules: Implement /post command
Browse files Browse the repository at this point in the history
Posts messages for new release builds to https://t.me/StatiXOSReleases.
Also improve text formatting wherever possible.
  • Loading branch information
pranayadmn committed Jul 31, 2024
1 parent 1c5e866 commit b99e5d6
Show file tree
Hide file tree
Showing 4 changed files with 117 additions and 8 deletions.
12 changes: 12 additions & 0 deletions maintainers.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"release": {
"version": 14,
"branch": "udc",
"codename": "UPSIDEDOWNCAKE"
},
"yunluo": {
"manufacturer": "Xiaomi",
"model": "Redmi Pad",
"maintainer": "Pranaya Deomani"
}
}
17 changes: 10 additions & 7 deletions statixbot/modules/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,28 @@
from typing import Dict

from pyrogram import Client, filters
from pyrogram.enums import ParseMode
from pyrogram.types import Message

from statixbot.Module import ModuleBase

cmds: Dict[str, str] = {}


def add_cmd(cmd: str, desc: str) -> None:
"""Add command to the help module."""
cmds[cmd] = desc


class Module(ModuleBase):
async def register(self, app: Client) -> None:
"""Register the /help command."""

@app.on_message(filters.command("help"))
async def help_handler(client: Client, message: Message) -> None:
help_text: str = "Available commands:\n"
help_text: str = "<b>Available commands:</b>\n"
for command, description in cmds.items():
help_text += f"/{command}: {description}\n"
await message.reply_text(help_text)
help_text += f"- /{command}: {description}\n"
await message.reply_text(help_text, parse_mode=ParseMode.HTML)


def add_cmd(cmd: str, desc: str) -> None:
"""Add command to the help module."""
cmds[cmd] = desc
add_cmd("help", "Sends this message.")
94 changes: 94 additions & 0 deletions statixbot/modules/post.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# Copyright 2024 StatiXOS
#
# Use of this source code is governed by an MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT.

import json
import logging
from pathlib import Path
from typing import Dict

from pyrogram import Client, filters
from pyrogram.enums import ParseMode
from pyrogram.types import Message

from statixbot.Auth import authorized
from statixbot.Module import ModuleBase

from .help import add_cmd

log: logging.Logger = logging.getLogger(__name__)

JSON_FILE_PATH: Path = Path(__file__).parent.parent.parent / "maintainers.json"


def load_json_data(file_path: Path) -> Dict:
"""Load JSON data from a file."""
try:
with open(file_path, "r") as file:
return json.load(file)
except FileNotFoundError:
log.error(f"File not found: {file_path}")
return {}
except json.JSONDecodeError as e:
log.error(f"Error decoding JSON file {file_path}: {e}")
return {}
except Exception as e:
log.error(f"Unexpected error while loading JSON file {file_path}: {e}")
return {}


JSON_DATA: Dict = load_json_data(JSON_FILE_PATH)


class Module(ModuleBase):
async def register(self, app: Client) -> None:
"""Register the /post command."""

@app.on_message(filters.command("post"))
@authorized
async def post_message(client: Client, message: Message) -> None:
try:
args: str = message.text.split(maxsplit=2)
if len(args) != 3:
await message.reply_text(
"Usage: /post <code>&lt;codename&gt;</code> <code>&lt;changelog&gt;</code>",
parse_mode=ParseMode.HTML,
)
return

codename: str = args[1]
changelog: str = args[2]

if codename not in JSON_DATA:
await message.reply_text(f"Codename `{codename}` not found in database.")
return

data: Dict = JSON_DATA
release: Dict = data.get("release", {})
device: Dict = data.get(codename, {})

message_text: str = (
f"#{codename} #{release.get('branch', 'unknown')}\n"
f"New **StatiXOS {release.get('codename', 'UNKNOWN')}** build for **{device.get('manufacturer', 'Unknown')} {device.get('model', 'Unknown')} ({codename})**!\n\n"
f"**Maintainer:** {device.get('maintainer', 'Unknown')}\n"
f"[Download](https://downloads.statixos.com/{release.get('version', '0')}-{release.get('codename', 'UNKNOWN')}/{codename}) | [Changelog]({changelog})"
)

await client.send_message(
chat_id="-1001238532711",
text=message_text,
parse_mode=ParseMode.MARKDOWN,
disable_web_page_preview=True,
)
await message.reply_text("Successfully posted the build to @StatiXOSReleases!")

except Exception as e:
log.error(f"Error posting message: {e}")
await message.reply_text("An error occurred while posting the message.")

add_cmd(
"post <code>&lt;codename&gt;</code> <code>&lt;changelog&gt;</code>",
"Post a new build to @StatiXOSReleases.",
)
2 changes: 1 addition & 1 deletion statixbot/modules/start.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,4 @@ async def start(client: Client, message: Message) -> None:
"'Ssup! What would you like me to do?\nUse /help to get a list of all commands and their usage."
)

add_cmd("start", "Starts the bot.")
add_cmd("start", "Starts me! You've probably already used this.")

0 comments on commit b99e5d6

Please sign in to comment.