Python - Timing messages to be sent

I have made my bot working, but now I have to make sure that in a certain period of time, it can send a message to tell viewers something (like Nightbot.)

Here is the code:

I know that I have to use the sleep function, but I have no idea where to insert it.

Timers or threading. I don’t really know how either is done in python.

I have added the timed message, but it can’t receive messages during that time.
So, every message that is sent during the timer, is only received when the sendMessage() is been called.

Here’s extra code:
sendMessage(s, "Hope you are enjoying my stream!\r\n")

Should I put that before or after I get messages from the chat?

sleep tells the thread to wait and do nothing. In a single-thread program like yours, it means your program will do nothing at all. The waiting needs to happen in another thread, or you need to check between received messages if enough time has passed (but then you need to wait for a message for your repeats to fire)

As @3ventic said, sleep blocks the current thread, so every event you receive won’t get processed. This means that a PING will stay unanswered, and will result in you being disconnected. You would likely have to get into the threading module or the asyncio module.

As of writing this, I’m working on a Twitch IRC Library for python, based on asyncio. If you’re interested, you can find it here

Something else I just want to say: use snake_case for functions, as of PEP 8

~ martmists

You will have to learn how to use the threading module (or subprocess, although not preferred).

A hacky way to get out of learning threading would be to keep track of time in your script.

  1. Specify the rate of the timer, let’s say 10 seconds.
  2. Grab the initial time at the start of the script using the time module. (outside of any loop)
  3. Grab the current time inside the while loop.
  4. Test to see if (current_time - initial_time) is equal to or greater than the rate.
  5. If so, display the message and reset the initial time.

These are the Python 2.7.X docs for the modules I talked about:


This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.