MrMissx / Telegram_Forwarder

Simple telegram bot to forward message from channel/group
GNU General Public License v3.0
511 stars 465 forks source link

send message question #83

Closed madlifer closed 1 year ago

madlifer commented 1 year ago

I'm also writing my forwarding robot, but I use my own account and use the telethon library. I have encountered some problems and would like to ask you for advice.

When the message sent by the source channel contains multiple pictures, the forwarding robot will split it into multiple messages for processing. it cannot handle the situation of multiple pictures in one message.

Below is the code that I tried to fix but failed, can you help me see where the problem is and how to fix it?

    @client.on(events.NewMessage(chats=list(ORIGINAL_CHANNELS.keys())))
    async def handle_message(message):
        # 获取消息的链接
        source_channel = ORIGINAL_CHANNELS.get(message.chat_id, None)
        message_link = f"https://t.me/c/{str(message.chat_id)[4:]}/{message.id}"
        if not source_channel:
            return
        # 记录原始频道发送消息的日志
        # log_message = f"{source_channel} 频道发送了一条消息,消息链接为:{message_link}\n"

        # 获取消息的内容和附件
        content = message.message.message
        attachments = message.message.media

        message_images = []

        for attachment in attachments:
            if isinstance(attachment, types.MessageMediaPhoto):
                  message_images.append(client.download_media(attachment.photo))

          # 将消息内容和附件发送到目标频道
          # TelegramClient.send_message()
          await client.send_file(TARGET_CHANNEL_ID, caption=content, file=message_images)
madlifer commented 1 year ago

here is the full code if you need:

# coding: utf-8
import os
import datetime
from telethon.sync import TelegramClient
from telethon.tl.types import InputPeerChannel
from telethon.tl.types import MessageMediaWebPage
from telethon import events
from telethon.sessions import StringSession
from telethon.tl import types
from typing import Dict, List, Union

# 替换为你的API ID和API Hash
API_ID = XXXX
API_HASH = 'XXXXXXXXXXXXXXX'
SESSION_STRING = 'XXXXXXXXXXXXXX'

# 替换为目标频道和原始频道的ID
TARGET_CHANNEL_ID = -1001234567890
ORIGINAL_CHANNELS = {
    -1001234567890: 'TESTCHANNEL_1',
    -1001234567890: 'TESTCHANNEL_2',
}

# 替换为关键字替换的配置属性
KEYWORD_REPLACEMENTS = {
    'DOG': 'CAT',
    '张三': '李四',
    # 添加更多的关键字替换配置
}

# 替换为不进行转发的关键字
EXCLUDE_KEYWORDS = ['stop', 'fuck', 'reply']
session = StringSession(SESSION_STRING)

# 创建 TelegramClient 对象
# with TelegramClient(SESSION_STRING, API_ID, API_HASH) as client:
with TelegramClient(session, api_id=API_ID, api_hash=API_HASH) as client:
    # 获取目标频道的输入对等体
    os.system('clear')
    print('===========================================\n')
    print('[' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + '] 开始监听消息ing...\n')
    print('===========================================\n')
    target_channel = InputPeerChannel(TARGET_CHANNEL_ID, 0)
    # 保存消息图片的数组

    # 处理新消息的函数
    @client.on(events.NewMessage(chats=list(ORIGINAL_CHANNELS.keys())))
    async def handle_message(message):
        # 获取消息的链接
        source_channel = ORIGINAL_CHANNELS.get(message.chat_id, None)
        message_link = f"https://t.me/c/{str(message.chat_id)[4:]}/{message.id}"
        if not source_channel:
            return
        # 记录原始频道发送消息的日志
        # log_message = f"{source_channel} 频道发送了一条消息,消息链接为:{message_link}\n"

        # 获取消息的内容和附件
        content = message.message.message
        attachments = message.message.media

        # 检查是否存在需要替换的关键字
        keyword_found = False
        for keyword_a in KEYWORD_REPLACEMENTS.keys():
            if keyword_a in content:
                keyword_found = True
                break

        if keyword_found:
            # 替换关键字
            for keyword_a, keyword_b in KEYWORD_REPLACEMENTS.items():
                content = content.replace(keyword_a, keyword_b)

        # 检查是否包含不进行转发的关键字
        exclude_keyword_found = False
        exclude_keyword = ''
        for keyword in EXCLUDE_KEYWORDS:
            if keyword in content:
                exclude_keyword_found = True
                exclude_keyword = keyword
                break

        # 如果包含不进行转发的关键字,则记录日志并返回
        if exclude_keyword_found:
            # log_message = f"该消息未转发,原因为出现关键字'{exclude_keyword}'\n"
            print("来源于 " + source_channel + " 的消息链接:" + message_link + " 未转发,原因为出现关键字:"+ exclude_keyword + "\n")
        else:
            # log_message = f"已转发该条消息,来源于 {source_channel}\n"
            print("来源于 " + source_channel + " 的消息链接:" + message_link + " 转发成功!\n")

            # 在转发的消息后添加来源注明
            source_text = f"\n======\n来源频道: [{source_channel}]({message_link})"
            content = content + source_text

            message_images = []

            for attachment in attachments:
                if isinstance(attachment, types.MessageMediaPhoto):
                    message_images.append(client.download_media(attachment.photo))

            # 将消息内容和附件发送到目标频道
            # TelegramClient.send_message()
            await client.send_file(TARGET_CHANNEL_ID, caption=content, file=message_images)

        # 输出日志到文件
        # with open('log.txt', 'a') as file:
            #file.write(log_message)

    # 启动消息监听
    client.add_event_handler(handle_message, events.NewMessage())

    # 运行客户端
    client.run_until_disconnected()
stale[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.