简体   繁体   English

无法使用 discord.py 向 Discord 发送消息

[英]Unable to send a message to Discord using discord.py

I'm trying to simply create a function that sends a discord message to a specific channel when the bot runs.我试图简单地创建一个 function 在机器人运行时将 discord 消息发送到特定通道。 I want to later call this function in a separate python script.我想稍后在单独的 python 脚本中调用这个 function。 The code below seems to run fine, and the bot appears online - but it is fails to send the message:下面的代码似乎运行良好,并且机器人出现在线 - 但它无法发送消息:

import discord

client = discord.Client()
client.run("ABCDeFGHIjklMNOP.QrSTuV-HIjklMNOP") # the token

@client.event
async def on_ready():
    logs_channel = client.get_channel(12345689123456789) # the channel ID
    await logs_channel.send("Bot is up and running")
on_ready()

I'm sure I'm missing something basic but I cannot figure out what it is.我确定我缺少一些基本的东西,但我无法弄清楚它是什么。 I've tried a similar function in Node.js and it works fine however, I would prefer the bot to work in python.我在 Node.js 中尝试了类似的 function 并且它工作正常,但是,我希望机器人在 python 中工作。 Discord.py is up to date, python is v3.10. Discord.py 是最新版本,python 是 v3.10。 Any help would be greatly appreciated.任何帮助将不胜感激。

Client.run is a blocking call, meaning that events registered after you call it won't actually be registered. Client.run是一个阻塞调用,这意味着在您调用它之后注册的事件实际上不会被注册。 Try calling Client.run after you register the event, as in:注册事件后尝试调用Client.run ,如下所示:

import discord

client = discord.Client()

@client.event
async def on_ready():
    logs_channel = client.get_channel(12345689123456789) # the channel ID
    await logs_channel.send("Bot is up and running")

client.run("ABCDeFGHIjklMNOP.QrSTuV-HIjklMNOP") # the token

You also probably do not want to be manually calling an event handler.您也可能不想手动调用事件处理程序。 If you want to send a message by calling a function, you probably want to consider writing a separate function to the event handler.如果您想通过调用 function 来发送消息,您可能需要考虑将单独的 function 写入事件处理程序。

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

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