I need assistance with properly scheduling my Python Telegram bot.
I have developed a bot using the python-telegram-bot library which is intended to operate from Monday to Thursday, specifically from 10 AM until 4:15 PM. On Fridays, it should be entirely inactive. Currently, the bot fails to halt at 4:15 PM as intended.
Here is the code that handles the scheduling:
import schedule
import time
from datetime import datetime
import pytz
from telegram.ext import Application, CommandHandler
# Bot configuration
TOKEN = 'your_bot_token'
source_chat = '@PriceUpdates'
dest_chat = '@MyChannel'
# Tehran timezone
tehran_tz = pytz.timezone('Asia/Tehran')
# Bot status
bot_active = False
def get_local_time():
return datetime.now(tehran_tz)
def start_bot_operations():
global bot_active
bot_active = True
print("Bot started working")
def stop_bot_operations():
global bot_active
bot_active = False
print("Bot stopped working")
async def check_working_hours():
while True:
current = get_local_time()
weekday = current.weekday() # 0=Monday, 4=Friday
hour = current.hour
minute = current.minute
# Check if it's Friday (weekday 4)
if weekday == 4:
if bot_active:
stop_bot_operations()
# Check working hours Monday-Thursday
elif weekday < 4:
if 10 <= hour < 16 or (hour == 16 and minute < 15):
if not bot_active:
start_bot_operations()
else:
if bot_active:
stop_bot_operations()
await asyncio.sleep(30) # Check every 30 seconds
async def message_handler(update, context):
if not bot_active:
return
# Process messages only when bot is active
message_text = update.message.text
processed_msg = f"Updated: {message_text}"
await context.bot.send_message(chat_id=dest_chat, text=processed_msg)
def main():
app = Application.builder().token(TOKEN).build()
app.add_handler(CommandHandler("start", message_handler))
# Start the scheduler
asyncio.create_task(check_working_hours())
app.run_polling()
if __name__ == '__main__':
main()
The issue I’m facing is that my bot continues to run past the 4:15 PM mark. Could someone please help identify any flaws within my time checking logic? I would appreciate any assistance!