简体   繁体   English

无法向 discord 通道 discord.py 发送消息

[英]Unable to send a message to a discord channel discord.py

I wish to send a message using this simple background task.我希望使用这个简单的后台任务发送消息。 However, no errors come through on my python shell, but the message doesn't send.但是,我的 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')

First, add () after is_closed in your while loop condition: while not client.is_closed(): otherwise, your while loop will always return an object rather than a bool and the condition will not be met.首先,在您的 while 循环条件中的is_closed之后添加()while not client.is_closed():否则,您的 while 循环将始终返回 object 而不是 bool,并且不会满足条件。

Then Change: channel = discord.Object(id='791003444726988850') to: channel = client.get_channel(791003444726988850)然后将: channel = discord.Object(id='791003444726988850')更改为: channel = client.get_channel(791003444726988850)

lastly change: await client.send_message(channel, counter) to: await channel.send(counter)最后将: await client.send_message(channel, counter)更改为: await channel.send(counter)

Full code:完整代码:

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

I see you're using code similar to this , are you using a login token to run the bot as in client.run('token') ?我看到您正在使用与此类似的代码,您是否像在client.run('token')中那样使用登录令牌来运行机器人?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM