Skip to content Skip to sidebar Skip to footer

Discord.py Uptime

Using discord.py, I'm attempting to make a uptime script, im not sure if it would be a f string ( like await ctx.send(f'client.uptime') or a something else, im seriously new to di

Solution 1:

So I actually was wondering the same thing, and one of the answers here gave me the idea.

I'm a little overly verbose in part of it, but if you're new it should help. Some of the things that are done to get the uptime itself aren't gone too far in depth, but the code basically just returns a string that tells you in h:m:s how long your bot has been running.

Assuming you're doing this as a cog, here's how I did it (Note: this will work outside of a cog if you just format it like you would a command outside of a cog. The logic doesn't change, just how the command is formed)

import discord ----------#imports discord.pyimport datetime, time ---#this is the important set for generating an uptimefrom discord.ext import commands

#this is very important for creating a cogclasswhateverYouNameYourCog(commands.Cog):
    def__init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()asyncdefon_ready(self):
        print(f'{self} has been loaded') 
        global startTime --------#global variable to be used later in cog
        startTime = time.time()--# snapshot of time when listener sends on_ready#create a command in the cog    @commands.command(name='Uptime')asyncdef_uptime(self,ctx):

        # what this is doing is creating a variable called 'uptime' and assigning it# a string value based off calling a time.time() snapshot now, and subtracting# the global from earlier
        uptime = str(datetime.timedelta(seconds=int(round(time.time()-startTime))))
        await ctx.send(uptime)

#needed or the cog won't rundefsetup(bot)
    bot.add_cog(whateverYouNameYourCog(bot))    enter code here

Solution 2:

Your example would be ctx.send(f"{client.uptime}") the curly braces in an f string is where the variable is. However, I think discord.py doesn't have a .uptime feature. You would need to save the time the bot started up then calculate the time difference when the command is run. You would use something like this.

Solution 3:

import discord, datetime, time
from discord.ext import commands

@commands.command(pass_context=True)asyncdefuptime(self, ctx):
        current_time = time.time()
        difference = int(round(current_time - start_time))
        text = str(datetime.timedelta(seconds=difference))
        embed = discord.Embed(colour=0xc8dc6c)
        embed.add_field(name="Uptime", value=text)
        embed.set_footer(text="<bot name>")
        try:
            await ctx.send(embed=embed)
        except discord.HTTPException:
            await ctx.send("Current uptime: " + text)

Post a Comment for "Discord.py Uptime"