Home > Mobile >  Bot Discord Python - Update channel name in a background loop
Bot Discord Python - Update channel name in a background loop

Time:04-03

I'm developping a little Discord Bot and I'm stuck on something.

To update a channe name, I need the bot context.

But on my background task, there is no context at all, so I can't figure it out how to achieve what I need. So the code above cannot work because of the line 23, where ctx doesn't exist

selectedVcChannel = discord.utils.get(ctx.guild.channels, name=VcChannelName)

I tried to make the ctx variable global, and tried to put the channel in a variable, but after changing the first time the name, the second time doesn't work anymore. That's why I'm trying to get it in all loops with discord.utils.get.

(VcChannelName is set in another function not showed here, don't worry about it).

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

selectedVcChannel = None
VcChannelName = None

bot = commands.Bot(command_prefix="!")

# Background task
async def background_task():
    await bot.wait_until_ready()

    while not bot.is_closed():
        await call_api()
        await asyncio.sleep(10)

# Call of the web page and update channel name
async def call_api():
    global selectedVcChannel
    global VcChannelName

    if VcChannelName:
        selectedVcChannel = discord.utils.get(ctx.guild.channels, name=VcChannelName)
        response = requests.get('https://MyAPI')
        respDecoded = response.content.decode("utf-8")
        VcChannelName = TranslationChannelName   respDecoded
        await selectedVcChannel.edit(name=VcChannelName)

# Start bot
bot.loop.create_task(background_task())
bot.run(TOKEN)

How can I use the context commands in the background loop easily ?

Thanks

CodePudding user response:

You could try this, to loop through the guilds your bot is a member of with bot.guilds and call discord.utils.get on each guild's channels. Altough using id instead of name would probably be better. You can keep the ids in a database maybe.

You can't get context in a background task because it is something exclusive to the bot commands.


if VcChannelName:
    for guild in bot.guilds:
        # if you want to find the channel by id
        # selectedVcChannel = discord.utils.get(guild.channels, id=voice_channel_id)
        selectedVcChannel = discord.utils.get(guild.channels, name=VcChannelName)
        # If you want the first channel found with the name of 'VcChannelName' 
        # you can add this condition with a break statement,
        # you obviously don't need this if you use id
        if selectedVcChannel:
           break

    if selectedVcChannel:
        response = requests.get('https://MyAPI')
        respDecoded = response.content.decode("utf-8")
        VcChannelName = TranslationChannelName   respDecoded
        await selectedVcChannel.edit(name=VcChannelName)
  • Related