Upload to gitea
This commit is contained in:
commit
d3d25c68f9
12 files changed
+500
No files matched your search
@@ -0,0 +1,9 @@
|
||||
# 不要把機密和本機資料打包進 image
|
||||
.env
|
||||
data/
|
||||
.git/
|
||||
.gitignore
|
||||
__pycache__/
|
||||
*.pyc
|
||||
docker-compose.yml
|
||||
release.ps1
|
||||
@@ -0,0 +1,9 @@
|
||||
# Secrets
|
||||
.env
|
||||
|
||||
# SQLite
|
||||
data/
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.pyc
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
FROM python:3.11-slim
|
||||
WORKDIR /app
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
COPY . .
|
||||
|
||||
# 不緩衝 print,docker logs 才會即時看到
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
# 資料庫放在獨立的 volume
|
||||
ENV DB_PATH=/data/lunarhelper.db
|
||||
VOLUME ["/data"]
|
||||
|
||||
CMD ["python", "main.py"]
|
||||
@@ -0,0 +1,97 @@
|
||||
from typing import Optional
|
||||
|
||||
import discord
|
||||
from discord import app_commands
|
||||
from discord.ext import commands
|
||||
|
||||
import db
|
||||
|
||||
|
||||
def summary(guild: discord.Guild) -> str:
|
||||
def get(key):
|
||||
return db.get_setting(guild.id, key)
|
||||
|
||||
def channel_text(key):
|
||||
channel = guild.get_channel(get(key))
|
||||
return channel.mention if channel else "未設定"
|
||||
|
||||
return (
|
||||
"**私人包廂**\n"
|
||||
f"觸發頻道:{channel_text('trigger_channel')}\n"
|
||||
f"包廂名稱:{get('room_name')}\n"
|
||||
f"空房刪除:{get('empty_seconds')} 秒\n"
|
||||
"**簽到**\n"
|
||||
f"簽到文字:{get('signin_text')}\n"
|
||||
f"簽到獎勵:{get('signin_reward')} {get('currency_name')}\n"
|
||||
f"回應表符:{get('signin_reaction')}\n"
|
||||
f"簽到頻道:{channel_text('signin_channel')}"
|
||||
)
|
||||
|
||||
|
||||
async def apply(interaction: discord.Interaction, **values):
|
||||
"""寫入有填的項目(空白視為沒填),並回覆目前的設定"""
|
||||
with db.conn:
|
||||
for key, value in values.items():
|
||||
if isinstance(value, str):
|
||||
value = value.strip()
|
||||
if value not in (None, ""):
|
||||
db.set_setting(interaction.guild.id, key, value)
|
||||
await interaction.response.send_message(summary(interaction.guild), ephemeral=True)
|
||||
|
||||
|
||||
@app_commands.guild_only()
|
||||
@app_commands.default_permissions(administrator=True)
|
||||
class Settings(commands.GroupCog, group_name="設定", group_description="機器人設定(管理員)"):
|
||||
@app_commands.command(name="查看", description="查看目前的設定")
|
||||
async def show(self, interaction: discord.Interaction):
|
||||
await apply(interaction)
|
||||
|
||||
@app_commands.command(name="包廂", description="設定私人包廂,只會更新有填的項目")
|
||||
@app_commands.describe(
|
||||
觸發頻道="進入這個語音頻道就會建立包廂",
|
||||
包廂名稱="新包廂的名稱",
|
||||
空房秒數="包廂沒人超過幾秒就刪除",
|
||||
)
|
||||
async def rooms(
|
||||
self,
|
||||
interaction: discord.Interaction,
|
||||
觸發頻道: Optional[discord.VoiceChannel] = None,
|
||||
包廂名稱: Optional[app_commands.Range[str, 1, 100]] = None,
|
||||
空房秒數: Optional[app_commands.Range[int, 5, 86400]] = None,
|
||||
):
|
||||
await apply(
|
||||
interaction,
|
||||
trigger_channel=觸發頻道 and 觸發頻道.id,
|
||||
room_name=包廂名稱,
|
||||
empty_seconds=空房秒數,
|
||||
)
|
||||
|
||||
@app_commands.command(name="簽到", description="設定簽到,只會更新有填的項目")
|
||||
@app_commands.describe(
|
||||
簽到文字="訊息內容完全等於這段文字才算簽到,如 月眠🙏",
|
||||
簽到獎勵="每次簽到獲得的數量",
|
||||
貨幣名稱="點數的名稱,如 願力",
|
||||
回應表符="簽到成功時機器人加上的反應",
|
||||
簽到頻道="只偵測這個頻道",
|
||||
)
|
||||
async def signin(
|
||||
self,
|
||||
interaction: discord.Interaction,
|
||||
簽到文字: Optional[str] = None,
|
||||
簽到獎勵: Optional[app_commands.Range[int, 1]] = None,
|
||||
貨幣名稱: Optional[str] = None,
|
||||
回應表符: Optional[str] = None,
|
||||
簽到頻道: Optional[discord.TextChannel] = None,
|
||||
):
|
||||
await apply(
|
||||
interaction,
|
||||
signin_text=簽到文字,
|
||||
signin_reward=簽到獎勵,
|
||||
currency_name=貨幣名稱,
|
||||
signin_reaction=回應表符,
|
||||
signin_channel=簽到頻道 and 簽到頻道.id,
|
||||
)
|
||||
|
||||
|
||||
async def setup(bot: commands.Bot):
|
||||
await bot.add_cog(Settings())
|
||||
@@ -0,0 +1,51 @@
|
||||
from datetime import datetime
|
||||
|
||||
import discord
|
||||
from discord import app_commands
|
||||
from discord.ext import commands
|
||||
|
||||
import db
|
||||
from config import TZ
|
||||
|
||||
|
||||
class Signin(commands.Cog):
|
||||
def __init__(self, bot: commands.Bot):
|
||||
self.bot = bot
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_message(self, message: discord.Message):
|
||||
if message.author.bot or not message.guild:
|
||||
return
|
||||
guild_id = message.guild.id
|
||||
if message.channel.id != db.get_setting(guild_id, "signin_channel"):
|
||||
return
|
||||
if message.content.strip() != db.get_setting(guild_id, "signin_text"):
|
||||
return
|
||||
|
||||
today = datetime.now(TZ).date().isoformat()
|
||||
with db.conn:
|
||||
signed = db.try_signin(
|
||||
guild_id, message.author.id, db.get_setting(guild_id, "signin_reward"), today
|
||||
)
|
||||
if not signed:
|
||||
return
|
||||
|
||||
try:
|
||||
await message.add_reaction(db.get_setting(guild_id, "signin_reaction"))
|
||||
except discord.HTTPException:
|
||||
pass # 表符失效(例如被刪除)時不影響簽到
|
||||
|
||||
@app_commands.command(name="餘額", description="查看自己的點數")
|
||||
@app_commands.guild_only()
|
||||
async def balance(self, interaction: discord.Interaction):
|
||||
user = interaction.user
|
||||
guild_id = interaction.guild_id
|
||||
await interaction.response.send_message(
|
||||
f"{user.mention} 目前有 {db.get_points(guild_id, user.id)} "
|
||||
f"{db.get_setting(guild_id, 'currency_name')}",
|
||||
allowed_mentions=discord.AllowedMentions.none(), # 公開訊息,不要 tag 到自己
|
||||
)
|
||||
|
||||
|
||||
async def setup(bot: commands.Bot):
|
||||
await bot.add_cog(Signin(bot))
|
||||
@@ -0,0 +1,125 @@
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
import discord
|
||||
from discord.ext import commands
|
||||
|
||||
import db
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class VoiceRooms(commands.Cog):
|
||||
def __init__(self, bot: commands.Bot):
|
||||
self.bot = bot
|
||||
self.timers: dict[int, asyncio.Task] = {} # 包廂頻道 ID → 等待刪除的計時器
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_ready(self):
|
||||
# 補上離線期間錯過的事件;on_ready 在重連後會再觸發,所以這裡要能重複執行
|
||||
for room_id in db.get_rooms():
|
||||
channel = self.bot.get_channel(room_id)
|
||||
if channel is not None:
|
||||
self.refresh_timer(channel)
|
||||
continue
|
||||
# 快取沒有不代表頻道不在(伺服器可能暫時 unavailable),確認過才清掉
|
||||
try:
|
||||
await self.bot.fetch_channel(room_id)
|
||||
except discord.NotFound:
|
||||
with db.conn:
|
||||
db.remove_room(room_id)
|
||||
except discord.HTTPException:
|
||||
log.exception("無法確認包廂 %s 是否存在", room_id)
|
||||
|
||||
for guild in self.bot.guilds:
|
||||
trigger = guild.get_channel(db.get_setting(guild.id, "trigger_channel"))
|
||||
if trigger is None:
|
||||
log.warning("伺服器 %s 找不到觸發頻道,請用 /設定 包廂 設定", guild.name)
|
||||
continue
|
||||
for member in trigger.members:
|
||||
if not member.bot:
|
||||
await self.create_room(member, trigger)
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_voice_state_update(
|
||||
self, member: discord.Member, before: discord.VoiceState, after: discord.VoiceState
|
||||
):
|
||||
if before.channel == after.channel:
|
||||
return # 靜音、開鏡頭之類的狀態變更
|
||||
|
||||
for channel in (before.channel, after.channel):
|
||||
if channel is not None and db.is_room(channel.id):
|
||||
self.refresh_timer(channel)
|
||||
|
||||
if (
|
||||
after.channel is not None
|
||||
and after.channel.id == db.get_setting(member.guild.id, "trigger_channel")
|
||||
and not member.bot
|
||||
):
|
||||
await self.create_room(member, after.channel)
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_guild_channel_delete(self, channel: discord.abc.GuildChannel):
|
||||
with db.conn:
|
||||
db.remove_room(channel.id)
|
||||
timer = self.timers.pop(channel.id, None)
|
||||
if timer is not None:
|
||||
timer.cancel()
|
||||
|
||||
async def create_room(self, member: discord.Member, trigger: discord.VoiceChannel):
|
||||
guild = member.guild
|
||||
category = trigger.category
|
||||
|
||||
# 指定 overwrites 就不會自動同步類別權限,所以要自己把類別的權限帶過來
|
||||
overwrites = dict(category.overwrites) if category else {}
|
||||
overwrites[guild.me] = discord.PermissionOverwrite(
|
||||
view_channel=True, connect=True, manage_channels=True, move_members=True
|
||||
)
|
||||
overwrites[member] = discord.PermissionOverwrite(
|
||||
view_channel=True, connect=True, manage_channels=True, set_voice_channel_status=True
|
||||
)
|
||||
|
||||
try:
|
||||
room = await guild.create_voice_channel(
|
||||
db.get_setting(guild.id, "room_name"),
|
||||
category=category,
|
||||
overwrites=overwrites,
|
||||
reason=f"{member} 的私人包廂",
|
||||
)
|
||||
except discord.HTTPException:
|
||||
log.exception("無法替 %s 建立包廂", member)
|
||||
return
|
||||
|
||||
with db.conn:
|
||||
db.add_room(room.id)
|
||||
# 先開始倒數,如果來不及移動(成員已離開)包廂也會被清掉;移動成功時會取消
|
||||
self.refresh_timer(room)
|
||||
|
||||
try:
|
||||
await member.move_to(room, reason="移動到私人包廂")
|
||||
except discord.HTTPException:
|
||||
log.warning("無法把 %s 移動到包廂 %s", member, room.id)
|
||||
|
||||
def refresh_timer(self, channel: discord.VoiceChannel):
|
||||
"""有人就取消計時,沒人就開始計時(只剩其他機器人也算沒人)"""
|
||||
if any(not m.bot for m in channel.members):
|
||||
timer = self.timers.pop(channel.id, None)
|
||||
if timer is not None:
|
||||
timer.cancel()
|
||||
elif channel.id not in self.timers:
|
||||
self.timers[channel.id] = asyncio.create_task(self.delete_later(channel))
|
||||
|
||||
async def delete_later(self, channel: discord.VoiceChannel):
|
||||
await asyncio.sleep(db.get_setting(channel.guild.id, "empty_seconds"))
|
||||
# 要在刪除前移除,否則 on_guild_channel_delete 會把正在刪除的自己取消
|
||||
del self.timers[channel.id]
|
||||
try:
|
||||
await channel.delete(reason="包廂已空")
|
||||
except discord.NotFound:
|
||||
pass
|
||||
except discord.HTTPException:
|
||||
log.exception("無法刪除包廂 %s", channel.id)
|
||||
|
||||
|
||||
async def setup(bot: commands.Bot):
|
||||
await bot.add_cog(VoiceRooms(bot))
|
||||
@@ -0,0 +1,20 @@
|
||||
import os
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
VERSION = "V1.0.0"
|
||||
TZ = ZoneInfo("Asia/Taipei")
|
||||
DB_PATH = os.getenv("DB_PATH", "./data/lunarhelper.db")
|
||||
|
||||
# 管理員用 /設定 修改的項目,每個伺服器各自一份,這裡只是預設值
|
||||
# 從資料庫讀出來時會轉成這裡的型別
|
||||
# 兩個頻道的預設值是測試伺服器的,其他伺服器要先用 /設定 指定才會運作
|
||||
DEFAULT_SETTINGS = {
|
||||
"trigger_channel": 1360009767262748867,
|
||||
"room_name": "🥂 °·˚|私人包廂",
|
||||
"empty_seconds": 30,
|
||||
"signin_text": "月眠🙏",
|
||||
"signin_reward": 1,
|
||||
"currency_name": "願力",
|
||||
"signin_reaction": "🙏",
|
||||
"signin_channel": 1567408046479515718,
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
"""SQLite 資料層
|
||||
|
||||
所有函式都是同步的,且呼叫端不會在讀寫中間 await,
|
||||
所以在 asyncio 單執行緒下每個操作都是原子的,不會有同時寫入的問題。
|
||||
寫入要用 `with db.conn:` 包起來才會 commit。
|
||||
|
||||
設定和點數都是每個伺服器各自一份。
|
||||
"""
|
||||
import os
|
||||
import sqlite3
|
||||
|
||||
from config import DB_PATH, DEFAULT_SETTINGS
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
guild_id INTEGER NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
value TEXT NOT NULL,
|
||||
PRIMARY KEY (guild_id, key)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS members (
|
||||
guild_id INTEGER NOT NULL,
|
||||
user_id INTEGER NOT NULL,
|
||||
points INTEGER NOT NULL DEFAULT 0,
|
||||
total_signin INTEGER NOT NULL DEFAULT 0,
|
||||
last_signin TEXT,
|
||||
PRIMARY KEY (guild_id, user_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS voice_rooms (
|
||||
channel_id INTEGER PRIMARY KEY
|
||||
);
|
||||
"""
|
||||
|
||||
os.makedirs(os.path.dirname(DB_PATH) or ".", exist_ok=True)
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
conn.executescript(SCHEMA)
|
||||
|
||||
|
||||
# ===== 設定 =====
|
||||
def get_setting(guild_id: int, key: str):
|
||||
row = conn.execute(
|
||||
"SELECT value FROM settings WHERE guild_id = ? AND key = ?", (guild_id, key)
|
||||
).fetchone()
|
||||
default = DEFAULT_SETTINGS[key]
|
||||
return type(default)(row["value"]) if row else default
|
||||
|
||||
|
||||
def set_setting(guild_id: int, key: str, value):
|
||||
conn.execute(
|
||||
"INSERT INTO settings (guild_id, key, value) VALUES (?, ?, ?) "
|
||||
"ON CONFLICT (guild_id, key) DO UPDATE SET value = excluded.value",
|
||||
(guild_id, key, str(value)),
|
||||
)
|
||||
|
||||
|
||||
# ===== 簽到 =====
|
||||
def try_signin(guild_id: int, user_id: int, reward: int, today: str) -> bool:
|
||||
"""這個伺服器今天還沒簽到才加點數,回傳是否簽到成功"""
|
||||
cur = conn.execute(
|
||||
"INSERT INTO members (guild_id, user_id, points, total_signin, last_signin) "
|
||||
"VALUES (?, ?, ?, 1, ?) "
|
||||
"ON CONFLICT (guild_id, user_id) DO UPDATE SET "
|
||||
"points = points + excluded.points, "
|
||||
"total_signin = total_signin + 1, "
|
||||
"last_signin = excluded.last_signin "
|
||||
"WHERE last_signin IS NULL OR last_signin <> excluded.last_signin",
|
||||
(guild_id, user_id, reward, today),
|
||||
)
|
||||
return cur.rowcount == 1
|
||||
|
||||
|
||||
def get_points(guild_id: int, user_id: int) -> int:
|
||||
row = conn.execute(
|
||||
"SELECT points FROM members WHERE guild_id = ? AND user_id = ?", (guild_id, user_id)
|
||||
).fetchone()
|
||||
return row["points"] if row else 0
|
||||
|
||||
|
||||
# ===== 私人包廂 =====
|
||||
def add_room(channel_id: int):
|
||||
conn.execute("INSERT OR IGNORE INTO voice_rooms (channel_id) VALUES (?)", (channel_id,))
|
||||
|
||||
|
||||
def remove_room(channel_id: int):
|
||||
conn.execute("DELETE FROM voice_rooms WHERE channel_id = ?", (channel_id,))
|
||||
|
||||
|
||||
def is_room(channel_id: int) -> bool:
|
||||
row = conn.execute("SELECT 1 FROM voice_rooms WHERE channel_id = ?", (channel_id,)).fetchone()
|
||||
return row is not None
|
||||
|
||||
|
||||
def get_rooms() -> list[int]:
|
||||
return [r["channel_id"] for r in conn.execute("SELECT channel_id FROM voice_rooms")]
|
||||
@@ -0,0 +1,10 @@
|
||||
# TrueNAS 部署用:Apps → Discover Apps → Install via YAML
|
||||
services:
|
||||
lunar-helper:
|
||||
image: gitea.sthkm3.org/sthkm3/lunarhelper:latest
|
||||
container_name: lunar-helper
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
DISCORD_BOT_TOKEN: ${DISCORD_BOT_TOKEN}
|
||||
volumes:
|
||||
- /mnt/Encrypt6T/LunarHelper:/data
|
||||
@@ -0,0 +1,34 @@
|
||||
import os
|
||||
|
||||
import discord
|
||||
from discord.ext import commands
|
||||
|
||||
from config import VERSION
|
||||
|
||||
EXTENSIONS = [
|
||||
"cogs.voice_rooms",
|
||||
"cogs.signin",
|
||||
"cogs.settings",
|
||||
]
|
||||
|
||||
|
||||
class LunarHelper(commands.Bot):
|
||||
def __init__(self):
|
||||
intents = discord.Intents.default()
|
||||
intents.message_content = True # 偵測簽到文字(需在 Developer Portal 開啟)
|
||||
super().__init__(command_prefix=commands.when_mentioned, intents=intents)
|
||||
|
||||
async def setup_hook(self):
|
||||
for ext in EXTENSIONS:
|
||||
await self.load_extension(ext)
|
||||
await self.tree.sync()
|
||||
|
||||
async def on_ready(self):
|
||||
print(f"Logged in as {self.user},版本{VERSION}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
token = os.getenv("DISCORD_BOT_TOKEN")
|
||||
if not token:
|
||||
raise SystemExit("請設定環境變數 DISCORD_BOT_TOKEN")
|
||||
LunarHelper().run(token, root_logger=True)
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
# 用法:.\release.ps1
|
||||
# 從 config.py 讀版本號 → build image → 推到 gitea registry → 打 git tag
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$Image = "gitea.sthkm3.org/sthkm3/lunarhelper"
|
||||
$Version = (Select-String -Path config.py -Pattern 'VERSION = "V?([^"]+)"').Matches[0].Groups[1].Value
|
||||
|
||||
if (git status --porcelain) {
|
||||
throw "有未 commit 的修改,請先 commit 再發布"
|
||||
}
|
||||
if (git tag --list "v$Version") {
|
||||
throw "v$Version 已經發布過了,請先更新 config.py 的 VERSION"
|
||||
}
|
||||
|
||||
docker build -t "${Image}:$Version" -t "${Image}:latest" .
|
||||
if ($LASTEXITCODE) { throw "docker build 失敗" }
|
||||
# Cloudflare 對單一請求有 100 秒限制,大的 layer 可能 524 逾時;
|
||||
# 已上傳的 layer 會被略過,所以重試幾次通常就會成功
|
||||
function Push-WithRetry($Ref) {
|
||||
for ($i = 1; $i -le 5; $i++) {
|
||||
docker push $Ref
|
||||
if (-not $LASTEXITCODE) { return }
|
||||
Write-Host "推送失敗,重試 ($i/5)..."
|
||||
}
|
||||
throw "docker push $Ref 失敗"
|
||||
}
|
||||
|
||||
Push-WithRetry "${Image}:$Version"
|
||||
Push-WithRetry "${Image}:latest"
|
||||
|
||||
git tag "v$Version"
|
||||
git push origin "v$Version"
|
||||
|
||||
Write-Host "已發布 ${Image}:$Version"
|
||||
@@ -0,0 +1,2 @@
|
||||
discord.py>=2.7,<3
|
||||
tzdata
|
||||
Reference in new issue
Block a user