'Running codes from a list once python
Here I have a code, but I want all of this code to run at same time without each waiting for other to finish before the other run.
from telegram import *
from telegram.ext import *
import telegram
IDs = [1111,2222,3333,4444]
def start(update,context) -> None:
while True:
for user in IDs:
context.bot.send_message(user,f"hello {user}")
Is there a way to send messages to all of these users at once without waiting for it to send to 1111, then 2222,3333 and 4444...?
Solution 1:[1]
With a huge caveat, yes. You can use asyncio if the calls to send_message
can not block the process. This offers concurrency and not parallelism. It would look something like this:
import asyncio
async def main():
await start(None, None)
async def send_message(user, msg):
"""Has to be non-blocking.
That is, there has to be a way to instruct the loop to come back and
check later. For instance, if this is an api that returns a task
handle, you can call `asyncio.sleep(1)` between every call to check
the task status. That way the thread can move back to the loop for 1
second at a time.
"""
print(f"{msg} {user}")
async def start(update, context) -> None:
await asyncio.gather(
*[
asyncio.create_task(send_message(user, "hello"))
for user in [1111, 2222, 3333, 4444]
]
)
if __name__ == "__main__":
asyncio.run(main())
But that may not work in your case at all, if the call to send_message
waits for a response before continuing.
Here is a good answer to multiprocessing vs multithreading vs asyncio in Python 3
Solution 2:[2]
PTB comes with a built-in tool to run I/O bound tasks in a thread pool - Dispatcher.run_async
. Note that this has nothing to do with asyncio
. Please see this wiki page for more details.
Note that the recently published pre-release v20.0a0 introduces asyncio
to PTB, so starting from v20.x, the answer given by @theherk will indeed by applicable.
Disclaimer: I'm currently the maintainer of python-telegram-bot
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | CallMeStag |