LoginSignup
0
0

More than 1 year has passed since last update.

subprocessを使ってdiscord上からUbuntuPCの再起動

Last updated at Posted at 2023-02-20

※初投稿です。文章力に自信はないですがよろしくお願いします。
Discord.pyとsubprocessを使用し、Discord上でUbuntu22.04.1が入っているPCの再起動をする方法を紹介します。
関係ない話ですが私はサーバーの再起動として使用しています。

バージョンなど

$ lsb_release -a
Description: Ubuntu 22.04.1 LTS

$ python3 --version
Python 3.10.6

$ pip show discord
Version: 2.1.0 

補足

今回はDiscordのスラッシュコマンドを使用します。また、@bot.tree.commandを使用しています。

スラッシュコマンドとは

スラッシュコマンドとはチャンネル、またはDM(ダイレクトメッセージ)で"/"から始まるコマンドを打つことでbotにコマンドを送信するものです。
surassyucommand.png

実装

※実装するときに友達の@Shichimiiに手伝ってもらいました。ありがとう。もう一度言います。ありがとう!

基本コード

注意
お使いの環境によっては正常に動作しない可能性があります。ご了承ください。

import discord
import subprocess
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='/',help_command=None,intents=intents)

@bot.tree.command(name="reboot",description="注意:このコマンドを使用するとPCを再起動します。")
async def restart(ctx):
    await ctx.response.send_message("再起動します。")
    subprocess.run(["reboot"])
bot.run('your_token')

簡単な説明

@bot.tree.command(name="reboot",description="注意:このコマンドを使用するとPCを再起動します。")

name=のところは"/"の後に打ち込む文字を指します。ここでは/rebootと打ち込むことによってコマンドが実行されます。
description=のところはスラッシュコマンドの説明文の部分です。(下画像参照)
description.png

await ctx.response.send_message("再起動します。")

ここではコマンドの応答メッセージを送信します。たぶんメッセージ送らないと厄介なことになると思うので...

bot.run('your_token')

your_tokenのところは自分のbotのtokenを貼り付けてください。
ここから確認できます。

別パターン

もし1分後に再起動させる場合は

import discord
import subprocess
import time
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='/',help_command=None,intents=intents)

@bot.tree.command(name="reboot",description="注意:このコマンドを使用するとPCを再起動します。")
async def restart(ctx):
    await ctx.response.send_message("1分後に再起動します。")
    time.sleep(60)
    subprocess.run(["reboot"])
bot.run('your_token')

となります。

time.sleep(60)

これは60秒待つという意味です。

結果

reboot.png
無事再起動されました!眠い...(朝4時)

お読みいただきありがとうございました。皆さんも楽しいbotライフをお過ごしください(?)

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0