import asyncio
from telethon.sync import TelegramClient
from telethon.errors import ChatIdInvalidError
class TelegramForwarder:
def __init__(self, api_id, api_hash, phone_number):
self.api_id = api_id
self.api_hash = api_hash
self.phone_number = phone_number
self.client = TelegramClient('session_' + phone_number, api_id, api_hash)
async def forward_messages_to_channel_pairs(self, chat_pairs, keywords, signature):
await self.client.connect()
if not await self.client.is_user_authorized():
await self.client.send_code_request(self.phone_number)
await self.client.sign_in(self.phone_number, input('Enter the code: '))
# Adjusted to handle three values: source_id, destination_id, and topic_id
last_message_ids = {source_id: (await self.client.get_messages(source_id, limit=1))[0].id for source_id, _, _ in chat_pairs}
while True:
print("Checking for messages and forwarding them...")
for source_chat_id, destination_chat_id, topic_id in chat_pairs:
# Get new messages since the last checked message for the current source chat
messages = await self.client.get_messages(source_chat_id, min_id=last_message_ids[source_chat_id], limit=None)
for message in reversed(messages):
if keywords:
if message.text and any(keyword in message.text.lower() for keyword in keywords):
print(f"Message contains a keyword: {message.text}")
await self.forward_message(destination_chat_id, message.text, signature, topic_id)
else:
await self.forward_message(destination_chat_id, message.text, signature, topic_id)
last_message_ids[source_chat_id] = max(last_message_ids[source_chat_id], message.id)
await asyncio.sleep(5)
async def forward_message(self, destination_chat_id, message_text, signature, topic_id=None):
try:
entity = await self.client.get_input_entity(destination_chat_id)
# Convert topic ID if it's out of valid range
if topic_id is not None:
topic_id = self.convert_to_signed_integer(topic_id)
# Only proceed if topic_id is valid
if self.is_valid_signed_integer(topic_id):
await self.client.send_message(entity, message_text + f"\n\n{signature}", reply_to=topic_id)
print(f"Message forwarded to topic {topic_id} in chat {destination_chat_id}")
else:
print(f"Invalid topic ID: {topic_id}, skipping.")
else:
await self.client.send_message(entity, message_text + f"\n\n{signature}")
print(f"Message forwarded to chat {destination_chat_id}")
except ChatIdInvalidError:
print(f"Invalid chat ID: {destination_chat_id}.")
except Exception as e:
print(f"Failed to forward to {destination_chat_id}: {e}")
def convert_to_signed_integer(self, number):
"""Convert an unsigned integer to a signed integer."""
if number > 2147483647:
return number - 4294967296
return number
def is_valid_signed_integer(self, number):
"""Check if the number is within the valid range of a signed 32-bit integer."""
return -2147483648
Подробнее здесь: [url]https://stackoverflow.com/questions/79114436/replit-code-not-showing-output-after-sometimes-without-showing-anything-it-come[/url]
Это код, он связан с автоматической пересылкой сообщений Telegram с использованием идентификатора исходного чата и идентификатора целевого чата. [code] import asyncio from telethon.sync import TelegramClient from telethon.errors import ChatIdInvalidError
if not await self.client.is_user_authorized(): await self.client.send_code_request(self.phone_number) await self.client.sign_in(self.phone_number, input('Enter the code: '))
# Adjusted to handle three values: source_id, destination_id, and topic_id last_message_ids = {source_id: (await self.client.get_messages(source_id, limit=1))[0].id for source_id, _, _ in chat_pairs}
while True: print("Checking for messages and forwarding them...") for source_chat_id, destination_chat_id, topic_id in chat_pairs: # Get new messages since the last checked message for the current source chat messages = await self.client.get_messages(source_chat_id, min_id=last_message_ids[source_chat_id], limit=None)
for message in reversed(messages): if keywords: if message.text and any(keyword in message.text.lower() for keyword in keywords): print(f"Message contains a keyword: {message.text}") await self.forward_message(destination_chat_id, message.text, signature, topic_id) else: await self.forward_message(destination_chat_id, message.text, signature, topic_id)
# Convert topic ID if it's out of valid range if topic_id is not None: topic_id = self.convert_to_signed_integer(topic_id) # Only proceed if topic_id is valid if self.is_valid_signed_integer(topic_id): await self.client.send_message(entity, message_text + f"\n\n{signature}", reply_to=topic_id) print(f"Message forwarded to topic {topic_id} in chat {destination_chat_id}") else: print(f"Invalid topic ID: {topic_id}, skipping.") else: await self.client.send_message(entity, message_text + f"\n\n{signature}") print(f"Message forwarded to chat {destination_chat_id}")
except ChatIdInvalidError: print(f"Invalid chat ID: {destination_chat_id}.") except Exception as e: print(f"Failed to forward to {destination_chat_id}: {e}")
def convert_to_signed_integer(self, number): """Convert an unsigned integer to a signed integer.""" if number > 2147483647: return number - 4294967296 return number
def is_valid_signed_integer(self, number): """Check if the number is within the valid range of a signed 32-bit integer.""" return -2147483648
Я новичок и только начал изучать язык C++. Когда я выполняю этот базовый код с использованием цикла while, я не получаю выходные данные в VS Code, но я получаю выходные данные в онлайн-компиляторе.
#include использование пространства имен std;...
Использование AWS SDK для загрузки и скачивания изображений и текста. но
Получил эту ошибку в Xcode 15, но работает хорошо для более ранней версии Xcode. Пожалуйста, помогите решить эту проблему.
AWSiOSSDKv2 AWSURLResponseSerialization.m line:263 |...
Я реализую неблокирующую логику повтора для запроса POST на Java, используя CompletableFuture. Цель состоит в том, чтобы повторить запрос до n раз и вернуть окончательный результат (успех или неудачу) после завершения всех попыток. Вот как я начинаю...
В моем скрипте есть несколько функций, которые выполняют запросы API REST API. Поскольку мне нужно обрабатывать сценарии ошибок, я установил механизм повтора, как показано ниже.
В моем скрипте есть несколько функций, которые выполняют запросы API REST API. Поскольку мне нужно обрабатывать сценарии ошибок, я установил механизм повтора, как показано ниже.