Search code examples
pythonpygamediscord.pypython-multithreading

Why does Python Threading run a function when I don't tell it to?


I am trying to make my code take messages from discord using discord api and putting it on a black screen with said message in the center using pygame. I am trying to run both functions using the threading api and declare p1 and p2 in the main_process() function. Even though I only tell it to run p2, it still runs only p1. Why does it do this? Am I missing something?

My code

import discord
import pygame
from threading import Thread

client = discord.Client()
new_message = "Potato"

color = (255, 255, 255)


def main_process():
    p1 = Thread(target=main_window())
    p2 = Thread(target=get_message())
    p2.start()


def main_window():
    print("start function 1")
    pygame.init()
    pygame.font.init()

    font = pygame.font.SysFont(None, 45)
    info = pygame.display.Info()
    screen = pygame.display.set_mode((info.current_w, info.current_h), pygame.FULLSCREEN)
    screen_rect = screen.get_rect()
    clock = pygame.time.Clock()

    last_message = new_message
    txt = font.render(new_message, True, color)

    done = False
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    done = True

        if new_message != last_message:
            last_message = new_message
            txt = font.render(new_message, True, color)

        screen.fill((30, 30, 30))
        screen.blit(txt, txt.get_rect(center=screen_rect.center))

        pygame.display.flip()
        clock.tick(30)


def get_message():
    print("start function 2")

    @client.event
    async def on_ready():
        print('We have logged in as {0.user}'.format(client))

    @client.event
    async def on_message(message):
        if message.author == client.user or message.author.id == "MY_USER_ID":
            return
        if message.channel.id == MY_MESSAGE_CHANNEL_ID:
            if message.content != " ":
                global new_message
                new_message = message.content

    client.run("MY_ACCESS_TOKIN")


if __name__ == '__main__':
    main_process()

I am also a newbie to Python so any changes and suggestions are welcome! Thanks so much!


Solution

  • I would very much suggest using asyncio. That's what 90% of people use to make discord bots, including me, and it has worked.

    If you really do want to do it this way then get rid of the parenthases in p1 = Thread(target=main_window())

    That line would become p1 = Thread(target=main_window).

    Hope that helps. Usually you gotta remove parenthases when doin somethin like that. I might be wrong tho.