hungernetbot 1.0.dev1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hungernetbot/__init__.py +15 -0
- hungernetbot/__main__.py +4 -0
- hungernetbot/bot.py +126 -0
- hungernetbot/commands/__init__.py +11 -0
- hungernetbot/commands/general.py +42 -0
- hungernetbot/commands/github.py +117 -0
- hungernetbot/commands/posts.py +76 -0
- hungernetbot/commands/server.py +231 -0
- hungernetbot/config.py +81 -0
- hungernetbot/database.py +164 -0
- hungernetbot/embeds.py +31 -0
- hungernetbot/emojis.py +160 -0
- hungernetbot/github/__init__.py +3 -0
- hungernetbot/github/dispatcher.py +83 -0
- hungernetbot/github/events.py +246 -0
- hungernetbot/github/repo.py +16 -0
- hungernetbot/github/security.py +12 -0
- hungernetbot/github/server.py +59 -0
- hungernetbot/posts.py +253 -0
- hungernetbot/runner.py +15 -0
- hungernetbot/webhooks.py +126 -0
- hungernetbot-1.0.dev1.dist-info/METADATA +127 -0
- hungernetbot-1.0.dev1.dist-info/RECORD +27 -0
- hungernetbot-1.0.dev1.dist-info/WHEEL +5 -0
- hungernetbot-1.0.dev1.dist-info/entry_points.txt +2 -0
- hungernetbot-1.0.dev1.dist-info/licenses/LICENSE +674 -0
- hungernetbot-1.0.dev1.dist-info/top_level.txt +1 -0
hungernetbot/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from importlib.metadata import PackageNotFoundError, version as package_version
|
|
2
|
+
|
|
3
|
+
from mapres import setGlobalMaps
|
|
4
|
+
|
|
5
|
+
from .emojis import EmojiMap
|
|
6
|
+
from .config import Settings
|
|
7
|
+
|
|
8
|
+
try:
|
|
9
|
+
__version__ = package_version('hungernetbot')
|
|
10
|
+
except PackageNotFoundError:
|
|
11
|
+
__version__ = '0.0.0'
|
|
12
|
+
|
|
13
|
+
setGlobalMaps(EmojiMap)
|
|
14
|
+
|
|
15
|
+
__all__ = ['__version__', 'Settings', 'EmojiMap']
|
hungernetbot/__main__.py
ADDED
hungernetbot/bot.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import logging
|
|
3
|
+
|
|
4
|
+
import discord
|
|
5
|
+
import uvicorn
|
|
6
|
+
from calagoapi import Panel
|
|
7
|
+
from calagoapi.extensions import enable
|
|
8
|
+
from discord.ext import commands
|
|
9
|
+
|
|
10
|
+
from .commands import register_commands
|
|
11
|
+
from .config import Settings
|
|
12
|
+
from .database import Database
|
|
13
|
+
from .embeds import branded_embed, status_emoji
|
|
14
|
+
from .github import create_github_app
|
|
15
|
+
from .github.dispatcher import GitHubDispatcher
|
|
16
|
+
from .webhooks import create_bridge_webhook
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class HungerNetBot(commands.Bot):
|
|
23
|
+
def __init__(self, settings: Settings):
|
|
24
|
+
super().__init__(
|
|
25
|
+
command_prefix='!',
|
|
26
|
+
intents=discord.Intents.default(),
|
|
27
|
+
help_command=None,
|
|
28
|
+
)
|
|
29
|
+
self.settings = settings
|
|
30
|
+
self.database = Database(settings.database_path)
|
|
31
|
+
self.panel = None
|
|
32
|
+
self.server = None
|
|
33
|
+
self.bridge_webhook = None
|
|
34
|
+
self.github_server = None
|
|
35
|
+
self._service_tasks = []
|
|
36
|
+
self._ready_notification_sent = False
|
|
37
|
+
|
|
38
|
+
async def setup_hook(self):
|
|
39
|
+
self.settings.posts_directory.mkdir(parents=True, exist_ok=True)
|
|
40
|
+
await self.database.connect()
|
|
41
|
+
enable(
|
|
42
|
+
'minecraft',
|
|
43
|
+
config={
|
|
44
|
+
'bridge_url': self.settings.bridge_url,
|
|
45
|
+
'bridge_token_id': self.settings.bridge_token_id,
|
|
46
|
+
'bridge_token_secret': self.settings.bridge_token_secret,
|
|
47
|
+
},
|
|
48
|
+
)
|
|
49
|
+
self.panel = Panel(
|
|
50
|
+
url=self.settings.panel_url,
|
|
51
|
+
api_key=self.settings.panel_api_key,
|
|
52
|
+
name='HungerNet Panel',
|
|
53
|
+
)
|
|
54
|
+
self.server = await asyncio.to_thread(
|
|
55
|
+
self.panel.minecraft.getServer,
|
|
56
|
+
self.settings.server_id,
|
|
57
|
+
name=self.settings.server_name,
|
|
58
|
+
address=f'{self.settings.server_domain}:{self.settings.server_port}',
|
|
59
|
+
bridge_url=self.settings.bridge_url,
|
|
60
|
+
bridge_token_id=self.settings.bridge_token_id,
|
|
61
|
+
bridge_token_secret=self.settings.bridge_token_secret,
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
register_commands(self)
|
|
65
|
+
dispatcher = GitHubDispatcher(self, self.database, self.settings.owner_id)
|
|
66
|
+
github_app = create_github_app(self.settings, dispatcher)
|
|
67
|
+
github_config = uvicorn.Config(
|
|
68
|
+
github_app,
|
|
69
|
+
host=self.settings.webhook_host,
|
|
70
|
+
port=self.settings.github_webhook_port,
|
|
71
|
+
log_config=None,
|
|
72
|
+
access_log=False,
|
|
73
|
+
)
|
|
74
|
+
self.github_server = uvicorn.Server(github_config)
|
|
75
|
+
self.bridge_webhook = create_bridge_webhook(self)
|
|
76
|
+
self._service_tasks = [
|
|
77
|
+
asyncio.create_task(self.github_server.serve(), name='github-webhook-server'),
|
|
78
|
+
asyncio.create_task(self.bridge_webhook.start(), name='bridge-webhook-server'),
|
|
79
|
+
]
|
|
80
|
+
|
|
81
|
+
if self.settings.dev_guild_ids:
|
|
82
|
+
for guild_id in self.settings.dev_guild_ids:
|
|
83
|
+
guild = discord.Object(id=guild_id)
|
|
84
|
+
self.tree.copy_global_to(guild=guild)
|
|
85
|
+
synced = await self.tree.sync(guild=guild)
|
|
86
|
+
logger.info('Synced %d command(s) to development guild %d.', len(synced), guild_id)
|
|
87
|
+
else:
|
|
88
|
+
synced = await self.tree.sync()
|
|
89
|
+
logger.info('Synced %d global command(s).', len(synced))
|
|
90
|
+
|
|
91
|
+
async def on_ready(self):
|
|
92
|
+
logger.info('Logged in as %s; connected to %d guild(s).', self.user, len(self.guilds))
|
|
93
|
+
if self._ready_notification_sent:
|
|
94
|
+
return
|
|
95
|
+
self._ready_notification_sent = True
|
|
96
|
+
channel = self.get_channel(self.settings.notification_channel_id)
|
|
97
|
+
if channel is None:
|
|
98
|
+
try:
|
|
99
|
+
channel = await self.fetch_channel(self.settings.notification_channel_id)
|
|
100
|
+
except (discord.NotFound, discord.Forbidden):
|
|
101
|
+
logger.exception('Cannot access the configured notification channel.')
|
|
102
|
+
return
|
|
103
|
+
if isinstance(channel, discord.abc.Messageable):
|
|
104
|
+
await channel.send(
|
|
105
|
+
embed=branded_embed(
|
|
106
|
+
'HungerNet Bot ready',
|
|
107
|
+
{
|
|
108
|
+
'Status': f'{status_emoji(True)} Online',
|
|
109
|
+
'Commands': f'{len(self.tree.get_commands())} slash commands loaded',
|
|
110
|
+
},
|
|
111
|
+
)
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
async def close(self):
|
|
115
|
+
if self.bridge_webhook is not None:
|
|
116
|
+
await self.bridge_webhook.stop()
|
|
117
|
+
if self.github_server is not None:
|
|
118
|
+
self.github_server.should_exit = True
|
|
119
|
+
if self._service_tasks:
|
|
120
|
+
await asyncio.gather(*self._service_tasks, return_exceptions=True)
|
|
121
|
+
if self.server is not None:
|
|
122
|
+
self.server.closeBridge()
|
|
123
|
+
if self.panel is not None:
|
|
124
|
+
self.panel.close()
|
|
125
|
+
await self.database.close()
|
|
126
|
+
await super().close()
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
from .general import register_general_commands
|
|
2
|
+
from .github import register_github_commands
|
|
3
|
+
from .posts import register_post_command
|
|
4
|
+
from .server import register_server_commands
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def register_commands(bot):
|
|
8
|
+
register_general_commands(bot)
|
|
9
|
+
register_github_commands(bot)
|
|
10
|
+
register_post_command(bot)
|
|
11
|
+
register_server_commands(bot)
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import discord
|
|
2
|
+
from discord import app_commands
|
|
3
|
+
from mapres import res
|
|
4
|
+
|
|
5
|
+
from ..embeds import branded_embed
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def register_general_commands(bot):
|
|
9
|
+
@bot.tree.command(name='ping', description='Check whether the bot is responding.')
|
|
10
|
+
async def ping(interaction: discord.Interaction):
|
|
11
|
+
latency = round(bot.latency * 1000)
|
|
12
|
+
await interaction.response.send_message(
|
|
13
|
+
embed=branded_embed(':wave: Pong', {'Latency': f'{latency} ms'}),
|
|
14
|
+
ephemeral=True,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
@bot.tree.command(name='help', description='Show the bot command overview.')
|
|
18
|
+
async def help_command(interaction: discord.Interaction):
|
|
19
|
+
embed = branded_embed(
|
|
20
|
+
'HungerNet Bot',
|
|
21
|
+
description='Server management, GitHub activity, and configurable posts.',
|
|
22
|
+
)
|
|
23
|
+
server_icon = res(':status_online:')
|
|
24
|
+
github_icon = res(':git_branch:')
|
|
25
|
+
posts_icon = res(':hungernet:')
|
|
26
|
+
embed.add_field(
|
|
27
|
+
name=f'{server_icon} Server',
|
|
28
|
+
value='`/server status`, `/server players`, `/server admin run`, '
|
|
29
|
+
'`/server admin power`, `/server admin statistics`',
|
|
30
|
+
inline=False,
|
|
31
|
+
)
|
|
32
|
+
embed.add_field(
|
|
33
|
+
name=f'{github_icon} GitHub',
|
|
34
|
+
value='`/github link`, `/github unlink`, `/github list`, `/github route`',
|
|
35
|
+
inline=False,
|
|
36
|
+
)
|
|
37
|
+
embed.add_field(
|
|
38
|
+
name=f'{posts_icon} Posts',
|
|
39
|
+
value='`/post <name>` sends a configured `.md` or `.yaml` post to this channel.',
|
|
40
|
+
inline=False,
|
|
41
|
+
)
|
|
42
|
+
await interaction.response.send_message(embed=embed, ephemeral=True)
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import discord
|
|
2
|
+
from discord import app_commands
|
|
3
|
+
from mapres import res
|
|
4
|
+
|
|
5
|
+
from ..database import EVENT_CATEGORIES
|
|
6
|
+
from ..embeds import branded_embed, truncate
|
|
7
|
+
from ..github.repo import parse_repository
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
async def _require_manage_server(interaction):
|
|
11
|
+
if interaction.guild is None or not interaction.user.guild_permissions.manage_guild:
|
|
12
|
+
await interaction.response.send_message(
|
|
13
|
+
embed=branded_embed(':ban: Access denied', {'Reason': 'Manage Server permission is required.'}),
|
|
14
|
+
ephemeral=True,
|
|
15
|
+
)
|
|
16
|
+
return False
|
|
17
|
+
return True
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def register_github_commands(bot):
|
|
21
|
+
group = app_commands.Group(name='github', description='Manage GitHub repositories and event routing.')
|
|
22
|
+
|
|
23
|
+
@group.command(name='link', description='Link a GitHub repository to this server.')
|
|
24
|
+
@app_commands.describe(repository='owner/name or a GitHub URL', channel='Default event channel')
|
|
25
|
+
@app_commands.default_permissions(manage_guild=True)
|
|
26
|
+
@app_commands.guild_only()
|
|
27
|
+
async def link(interaction: discord.Interaction, repository: str, channel: discord.TextChannel = None):
|
|
28
|
+
if not await _require_manage_server(interaction):
|
|
29
|
+
return
|
|
30
|
+
try:
|
|
31
|
+
owner, name = parse_repository(repository)
|
|
32
|
+
except ValueError as exc:
|
|
33
|
+
await interaction.response.send_message(str(exc), ephemeral=True)
|
|
34
|
+
return
|
|
35
|
+
target = channel or interaction.channel
|
|
36
|
+
channel_id = target.id if isinstance(target, discord.TextChannel) else None
|
|
37
|
+
await bot.database.link_repo(interaction.guild_id, owner, name, channel_id)
|
|
38
|
+
destination = target.mention if target else 'no default channel'
|
|
39
|
+
await interaction.response.send_message(
|
|
40
|
+
embed=branded_embed(':user_plus: Repository linked', {'Repository': f'`{owner}/{name}`', 'Channel': destination}),
|
|
41
|
+
ephemeral=True,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
@group.command(name='unlink', description='Unlink a repository from this server.')
|
|
45
|
+
@app_commands.describe(repository='owner/name or a GitHub URL')
|
|
46
|
+
@app_commands.default_permissions(manage_guild=True)
|
|
47
|
+
@app_commands.guild_only()
|
|
48
|
+
async def unlink(interaction: discord.Interaction, repository: str):
|
|
49
|
+
if not await _require_manage_server(interaction):
|
|
50
|
+
return
|
|
51
|
+
try:
|
|
52
|
+
owner, name = parse_repository(repository)
|
|
53
|
+
except ValueError as exc:
|
|
54
|
+
await interaction.response.send_message(str(exc), ephemeral=True)
|
|
55
|
+
return
|
|
56
|
+
removed = await bot.database.unlink_repo(interaction.guild_id, owner, name)
|
|
57
|
+
label = ':trash: Repository unlinked' if removed else ':circle_question_red: Repository was not linked'
|
|
58
|
+
await interaction.response.send_message(
|
|
59
|
+
embed=branded_embed(label, {'Repository': f'`{owner}/{name}`'}),
|
|
60
|
+
ephemeral=True,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
@group.command(name='list', description='List repositories linked to this server.')
|
|
64
|
+
@app_commands.default_permissions(manage_guild=True)
|
|
65
|
+
@app_commands.guild_only()
|
|
66
|
+
async def list_repositories(interaction: discord.Interaction):
|
|
67
|
+
if not await _require_manage_server(interaction):
|
|
68
|
+
return
|
|
69
|
+
repositories = await bot.database.list_repos(interaction.guild_id)
|
|
70
|
+
if not repositories:
|
|
71
|
+
await interaction.response.send_message(
|
|
72
|
+
embed=branded_embed(':file_question_yellow: No repositories linked', {'Next step': 'Use `/github link` to add one.'}),
|
|
73
|
+
ephemeral=True,
|
|
74
|
+
)
|
|
75
|
+
return
|
|
76
|
+
lines = []
|
|
77
|
+
for repo in repositories:
|
|
78
|
+
channel_text = f'<#{repo.channel_id}>' if repo.channel_id else 'no default channel'
|
|
79
|
+
lines.append(f'• `{repo.full_name}` → {channel_text}')
|
|
80
|
+
embed = branded_embed(':git_branch: Linked repositories', description=truncate('\n'.join(lines), 4000))
|
|
81
|
+
embed.set_footer(text=f'{len(repositories)} linked')
|
|
82
|
+
await interaction.response.send_message(embed=embed, ephemeral=True)
|
|
83
|
+
|
|
84
|
+
@group.command(name='route', description='Route one GitHub event category to a channel.')
|
|
85
|
+
@app_commands.describe(repository='owner/name or a GitHub URL', category='GitHub event category', channel='Destination channel')
|
|
86
|
+
@app_commands.choices(category=[app_commands.Choice(name=value.title(), value=value) for value in EVENT_CATEGORIES])
|
|
87
|
+
@app_commands.default_permissions(manage_guild=True)
|
|
88
|
+
@app_commands.guild_only()
|
|
89
|
+
async def route(
|
|
90
|
+
interaction: discord.Interaction,
|
|
91
|
+
repository: str,
|
|
92
|
+
category: app_commands.Choice[str],
|
|
93
|
+
channel: discord.TextChannel,
|
|
94
|
+
):
|
|
95
|
+
if not await _require_manage_server(interaction):
|
|
96
|
+
return
|
|
97
|
+
try:
|
|
98
|
+
owner, name = parse_repository(repository)
|
|
99
|
+
except ValueError as exc:
|
|
100
|
+
await interaction.response.send_message(str(exc), ephemeral=True)
|
|
101
|
+
return
|
|
102
|
+
await bot.database.set_channel_route(
|
|
103
|
+
interaction.guild_id,
|
|
104
|
+
owner,
|
|
105
|
+
name,
|
|
106
|
+
category.value,
|
|
107
|
+
channel.id,
|
|
108
|
+
)
|
|
109
|
+
await interaction.response.send_message(
|
|
110
|
+
embed=branded_embed(
|
|
111
|
+
':schedule_check: Route updated',
|
|
112
|
+
{'Repository': f'`{owner}/{name}`', 'Category': category.value, 'Channel': channel.mention},
|
|
113
|
+
),
|
|
114
|
+
ephemeral=True,
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
bot.tree.add_command(group)
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import discord
|
|
2
|
+
from discord import app_commands
|
|
3
|
+
|
|
4
|
+
from ..embeds import branded_embed
|
|
5
|
+
from ..posts import load_post
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def register_post_command(bot):
|
|
9
|
+
@bot.tree.command(name='post', description='Publish a configured Markdown or YAML post here.')
|
|
10
|
+
@app_commands.describe(name='Post file name, optionally ending in .md or .yaml')
|
|
11
|
+
@app_commands.default_permissions(manage_guild=True)
|
|
12
|
+
@app_commands.guild_only()
|
|
13
|
+
async def post(interaction: discord.Interaction, name: str):
|
|
14
|
+
if not interaction.user.guild_permissions.manage_guild:
|
|
15
|
+
await interaction.response.send_message(
|
|
16
|
+
embed=branded_embed(':ban: Access denied', {'Reason': 'Manage Server permission is required.'}),
|
|
17
|
+
ephemeral=True,
|
|
18
|
+
)
|
|
19
|
+
return
|
|
20
|
+
|
|
21
|
+
try:
|
|
22
|
+
definition = load_post(name, bot.settings.posts_directory)
|
|
23
|
+
except (FileNotFoundError, ValueError) as exc:
|
|
24
|
+
await interaction.response.send_message(
|
|
25
|
+
embed=branded_embed(':circle_alert: Post not sent', {'Reason': str(exc)}),
|
|
26
|
+
ephemeral=True,
|
|
27
|
+
)
|
|
28
|
+
return
|
|
29
|
+
|
|
30
|
+
if not isinstance(interaction.channel, discord.abc.Messageable):
|
|
31
|
+
await interaction.response.send_message(
|
|
32
|
+
embed=branded_embed(':circle_alert: Post not sent', {'Reason': 'This channel cannot receive messages.'}),
|
|
33
|
+
ephemeral=True,
|
|
34
|
+
)
|
|
35
|
+
return
|
|
36
|
+
|
|
37
|
+
kwargs = {'allowed_mentions': definition.allowed_mentions}
|
|
38
|
+
if definition.content:
|
|
39
|
+
kwargs['content'] = definition.content
|
|
40
|
+
if definition.embeds:
|
|
41
|
+
kwargs['embeds'] = definition.embeds
|
|
42
|
+
if definition.poll is not None:
|
|
43
|
+
kwargs['poll'] = definition.poll
|
|
44
|
+
if definition.attachments:
|
|
45
|
+
kwargs['files'] = definition.attachments
|
|
46
|
+
if definition.view is not None:
|
|
47
|
+
kwargs['view'] = definition.view
|
|
48
|
+
if definition.suppress_embeds:
|
|
49
|
+
kwargs['suppress_embeds'] = True
|
|
50
|
+
if definition.silent:
|
|
51
|
+
kwargs['silent'] = True
|
|
52
|
+
if definition.tts:
|
|
53
|
+
kwargs['tts'] = True
|
|
54
|
+
if len(kwargs) == 1:
|
|
55
|
+
await interaction.response.send_message(
|
|
56
|
+
embed=branded_embed(':circle_alert: Post not sent', {'Reason': 'The post definition has no message content.'}),
|
|
57
|
+
ephemeral=True,
|
|
58
|
+
)
|
|
59
|
+
return
|
|
60
|
+
|
|
61
|
+
await interaction.response.defer(ephemeral=True, thinking=True)
|
|
62
|
+
try:
|
|
63
|
+
await interaction.channel.send(**kwargs)
|
|
64
|
+
except (discord.Forbidden, discord.HTTPException) as exc:
|
|
65
|
+
await interaction.followup.send(
|
|
66
|
+
embed=branded_embed(':circle_alert: Post not sent', {'Reason': str(exc)}),
|
|
67
|
+
ephemeral=True,
|
|
68
|
+
)
|
|
69
|
+
else:
|
|
70
|
+
await interaction.followup.send(
|
|
71
|
+
embed=branded_embed(':check: Post sent', {'File': name}),
|
|
72
|
+
ephemeral=True,
|
|
73
|
+
)
|
|
74
|
+
finally:
|
|
75
|
+
for file in definition.attachments:
|
|
76
|
+
file.close()
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
|
|
3
|
+
import discord
|
|
4
|
+
from discord import app_commands
|
|
5
|
+
from mapres import res
|
|
6
|
+
|
|
7
|
+
from ..embeds import branded_embed, status_emoji, truncate
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
async def _authorized(interaction, settings):
|
|
11
|
+
if interaction.user.id == settings.owner_id:
|
|
12
|
+
return True
|
|
13
|
+
return any(role.id == settings.server_staff_role_id for role in interaction.user.roles)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
async def _deny(interaction):
|
|
17
|
+
await interaction.followup.send(
|
|
18
|
+
embed=branded_embed(':ban: Access denied', {'Reason': 'You need the server staff role to use this action.'}),
|
|
19
|
+
ephemeral=True,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class PowerControlView(discord.ui.View):
|
|
24
|
+
def __init__(self, bot):
|
|
25
|
+
super().__init__(timeout=30)
|
|
26
|
+
self.bot = bot
|
|
27
|
+
|
|
28
|
+
async def perform(self, interaction, action):
|
|
29
|
+
await interaction.response.defer(ephemeral=True, thinking=True)
|
|
30
|
+
if not await _authorized(interaction, self.bot.settings):
|
|
31
|
+
await _deny(interaction)
|
|
32
|
+
return
|
|
33
|
+
try:
|
|
34
|
+
await asyncio.to_thread(self.bot.server.powerAction, action)
|
|
35
|
+
except Exception as exc:
|
|
36
|
+
await interaction.followup.send(
|
|
37
|
+
embed=branded_embed(':circle_alert: Power action failed', {'Error': truncate(exc, 1000)}),
|
|
38
|
+
ephemeral=True,
|
|
39
|
+
)
|
|
40
|
+
return
|
|
41
|
+
await interaction.followup.send(
|
|
42
|
+
embed=branded_embed(':check: Power action sent', {'Action': action.title()}),
|
|
43
|
+
ephemeral=True,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
@discord.ui.button(label='Start', emoji=res(':start:'))
|
|
47
|
+
async def start_button(self, interaction: discord.Interaction, button: discord.ui.Button):
|
|
48
|
+
await self.perform(interaction, 'start')
|
|
49
|
+
|
|
50
|
+
@discord.ui.button(label='Restart', emoji=res(':restart:'))
|
|
51
|
+
async def restart_button(self, interaction: discord.Interaction, button: discord.ui.Button):
|
|
52
|
+
await self.perform(interaction, 'restart')
|
|
53
|
+
|
|
54
|
+
@discord.ui.button(label='Stop', emoji=res(':stop:'))
|
|
55
|
+
async def stop_button(self, interaction: discord.Interaction, button: discord.ui.Button):
|
|
56
|
+
await self.perform(interaction, 'stop')
|
|
57
|
+
|
|
58
|
+
@discord.ui.button(label='Terminate', emoji=res(':kill:'))
|
|
59
|
+
async def terminate_button(self, interaction: discord.Interaction, button: discord.ui.Button):
|
|
60
|
+
await self.perform(interaction, 'kill')
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def register_server_commands(bot):
|
|
64
|
+
server_group = app_commands.Group(name='server', description='Check and manage the configured Minecraft server.')
|
|
65
|
+
admin_group = app_commands.Group(name='admin', description='Staff server controls.')
|
|
66
|
+
|
|
67
|
+
@server_group.command(name='status', description='Check the configured server status.')
|
|
68
|
+
async def status(interaction: discord.Interaction):
|
|
69
|
+
await interaction.response.defer(thinking=True)
|
|
70
|
+
try:
|
|
71
|
+
online = await asyncio.to_thread(bot.server.isOnline)
|
|
72
|
+
except Exception as exc:
|
|
73
|
+
await interaction.followup.send(
|
|
74
|
+
embed=branded_embed(':circle_alert: Status unavailable', {'Error': truncate(exc, 1000)}),
|
|
75
|
+
ephemeral=True,
|
|
76
|
+
)
|
|
77
|
+
return
|
|
78
|
+
label = 'Online' if online else 'Offline'
|
|
79
|
+
await interaction.followup.send(
|
|
80
|
+
embed=branded_embed(
|
|
81
|
+
f'{status_emoji(online)} {bot.settings.server_name}',
|
|
82
|
+
{'Status': label},
|
|
83
|
+
)
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
@server_group.command(name='players', description='List online players on the server.')
|
|
87
|
+
async def players(interaction: discord.Interaction):
|
|
88
|
+
await interaction.response.defer(thinking=True)
|
|
89
|
+
|
|
90
|
+
def read_players():
|
|
91
|
+
count = bot.server.bridge.getPlayerCount()
|
|
92
|
+
result = bot.server.bridge.getPlayers()
|
|
93
|
+
if isinstance(result, dict):
|
|
94
|
+
result = result.get('players', [])
|
|
95
|
+
if isinstance(result, list):
|
|
96
|
+
names = [
|
|
97
|
+
player.get('name', str(player)) if isinstance(player, dict) else str(player)
|
|
98
|
+
for player in result
|
|
99
|
+
]
|
|
100
|
+
else:
|
|
101
|
+
names = [str(result)] if result else []
|
|
102
|
+
return count, names
|
|
103
|
+
|
|
104
|
+
try:
|
|
105
|
+
count, names = await asyncio.to_thread(read_players)
|
|
106
|
+
except Exception as exc:
|
|
107
|
+
await interaction.followup.send(
|
|
108
|
+
embed=branded_embed(':circle_alert: Players unavailable', {'Error': truncate(exc, 1000)}),
|
|
109
|
+
ephemeral=True,
|
|
110
|
+
)
|
|
111
|
+
return
|
|
112
|
+
output_text = '\n'.join(names) if names else 'No players online.'
|
|
113
|
+
player_icon = res(':players:')
|
|
114
|
+
await interaction.followup.send(
|
|
115
|
+
embed=branded_embed(
|
|
116
|
+
f'{player_icon} {bot.settings.server_name} players',
|
|
117
|
+
{'Count': str(count), 'Players': output_text},
|
|
118
|
+
)
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
@admin_group.command(name='run', description='Run a command on the Minecraft server.')
|
|
122
|
+
@app_commands.describe(command='Console command to run')
|
|
123
|
+
async def run_command(interaction: discord.Interaction, command: str):
|
|
124
|
+
await interaction.response.defer(thinking=True, ephemeral=True)
|
|
125
|
+
if not await _authorized(interaction, bot.settings):
|
|
126
|
+
await _deny(interaction)
|
|
127
|
+
return
|
|
128
|
+
try:
|
|
129
|
+
output = await asyncio.to_thread(bot.server.sendCommand, command, show_console=True)
|
|
130
|
+
except Exception as exc:
|
|
131
|
+
output = f'Error: {exc}'
|
|
132
|
+
output_text = truncate(output or 'No output', 900)
|
|
133
|
+
await interaction.followup.send(
|
|
134
|
+
embed=branded_embed(
|
|
135
|
+
':terminal_blue: Console command',
|
|
136
|
+
{'Command': f'`{truncate(command, 900)}`', 'Output': f'```\n{output_text}```'},
|
|
137
|
+
),
|
|
138
|
+
ephemeral=True,
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
@admin_group.command(name='power', description='Open server power controls or run a specific action.')
|
|
142
|
+
@app_commands.describe(action='Optional action to perform immediately')
|
|
143
|
+
@app_commands.choices(action=[
|
|
144
|
+
app_commands.Choice(name='Start', value='start'),
|
|
145
|
+
app_commands.Choice(name='Restart', value='restart'),
|
|
146
|
+
app_commands.Choice(name='Stop', value='stop'),
|
|
147
|
+
app_commands.Choice(name='Terminate', value='kill'),
|
|
148
|
+
])
|
|
149
|
+
async def power(interaction: discord.Interaction, action: app_commands.Choice[str] = None):
|
|
150
|
+
await interaction.response.defer(thinking=True, ephemeral=True)
|
|
151
|
+
if not await _authorized(interaction, bot.settings):
|
|
152
|
+
await _deny(interaction)
|
|
153
|
+
return
|
|
154
|
+
if action is None:
|
|
155
|
+
try:
|
|
156
|
+
online = await asyncio.to_thread(bot.server.isOnline)
|
|
157
|
+
status = 'Online' if online else 'Offline'
|
|
158
|
+
except Exception as exc:
|
|
159
|
+
status = f'Unavailable: {truncate(exc, 700)}'
|
|
160
|
+
power_icon = res(':circle_power_yellow:')
|
|
161
|
+
await interaction.followup.send(
|
|
162
|
+
embed=branded_embed(f'{power_icon} {bot.settings.server_name} power', {'Status': status}),
|
|
163
|
+
view=PowerControlView(bot),
|
|
164
|
+
ephemeral=True,
|
|
165
|
+
)
|
|
166
|
+
return
|
|
167
|
+
try:
|
|
168
|
+
await asyncio.to_thread(bot.server.powerAction, action.value)
|
|
169
|
+
except Exception as exc:
|
|
170
|
+
await interaction.followup.send(
|
|
171
|
+
embed=branded_embed(':circle_alert: Power action failed', {'Error': truncate(exc, 1000)}),
|
|
172
|
+
ephemeral=True,
|
|
173
|
+
)
|
|
174
|
+
return
|
|
175
|
+
await interaction.followup.send(
|
|
176
|
+
embed=branded_embed(':check: Power action sent', {'Action': action.name}),
|
|
177
|
+
ephemeral=True,
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
@admin_group.command(name='statistics', description='Show server resource and Minecraft statistics.')
|
|
181
|
+
async def statistics(interaction: discord.Interaction):
|
|
182
|
+
await interaction.response.defer(thinking=True, ephemeral=True)
|
|
183
|
+
if not await _authorized(interaction, bot.settings):
|
|
184
|
+
await _deny(interaction)
|
|
185
|
+
return
|
|
186
|
+
|
|
187
|
+
def read_statistics():
|
|
188
|
+
bot.server.refresh()
|
|
189
|
+
return {
|
|
190
|
+
'status': bot.server.getStatus(),
|
|
191
|
+
'RAM': bot.server.getRAM(gb=True),
|
|
192
|
+
'CPU': bot.server.getCPU(),
|
|
193
|
+
'Disk': bot.server.getDisk(gb=True),
|
|
194
|
+
'Network in': bot.server.getNetworkIn(),
|
|
195
|
+
'Network out': bot.server.getNetworkOut(),
|
|
196
|
+
'Uptime': bot.server.getUptime(formatted=True),
|
|
197
|
+
'TPS': bot.server.bridge.getTPS('1m'),
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
try:
|
|
201
|
+
stats = await asyncio.to_thread(read_statistics)
|
|
202
|
+
except Exception as exc:
|
|
203
|
+
await interaction.followup.send(
|
|
204
|
+
embed=branded_embed(':circle_alert: Statistics unavailable', {'Error': truncate(exc, 1000)}),
|
|
205
|
+
ephemeral=True,
|
|
206
|
+
)
|
|
207
|
+
return
|
|
208
|
+
|
|
209
|
+
status_icon = status_emoji(stats['status'] == 'running')
|
|
210
|
+
statistics_icon = res(':statistics:')
|
|
211
|
+
cpu = stats['CPU']
|
|
212
|
+
ram = stats['RAM']
|
|
213
|
+
disk = stats['Disk']
|
|
214
|
+
network_in = stats['Network in']
|
|
215
|
+
network_out = stats['Network out']
|
|
216
|
+
fields = {
|
|
217
|
+
f'{status_icon} Status': stats['status'],
|
|
218
|
+
f'{statistics_icon} CPU': f'{cpu}%',
|
|
219
|
+
'RAM': f'{ram} GiB',
|
|
220
|
+
'Disk': f'{disk} GiB',
|
|
221
|
+
'Network': f'In {network_in} MiB · Out {network_out} MiB',
|
|
222
|
+
'Uptime': str(stats['Uptime']),
|
|
223
|
+
'TPS (1m)': str(stats['TPS']),
|
|
224
|
+
}
|
|
225
|
+
await interaction.followup.send(
|
|
226
|
+
embed=branded_embed(f'{statistics_icon} {bot.settings.server_name} statistics', fields),
|
|
227
|
+
ephemeral=True,
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
server_group.add_command(admin_group)
|
|
231
|
+
bot.tree.add_command(server_group)
|