首页 > 解决方案 > Python Discord Bot - 只需从 Python 脚本向频道发送消息

问题描述

我只想制作一个这样的 Python Discord Bot:

# Bot
class DiscordBot:
    def __init__(self, TOKEN: str):
    # create / run bot

    def send_msg(self, channel_id: int, message: str):
    # send message to the channel


# Some other Script
my_notifier = DiscordBot("TOKEN")
my_notifier.send_msg(12345, "Hello!")

这有可能吗?我不想等待任何用户消息或东西发送消息。

更新:我真的只想让机器人在我从 python 文件中的不同点调用它时发送消息。我既不想在开始时也不想在间隔中发送消息。就像这样: bot.send_msg(channel, msg)

标签: pythondiscorddiscord.py

解决方案


如果您希望您的机器人在准备好后立即发送消息。您可以使用 to on_ready 事件执行此操作。

client = discord.Client()

@client.event
async def on_ready():  #  Called when internal cache is loaded

    channel = client.get_channel(channel_id) #  Gets channel from internal cache
    await channel.send("hello world") #  Sends message to channel


client.run("your_token_here")  # Starts up the bot

您可以查看 discord.py 中的文档以获取更多信息。 https://discordpy.readthedocs.io/en/latest/index.html


推荐阅读