【问题标题】:Unclosed client session未关闭的客户端会话
【发布时间】:2021-09-06 16:57:59
【问题描述】:

我正在尝试向 discord bot 发出命令,该命令从该脚本中获取列表并从中随机发送一个。我大约一个月前在 Python 中启动了程序,所以这对我来说实际上很难。

问题是当我运行此脚本时出现错误:未关闭的客户端会话 client_session:

import asyncpraw
import asyncio
from aiohttp import ClientSession

async def get_meme(posses=100):
    posts = []
    async with ClientSession() as session:
        async for subreddit in subreddits:
            sub = await reddit.subreddit(subreddit).top(limit=posses, time_filter="week")
            for post in sub:
                await posts.append(post.url)
        await session.close()
        return posts


async def main():
    task = asyncio.create_task(get_meme())
    reddit_memes = await task
    print(reddit_memes)

【问题讨论】:

    标签: python python-3.x discord.py python-asyncio


    【解决方案1】:

    我可以看到您正在尝试制作 meme 命令。我会推荐asyncpraw reddit API。这是一个简单的例子:-

    import asyncpraw #Register at https://www.reddit.com/prefs/apps
    
    reddit = asyncpraw.Reddit(client_id = 'client_id',
                         client_secret = 'client_secret',
                         username = 'username',
                         password = 'password',
                         user_agent = 'user_agent')
    
    
    @client.command()
    async def meme(ctx):
      subreddit = await reddit.subreddit("memes")
      all_subs = []
      top = subreddit.top(limit = 100)
      async for submission in top:
          
        all_subs.append(submission)
        
      random_sub = random.choice(all_subs)
      name = random_sub.title
      url = random_sub.url
      link = random_sub.permalink
      embed = discord.Embed(title=name color=ctx.author.color)
      embed.set_image(url=url)
      await ctx.send(embed=embed)
    

    【讨论】:

    • 其实我做了这样的事情,但我需要先将它附加到'posts'变量,然后更改我的reddit_memes值,因为如果我这样做并且想要例如从获得100个热门帖子10 个 subreddits 会对机器人造成很大的滞后(我认为它会和图像我想每隔一小时重复一次......)编辑:抱歉英语不好,这不是我的母语 lang
    • 没关系,我问了一个问题,我也遇到了这个问题,已经解决了。 Here 是我问的问题。
    • 谢谢,这正是我想要的:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    相关资源
    最近更新 更多