tandemdude / hikari-lightbulb

Simple, elegant and powerful command handler for the Python Discord library, Hikari.
https://hikari-lightbulb.readthedocs.io/en/latest/
MIT License
200 stars 30 forks source link

Tasks are hardcoded to support a single bot instance #346

Closed snazzyfox closed 4 months ago

snazzyfox commented 1 year ago

Steps to reproduce

I have a bot that runs in multiple servers, and each one uses a separate discord token so they have different usernames and pfps. I have all of them running in parallel. The periodic tasks extension from lightbulb appears to only work for the last bot it's loaded for.

For example:

bot1 = BotApp(token='TOKEN1')
bot2 = BotApp(token='TOKEN2')

@tasks.task(s=15, auto_start=True, pass_app=True)
async def test_task(app: BotApp):
    print(app.get_me().username)

tasks.load(bot1)
tasks.load(bot2)

async def main():
   return await asyncio.gather(bot1.start(), bot2.start())

asyncio.run(main())

Expected result

Every 15 seconds, username for both bots are printed.

Actual result

Only username for the last bot is printed.

System info

hikari-lightbulb (2.3.3)
hikari (2.0.0.dev120) [9ade5395]
located at C:\Users\snazzy\AppData\Local\pypoetry\Cache\virtualenvs\discord-bot-LLZcAbwq-py3.11\Lib\site-packages\hikari
CPython 3.11.4 MSC v.1934 64 bit (AMD64)
Windows SNAZZY-PC 10 10.0.22621 AMD64 Intel64 Family 6 Model 167 Stepping 1, GenuineIntel

Further info

I dug around in the code and found out that the Task class keeps track of registered tasks and the bot they're registered on globally as a static variable. This means the module assumes that one and only one bot instance can exist at a time, and there can only be a single global list of tasks.

Given the design of the class, it doesn't look like it's possible to enable it for multiple bots unless I completely copy/paste the entire class, since references to the app is always Task._app, instead of self.app or cls.app.

I understand that solving this can possibly result in a breaking api change. If this can't be fixed, I think it's at least helpful to document this behavior, and maybe throw an error on tasks.load if they're being registered in a second bot.

Checklist

tandemdude commented 4 months ago

I know its been a while - this feature is supported now by v3 of Lightbulb. I do not intend to backport an implementation to v2.