Home > Software design >  Cannot assign to global variable in on_ready()
Cannot assign to global variable in on_ready()

Time:01-26

I am trying to code a discord bot that simultaneously prints new messages and sends user input from console to a selected channel. Here is what I have so far:

import discord
from threading import Thread
from asyncio import run

intents = discord.Intents.all()
intents.members = True
client = discord.Client(intents=intents,chunk_guilds_at_startup=False)

main_channel = int(input('Enter channel ID you want to chat in: '))

channel = 613

@client.event
async def on_ready():
  global channel
  channel = await client.fetch_channel(main_channel)

async def send():
  while True:
    await channel.send(input('Send a message: '))
  
z = Thread(target=lambda:run(send()))
z.start()

try:
  client.run('##########################')
except discord.errors.HTTPException:
  from os import system
  system('kill 1')

I get TypeError: 'int' object has no attribute 'send' on line 42. Why is the global variable not getting assigned to in on_ready()?

CodePudding user response:

You need to wait for on_ready() to be called before starting the thread. You can start the thread from the function.

@client.event
async def on_ready():
  global channel
  channel = await client.fetch_channel(main_channel)
  Thread(target=lambda:run(send())).start()
  • Related