如何将aioredis与discord.py一起使用?

2024-06-08 12:19:19 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用aioredisdiscord.py

问题是我不知道如何将discord.ext.commandsaioredis.create_redis_pool一起使用

我正在启动discord机器人

from discord.ext import commands

@bot.command("get_count")
async def get_count(ctx):
    count = get_reactions_count()
    # I need to somehow define async redis connection and use it here for example
    await ctx.send("some text")

bot = commands.Bot()
bot.run(config.TOKEN)

但在这种情况下,我如何定义redis客户端

我知道我们可以这样做,但这是一个最佳的解决方案吗

@bot.command("get_count")
async def get_count(ctx):
    redis = await aioredis.create_redis_pool(
        'redis://localhost')
    count = get_reactions_count()
    # and use redis connection here
    await ctx.send("some text")

Tags: redisgetasyncdefbotcountcreateawait
1条回答
网友
1楼 · 发布于 2024-06-08 12:19:19

要使连接保持活动状态,只需将其作为所谓的“bot-var”使用即可

bot.my_variable = 'whatever'

您可以对池执行相同的操作,有两种方法:

一,

@bot.event
async def on_ready():
    bot.pool = await aioredis.create_redis_pool(...)
bot.pool = bot.loop.run_until_complete(aioredit.create_redis_pool(...))

简单地使用它bot.pool.some_method

第二种方法是首选方法,可以多次调用on_ready事件

您还希望将redis事件循环与bot的循环“连接”,从文档中我可以看到aioredis.create_redis_poolloop作为可选参数

await aioredis.create_redis_pool(..., loop=bot.loop)

相关问题 更多 >