Python Discord Bot - 只需从 Python 脚本向频道发送消息

时间:2021-03-30 13:42:25

标签: python discord discord.py

我只想制作一个这样的 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)

3 个答案:

答案 0 :(得分:0)

如果您希望您的机器人在准备好后立即发送消息。你可以通过 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

答案 1 :(得分:0)

如果您希望在特定时间间隔后发送消息,您可以使用 tasks 中的 discord.ext

使用任务的示例:

import discord
from discord.ext import commands, tasks # Importing tasks here

@task.loop(seconds=300) # '300' is the time interval in seconds.
async def send_message():
    """Sends the message every 300 seconds (5 minutes) in a channel."""
    channel = client.get_channel(CHANNEL_ID)
    await channel.send("Message")

send_message.start()
client.run('MY TOKEN')

基本上这个函数每 300 秒运行一次。

参考:
discord.ext.tasks

答案 2 :(得分:0)

如果您只想发送消息,则需要一个实现 abc Messagable 的对象。 喜欢 (discord.Channel, discord.User, discord.Member)

然后你可以对它们使用send方法。 示例:

async def send_msg(channel: discord.Channel, message):
    await channel.send(message)

并且只需从任何其他异步函数调用该函数。

async def foo():
    channel = bot.get_channel(channel_id)
    await send_message(channel, "Hello World")
    print("Done")