gpt4 book ai didi

python - 不和谐、粗暴、阻塞

转载 作者:太空宇宙 更新时间:2023-11-03 14:49:40 25 4
gpt4 key购买 nike

所以我正在 python 上编写不和谐的机器人,我想创建一个后台任务来检查 subreddit 中是否有新提交的内容,并在有一定天赋的情况下发布它。但是当我尝试启动我的机器人时,它以前运行得很好,它只是等待一些东西并且不会启动。我该怎么办?

async def reddit_task():
await bot.wait_until_ready()
start_time = time.time()
reddit = praw.Reddit(different keys)
subreddit = reddit.subreddit('certain subreddit')
for submission in subreddit.stream.submissions():
if submission.created_utc > start_time:
if submission.link_flair_text == 'certain flair':
em = discord.Embed(title=submission.title+'\n'+submission.shortlink)
if len(submission.preview) > 1:
em.set_image(url=submission.preview['images'][0]['source']['url'])
await bot.send_message(discord.Object(id='my channel id'), embed=em)

else:
pass

if __name__ == "__main__":
for extension in startup_extensions:
try:
bot.load_extension(extension)
except Exception as e:
exc = '{}: {}'.format(type(e).__name__, e)
print('Failed to load extension {}\n{}'.format(extension, exc))
bot.loop.create_task(reddit_task())
bot.run(config.bot_beta_token)

最佳答案

我也遇到了这个问题,因为 subreddit.stream.submissions() 阻塞了 for 循环。所以我通过使用无限循环和 subreddit.stream.submissions(pause_after=0) 解决了这个问题,因此如果没有新帖子,它会返回 None 然后等待 60 秒再检查再次。

async def reddit_task():
await client.wait_until_ready()
start_time = time.time()

reddit = praw.Reddit("<client_stuff>")
subreddit = reddit.subreddit("<some_subreddit>")
submissions = subreddit.stream.submissions(pause_after=0)

while not client.is_closed:
submission = next(submissions)

if submission is None:
# Wait 60 seconds for a new submission
await asyncio.sleep(60)

elif submission.created_utc > start_time:
<do_stuff_with_submission>

关于python - 不和谐、粗暴、阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45961880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com