我想使用我的用户帐户本身而不是机器人帐户将消息从一个频道转发到另一个频道。在线有许多代码可用于此,但它们都只适用于机器人,没有一个适用于用户帐户,但不确定为什么。 所以我想写我自己的。
这是我的代码
import os
from dotenv import load_dotenv
load_dotenv()
from telethon import TelegramClient, events
api_id = os.getenv("API_ID")
api_hash = os.getenv("API_HASH")
client = TelegramClient(os.getenv("SESSION_NAME"), api_id, api_hash)
# Log in to your account
client.start()
# Source and target channels
source_channel = os.getenv("FROM_CHANNEL_ID")
target_channel = os.getenv("TO_CHANNEL_ID")
# Get the latest messages from the source channel
async def get_messages(channel):
messages = await client.get_messages(channel, limit=1)
print(messages)
return messages
# Forward the messages to the target channel
async def forward_messages(messages, channel):
for message in messages:
await client.forward_messages(channel, message)
# Get the latest messages from the source channel
messages = client.loop.run_until_complete(get_messages(source_channel))
# Forward the messages to the target channel
client.loop.run_until_complete(forward_messages(messages, target_channel))
在终端中,当我第一次运行代码时,它要求输入电话号码和 otp,但从那以后,它也没有要求,我只在终端中看到这个
Server sent a very new message with ID 7229358410288965633, ignoring (see FAQ for details)
Server sent a very new message with ID 7229358410321502209, ignoring (see FAQ for details)
好吧,在阅读了文档之后 我能够用这段代码解决它
import os
from dotenv import load_dotenv
load_dotenv()
from telethon import TelegramClient, events
api_id = os.getenv("API_ID")
api_hash = os.getenv("API_HASH")
client = TelegramClient(os.getenv("SESSION_NAME"), api_id, api_hash)
print("Client Starting...")
# Log in to your account
client.start()
print("Client Created")
# Source and target channels
source_channel_id = int(os.getenv("FROM_CHANNEL_ID"))
target_channel_id = int(os.getenv("TO_CHANNEL_ID"))
print("Channels Loaded")
# keep getting all live messages from source channel
@client.on(events.NewMessage(chats=source_channel_id))
async def handler(event):
print(event.message)
# send message to target channel
await client.send_message(target_channel_id, event.message)
print("Message Sent")
# run until disconnect
client.run_until_disconnected()