【发布时间】:2020-06-20 07:57:54
【问题描述】:
使用discord.py,我正在尝试制作uptime 脚本,我不确定它是否会是f string(比如等待ctx.send(f"client.uptime") 或其他东西,
我是discord.py 的新手,刚开始学习,有人可以帮忙吗?
【问题讨论】:
标签: python discord.py uptime
使用discord.py,我正在尝试制作uptime 脚本,我不确定它是否会是f string(比如等待ctx.send(f"client.uptime") 或其他东西,
我是discord.py 的新手,刚开始学习,有人可以帮忙吗?
【问题讨论】:
标签: python discord.py uptime
所以我实际上也在想同样的事情,这里的一个答案给了我这个想法。
我在其中的一部分有点过于冗长,但如果你是新手,它应该会有所帮助。为获得正常运行时间本身所做的一些事情并没有深入,但代码基本上只是返回一个字符串,以 h:m:s 的形式告诉你你的机器人已经运行了多长时间。
假设你是作为一个齿轮来做这个的,我就是这样做的 (注意:如果你只是像在 cog 之外的命令一样格式化它,这将在 cog 之外工作。逻辑不会改变,只是命令的形成方式)
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
【讨论】:
您的示例是ctx.send(f"{client.uptime}") f 字符串中的花括号是变量所在的位置。但是,我认为 discord.py 没有.uptime 功能。您需要保存机器人启动的时间,然后计算命令运行时的时间差。你会使用this之类的东西。
【讨论】:
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)
【讨论】:
start_time 不是此范围内定义的变量