Reputation: 31
I just want to make a Python Discord Bot like this:
# 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. I neither want to send a message on start nor in an intervall. Just by something like: bot.send_msg(channel, msg)
Upvotes: 2
Views: 17503
Reputation: 155
If you just want to send a message you need a object that implements the abc Messagable. Like (discord.Channel, discord.User, discord.Member)
then you can use the send method on them. Example:
async def send_msg(channel: discord.Channel, message):
await channel.send(message)
And just call the function from any other async function.
async def foo():
channel = bot.get_channel(channel_id)
await send_message(channel, "Hello World")
print("Done")
Upvotes: 1
Reputation: 127
If you are looking to send a message after a specific interval, you can use tasks
from discord.ext
.
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.
Reference:
discord.ext.tasks
Upvotes: 0
Reputation: 155
If you want your bot to send a message right after its ready. You can do this with to on_ready event.
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. https://discordpy.readthedocs.io/en/latest/index.html
Upvotes: 1