首页 > 解决方案 > 未关闭的客户端会话

问题描述

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

问题是当我运行此脚本时出现错误:未关闭的客户端会话 client_session: <aiohttp.client.ClientSession object at 0x000002EE51BE5B80>

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)

标签: pythonpython-3.xdiscord.pypython-asyncio

解决方案


我可以看到您正在尝试制作 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)

推荐阅读