Upload to gitea
This commit is contained in:
commit
d3d25c68f9
12 files changed
+500
No files matched your search
@@ -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))
|
||||
Reference in new issue
Block a user