Skip to content
Advertisement

Which method is the best for starting the bot in discord.py? login() and connect() vs start() vs run()

So, to connect the bot to discord.py, there are several methods:


What is the difference between them and which one is the best for running the bot?

Advertisement

Answer

I believe the official documentation is very clear:

  • start() is shorthand coroutine for login() + connect().
  • run() is a blocking call which means that

    This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.

There is no “best” method. If you want a synchronous execution, go for run(). start() (or login() + connect()) are more suitable for asynchronous executions.

Example with run()

With run() you don’t have to manage any event loop:

try:
    loop.run_until_complete(start(*args, **kwargs))
except KeyboardInterrupt:
    loop.run_until_complete(logout())
    # cancel all tasks lingering
finally:
    loop.close()

Example with start()

According to the docs, start() is

a blocking call that abstracts away the event loop initialisation from you.

This means that you need to place start() in an event loop.

from discord.ext import commands
import asyncio

client = commands.Bot(command_prefix = '!')

@client.event
async def on_ready():
    print("Ready")

loop = asyncio.get_event_loop()
loop.run_until_complete(client.start('TOKEN'))
Advertisement