向电报机器人的所有用户发送消息

时间:2021-07-06 22:19:58

标签: sqlite telegram telegram-bot py-telegram-bot-api

我正在使用 pyTelegramBotAPI (telebot)。我需要向所有机器人用户发送消息,但经过多次尝试,我的代码根本不起作用(没有错误,但它不发送消息)。我已经将 user_id 存储在 SQLLite 数据库中的名为“test”的表中。将不胜感激一些帮助。

我的代码:

import sqlite3
import telebot

TOKEN = ""
bot = telebot.TeleBot(TOKEN)

conn = sqlite3.connect('db/database.db', check_same_thread=False)
cursor = conn.cursor()

def db_table_val(user_id: int, user_name: str, user_surname: str, username: str):
    cursor.execute('INSERT INTO test (user_id, user_name, user_surname, username) VALUES (?, ?, ?, ?)', (user_id, user_name, user_surname, username))
    conn.commit()

@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.chat.id, 'Welcome!')

@bot.message_handler(content_types=['text'])
def get_text_messages(message):
    if message.text.lower() == 'Hi!':
        bot.send_message(message.chat.id, 'Hi! You are cool!')
        
        us_id = message.from_user.id
        us_name = message.from_user.first_name
        us_sname = message.from_user.last_name
        username = message.from_user.username
        
        db_table_val(user_id=us_id, user_name=us_name, user_surname=us_sname, username=username)

@bot.message_handler(commands=['newrm'])
def step_Set_Rm(message):
    cid = message.chat.id
    userRm = message.text
    conn = sqlite3.connect("database.db")
    cursor = conn.cursor()
    cursor.execute("SELECT user_id FROM test")
    users_list = cursor.fetchall()
    bot.send_message(users_list, userRm)
    conn.commit()
    conn.close()
    bot.send_message(message.chat.id, 'Отправлено!')

bot.polling(none_stop=True)

1 个答案:

答案 0 :(得分:0)

您可以在不使用任何第三方模块的情况下将用户 id 列在列表中:

import telebot

TOKEN = ""
bot = telebot.TeleBot(TOKEN)

admin = # your chat id
users = []

@bot.message_handler(commands=['start'])
def start_message(msg):
    bot.send_message(msg.chat.id, 'Welcome!')
    if msg.chat.id not in users: # if the id isn't already in the users list
        users.append(msg.chat.id)

@bot.message_handler(commands=['send_at_all'])
def sendAtAll(msg):
    if msg.chat.id == admin: # only if YOU start the command the message will be sent
        for id in users: # for every user that has start the bot
            bot.send_message(id, "I'm sending this message at all the users")

# If an user wants to stop the notifications...

@bot.message_handler(commands=['unsubscribe'])
def sendAtAll(msg):
    del users[msg.chat.id]
    bot.send_message(msg.chat.id, "If you want to receive the notification click /start")


# Every time you are going to restart the bot polling the content of the users list will be deleated so...

@bot.message_handler(commands=['save_user_list'])
def sendAtAll(msg):
    if msg.chat.id == admin:
        bot.send_message(admin, users) 
# the list will be sent to your telegram chat, when you activate the bot you can add the list manually

bot.polling()

为我的英语不好而道歉