Search code examples
databasetelebot

How can I send a broadcast message to multiple chat ids


I tried to send a message to all bot users through their CHAT_IDs but failed.

@bot.message_handler(commands=['cast'])
def send_cast(message):
    msg = message.text.split(None,1)[1]
    user = message.from_user.id
    #start_db
    conn = connect_to_db()
    cursor = conn.cursor()
    db_users = "select user_id from UFM_USERS where type ='ORD'"
    cursor.execute(db_users)
    u = cursor.fetchall()
    users = [row[0] for row in u]
    conn.commit()
    #fetch users

users retrieve as 7667...,4665....,9877...,8665...,3566,28579..,5679...,687... but again it doesn't send to the users.

    try:
        if user not in m.admin:
           bot.send_message(message.chat.id,text=f"You require admin permission to do this ‼️",parse_mode = "Markdown")
        else:
            #bot.send_message(message.chat.id,f'_These are your users_\n{users}',parse_mode = "Markdown")
            bot.send_message(chat_id=users,text=msg,parse_mode = "Markdown")
    except Exception as e:
        bot.send_message(message.chat.id, 
                         f'*Oooops... Something went wrong.*',
                         parse_mode = "Markdown")

That's my code but if it's sends a massage, it sends to one user not all. How can I resolve it.


Solution

  • You indicated that users is a list. bot.send_message takes one chat_id as a value not a list of them. So, for loop will solve this problem:

    for user in users:
        bot.send_message(chat_id=user,text=msg,parse_mode = "Markdown")
    

    In addition, I recommend reading telegram bot API limits for sending bulk messages.