skip to Main Content

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…?

2

Answers


  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

    Login or Signup to reply.
  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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search