Dar*_*kes 6 python discord discord.py
我想写一条机器人消息来不和谐而无需命令。但是当我运行代码时遇到了问题。错误提示:“NoneType”对象没有属性“send”
回溯(最近一次调用最后一次):文件“D:/Development/Code Python/Bot Discord/discord-testbot.py”,第18行,在my_background_task等待channel.send(channel,'New')
AttributeError:'NoneType'对象没有属性“发送”
import discord
client = discord.Client()
@client.event
async def on_ready():
print('Bot is ready')
async def my_background_task():
await client.wait_until_ready()
await channel.send(channel, 'Bot say')
client.loop.create_task(my_background_task())
client.run(tokenBot)
Run Code Online (Sandbox Code Playgroud)
如果我删除 line channel = client.get_channel(574514361394266125),则会引发另一个错误,指出名称“channel”未定义。
小智 7
这个对我有用。看来你是client.get_channel(id)在你之前打电话的client.wait_until_ready()(你已经发送了编辑后的代码,所以我不能保证)。
这段代码对我来说效果很好:
async def background():
await client.wait_until_ready()
channel = client.get_channel(int(MY_CHANNEL))
await channel.send("Test")
client.loop.create_task(background())
Run Code Online (Sandbox Code Playgroud)
自discord.py v1.1起,您可以更轻松、更安全地声明和管理后台任务。
这就是我们在 cog 中的做法:
import discord
from discord.ext import tasks, commands
class OnReady_Message(commands.Cog):
def __init__(self, client):
self.client = client
self.send_onready_message.start()
def cog_unload(self):
self.send_onready_message.close()
return
# task
@tasks.loop(count = 1) # do it only one time
async def send_onready_message(self):
channel = self.client.get_channel(int(MY_CHANNEL))
await channel.send("Test")
@send_onready_message.before_loop # wait for the client before starting the task
async def before_send(self):
await self.client.wait_until_ready()
return
@send_onready_message.after_loop # destroy the task once it's done
async def after_send(self):
self.send_onready_message.close()
return
Run Code Online (Sandbox Code Playgroud)
最后,为了运行任务,send_onready_message()我们可以创建一个Task_runner()对象或简单地在任务实例中创建。
这将使您轻松运行所有任务:
# importing the tasks
from cogs.tasks.on_ready_task import OnReady_Message
class Task_runner:
def __init__(self, client)
self.client = client
def run_tasks(self):
OnReady_Message(self.client)
return
Run Code Online (Sandbox Code Playgroud)
在你的主文件中:
import discord
from discord.ext import commands
from cogs.tasks.task_runner import Task_runner
client = commands.Bot(command_prefix = PREFIX)
runner = Task_runner(client)
runner.run_tasks()
client.run(token)
Run Code Online (Sandbox Code Playgroud)
没有Task_runner()我们有:
import discord
from discord.ext import commands
from cogs.tasks.on_ready_task import OnReady_Message
client = commands.Bot(command_prefix = PREFIX)
OnReady_Message(client)
client.run(TOKEN)
Run Code Online (Sandbox Code Playgroud)
仅当您的discord.py版本是最新时,上面的示例才有效。
要知道是否是这样,您可以在终端中运行:
>>> import discord
>>> discord.__version__
'1.2.3'
Run Code Online (Sandbox Code Playgroud)
如果您的版本较旧,您可以在终端中使用以下命令进行更新:
pip install discord.py --upgrade
Run Code Online (Sandbox Code Playgroud)
希望有帮助!