0

I am using a discord selfbot wrapper library: https://github.com/Merubokkusu/Discord-S.C.U.M

This is the structure of my code:

import discum   
import multiprocessing  
import time

print("This message is repeated when a new process is started")
# Do something to read my user token from a file here
user_token = "MY TOKEN HERE"

bot = discum.Client(token=user_token, log= False)

def spam():
    while True:
        bot.sendMessage(channel_id, "test")
        time.sleep(2)

def start_process():
    new_process = multiprocessing.Process(target=spam)
    new_process.start()
    return new_process

def stop_process(process_to_stop):
    process_to_stop.terminate()

@bot.gateway.command
def on_ready(resp):
    if resp.event.ready_supplemental:
        user = bot.gateway.session.user
        print("LOGGED INTO ACCOUNT: {}#{}".format(user['username'], user['discriminator']))

@bot.gateway.command
def on_message(resp):
    global process

    if resp.event.message:
        m = resp.parsed.auto()

        if m["content"] == "start":
            process = start_process()
        elif m["content"] == "stop":
            stop_process(process)


if __name__ == "__main__":
    bot.gateway.run(auto_reconnect=True)

I've noticed that all code outside the if __name__ == "__main__" statement (i.e all the code right before the function definitions) gets rerun everytime a new process is created (Noticed at the line 4 print message) due to the way multiprocessing works. (https://stackoverflow.com/a/45595064/15088347)

My issue is that I need to do something in my code to read the user token from a file to initialize the bot = discum.Client(token=user_token, log= False) variable, but it I can't move the bot initialization into the if __name__ == "__main__" statement or else the wrapper functions @bot.gateway.command and function inside the spam process bot.sendMessage(channel_id,"test")will not be declared.

How would I prevent the code outside the if __name__ == "__main__" block from being executed when a new process is started?

bone
  • 1
  • child processes don't necessarily inherit file handles anyway (open ports etc..) when using spawn, so it's not recommended to try to have a client (the bot) exist in multiple processes. Unless you're truly cpu limited, I'd go for threading here instead... You may also be able to get around this using "fork" on a non-windows system (it's almost trivial these days to run ubuntu next to windows with wsl2) – Aaron Jun 24 '21 at 20:21
  • I was only using multiprocessing over threading because I could dynamically start and terminate the processes depending on conditions received by the client. From what I've seen, you can't simply just kill a thread the same way you can terminate a subprocess. Is there a better way apply this logic with threads? – bone Jun 24 '21 at 21:34

0 Answers0