[英]Unable to send a message to a discord channel discord.py
我希望使用这个简单的后台任务发送消息。 但是,我的 python shell 上没有出现任何错误,但没有发送消息。
import discord
import asyncio
client = discord.Client()
async def my_background_task():
await client.wait_until_ready()
counter = 0
channel = discord.Object(id='791003444726988850')
while not client.is_closed:
counter += 1
await client.send_message(channel, counter)
await asyncio.sleep(60) # task runs every 60 seconds
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
client.loop.create_task(my_background_task())
client.run('MY BOT TOKEN')
首先,在您的 while 循环条件中的is_closed
之后添加()
: while not client.is_closed():
否则,您的 while 循环将始终返回 object 而不是 bool,并且不会满足条件。
然后将: channel = discord.Object(id='791003444726988850')
更改为: channel = client.get_channel(791003444726988850)
最后将: await client.send_message(channel, counter)
更改为: await channel.send(counter)
完整代码:
import discord
import asyncio
client = discord.Client()
async def my_background_task():
await client.wait_until_ready()
counter = 0
channel = client.get_channel(791003444726988850)
while not client.is_closed():
counter += 1
await channel.send(counter)
await asyncio.sleep(60) # task runs every 60 seconds
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
client.loop.create_task(my_background_task())
client.run('MY BOT TOKEN')
我看到您正在使用与此类似的代码,您是否像在client.run('token')
中那样使用登录令牌来运行机器人?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.