我正在discord.py中制作一个机器人,并使用异步praw拥有一个完全工作的meme命令(praw没有工作)。但是这个模因的出现需要8到10秒的时间。有没有办法缩短时间?这是密码:-
@client.command(aliases=['memes'])
async def meme(ctx):
subreddit = await reddit.subreddit("memes")
all_subs = []
top = subreddit.top(limit = 200)
async for submission in top:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
ups = random_sub.score
link = random_sub.permalink
comments = random_sub.num_comments
embed = discord.Embed(title=name,url=f"https://reddit.com{link}", color=ctx.author.color)
embed.set_image(url=url)
embed.set_footer(text = f"{ups} {comments}")
await ctx.send(embed=embed)发布于 2021-04-15 11:08:15
这需要一段时间,因为每次执行命令时,总是会生成一个要从中选择的提交列表,但是在命令执行后列表就会消失,这意味着每次执行命令都会生成200个posts,只需从一个命令中选择
如果你想要一个更高效,更快的方式,让它成为一个单独的功能!
all_subs = []
async def gen_memes():
subreddit = await reddit.subreddit("memes")
top = subreddit.top(limit = 200)
async for submission in top:
all_subs.append(submission)
@client.event
async def on_ready():
await gen_memes() # generate memes when bot starts
@client.command(aliases=['memes'])
async def meme(ctx):
random_sub = random.choice(all_subs)
all_subs.remove(random_sub)
name = random_sub.title
url = random_sub.url
ups = random_sub.score
link = random_sub.permalink
comments = random_sub.num_comments
embed = discord.Embed(title=name,url=f"https://reddit.com{link}", color=ctx.author.color)
embed.set_image(url=url)
embed.set_footer(text = f"{ups} {comments}")
await ctx.send(embed=embed)
if len(all_subs) <= 20: # meme collection running out owo
await gen_memes()当然,这不是最有效的方法,如果你想在一定的时间间隔内填充你的模因,你可以使用discord.ext.tasks!
https://stackoverflow.com/questions/67101891
复制相似问题