You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现Telegram机器人随机消息片段组合功能求助

实现Telegram机器人随机拼接消息片段功能

修改思路

把原固定消息拆分为3个片段组,每个组包含3种不同表述,每次发送时从每个组随机选一个片段拼接成完整消息。具体修改步骤如下:

  • 定义三个消息片段组,分别存储不同表述的片段
  • 在遍历用户的循环中,从每个片段组随机选取一个片段,拼接成完整消息
  • 替换原代码中固定消息的逻辑

修改后的完整代码

from telethon.sync import TelegramClient
from telethon.tl.types import InputPeerUser
from telethon.errors.rpcerrorlist import PeerFloodError
import sys
import csv
import random
import time
from numpy.random import default_rng
from time import sleep

api_id = 1234567   #Enter Your 7 Digit Telegram API ID.
api_hash = 'hash'   #Enter Yor 32 Character API Hash.
phone = 'phonenumber'   #Enter Your Mobilr Number With Country Code.
client = TelegramClient(phone, api_id, api_hash)

rng = default_rng()

SLEEP_TIME_2 = 100
SLEEP_TIME_1 = 40
client = TelegramClient(phone, api_id, api_hash)

client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    client.sign_in(phone, input('Enter the code: '))

users = []
with open(r"Scrapped.csv", encoding='UTF-8') as f:
    rows = csv.reader(f,delimiter=",",lineterminator="\n")
    next(rows, None)
    for row in rows:
        user = {}
        user['username'] = row[0]
        user['id'] = int(row[1])
        user['access_hash'] = int(row[2])
        user['name'] = row[3]
        users.append(user)

mode = int(input("Enter 1 to send by user ID or 2 to send by username: "))

# 定义三个消息片段组,每个组3种表述
segment_group1 = [
    "Hey I'm new to software trading",
    "I'm just getting started with algorithmic trading",
    "I've recently dived into software-based trading"
]

segment_group2 = [
    ", how has Ainstein been performing for you?",
    ", could you share how Ainstein has worked for you?",
    ", I'm curious how Ainstein has been performing for you?"
]

segment_group3 = [
    " Any problems you have encountered?",
    " Have you run into any issues with it?",
    " Did you face any problems while using it?"
]

for user in users:
    if mode == 2:
        if user['username'] == "":
            continue
        receiver = client.get_input_entity(user['username'])
    elif mode == 1:
        receiver = InputPeerUser(user['id'],user['access_hash'])
    else:
        print("Invalid Mode. Exiting.")
        client.disconnect()
        sys.exit()
    
    # 从每个片段组随机选一个,拼接成完整消息
    message = (random.choice(segment_group1) 
               + random.choice(segment_group2) 
               + random.choice(segment_group3))
    
    try:
        SLEEP_TIME = rng.uniform(37, 67)
        print("Sending Message to:", user['name'])
        client.send_message(receiver, message.format(user['name']))
        print("Waiting {} seconds".format(SLEEP_TIME))
        time.sleep(SLEEP_TIME)
    except PeerFloodError:
        print("Getting Flood Error from telegram. Script is stopping now. Please try again after some time.")
        print("Waiting {} seconds".format(SLEEP_TIME_2))
        time.sleep(SLEEP_TIME_2)
    except Exception as e:
        print("Error:", e)
        print("Trying to continue...")
        print("Waiting {} seconds".format(SLEEP_TIME_1))
        time.sleep(SLEEP_TIME_1)
client.disconnect()
print("Done. Message sent to all users.")

关键代码说明

  • segment_group1/2/3:三个列表分别存储不同的消息片段,每个列表包含3种不同表述,可根据需求修改内容
  • random.choice(segment_groupX):从对应片段组中随机选取一个元素
  • 字符串拼接:用+运算符将三个随机片段连接成完整消息,注意片段末尾的标点和空格,保证拼接后语句通顺

内容的提问来源于stack exchange,提问作者Community of Traders

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 21:01:05