Hello coders! I made a Discord bot in Python, but every time I close the tab, the bot goes offline.
Here is Main.Py
# Required packages
import discord
import os
from discord.ext import commands
from keep_alive import keep_alive
# Bot token is in .env
TOKEN = os.getenv('TOKEN')
# Keeps the bot online 24/7
keep_alive()
# Bot prefix and required intents (Administrator)
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())
bot.remove_command('help')
# Bot status
@bot.event
async def on_ready():
activity = discord.Activity(type=discord.ActivityType.watching, name="!cmds")
await bot.change_presence(status=discord.Status.dnd, activity=activity)
print("Bot status is active.")
# !kick command
@bot.command(name='kick')
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
try:
await member.kick(reason=reason)
if reason:
await ctx.send(f"{member} has been kicked for {reason}.")
else:
await ctx.send(f"{member} has been kicked.")
print("Kick command is active.")
except discord.Forbidden:
await ctx.send("Could not kick.")
# !mute command
@bot.command(name='mute')
@commands.has_permissions(manage_roles=True, manage_channels=True)
async def mute(ctx, member: discord.Member, *, reason=None):
try:
role = discord.utils.get(ctx.guild.roles, name="Muted")
if not role:
role = await ctx.guild.create_role(name="Muted")
for channel in ctx.guild.channels:
await channel.set_permissions(role, send_messages=False)
await member.add_roles(role, reason=reason)
if reason:
await ctx.send(f"{member} has been muted for {reason}.")
else:
await ctx.send(f"{member} has been muted.")
print("Mute command is active.")
except discord.Forbidden:
await ctx.send(f"Uh oh! I could not mute {member}.")
# !ban command
@bot.command(name='ban')
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member, *, reason=None):
try:
await member.ban(reason=reason)
if reason:
await ctx.send(f"{member} has been banned for {reason}.")
else:
await ctx.send(f"{member} has been banned.")
print("Ban command is active.")
except discord.Forbidden:
await ctx.send("Uh oh, I could not ban the specified user.")
# !cmds command
@bot.command(name='cmds')
async def help(ctx):
try:
color_code = int('446be5', 16) # converts the hex code to an integer
embed = discord.Embed(title='Commands', description='Lists all available commands', color=color_code)
embed.set_thumbnail(url='https://th.bing.com/th/id/R.8a591f7d06683be63321fefc7c1cb1dd?rik=gl%2bGpLeJF%2f%2bPjw&pid=ImgRaw&r=0')
embed.add_field(name='!ban @user', value='Bans the specified user')
embed.add_field(name='!kick @user', value='Kicks the specified user')
embed.add_field(name='!mute @user', value='Mutes the specified user from chatting and talking in voice channels')
embed.add_field(name='!servers', value='Owner **ONLY** command that sends the owner the servers that the bot is invited to')
embed.add_field(name='!unban @user', value='Unbans the specified user')
embed.add_field(name='!unmute 2user', value='Unmutes the specified user')
embed.add_field(name='!help', value='Sends this embed in the specified channel')
await ctx.send(embed=embed)
except discord.Forbidden:
await ctx.send('I do not have permission to send messages in this channel.')
except Exception as e:
await ctx.send(f'An error occurred: {e}')
@bot.command()
@commands.has_role('admin')
async def unban(ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f"{user.mention} has been unbanned.")
return
@bot.command()
@commands.has_role('admin')
async def unmute(ctx, member: discord.Member):
await member.edit(mute=False)
await ctx.send(f"{member.mention} has been unmuted.")
# !help command
@bot.command(name='help')
async def help(ctx):
try:
color_code = int('446be5', 16) # converts the hex code to an integer
embed = discord.Embed(title='Commands', description='Lists all available commands', color=color_code)
embed.set_thumbnail(url='https://th.bing.com/th/id/R.8a591f7d06683be63321fefc7c1cb1dd?rik=gl%2bGpLeJF%2f%2bPjw&pid=ImgRaw&r=0')
embed.add_field(name='!ban @user', value='Bans the specified user')
embed.add_field(name='!kick @user', value='Kicks the specified user')
embed.add_field(name='!mute @user', value='Mutes the specified user from chatting and talking in voice channels')
embed.add_field(name='!servers', value='Owner **ONLY** command that sends the owner the servers that the bot is invited to')
embed.add_field(name='!help', value='Sends this embed in the specified channel')
await ctx.send(embed=embed)
except discord.Forbidden:
await ctx.send('I do not have permission to send messages in this channel.')
except Exception as e:
await ctx.send(f'An error occurred: {e}')
# !servers command (Owner only) (DM the owner the servers)
@bot.command()
async def servers(ctx):
if ctx.author.id == 921216944215056414: # Replace this with your own user ID
server_list = []
for guild in bot.guilds:
invite_link = await guild.text_channels[0].create_invite(max_age=300)
server_list.append(invite_link.url)
servers = "\n".join(server_list)
await ctx.author.send(f"Here are the servers I am in:\n{servers}")
await ctx.send("Check your DMs for the server list!")
else:
await ctx.send("This command can only be used by the owner of the bot.")
# Unknown command
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send("Unknown command, use !cmds to view all commands")
#Bot token
bot.run(TOKEN)
keep_alive.py
from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def home():
return "<b> <center> AdminEssentials is now online! </center> </b>"
def run():
app.run(host='0.0.0.0',port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
Thank you!