提问人:Fedor Pasynkov 提问时间:11/6/2023 更新时间:11/6/2023 访问量:32
如何提高 Python Telethon 代码的性能?
How to increase performance of my Python's Telethon Code?
问:
我基本上需要使这段代码更快,因为有时有很多消息,如果它跳过消息,我会失去客户端。我尝试了一些异步方法,但它们没有帮助。也许有更快的库或具有类似库的编程语言?
from telethon import TelegramClient, events, sync
from datetime import datetime
import re
import asyncio
import logging
logging.basicConfig(level=logging.INFO)
class MessageBatchProcessor:
def __init__(self, batch_size=10, batch_interval=6):
self.message_batch = []
self.batch_size = batch_size
self.batch_interval = batch_interval
async def process_batch(self, client, chat_dict, exchange_keywords_re, channel_name):
while True:
current_time = datetime.now()
if len(self.message_batch) >= self.batch_size or any(
(current_time - event['timestamp']).seconds > 5 for event in self.message_batch):
logging.info("Processing batch...")
for event in self.message_batch:
if exchange_keywords_re.search(event['message'].raw_text):
try:
await event['message'].forward_to(channel_name)
channel_id = event['message'].message.peer_id.channel_id
await client.send_message(entity=channel_name, message=chat_dict[channel_id])
except KeyError as e:
logging.error(f"KeyError: {e} - Channel ID not found in chat_dict.")
except Exception as e:
logging.error(f"An unexpected error occurred: {e}")
self.message_batch = []
await asyncio.sleep(self.batch_interval)
# Your existing code for initialization
api_id = ''
api_hash = ''
channel_name = ''
exchange_keywords = ["менять", "меняю", "меняет", "менял", "меняйте", "обмен", "крипту", "крипта", "курс", "рупии", "руппи"]
exchange_keywords_re = re.compile(r'\b(?:{})\b'.format("|".join(re.escape(word) for word in exchange_keywords)), re.IGNORECASE)
chat_dict = {
1720352497: "",
1503790351: "",
1122616041: "",
1676001373: "",
1605996131: "",
1595332067: "",
1465267513: "",
1537393491: "",
}
client = TelegramClient('anon', api_id, api_hash)
batch_processor = MessageBatchProcessor()
@client.on(events.NewMessage(chats=tuple(chat_dict.keys())))
async def main(event):
timestamped_event = {'message': event, 'timestamp': datetime.now()}
batch_processor.message_batch.append(timestamped_event)
# Schedule the batch processing
client.loop.create_task(batch_processor.process_batch(client, chat_dict, exchange_keywords_re, channel_name))
client.start()
client.run_until_disconnected()
答: 暂无答案
评论