Search code examples
pythonwebhookspython-multithreading

Variable passed to multiple threads of the same function


I am currently working on a system that sends webhooks to multiple Discord using dhooks.

This is the function used to call the function which sends the webhooks. The length of webhooks is 2 and it's a list of lists.

for hook in webhooks:
    thread.start_new_thread(send_hook,(hook, embed, tag))

This is the send_hook function:

def send_hook(hook, embed, tag):

    embed.set_footer(text="{} x Will".format(hook[0])) <-- This is the part where the error happens

    webhook = Webhook(hook[1])
    webhook.send(embed=embed)

The error I am getting is, when I set the footer in line 2 of send_hook, the variable inserted into the embed variable is sometimes sent to the wrong webhooks - almost as if its being over ridden.

As an example:

This is my list webhooks: [["Webhook 1 text", "discordwebhook1"], ["Webhook 2 text", "discordwebhook1"]].

What will happen is that in the channel of discordwebhook1 the footer will say "Webhook 1 text", but in the channel of discordwebhoo2 the footer will say "Webhook 1 text" as-well.

I have tried creating a new variable of the embed in the send_hook function - however this also didn't work (code below).

def send_hook(hook, embed, tag):
    new_embed = embed
    new_embed.set_footer(text="{} x Will".format(hook[0])) <-- This is the part where the error happens

    webhook = Webhook(hook[1])
    webhook.send(embed=new_embed)

I appreciate all help!

Thanks


Solution

  • How do you get 'embed'? Notice that 'embed' and 'tag' are always passed to every newly created thread, you need to do a deepcopy of each if necessary

    from copy import deepcopy
    
    for hook in webhooks:
        thread.start_new_thread(send_hook,(hook, deepcopy(embed), tag))