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?