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)

如果你只想发送一条消息,你需要一个实现abcMessagable的对象。喜欢(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")

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

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

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

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

使用任务的示例:

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

最新更新