简体   繁体   English

Telegram 机器人消息按计划转发

[英]Telegram bot message forwarding on schedule

I would like to forward messages from one telegram channel to another in a given time.我想在给定时间内将消息从一个电报频道转发到另一个频道。 I'm using the python-telegram-bot v20.0 library for this.为此,我正在使用 python-telegram-bot v20.0 库。 Without scheduling it works like a charm, but when trying to schedule it doesn't give an error, but runs forever and nothing happens.没有安排它就像一个魅力,但当试图安排它不会给出错误,而是永远运行并且没有任何反应。

Here is a reproducible example:这是一个可重现的例子:

from datetime import datetime, timedelta
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from telegram import Bot
import asyncio


BOT = Bot(...)
CHANNEL_FROM = ...
CHANNEL_TO = ...
MESSAGE_ID = 97
TIME = datetime.now() + timedelta(seconds=10)


async def prepare_message():
    message_status = await BOT.forward_message(chat_id=CHANNEL_TO, from_chat_id=CHANNEL_FROM, message_id=MESSAGE_ID)
    if message_status:
        print(f"Scheduled message {MESSAGE_ID} sent successfully.")


async def send_message():
    # That doesn't work
    for i in range(2):
        scheduler.add_job(prepare_message, 'date', run_date=TIME)
        print(f"Added job to send message {MESSAGE_ID} from channel {CHANNEL_FROM} to channel {CHANNEL_TO} at {TIME}")
    
    # That works
    message_status = await BOT.forward_message(chat_id=CHANNEL_TO, from_chat_id=CHANNEL_FROM, message_id=MESSAGE_ID)
    if message_status:
        print(f"Regular message {MESSAGE_ID} sent successfully")


scheduler = AsyncIOScheduler()
scheduler.add_job(send_message, "interval", days=1, start_date="2022-01-01 00:00:00", timezone="UTC")
scheduler.start()

asyncio.run(send_message())

while True:
    pass

The output of this snippet is这个片段的 output 是

Added job to send message 97 from channel ... to channel ... at 2023-01-24 20:51:16.471834
Added job to send message 97 from channel ... to channel ... at 2023-01-24 20:51:16.471834
Regular message 97 sent successfully

Would be grateful if anyone could help me make it work.如果有人能帮助我让它发挥作用,我将不胜感激。

while True:
    pass

will not give the event loop a chance to do anything, as this loop is blocking.不会给事件循环做任何事情的机会,因为这个循环是阻塞的。 As your main goal seems to be to have the scheduler running forever, I recommend to have a look at the APScheduler examples .由于您的主要目标似乎是让调度程序永远运行,我建议您查看APScheduler示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM