Python Forum
How to make my Telegram bot stop working at 16:15 and not work on Fridays?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to make my Telegram bot stop working at 16:15 and not work on Fridays?
#1
I have a Telegram bot written in Python using the Telethon library. The bot is supposed to function from 10:00 to 16:15 from Saturday to Thursday, and it should be completely inactive on Fridays. However, I'm having trouble getting the bot to stop exactly at 16:15. The bot currently doesn't stop correctly at the specified time.

import logging
import re
import random
import jdatetime
from telethon import TelegramClient, events
from datetime import datetime, timedelta
import asyncio
import pytz

# اطلاعات API

group_usernames = ['@gheymateTehran2', '@DOLARRATE1', '@gheymateTehran']  # نام‌های کاربری سه گروه

# اطلاعات کانال جدید
new_channel_id = 'https://t.me/Akhbargeymat'
target_channel_id = '@DolarRates'

# تنظیمات لاگینگ
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# تنظیمات پراکسی (در صورت نیاز)
proxy = None  # ('socks5', '127.0.0.1', 9050)  # نمونه برای پراکسی SOCKS5

# ایجاد کلاینت تلگرام با تنظیمات پراکسی
client = TelegramClient('session_name', api_id, api_hash, proxy=proxy)

# قفل برای مدیریت ارسال پیام
send_lock = asyncio.Lock()

# متغیر زمان آخرین ارسال پیام
last_sent_time = datetime(1970, 1, 1, tzinfo=pytz.UTC)

# متغیر سراسری برای ذخیره عدد جدید دلار
global_new_number_str = "نامشخص"  # مقدار اولیه

# متغیر وضعیت کارکرد بات
is_running = False

# تابع محاسبه ساعت به وقت تهران
def tehran_time():
    tehran_tz = pytz.timezone('Asia/Tehran')
    return datetime.now(tehran_tz)

async def send_message_to_channel(message):
    try:
        logger.info(f"Sending message to channel: {message}")
        await client.send_message(channel_id, message)
    except Exception as e:
        logger.error(f"Failed to send message: {e}")

def get_persian_date():
    today = jdatetime.date.today()
    return today.strftime('%Y/%m/%d')

async def process_message_text(text):
    global last_sent_time, global_new_number_str
    current_time = tehran_time()

    async with send_lock:
        if (current_time - last_sent_time).total_seconds() < 60:
            logger.info("Skipping message send due to time limit.")
            return None

        # پیدا کردن اولین عدد 5 رقمی در متن
        match = re.search(r'\b\d{2},\d{3}\b', text)
        if match:
            # استخراج عدد
            original_number = match.group()
            # حذف کاما و تبدیل به عدد صحیح
            number = int(original_number.replace(',', ''))
            # کاهش عدد به مقدار 50
            new_number = number - 50
            # تبدیل عدد جدید به رشته با فرمت مناسب
            new_number_str = f'{new_number:,}'
            
            # ذخیره عدد جدید در متغیر سراسری
            global_new_number_str = new_number_str
            
            # ایجاد پیام خروجی
            processed_text = f"""
    ✨ #نرخ_دلار

    📆 تاریخ: {get_persian_date()}

    💸 #دلار سبزه : {new_number_str} تومان

    🌟 بروزترین قیمت‌ها رو همین حالا مشاهده کنید.

    📲 کانال قیمت #دلار تهران 👇
    🆔@DolarRates
            """
            last_sent_time = current_time
            return processed_text.strip()
        else:
            logger.error("No 5-digit number found in the text.")
            return None

# تابع پردازش پیام‌های کانال جدید
def process_new_channel_message(text):
    # حذف موارد ناخواسته
    text = re.sub(r'🔸دلار آمريکا.*?\n', '', text)
    text = re.sub(r'⏰ساعت.*?\n', '', text)
    text = re.sub(r'✅ @Akhbargeymat', '', text)
    text = re.sub(r'✅ .*?\n', '', text)
    text = text.replace('🔸', '')
    text = text.replace('✅', '')  # حذف علامت ✅
    text = text.replace('****', '')  # حذف ****

    # جایگزینی پرچم‌ها
    text = text.replace('يورو', '🇪🇺 يورو')
    text = text.replace('پوند انگليس', '🇬🇧 پوند انگليس')
    text = text.replace('درهم امارات', '🇦🇪 درهم امارات')
    text = text.replace('يوآن چين', '🇨🇳 يوآن چين')
    text = text.replace('لير ترکيه', '🇹🇷 لير ترکيه')
    text = text.replace('دینار کویت', '🇰🇼 دینار کویت')
    
    text = text.replace('🔹', '🟡')
    text = text.replace('@Akhbargeymat', '')

    # راست‌چین کردن
    lines = text.split('\n')
    aligned_text = '\n'.join(line.strip() for line in lines if line.strip())
    
    # اضافه کردن متن جدید
    additional_text = """
🌟 بروزترین قیمت‌ها رو همین حالا مشاهده کنید.

📲 کانال قیمت #دلار تهران 👇
🆔@DolarRates
    """
    return aligned_text.strip() + '\n\n' + additional_text.strip()

# تابع خواندن آخرین پیام‌ها از گروه‌ها و ارسال جدیدترین پیام هر یک دقیقه
async def read_latest_posts():
    while is_running:
        for group_username in group_usernames:
            try:
                logger.info(f"Reading latest post from {group_username}")
                messages = await client.get_messages(group_username, limit=1)
                if messages:
                    latest_message = messages[0]
                    processed_text = await process_message_text(latest_message.text)
                    if processed_text:
                        logger.info(f"Latest post fetched from {group_username}: {processed_text}")
                        await send_message_to_channel(processed_text)
            except Exception as e:
                logger.error(f"Failed to read latest post from {group_username}: {e}")
        await asyncio.sleep(60)  # انتظار یک دقیقه

# تابع خواندن و ارسال پیام از کانال جدید هر 40 دقیقه بدون محدودیت زمانی
async def read_and_forward_from_new_channel():
    while is_running:
        try:
            logger.info(f"Reading latest post from {new_channel_id}")
            messages = await client.get_messages(new_channel_id, limit=1)
            if messages:
                latest_message = messages[0]
                processed_text = process_new_channel_message(latest_message.text)
                if processed_text:
                    logger.info(f"Latest post fetched from {new_channel_id}: {processed_text}")
                    await send_message_to_channel(processed_text)
                    await asyncio.sleep(2400)  # انتظار 40 دقیقه
        except Exception as e:
            logger.error(f"Failed to read and forward from new channel: {e}")

# هندلر برای پیام‌های جدید
@client.on(events.NewMessage(chats=group_usernames))
async def handler(event):
    if is_running:
        try:
            processed_text = await process_message_text(event.message.text)
            if processed_text:
                logger.info(f"New message received from {event.chat.username}: {processed_text}")
                await send_message_to_channel(processed_text)
        except Exception as e:
            logger.error(f"Failed to handle new message from {event.chat.username}: {e}")

# ارسال پیام‌های خوش‌آمدگویی و خداحافظی
async def send_greeting_messages():
    while is_running:
        now = tehran_time()
        if now.hour == 10 and now.minute == 0:
            await send_message_to_channel("به نام خدا")
        elif now.hour == 19 and now.minute == 0:
            await send_message_to_channel("به امید دیدار")
        await asyncio.sleep(60)  # بررسی هر دقیقه

# ارسال پیام‌های خودکار هر 5 تا 8 دقیقه
async def automated_posting():
    while is_running:
        tehran_current_time = tehran_time().strftime('%H:%M:%S')
        special_message = f"""
✨ #نرخ_دلار

📆 تاریخ: {get_persian_date()}

مـعامله انجام شد✅

💸 #دلار سبزه : {global_new_number_str} تومان

🌟 بروزترین قیمت‌ها رو همین حالا مشاهده کنید.

📲 کانال قیمت #دلار تهران 👇
🆔@DolarRates
        """
        await send_message_to_channel(special_message.strip())
        await asyncio.sleep(random.randint(300, 480))  # انتظار بین 5 الی 8 دقیقه

# تابع متوقف کردن فعالیت ربات
async def shutdown_bot():
    global is_running
    is_running = False
    logger.info("Bot activities have been stopped.")

async def main():
    global is_running
    logger.info("Starting client...")
    try:
        await client.start(phone_number)
    except Exception as e:
        logger.error(f"Failed to start client: {e}")
    else:
        logger.info("Client started.")
        while True:
            now = tehran_time()

            # Check for exact time to stop
            if now.hour == 17 and now.minute == 15:
                if is_running:
                    await shutdown_bot()
                    logger.info("Bot has been stopped exactly at 17:15.")

            # Check for weekdays and time range to start
            if now.weekday() != 4 and (10 <= now.hour < 16 or (now.hour == 16 and now.minute < 15)):
                if not is_running:
                    is_running = True
                    logger.info("Bot is starting its activities.")
                    await asyncio.gather(
                        send_greeting_messages(), 
                        automated_posting(),
                        read_and_forward_from_new_channel(),
                        read_latest_posts()
                    )

            # More precise time check every second
            await asyncio.sleep(1)

if __name__ == "__main__":
    logger.info("Running main...")
    client.loop.run_until_complete(main())
    client.run_until_disconnected()
I have tried to make the bot work from 10:00 to 16:15 from Saturday to Thursday and stop exactly at 16:15. However, it doesn't stop as expected. Could anyone help me identify what I'm doing wrong?

Thank you in advance for your help!
Larz60+ write Aug-07-2024, 05:32 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Tgas added fir you this time, please use BBCode tags on future posts.
Reply
#2
You can stop it like this:

            # Check if it's Friday (weekday 4)
            if now.weekday() == 4:
                if is_running:
                    await shutdown_bot()
                    logger.info("Bot has been stopped for Friday.")
                await asyncio.sleep(60)  # Check again after 1 minute
                continue

            # Stop the bot at 16:15 and ensure it remains stopped until 10:00 next day
            if (now.hour == 16 and now.minute >= 15) or (now.hour < 10):
                if is_running:
                    await shutdown_bot()
                    logger.info("Bot has been stopped for the day.")
                # Wait until it's past 10:00 the next day
                if now.hour < 10:
                    await asyncio.sleep(60)  # Check again after 1 minute
                    continue
Reply
#3
(Aug-09-2024, 07:54 AM)wewer Wrote: You can stop it like this:

            # Check if it's Friday (weekday 4)
            if now.weekday() == 4:
                if is_running:
                    await shutdown_bot()
                    logger.info("Bot has been stopped for Friday.")
                await asyncio.sleep(60)  # Check again after 1 minute
                continue

            # Stop the bot at 16:15 and ensure it remains stopped until 10:00 next day
            if (now.hour == 16 and now.minute >= 15) or (now.hour < 10):
                if is_running:
                    await shutdown_bot()
                    logger.info("Bot has been stopped for the day.")
                # Wait until it's past 10:00 the next day
                if now.hour < 10:
                    await asyncio.sleep(60)  # Check again after 1 minute
                    continue

Not working bro :(


import logging
import re
import random
import jdatetime
from telethon import TelegramClient, events
from datetime import datetime, timedelta
import asyncio
import pytz

# اطلاعات API

group_usernames = ['@gheymateTehran2', '@DOLARRATE1', '@gheymateTehran'] # نام‌های کاربری سه گروه

# اطلاعات کانال جدید
new_channel_id = 'https://t.me/Akhbargeymat'
target_channel_id = '@DolarRates'

# تنظیمات لاگینگ
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# تنظیمات پراکسی (در صورت نیاز)
proxy = None # ('socks5', '127.0.0.1', 9050) # نمونه برای پراکسی SOCKS5

# ایجاد کلاینت تلگرام با تنظیمات پراکسی
client = TelegramClient('session_name', api_id, api_hash, proxy=proxy)

# قفل برای مدیریت ارسال پیام
send_lock = asyncio.Lock()

# متغیر زمان آخرین ارسال پیام
last_sent_time = datetime(1970, 1, 1, tzinfo=pytz.UTC)

# متغیر سراسری برای ذخیره عدد جدید دلار
global_new_number_str = "نامشخص" # مقدار اولیه

# متغیر وضعیت کارکرد بات
is_running = False

# تابع محاسبه ساعت به وقت تهران
def tehran_time():
tehran_tz = pytz.timezone('Asia/Tehran')
return datetime.now(tehran_tz)

async def send_message_to_channel(message):
try:
logger.info(f"Sending message to channel: {message}")
await client.send_message(channel_id, message)
except Exception as e:
logger.error(f"Failed to send message: {e}")

def get_persian_date():
today = jdatetime.date.today()
return today.strftime('%Y/%m/%d')

async def process_message_text(text):
global last_sent_time, global_new_number_str
current_time = tehran_time()

async with send_lock:
if (current_time - last_sent_time).total_seconds() < 60:
logger.info("Skipping message send due to time limit.")
return None

# پیدا کردن اولین عدد 5 رقمی در متن
match = re.search(r'\b\d{2},\d{3}\b', text)
if match:
# استخراج عدد
original_number = match.group()
# حذف کاما و تبدیل به عدد صحیح
number = int(original_number.replace(',', ''))
# کاهش عدد به مقدار 50
new_number = number - 50
# تبدیل عدد جدید به رشته با فرمت مناسب
new_number_str = f'{new_number:,}'

# ذخیره عدد جدید در متغیر سراسری
global_new_number_str = new_number_str

# ایجاد پیام خروجی
processed_text = f"""
✨ #نرخ_دلار

📆 تاریخ: {get_persian_date()}

💸 #دلار سبزه : {new_number_str} تومان

🌟 بروزترین قیمت‌ها رو همین حالا مشاهده کنید.

📲 کانال قیمت #دلار تهران 👇
🆔@DolarRates
"""
last_sent_time = current_time
return processed_text.strip()
else:
logger.error("No 5-digit number found in the text.")
return None

# تابع پردازش پیام‌های کانال جدید
def process_new_channel_message(text):
# حذف موارد ناخواسته
text = re.sub(r'🔸دلار آمريکا.*?\n', '', text)
text = re.sub(r'⏰ساعت.*?\n', '', text)
text = re.sub(r'✅ @Akhbargeymat', '', text)
text = re.sub(r'✅ .*?\n', '', text)
text = text.replace('🔸', '')
text = text.replace('✅', '') # حذف علامت ✅
text = text.replace('****', '') # حذف ****

# جایگزینی پرچم‌ها
text = text.replace('يورو', '🇪🇺 يورو')
text = text.replace('پوند انگليس', '🇬🇧 پوند انگليس')
text = text.replace('درهم امارات', '🇦🇪 درهم امارات')
text = text.replace('يوآن چين', '🇨🇳 يوآن چين')
text = text.replace('لير ترکيه', '🇹🇷 لير ترکيه')
text = text.replace('دینار کویت', '🇰🇼 دینار کویت')

text = text.replace('🔹', '🟡')
text = text.replace('@Akhbargeymat', '')

# راست‌چین کردن
lines = text.split('\n')
aligned_text = '\n'.join(line.strip() for line in lines if line.strip())

# اضافه کردن متن جدید
additional_text = """
🌟 بروزترین قیمت‌ها رو همین حالا مشاهده کنید.

📲 کانال قیمت #دلار تهران 👇
🆔@DolarRates
"""
return aligned_text.strip() + '\n\n' + additional_text.strip()

# تابع خواندن آخرین پیام‌ها از گروه‌ها و ارسال جدیدترین پیام هر یک دقیقه
async def read_latest_posts():
while is_running:
for group_username in group_usernames:
try:
logger.info(f"Reading latest post from {group_username}")
messages = await client.get_messages(group_username, limit=1)
if messages:
latest_message = messages[0]
processed_text = await process_message_text(latest_message.text)
if processed_text:
logger.info(f"Latest post fetched from {group_username}: {processed_text}")
await send_message_to_channel(processed_text)
except Exception as e:
logger.error(f"Failed to read latest post from {group_username}: {e}")
await asyncio.sleep(60) # انتظار یک دقیقه

# تابع خواندن و ارسال پیام از کانال جدید هر 40 دقیقه بدون محدودیت زمانی
async def read_and_forward_from_new_channel():
while is_running:
try:
logger.info(f"Reading latest post from {new_channel_id}")
messages = await client.get_messages(new_channel_id, limit=1)
if messages:
latest_message = messages[0]
processed_text = process_new_channel_message(latest_message.text)
if processed_text:
logger.info(f"Latest post fetched from {new_channel_id}: {processed_text}")
await send_message_to_channel(processed_text)
await asyncio.sleep(2400) # انتظار 40 دقیقه
except Exception as e:
logger.error(f"Failed to read and forward from new channel: {e}")

# هندلر برای پیام‌های جدید
@client.on(events.NewMessage(chats=group_usernames))
async def handler(event):
if is_running:
try:
processed_text = await process_message_text(event.message.text)
if processed_text:
logger.info(f"New message received from {event.chat.username}: {processed_text}")
await send_message_to_channel(processed_text)
except Exception as e:
logger.error(f"Failed to handle new message from {event.chat.username}: {e}")

# ارسال پیام‌های خوش‌آمدگویی و خداحافظی
async def send_greeting_messages():
while is_running:
now = tehran_time()
if now.hour == 10 and now.minute == 0:
await send_message_to_channel("به نام خدا")
elif now.hour == 19 and now.minute == 0:
await send_message_to_channel("به امید دیدار")
await asyncio.sleep(60) # بررسی هر دقیقه

# ارسال پیام‌های خودکار هر 5 تا 8 دقیقه
async def automated_posting():
while is_running:
tehran_current_time = tehran_time().strftime('%H:%M:%S')
special_message = f"""
✨ #نرخ_دلار

📆 تاریخ: {get_persian_date()}

مـعامله انجام شد✅

💸 #دلار سبزه : {global_new_number_str} تومان

🌟 بروزترین قیمت‌ها رو همین حالا مشاهده کنید.

📲 کانال قیمت #دلار تهران 👇
🆔@DolarRates
"""
await send_message_to_channel(special_message.strip())
await asyncio.sleep(random.randint(300, 480)) # انتظار بین 5 الی 8 دقیقه

# تابع متوقف کردن فعالیت ربات
async def shutdown_bot():
global is_running
is_running = False
logger.info("Bot activities have been stopped.")

async def main():
global is_running
logger.info("Starting client...")
try:
await client.start(phone_number)
except Exception as e:
logger.error(f"Failed to start client: {e}")
else:
logger.info("Client started.")
while True:
now = tehran_time()

# Check if it's Friday (weekday 4)
if now.weekday() == 4:
if is_running:
await shutdown_bot()
logger.info("Bot has been stopped for Friday.")
await asyncio.sleep(60) # Check again after 1 minute
continue

# Stop the bot at 16:15 and ensure it remains stopped until 10:00 next day
if (now.hour == 16 and now.minute >= 15) or (now.hour < 10):
if is_running:
await shutdown_bot()
logger.info("Bot has been stopped for the day.")
# Wait until it's past 10:00 the next day
if now.hour < 10:
await asyncio.sleep(60) # Check again after 1 minute
continue

# Check for weekdays and time range to start
if now.weekday() != 4 and (10 <= now.hour < 16 or (now.hour == 16 and now.minute < 15)):
if not is_running:
is_running = True
logger.info("Bot is starting its activities.")
await asyncio.gather(
send_greeting_messages(),
automated_posting(),
read_and_forward_from_new_channel(),
read_latest_posts()
)

# More precise time check every second
await asyncio.sleep(1)

if __name__ == "__main__":
logger.info("Running main...")
client.loop.run_until_complete(main())
client.run_until_disconnected()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Trying to Make Steganography Program Work For All Payload Types Stegosaurus 0 474 Sep-26-2024, 12:43 PM
Last Post: Stegosaurus
  hi need help to make this code work correctly atulkul1985 5 1,389 Nov-20-2023, 04:38 PM
Last Post: deanhystad
  newbie question - can't make code work tronic72 2 1,116 Oct-22-2023, 09:08 PM
Last Post: tronic72
  Why do I have to repeat items in list slices in order to make this work? Pythonica 7 2,014 May-22-2023, 10:39 PM
Last Post: ICanIBB
  Telegram bot python help! wolfdevs 0 987 Sep-07-2022, 11:34 AM
Last Post: wolfdevs
  how to make this error stop ? Mawixy 1 7,060 Apr-19-2022, 03:02 PM
Last Post: Mawixy
  Make my py script work only on 1 compter tomtom 14 4,914 Feb-20-2022, 06:19 PM
Last Post: DPaul
  Script stop work after 3 actioins - PLEASE WHERE IS THE PROBLEM? rondon442 0 1,776 Sep-27-2021, 05:40 PM
Last Post: rondon442
  Cannot make 'pandas' module to work... ellie145 2 4,623 Jan-05-2021, 09:38 PM
Last Post: ellie145
  How to make a telegram bot respond to the specific word in a sentence? Metodolog 2 6,903 Dec-22-2020, 07:30 AM
Last Post: martabassof

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020