python-3.x 无法为on_ready()中的全局变量赋值

ewm0tg9j  于 2023-02-01  发布在  Python
关注(0)|答案(1)|浏览(140)

我正在尝试编写一个discord机器人,它可以同时打印新消息并将用户输入从控制台发送到选定的通道。以下是我目前所做的工作:

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')

我在第42行得到了TypeError: 'int' object has no attribute 'send',为什么在on_ready()中没有给全局变量赋值?

w7t8yxp5

w7t8yxp51#

在启动线程之前,需要等待on_ready()被调用。可以从函数启动线程。

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

相关问题