-3
class MyClient(discord.Client):
    def __init__(self, *args, loop=None, **options):
        intents = discord.Intents.default()
        intents.members = True
        self.data = {}
        super().__init__(intents=intents, *args, loop=None, **options)

    async def on_ready(self):
        print('Logged on as {0}!'.format(self.user))
        for guild in self.guilds:
            members = []
            async for member in guild.fetch_members():
                members.append(member)
                if member.name == "Name":
                    await member.send("Hello :wave:")
            self.data[guild] = members
            print(self.data[guild])

    async def on_message(self, message):
        if message.author == self.user:
            return

        if message.content.startswith('$hello'):
            await message.author.send(":wave:")

    async def sendMessage(self, name, message):
        for guild in self.data:
            for member in self.data[guild]:
                if name == member.name:
                    print(member.name)
                    await member.send(message)

and in another file ie main.py or something,

client = MyClient()
client.run(TOKEN)

while True:
    sleep(5)
    client.sendMessage("Me", "Hello")

Ideal, I would use this to notify me once my other code is finished running or something similar to that nature. I've tried Threading as in this example https://stackoverflow.com/a/62894021/9092466, but I can't figure out how to make the code wait for the client to finish getting ready

1 Answers1

-1

using sleep is not recommended for async libraries like discord.py, you can use discord.py's tasks to run a loop

from discord.ext import tasks

class MyClient(discord.Client):
    def __init__(self, *args, loop=None, **options):
        intents = discord.Intents.default()
        intents.members = True
        self.data = {}
        super().__init__(intents=intents, *args, loop=None, **options)
        self.send_message.start()

    @tasks.loop(seconds= 5)
    async def send_message(self, name, message):
        for guild in self.data:
            for member in self.data[guild]:
                if name == member.name:
                    print(member.name)
                    await member.send(message)

    @send_message.before_loop
    async def before_sending(self): #waiting until the bot is ready
        print('waiting...')
        await self.bot.wait_until_ready()

References:

Łukasz Kwieciński
  • 13,310
  • 3
  • 17
  • 33
Ceres
  • 2,200
  • 1
  • 6
  • 22
  • so how would I call this? So let's say I'm training a model and I want discord to notify me when I'm finished. Would I do client.send_message(name, msg) – Jason Pham Feb 22 '21 at 17:27