【问题标题】:Unable to send a message to Discord using discord.py无法使用 discord.py 向 Discord 发送消息
【发布时间】:2022-01-15 09:14:38
【问题描述】:

我试图简单地创建一个函数,在机器人运行时向特定频道发送不和谐消息。我想稍后在一个单独的 python 脚本中调用这个函数。 下面的代码似乎运行良好,并且机器人出现在线 - 但它无法发送消息:

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

我确定我错过了一些基本的东西,但我无法弄清楚它是什么。我在 Node.js 中尝试了一个类似的函数,它工作正常,但是我更希望机器人在 python 中工作。 Discord.py 是最新的,python 是 v3.10。 任何帮助将不胜感激。

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    Client.run 是一个阻塞调用,这意味着在你调用它之后注册的事件实际上不会被注册。注册活动后尝试拨打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
    

    您也可能不想手动调用事件处理程序。如果您想通过调用函数来发送消息,您可能需要考虑为事件处理程序编写一个单独的函数。

    【讨论】:

      猜你喜欢
      • 2020-09-23
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 2021-06-14
      • 2021-03-02
      • 2020-03-20
      • 2021-05-29
      相关资源
      最近更新 更多