Reputation: 35
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 discord.py
and have just started learning it, can somebody help?
Upvotes: 2
Views: 11270
Reputation: 61
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.py
import datetime, time ---#this is the important set for generating an uptime
from discord.ext import commands
#this is very important for creating a cog
class whateverYouNameYourCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_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')
async def _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 run
def setup(bot)
bot.add_cog(whateverYouNameYourCog(bot)) enter code here
Upvotes: 6
Reputation: 1
import discord, datetime, time
from discord.ext import commands
@commands.command(pass_context=True)
async def uptime(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)
Upvotes: -1
Reputation: 2907
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.
Upvotes: 1