マイクラサーバーをDiscord Botで起動/停止する
自分が管理しているマイクラサーバーをDiscordから起動/停止できたら便利じゃね?ってことで始めた マイクラサーバーのメンバーのDiscordサーバーにBotを追加
メンバーがコマンドを打つことで操作を実現
必要なもの
手順
Discordからコマンドを受け取り,それに応じたシェルスクリプトを実行する
code:python
from discord.ext import commands
import discord
import subprocess
# intentの設定
intents = discord.Intents.default()
intents.message_content = True # メッセージの内容を読み取るために必要です
# Botの初期化時にintentsを指定
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'{bot.user} has connected to Discord!')
# コマンドの定義
# !startmc コマンドでサーバーを起動するシェルスクリプトを起動
@bot.command(name='startmc')
# サーバーの全員に許可
@commands.has_role('@everyone')
async def start_mc(ctx):
try:
subprocess.run(
# サーバー起動用のシェルスクリプト
check=True
)
await ctx.send('マインクラフトサーバーを起動しました!')
except subprocess.CalledProcessError as e:
await ctx.send(f'起動時にエラーが発生しました: {str(e)}')
# !stopmc コマンドでサーバーを停止するシェルスクリプトを起動
@bot.command(name='stopmc')
@commands.has_role('@everyone')
async def stop_mc(ctx):
try:
subprocess.run(
# サーバー停止用のシェルスクリプト
check=True
)
await ctx.send('マインクラフトサーバーを停止しました!')
except subprocess.CalledProcessError as e:
await ctx.send(f'停止時にエラーが発生しました: {str(e)}')
bot.run(
'YOUR_DISCORD_BOT_TOKEN'
)
今回のケースでは信頼できるメンバーしかいないためロールは@everyoneに設定
YOUR_DISCORD_BOT_TOKENを取得したトークンに書き換える
上記スクリプトをパスの通ったディレクトリに配置
マイクラサーバー,Discord Botを常駐させるため
これメチャクチャ苦戦した…
現在は!を使用するコマンドからスラッシュコマンドへ移行
ソースコード
参考