Вот как пример , а дальше сами
pip install python-telegram-bot==13.7
import logging
import os
import sqlite3
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import time
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
# Create a connection to the SQLite database and a cursor to execute queries
conn = sqlite3.connect('mailing_list.db')
c = conn.cursor()
# Create the subscribers table if it doesn't already exist
c.execute('''CREATE TABLE IF NOT EXISTS subscribers (id INTEGER PRIMARY KEY, username TEXT)''')
conn.commit()
TOKEN = os.environ['TELEGRAM_BOT_TOKEN'] = '5898965789:A6575757Gs933Rajo6755464564'
def send_mailing(update, context):
# Create a connection and cursor for this thread
conn = sqlite3.connect('mailing_list.db')
c = conn.cursor()
# Get a list of all subscribers from the database
subscribers = c.execute('''SELECT * FROM subscribers''').fetchall()
# Iterate over the subscribers and send them a message
for subscriber in subscribers:
context.bot.send_message(chat_id=subscriber[0], text='Это тестовая рассылка')
time.sleep(1) # pause for 1 second before sending the next message
# Respond to the user who sent the command
update.message.reply_text('Рассылка отправлена!')
# Close the connection and cursor
c.close()
conn.close()
# Define a function to remove a user from the subscribers list
def unsubscribe(update, context):
# Create a connection and cursor for this thread
conn = sqlite3.connect('mailing_list.db')
c = conn.cursor()
# Delete the user from the subscribers table
c.execute('''DELETE FROM subscribers WHERE id=?''', (update.effective_user.id,))
conn.commit()
# Respond to the user who sent the command
update.message.reply_text('Вы были удалены из списка рассылки!')
# Close the connection and cursor
c.close()
conn.close()
# Define a function to add a user to the subscribers list
def subscribe(update, context):
# Create a connection and cursor for this thread
conn = sqlite3.connect('mailing_list.db')
c = conn.cursor()
# Insert the user's ID and username into the subscribers table
c.execute('''INSERT INTO subscribers (id, username) VALUES (?, ?)''', (update.effective_user.id, update.effective_user.username))
conn.commit()
# Respond to the user who sent the command
update.message.reply_text('Вы добавлены в список рассылки!')
# Close the connection and cursor
c.close()
conn.close()
def error(update, context):
logger.warning('Обновление "%s" ошибка "%s"', update, context.error)
updater = Updater(TOKEN, use_context=True)
dp = updater.dispatcher
dp.add_handler(CommandHandler('mailing', send_mailing))
dp.add_handler(CommandHandler('subscribe', subscribe))
dp.add_handler(CommandHandler('unsubscribe', unsubscribe))
dp.add_error_handler(error)
updater.start_polling()
updater.idle()