Search code examples
pythondiscord

Python - stops job on discord


The plan for this bot is to wake up --> retrieve data I need --> terminate itself.

I've tried using client.logout() and client.close(), but the program won't stop after it runs. Any advice?

import discord
import os
from discord.ext import tasks
from discord.ext import commands


discord_client = discord.Client()

@discord_client.event
async def on_ready():
    for guild in discord_client.guilds:
        if guild.name == GUILD:
            break

    print(
        f'{discord_client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )

    # Send message when Bot wakes up
    channel = discord_client.get_channel(ID)
    await channel.send("*wakes up and starts working*")
    retrieve_data.start()

    await discord_client.logout()


@tasks.loop(count=1)
async def retrieve_data():
    # do things here
    

discord_client.run(TOKEN)

Solution

  • You don't have your token defined, import load_dotenv and call it, you have undefined variables, also logout() is deprecated so use close() instead and it works.

    import discord
    import os
    from discord.ext import tasks
    from dotenv import load_dotenv
    from discord.ext import commands
    
    
    load_dotenv()
    
    discord_client = discord.Client()
    
    
    @discord_client.event
    async def on_ready():
        # for guild in discord_client.guilds:
        #     if guild.name == GUILD:
        #         break
    
        # print(
        #     f'{discord_client.user} is connected to the following guild:\n'
        #     f'{guild.name}(id: {guild.id})'
        # )
    
        # Send message when Bot wakes up
        # channel = discord_client.get_channel(ID)
        # await channel.send("*wakes up and starts working*")
        await retrieve_data.start()
    
        await discord_client.close()
    
    
    @tasks.loop(count=1)
    async def retrieve_data():
        print("test")
    
    
    discord_client.run(os.getenv("TOKEN"))