Example #1
0
    def test_channels(self):
        chan1 = Channels(name=u'Channel1')
        self.session.add(chan1)
        self.assertEqual(chan1.name, u'Channel1')

        chan2 = Channels(name=u'Channel2')
        chan3 = Channels(name=u'Channel3')
        chan4 = Channels(name=u'Channel4')
        self.session.add_all([chan2, chan3, chan4])
Example #2
0
def guardar(RSS, resource, num, usuario):
    if resource == "rss":
        rss = RSS
    else:
        rss = resource
    try:
        d = feedparser.parse(rss)
        Rss = True
    except UnboundLocalError:
        Rss = False
    if Rss:
        title = d.feed.title
        url = d.feed.link
        Num_Mensaje = len(d.entries)
        try:
            logo = '<img src="'+d.feed.image.href+'">'
        except:
            logo = ""
        date = d.feed.published
        date = datetime.datetime.fromtimestamp(calendar.timegm(rfc822.parsedate(date)))
        try:
            T_Canal = Channels.objects.get(Title = title)
            T_Canal.Logo = logo
            T_Canal.RSS = rss
            T_Canal.Date = date
            T_Canal.Url = url
            T_Canal.NumMensaje = Num_Mensaje
        except Channels.DoesNotExist:
            T_Canal = Channels(Title = title, Logo = logo, RSS = rss, Date = date, Url = url, NumMensaje = Num_Mensaje)
        T_Canal.save()
        for N_noticia in d.entries:
            titulo = N_noticia.title
            link = N_noticia.link
            date = N_d.published
            date = datetime.datetime.fromtimestamp(calendar.timegm(rfc822.parsedate(date)))
            descripcion = N_d.description
            titular = d.feed.title
            try:
                T_num = CanalNum.objects.get(Titulo = titulo, Titular = titular)
                T_num.Link = link
                T_num.Date = date
                T_num.Descripcion = descripcion
            except CanalNum.DoesNotExist:
                T_num = CanalNum(Titulo = titulo, Titular = titular, Link = link, Date = date, Descripcion = descripcion)
            T_num.save()
        try:
            T_Num = CanalNum.objects.get()
    if resource != "rss":
        return HttpResponseRedirect("http://localhost:1234/canales/"+num)
Example #3
0
def show_dashboard():
    print(f"ROUTE: show_dashboard")
    if 'user_id' not in session:
        print(f"User id not found")
        return redirect('/')

    current_user = Users.query.get(session['user_id'])
    public_channels = Channels.get_public_channels()

    private_channels = Channels.query.filter_by(id=PRIVATE_CHANNEL)
    owned_channels = Channels.get_owned_channels(current_user.id)

    return render_template("dashboard_test.html",
                           user=current_user,
                           public_channels=public_channels,
                           owned_channels=owned_channels)
Example #4
0
def get_channel(update: Update, context: CallbackContext, user):
    bot = context.bot
    channels = list(Channels.select().where(Channels.admin != user).order_by(
        Channels.price.asc()).limit(40))
    if not channels:
        bot.send_message(
            chat_id=user.telegram_id,
            text=NO_CHANNELS,
            parse_mode=ParseMode.HTML,
        )
        return -1

    count = len(channels)

    def mk_button(channel):
        button_text = f'{channel.tid} ({channel.price} BIP)'
        return InlineKeyboardButton(button_text,
                                    callback_data=f'ad_{channel.uuid}')

    kb = InlineKeyboardMarkup(
        [list(map(mk_button, channels[i:i + 2])) for i in range(0, count, 2)])
    bot.send_message(chat_id=user.telegram_id,
                     text=CHOOSE_CHANNEL,
                     parse_mode=ParseMode.HTML,
                     reply_markup=kb)
    return 'CHOOSE_CHANNEL'
Example #5
0
 def test_logs(self):
     user3 = Users(username=u'user3')
     chan5 = Channels(name=u'Channel5')
     self.session.add_all([user3, chan5])
     log = Logs(log=u'Lorem Ipsum', user=user3.id, channel=chan5.id)
     self.session.add(log)
     n = self.session.query(Logs.user).group_by(Logs.user).count()
     self.assertEqual(n, 1)
Example #6
0
def my_channels(update: Update, context: CallbackContext, user: Users):
    bot = context.bot
    user_channels = Channels.filter(admin=user)
    keyboard = InlineKeyboardMarkup([[
        InlineKeyboardButton(f'{channel.tid} ({channel.price})',
                             callback_data=f'channel_{channel.tid}')
    ] for channel in user_channels])
    bot.send_message(chat_id=user.telegram_id,
                     text=NO_CHANNELS if not user_channels else MY_CHANNELS,
                     reply_markup=None if not user_channels else keyboard,
                     parse_mode=ParseMode.HTML)
Example #7
0
def guardar(RSS, resource, num, usuario):
    if resource == "rss":
        rss = RSS
    else:
        rss = resource
    try:
        d = feedparser.parse(rss)
        title = d.feed.title
        url = d.feed.link
        Rss = True
    except:
        Rss = False
    if Rss:
        try:
            logo = '<img src="'+d.feed.image.href+'">'
        except:
            logo = ""
        date = d.feed.published
        date = datetime.datetime.fromtimestamp(calendar.timegm(rfc822.parsedate(date)))
        # Guardar los nuevos canales de /canales
        try:
            T_Canal = Channels.objects.get(Title = title)
            T_Canal.Logo = logo
            T_Canal.RSS = rss
            T_Canal.Date = date
            T_Canal.Url = url
            T_Canal.NumMensaje = T_Canal.NumMensaje
        except Channels.DoesNotExist:
            T_Canal = Channels(Title = title, Logo = logo, RSS = rss, Date = date, Url = url, NumMensaje = 0)
        T_Canal.save()
        numNoticias = 0
        # Guardar las nuevas noticias de /canales/num
        for N_noticia in d.entries:
            titulo = N_noticia.title
            link = N_noticia.link
            date2 = N_noticia.published
            date2 = datetime.datetime.fromtimestamp(calendar.timegm(rfc822.parsedate(date2)))
            descripcion = N_noticia.description
            titular = d.feed.title
            try:
                T_num = CanalesNum.objects.get(Titulo = titulo, CanalId = T_Canal.id)
                T_num.Link = link
                T_num.Date = date2
                T_num.Descripcion = descripcion
                T_num.Titular = titular
            except CanalesNum.DoesNotExist:
                T_num = CanalesNum(Titulo = titulo, CanalId = T_Canal.id, Link = link, Date = date2, Descripcion = descripcion, Titular = titular)
                numNoticias = numNoticias + 1
            T_num.save()
        T_Canal.NumMensaje = T_Canal.NumMensaje + numNoticias
        T_Canal.save()
    # Si le das al boton de actualizar de /canales/num
    if resource != "rss":
        return HttpResponseRedirect("http://localhost:1234/canales/"+num)
Example #8
0
def create_new_channel():
    print(f"ROUTE: create_new_channel")
    print(f"Adding new channel")
    print(f"Channel form: {request.form}")

    current_user = Users.query.get(session['user_id'])

    if request.form['options'] == "public":
        channel_type = PUBLIC_CHANNEL
    else:
        channel_type = PRIVATE_CHANNEL

    channel_id = Channels.add_new_channel(current_user.id,
                                          request.form['channel_title'],
                                          request.form['channel_description'],
                                          channel_type)

    return redirect(url_for("show_channels_page"))
Example #9
0
def channel_chosen(update: Update, context: CallbackContext, user):
    bot = context.bot
    user_data = context.user_data
    info('--------- CHANNEL CHOSEN --------')
    if update.callback_query:
        info('callback query')
        info(update.callback_query.data)
    else:
        info('start command. args:')
        info(context.args)
        info(update.message)
    info('---------------------------------')
    if update.callback_query and not update.callback_query.data.startswith(
            'ad_'):
        return -1
    if not update.callback_query and not context.args:
        return start(update, context)

    ch_id = update.callback_query.data.split(
        '_')[1] if update.callback_query else context.args[0]
    channel = Channels.get(uuid=ch_id)
    if not channel:
        bot.send_message(chat_id=user.telegram_id,
                         text=ERROR_CHANNEL_DOESNT_EXIST,
                         parse_mode=ParseMode.HTML,
                         reply_markup=main_kb)
        return -1

    w = user.wallets.get()
    if check_balance(user) - float(w.reserved_balance) < channel.price:
        bot.send_message(chat_id=user.telegram_id,
                         text=NO_MONEY,
                         parse_mode=ParseMode.HTML,
                         reply_markup=main_kb)
        return -1

    user_data['channel'] = channel
    bot.send_message(chat_id=user.telegram_id,
                     text=CHANNEL_CHOSEN_TMPL.format(channel=channel.tid,
                                                     price=channel.price,
                                                     rules=channel.comment),
                     parse_mode=ParseMode.HTML,
                     reply_markup=ReplyKeyboardRemove())
    return 'CHANNEL_CHOSEN'
Example #10
0
def get_channel_username(update: Update, context: CallbackContext, user):
    bot = context.bot
    user_data = context.user_data
    message = update.message.text
    if is_main_menu(message):
        return start(update, context, custom_msg='Main menu')

    try:
        channel_id = int(message)
    except ValueError:
        if user_data.get('channel_id'):
            channel_id = user_data['channel_id']
        else:
            channel_id = message.strip('@').lower()
            channel_id = f"@{channel_id}"

    sender = update.message.from_user

    cur_bot = bot.get_me()
    try:
        admins = bot.get_chat_administrators(channel_id)
    except BadRequest:
        if user_data.get('second_attempt'):
            text = ERROR_CHANNEL_2
        else:
            user_data['second_attempt'] = True
            text = ERROR_CHANNEL

        user_data['channel_id'] = channel_id

        bot.send_message(chat_id=user.telegram_id,
                         text=text,
                         reply_markup=ReplyKeyboardMarkup(
                             [['Done'], ['Main menu']], resize_keyboard=1),
                         parse_mode=ParseMode.HTML)
        return

    chat_data = {
        chat_member.user: chat_member.status
        for chat_member in admins
    }

    if sender not in chat_data:
        bot.send_message(chat_id=user.telegram_id,
                         text=SENDER_NOT_AN_ADMIN,
                         parse_mode=ParseMode.HTML)
        return

    if cur_bot not in chat_data:
        bot.send_message(chat_id=user.telegram_id,
                         text=BOT_NOT_AN_ADMIN,
                         parse_mode=ParseMode.HTML)
        return

    text = ''
    channel = Channels.get_or_none(Channels.tid == channel_id)
    if channel is not None:
        if channel.admin == user:
            text += f"{CURR_PRICE}\n\n"
            text += format_channel_info(channel)
            text += '\n\nWrite down new price'
        else:
            bot.send_message(chat_id=user.telegram_id,
                             text=PRICE_LIST_EXISTS,
                             reply_markup=back_keyboard,
                             parse_mode=ParseMode.HTML)
            return
    else:
        channel = Channels(tid=channel_id, admin=user)
        text = SEND_PRICE

    user_data['channel'] = channel
    bot.send_message(chat_id=user.telegram_id,
                     text=text,
                     reply_markup=back_keyboard,
                     parse_mode=ParseMode.HTML)
    return 'PRICE'