Discord Bot Online 24/7

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!

I’m pretty sure that the pinger cannot be run inside the Repl. You could try using an external pinger.

2 Likes

now that replit-based pingers are gone due to egress limits, use

1 Like

On FreshPing, it is failing to detect it.

What did you try, and what happened?

1 Like

Even if you use an external pinger, it will not work, several of my bots that were on an external pingers uptime’s went down like 20%. I think replit changed something that stopped pingers, so the only good solution now is getting always on.

The way you worded that makes it sound like they’re trying to stop pingers. They’re not. It’s just that pingers won’t work with the new Replit hosting stuff.

3 Likes

try uptimerobot.com it works for me

2 Likes

I have two bots working 24/7. I use uptimerobot and works great!

Both bots are in python, for the lib is just:

from flask import Flask
from threading import Thread
  .....

keep_alive()

my_secret = os.environ['DISCORD_BOT_TOKEN']
bot.run(my_secret)

So try to use them.

2 Likes

I do too, just remember that whatever status it says on up-timer robot is not accurate, and you should use something to check the status of your discord bot instead of your website.

Uptimer robot is inaccurate because even if your repl is offline, it will still give the custom replit 404 or cannot boot, which uptimer robot cannot read, and will say that your website is “online”.

I still hadn’t any problems since I’m (and 20 others servers) constantly using the service.

But a good free alternative would be https://hetrixtools.com/ too.

It is probably fine how you are using it rn. Just remember to maybe not use replit when you are trying to register your bot for a bot list that requires a good uptime.

Yep, that I agree with you, by that time I will be paying a service or something like that. There’s a limit about how “free” you can go.

1 Like