python - 未关闭的客户端会话
问题描述
我正在尝试向 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)
解决方案
我可以看到您正在尝试制作 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)
推荐阅读
- sql-server - 在 SQL 查询中使用第二个 select 语句
- python - 无法从 boto3 注册 ECS 任务
- python - 显示每个绘制点的刻度
- c# - 如果对象的引用变量是超类类型,是否可以访问子类的属性?
- vb.net - 如何管理数据输入网页的超时?
- java - 如何在一个活动中将一个界面用于两个以上的后台 android 任务?
- redux - 如何在 redux-form 数字字段中本地化小数分隔符?
- batch-file - GPO .bat 文件不起作用注销/关闭删除文件和文件夹
- r - R S3 处理两个带 fread 的双 qoute
- r - 打开“.rattle”文件时如何解决以下错误?“.RGtkCall 中的错误(”S_gtk_file_chooser_dialog_new_with_backend