How to use aioredis with discord.py?

793 views Asked by At

How to use aioredis and discord.py?

The problem is that I don't know how to use discord.ext.commands with aioredis.create_redis_pool.

I'm starting discord bot via

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)

But how can I define redis client in this case?

PS I know that we can do like this, but is this an optimal solution?

@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")
1

There are 1 answers

0
Łukasz Kwieciński On BEST ANSWER

To keep a connection alive you can simply have it as a so called "bot var".

bot.my_variable = 'whatever'

You can do the same with the pool, there are two ways:

1.

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

To use it simply bot.pool.some_method

The second way is the preferred one, the on_ready event can be called multiple times.

You also wanted to "connect" the redis event loop with the bot's loop, from the docs I can see that aioredis.create_redis_pool takes loop as an optional parameter.

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