M
M
MarkBelousov5672021-05-24 13:42:38
Python
MarkBelousov567, 2021-05-24 13:42:38

How can a bot make a telegram mailing list using python?

У меня есть db таблица с 3 столбцами id, user_id и Status. Нажимая на /start пользователь подписывается на бота, а нажимая на /unsubscribe отписывается.
Вот код: (библиотека aiogram)<code lang="python">



# -*- coding: utf8 -*-

from aiogram import Bot, Dispatcher, executor, types
from aiogram.dispatcher import FSMContext
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher.filters.state import State, StatesGroup
import random
from random import randint
import time

import logging
import asyncio
from datetime import datetime
from aiogram import Bot, Dispatcher, executor, types
from chart import SQLighter

from aiogram.types import ReplyKeyboardRemove, \
  ReplyKeyboardMarkup, KeyboardButton, \
  InlineKeyboardMarkup, InlineKeyboardButton


bot = Bot(token= 'token' )
dp = Dispatcher(bot, storage=MemoryStorage())

@dp.message_handler(commands=['start'])
async def process_start_command(message: types.Message):
  await message.answer_sticker(r'https://tlgrm.ru/_/stickers/061/2ac/0612acc2-f6fd-3470-83df- 
            429ee8ba3d3b/192/25.webp')
  await message.reply("Вы успешно подписаны на этого бота. ВНИМАНИЕ!!! ваш ID не будет 
            отправлен не одному человеку, на вас не будут оформленны никакие платные подписки и                         
            другие платные услуги. Но если вы не хотите быть подписанным на бота, который будет 
            скидывать вам всякие ништяки от проверенных источников, то вы можете отписаться, 
            нажав на /unsubscribe. Если же вы не отписались, то спасибо за понимание. :-)")

  if(not db.subscriber_exists(message.from_user.id)):

    db.add_subscriber(message.from_user.id)
  else:

    db.update_subscription(message.from_user.id, True)


logging.basicConfig(level=logging.INFO)
db = SQLighter('db.db')


@dp.message_handler(commands=['unsubscribe'])
async def unsubscribe(message: types.Message):
  if(not db.subscriber_exists(message.from_user.id)):
    
    await message.answer("Вы итак не подписаны.")
  else:
    await message.answer("Вы успешно отписаны.")

@dp.message_handler(commands=['go'])
async def go(message: types.Message):
  for user in db:
    await bot.send_message("...")

if __name__ == '__main__':
  executor.start_polling(dp,skip_updates=True)

Код таблицы: (chart)

import sqlite3

class SQLighter:

    def __init__(self, database):

        self.connection = sqlite3.connect(database)
        self.cursor = self.connection.cursor()

    def get_subscriptions(self, status = True):
        
        with self.connection:
            return self.cursor.execute("SELECT * FROM `subscriptions` WHERE `status` = ?", (status,)).fetchall()

    def subscriber_exists(self, user_id):

        with self.connection:
            result = self.cursor.execute('SELECT * FROM `subscriptions` WHERE `user_id` = ?', (user_id,)).fetchall()
            return bool(len(result))

    def add_subscriber(self, user_id, status = True):

        with self.connection:
            return self.cursor.execute("INSERT INTO `subscriptions` (`user_id`, `status`) VALUES(?,?)", (user_id,status))

    def update_subscription(self, user_id, status):

        with self.connection:
            return self.cursor.execute("UPDATE `subscriptions` SET `status` = ? WHERE `user_id` = ?", (status, 
                user_id))

    def close(self):

        self.connection.close()

Заранее спасибо)
</code>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
o5a, 2021-05-26
@o5a

fetchall() in get_subscriptions in its current form will return nested lists with all fields. It is better to immediately return only the necessary information - a list of the id itself

...
    def get_subscriptions(self, status = True):
        with self.connection:
            return [x[0] for x in self.cursor.execute("SELECT user_id FROM `subscriptions` WHERE `status` = ?", (status,)).fetchall()]

then you can just directly use the ids when sending
@dp.message_handler(commands=['go'])
async def go(message: types.Message):
  subscriptions = db.get_subscriptions()
  for user in subscriptions:
    await bot.send_message(user, "...")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question