python - 如何使此脚本由消息触发实时运行
问题描述
我有这个脚本可以通过 Python 在 Telegram 上将消息从一个频道复制到另一个频道。这目前将运行一次,复制所有丢失的消息,然后完成。如何修改它以间隔运行或在频道中出现新消息时运行?
我还有其他使用的文件,例如带有 API 密钥/通道的 API 配置文件等。
即使有人可以帮助我指出正确的方向,我也会潜水更多。我对 Python 不是很熟悉。
import asyncio
import logging
from telethon.tl.patched import MessageService
from telethon.errors.rpcerrorlist import FloodWaitError
from telethon import TelegramClient
from telethon.sessions import StringSession
from settings import API_ID, API_HASH, forwards, get_forward, update_offset, STRING_SESSION
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
SENT_VIA = f'\n__Sent via__ `{str(__file__)}`'
def intify(string):
try:
return int(string)
except:
return string
async def forward_job():
''' the function that does the job '''
if STRING_SESSION:
session = StringSession(STRING_SESSION)
else:
session = 'forwarder'
async with TelegramClient(session, API_ID, API_HASH) as client:
confirm = ''' IMPORTANT
Are you sure that your `config.ini` is correct ?
You can run the `get_chat_info.py` script to confirm the `from` and `to`.
Press [ENTER] to continue:
'''
input(confirm)
error_occured = False
for forward in forwards:
from_chat, to_chat, offset = get_forward(forward)
if not offset:
offset = 0
last_id = 0
async for message in client.iter_messages(intify(from_chat), reverse=True, offset_id=offset):
if isinstance(message, MessageService):
continue
try:
await client.send_message(intify(to_chat), message)
last_id = str(message.id)
logging.info('forwarding message with id = %s', last_id)
update_offset(forward, last_id)
except FloodWaitError as fwe:
print(f'\n{fwe}\n\nRun the script again after some time. \
FloodWaitError Occured')
quit()
except Exception as err:
logging.exception(err)
error_occured = True
continue
if __name__ == "__main__":
assert forwards
asyncio.run(forward_job())
解决方案
您需要查看更新文档。使用它,您将能够在您的代码中获得一条新消息。
你也需要改变你的处理方式
看起来类似于:
from telethon import TelegramClient, events
client = TelegramClient(session, API_ID, API_HASH)
database = {}
for forward in forwards
from_chat, to_chat, offset = get_forward(forward)
database[from_chat] = {"to_chat": to_chat, "offset": offset}
@client.on(events.NewMessage)
async def my_event_handler(event):
to_chat = database.get(event.chat_id)
if to_chat:
await client.send_message(to_chat, event.message)
last_id = message.id
database[event.chat_id] = last_id
logging.info('forwarding message with id = %s', last_id)
client.start()
# TODO: do `iter_messages` initial or while script was not running
client.run_until_disconnected()
或者,如果您想定期调用它,您可以:
iter_messages
用循环 包装方法while True: # TODO: # do_iter_messages__and__forwarding() await asyncio.sleep(10)
iter_messages
或在延迟一段时间后再次从该方法 调用方法def do_iter_messages__and__forwarding(): # TODO: # for message in client.iter_messages(...): # do_message_forward(...) await asyncio.sleep(10) do_iter_messages__and__forwarding()
推荐阅读
- python - 如何使用 python selenium 通过文本查找 div 元素?
- excel - excel插件 | 在清单加载时在桌面 excel 上显示错误
- camera - Choregraphe 可以连接到外部摄像头吗?
- reactjs - 找不到模块“date-fns-tz”或其相应的类型声明
- javascript - 如果传递相同的参数,如何防止函数调用?
- c# - 从 VB.Net DLL 引用 DLL
- mysql - SQL 触发器 PHPMYADMIN
- node.js - 猫鼬 findOneAndUpdate 工作但给出错误
- c# - Hangfire 作业在控制台上显示错误但手动触发
- typescript - 无法解决@atoms/blabla | babel-plugin-module-resolver 和 react native