Skip to content

Instantly share code, notes, and snippets.

@FlamptX
Last active August 6, 2021 13:37
Show Gist options
  • Save FlamptX/ffd215fa1111148055f92a6fe24b430f to your computer and use it in GitHub Desktop.
Save FlamptX/ffd215fa1111148055f92a6fe24b430f to your computer and use it in GitHub Desktop.
Basically what I did is that I ran a file restart.py with an argument which was the channel id and then terminated the bot. Then in restart.py I ran the main file (bot.py) with the same argument and then in bot.py I checked if there was an argument, and if there was one, I would fetch the channel with it and send a message saying "Bot restarted!"

Rerun main bot file with a command in discord.py

This is a simple way to restart the bot within itself

Basically what I did is that I ran a file restart.py with an argument which was the channel id and then terminated the bot. Then in restart.py I ran the main file (bot.py) with the same argument and then in bot.py I checked if there was an argument, and if there was one, I would fetch the channel with it and send a message saying "Bot restarted!"

Example bot.py file:

from discord.ext import commands
import argparse
import os
import functools
import sys

parser = argparse.ArgumentParser()
parser.add_argument("id", nargs='?', default=None)
args = parser.parse_args()

bot = commands.bot(command_prefix="!")

@bot.event
async def on_ready():
    print("The bot is online and ready!")
    if args.id is not None:
        channel = bot.get_channel(int(args.id)) or await bot.fetch_channel(int(args.id))
        await channel.send("Bot restarted!")

@bot.command(aliases=["restart"], hidden=True)
@commands.is_owner()
async def _restart(ctx):
    await ctx.send("Restarting...")
    bot.loop.run_in_executor(None, functools.partial(os.system, "python restart.py " + str(ctx.channel.id)))  # fix by RamzziSudip
    sys.exit()

bot.run("TOKEN")

restart.py:

import os
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("id", nargs='?')
args = parser.parse_args()

os.system("python bot.py " + args.id)
You can contact me on discord (Flampt#0542) if you run into issues. I hope I can help.
@LuisPavelA
Copy link

Interesting

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment