[英]Python Discord Bot - Simply send a message to a channel from a Python Script
I just want to make a Python Discord Bot like this:我只想制作一个 Python Discord 机器人,如下所示:
# 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!")
Is this somehow posssible?这有可能吗? I don't want to wait for any user messages or stuff to send a message.
我不想等待任何用户消息或东西发送消息。
UPDATE: I really only want to make the bot send message whenever I call it from a different point in my python files.更新:我真的只想让机器人在我从 python 文件中的不同点调用它时发送消息。 I neither want to send a message on start nor in an intervall.
我既不想在开始时也不想在间隔中发送消息。 Just by something like:
bot.send_msg(channel, msg)
就像这样:
bot.send_msg(channel, msg)
If you want your bot to send a message right after its ready.如果您希望您的机器人在准备好后立即发送消息。 You can do this with to on_ready event.
您可以使用 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
You may look into the docs from discord.py for more information.您可以查看 discord.py 的文档以获取更多信息。 https://discordpy.readthedocs.io/en/latest/index.html
https://discordpy.readthedocs.io/en/latest/index.html
If you are looking to send a message after a specific interval, you can use tasks
from discord.ext
.如果您希望在特定时间间隔后发送消息,则可以使用
discord.ext
中的tasks
。
An example of using 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')
Basically this function runs every 300 seconds.基本上这个 function 每 300 秒运行一次。
Reference:参考:
discord.ext.tasks discord.ext.tasks
If you just want to send a message you need a object that implements the abc Messagable.如果您只想发送消息,则需要一个实现 abc Messagable 的 object。 Like (discord.Channel, discord.User, discord.Member)
喜欢(discord.Channel、discord.User、discord.Member)
then you can use the send method on them.然后您可以对它们使用 send 方法。 Example:
例子:
async def send_msg(channel: discord.Channel, message):
await channel.send(message)
And just call the function from any other async function.只需从任何其他异步 function 调用 function。
async def foo():
channel = bot.get_channel(channel_id)
await send_message(channel, "Hello World")
print("Done")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.