'How do you create a command that makes the bot go OFFLINE in discord.py

Is it possible?

I want to create a command for my discord bot that makes the bot offline for everyone. I want to type that command in any discord server and then the bot just goes offline. This is much easier than going into your files or terminal to press ctrl+c. Is a command like this possible to even make? And if so, can I please know how to add that command? I want to add some admin commands to my bot and this is definitely a great addition to the list. Thanks -



Solution 1:[1]

I would suggest choosing a more graceful exit for your bot, which would be using await bot.close() if you are using master branch of discord.py, it cleanly closes the websocket connection it makes to discord.

@bot.command()
async def shutdown(ctx):
   await ctx.send("Shutting down bot!")
   await bot.close()

If you are using the stable version, i.e 1.7.3 which is installed when you do pip install discord.py, you can use await bot.logout() instead

Unlike master branch's Bot.close, this drops all connections immediately.

@bot.command()
async def shutdown(ctx):
   await ctx.send("Shutting down bot!")
   await bot.logout()

Solution 2:[2]

If I'm understanding what you're trying to do here, you can just add a command that exits the bot.py program by making a call to something like sys.exit(). This would just terminate the program running the bot, making the bot go offline.

Solution 3:[3]

You can either use sys.exit() or os.exit() to terminate the process of your bot. Remember to save any data you may need to save before terminating the process.

sys.exit()

With sys.exit(), you can provide a message which will then be printed. E.g.:

import sys

sys.exit("Bot has been shut down")

os.exit()

With os.exit(), you can provide an exit code, which is a number. You may not really need that exit code, but it can be useful in a bash script. Usually, a code of 0 means the process terminated successfully. E.g.:

import os

os.exit(0)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SELECT stupidity FROM discord
Solution 2 mlb6300
Solution 3 Lezurex