F8te
F8te

Reputation: 129

Any other code doesn't run after I combined discord.py with my main script

I made a script that includes web scraping and api requests but I wanted to add discord.py for sending the results to my discord server but it stops after this:

client.run('token')

Is there any way to fix this?

Upvotes: 1

Views: 408

Answers (3)

Billy
Billy

Reputation: 1207

You need to use threads.

Python threading allows you to have different parts of your program run concurrently and can simplify your design.

What Is a Thread?

A thread is a separate flow of execution. This means that your program will have two things happening at once.

Getting multiple tasks running simultaneously requires a non-standard implementation of Python, writing some of your code in a different language, or using multiprocessing which comes with some extra overhead.

Starting a thread

The Python standard library provides threading

import threading
x = threading.Thread(target=thread_function, args=(1,))
x.start()

wrapping up

you need to create two threads for each loop. Create and run the discord client in a thread, use another thread for web scraping and API requests.

Upvotes: 3

Icebreaker454
Icebreaker454

Reputation: 1071

client.run seems to be a blocking operation. E.g. your code is not meant to be executed after client.run

You can try using loop.create_task() as described here, to create another coroutine that would run in background and feed some messages into your client.

Upvotes: 2

Masklinn
Masklinn

Reputation: 42342

The run method is completely blocking, so there are two ways I can see to solve this issue:

  1. create and run the client in a separate thread, and use a queue of some sort to communicate between the client and the rest
  2. use the start method, that returns an async coroutine which you can wrap into a task and multiplex with your scraping and API-requesting, assuming that also uses async coroutines

Upvotes: 2

Related Questions