我正在尝试创建一个 Discord 机器人,它会在没有任何用户交互/命令输入的情况下每 X 秒(例如每 3 秒)自动发送一条消息。
这是我拥有的代码:
import discord
from discord.ext import tasks, commands
bot = commands.Bot(command_prefix="!")
@bot.event
async def on_ready():
await bot.wait_until_ready()
print("Logged in as:")
print(bot.user.name)
print("------")
channel = bot.get_channel(IDasInteger)
print("Channel is:")
print(channel) #Prints None
get_price.start()
@tasks.loop(seconds=3)
async def get_price():
await bot.wait_until_ready()
channel = bot.get_channel(IDasInteger)
print("Channel is:")
print(channel) #Prints None
await channel.send('Test')
@get_price.before_loop
async def before ():
print("Before done.")
bot.run('MyTokenHere')
问题是,当我执行这段代码时,它给了我以下错误:
AttributeError: 'NoneType' object has no attribute 'send'
当我尝试打印通道变量时,它返回 None。 频道 ID 是正确的 - 我直接从 Discord 应用程序复制了它,没有对其值进行任何更改。
有什么想法吗?
谢谢
答案 0 :(得分:0)
您得到 None
的原因是 IDasInteger
未定义(至少在您提供的代码中。如果它在您的代码中定义,则它找不到频道并返回 {{1 }}。None
没有属性 send 并引发错误。
将频道 ID 更改为服务器中有效频道的 ID。
None
或者确保 functions channel = bot.get_channel(790279425633758682)
返回有效的频道 ID
注意:我使用有效的通道 ID 测试了我的服务器的代码,并且它按预期工作。