Esempio n. 1
0
async def wiki(message: types.Message):
    log(message)
    response = requests.get(
        "https://en.wikipedia.org/w/api.php?action=query&list=search&format=json&srsearch="
        + message.get_args())
    pages = create_data_list(response.json()['query']['search'], 'title')
    kb = create_inline_keyboard(pages, pages)
    await bot.send_message(message['chat']['id'],
                           "/wiki " + message.get_args() +
                           "\nWhich of these wikipedia pages do you mean?",
                           reply_markup=kb)
Esempio n. 2
0
    async def execute(cls, m: Message, state=None, **kwargs):
        user = m.from_user
        player = Player(tg_id=user.id)
        if not player.alive:
            await m.answer('%s мёртв.' % user.get_mention(player.name))
            return

        args = m.get_args()
        m.text = '/action' + ' type:f**k '
        m.text += args or 'поебаться |'
        await cls.execute_action(m)
Esempio n. 3
0
    async def test_filter_not_forwarded_messages(self):
        filter = ForwardedMessageFilter(is_forwarded=False)

        forwarded_message = Message(forward_date=round(
            datetime(2020, 5, 21, 5, 1).timestamp()),
                                    **MESSAGE)

        not_forwarded_message = Message(**MESSAGE)

        assert await filter.check(not_forwarded_message)
        assert not await filter.check(forwarded_message)
Esempio n. 4
0
async def set_name(message: types.Message):
    print(message.from_user['id'])
    print(message.get_args())
    if message.get_args() == '' or None:
        await message.answer("эммм. Пусто как-бы!")
    elif (db.exists(message.from_user['id']) == None):
        db.add_name(tg_id=message.from_user['id'], name=message.get_args())
        await message.answer("я тебя запомню, можешь скинуть фото")
    else:
        await message.answer(
            "эммм, я тебя и так знаю, но если хочешь сменить имя просто напиши /rename"
        )
Esempio n. 5
0
async def cmd_feedback(message: types.Message) -> None:
    rmsg = message.reply_to_message
    if (message.chat.id < 0 and not message.get_command().partition("@")[2]
            and (not rmsg or rmsg.from_user.id != BOT_ID) or message.forward_from):
        return
    arg = message.get_full_command()[1]
    if not arg:
        await message.reply("Function: Send feedback to my owner.\n"
                            "Usage: `/feedback@on9wordchainbot feedback`")
        return
    await message.forward(ADMIN_GROUP_ID)
    await message.reply("Feedback sent successfully.")
Esempio n. 6
0
async def handle_pause(message: types.Message):
    """ Turn the volume up/down. """
    # TODO Show keyboard
    if message.get_command() == '/vol_up':
        print('Volume up')
        audioplayer.volume_up()
    elif message.get_command() == '/vol_down':
        print('Volume down')
        audioplayer.volume_down()
    else:
        msg = "Volume command not valid"
    await bot.send_message(message.chat.id, msg)
Esempio n. 7
0
async def suggest(message: types.Message):
    log(message)
    global suggestions
    write_to(message['from']['username'] + ": " + message.get_args() + '\n',
             "suggestions.txt")
    suggestions.append(message['from']['username'] + ": " +
                       message.get_args() + '\n')
    await bot.send_message(
        chat_with_rudy_id, 'New suggestion\n\n' + message['from']['username'] +
        ': ' + message.get_args())
    await bot.send_message(
        message['chat']['id'], message['from']['username'] +
        ', your suggestion, "' + message.get_args() + '", has been saved.')
Esempio n. 8
0
    async def check(self, message: types.Message):
        check = await super(CommandStart, self).check(message)

        if check and self.deep_link is not None:
            if not isinstance(self.deep_link, re.Pattern):
                return message.get_args() == self.deep_link

            match = self.deep_link.match(message.get_args())
            if match:
                return {'deep_link': match}
            return False

        return check
Esempio n. 9
0
    async def test_callback_query_reserve_book(self):
        """Reserve state main message"""
        test_message = Message()
        test_message.chat = self.chat
        test_message.from_user = self.user
        test_message.message_id = 122

        test_callback_query = CallbackQuery()
        test_callback_query.message = test_message

        await self.callback_query_reserve_book(test_callback_query)
        passed, alert = self.assert_params(self.result_text,
                                           "Callback: reserve book")
        assert passed, alert
Esempio n. 10
0
    async def execute(cls, m: Message):
        player = Player(tg_id=m.from_user.id)
        lover_player = Player(tg_id=m.reply_to_message.from_user.id)

        can_date = await player.can_date(m.chat.id, lover_player)

        if not can_date['result']:
            await m.answer(player.cant_date_reason_exaplanation[can_date['reason']])
            return

        args = m.get_args()
        m.text = '/action' + ' type:dating '
        m.text += args or 'выстречаться |'
        await cls.execute_action(m)
Esempio n. 11
0
async def set_data(m: Message):
    global mailing_data

    if m.text:
        mailing_data.text = m.text
    elif m.photo:
        mailing_data.photo_id = m.photo[0].file_id
        mailing_data.caption = m.caption
    else:
        await m.answer('Некорректное сообщение')
        return

    m.set_action_path('/mailing_verify')

    await m.answer('Напишите "Старт" - чтобы начать рассылку, или "Отмена"')
Esempio n. 12
0
async def process_start_command(message: types.Message):
    if len(message.get_args()) != 0:
        contents = requests.get(
            f'{scathachBase}/{api.yande()}/?tags={message.get_args()}').json()
        getItem = contents['url']
        if not getItem:
            await bot.send_message(message.from_user.id,
                                   text=decorator.ErrorFlag())
            logger.info(decorator.badrequestMsg() + message.get_args())
        else:
            await bot.send_message(message.from_user.id, text=getItem)
            logger.info(decorator.successMsg() + message.get_args())

    else:
        await message.answer(decorator.ngaturArgs())
Esempio n. 13
0
async def process_start_command(message: types.Message):
    if len(message.get_args()) != 0:
        contents = requests.get(
            f'https://nekos.life/api/v2/img/{message.get_args()}').json()
        try:
            getItem = contents['url']
            await bot.send_animation(message.from_user.id, getItem)
            logger.info(decorator.successMsg() + message.get_args())

        except:
            await bot.send_message(message.from_user.id,
                                   text=decorator.ErrorFlag())
            logger.info(decorator.badrequestMsg() + message.get_args())
    else:
        await message.answer(decorator.ngaturArgs() + "\n" + decorator.nekos())
Esempio n. 14
0
    async def execute(cls, m: Message):
        player = Player(tg_id=m.from_user.id)
        partner_player = Player(tg_id=m.reply_to_message.from_user.id)

        can_marry = await player.can_marry(m.chat.id, partner_player)

        if not can_marry['result']:
            await m.answer(
                player.cant_marry_reason_exaplanation[can_marry['reason']])
            return

        args = m.get_args()
        m.text = '/action' + ' type:marriage '
        m.text += args or 'тебе свои руку и сердце |'
        await cls.execute_action(m)
Esempio n. 15
0
async def on_spam(f, message: types.Message):
    """
	что делать если тебя начинают заёбывать

	:param f: команда, которую насилуют
	:param message: собсна, сообщение адресованное боту
	"""
    import numpy as np
    try:
        await np.choice([[lambda: None], [lambda: message.reply('Я занят.')],
                         [lambda: message.reply('Заёбывай другого бота')]],
                        [200, 5 * spam[f][1], 1 * spam[f][1]])[0]()
        spam[f][1] = 0
    except TypeError:  # cannot await None
        pass
Esempio n. 16
0
async def start_mess_deeplink_m(message: types.Message):
    await r.write_user(message.chat.id)
    arg = message.get_args()
    await message.answer(
        'Ошибка в ссылке:\n'
        'https://t.me/apkxalvabot?start={}\n\nОбратитесь к администратору @bondiwest'
        .format(arg))
Esempio n. 17
0
async def start_mess_deeplink_m(message: types.Message):
    await r.write_user(message.chat.id)
    arg = message.get_args()
    await message.answer(
        '<b>Вы должны быть подписаны на канал</b> https://t.me/joinchat/AAAAAEXiHrMBos4MiA8UOg\n\n'
        'Подпишитесь на канал и запустите бота по ссылке:\n'
        'https://t.me/apkxalvabot?start={}'.format(arg))
Esempio n. 18
0
async def send_welcome(message: types.Message):
    if message.is_command() and message.text == '/help':
        await message.reply(
            "List of available commands:\n "
            "1. /help: Showing this message.\n"
            "2. /start: Starting bot query for your session.\n"
            "3. /weather <Your city or country>: Finding information about weather in "
            "your country or city.\n"
            "4. /top <film genre>: Will show top10 films of current genre."
            "\tAvailable chooses: \n"
            "Horrors, Fantastic, Shooters, Thrillers, Comedy's, Melodramas, Dramas"
        )
    else:
        if db.get("{}".format(message.from_user.id)) is not None:
            await message.reply("You've already started bot!\n"
                                "Your session will expire in: "
                                "{} seconds.".format(
                                    db.ttl(message.from_user.id)))
            return
        db.setex(message.from_user.id, timedelta(days=10), value="active")
        log.info('User: {username} registered with ID: {id}'.format(
            username=message.from_user.username, id=message.from_user.id))
        await message.reply("Hello! 😺 \n"
                            "My name is Riven and that's my async bot!\n"
                            "To see list of available commands type: /help")
Esempio n. 19
0
async def top_films_with_genre(message: types.Message):
    """
    Horrors: id1,
    Fantastic: id2,
    Shooters: id3,
    Thrillers: id4,
    Comedy's: id6,
    Melodramas: id7,
    Dramas: id8
    :param message:
    :return:
    """
    if message.is_command() and len(message.text) == 0:
        await message.reply(
            "There is no filter for films object. Sending top 20 random films!"
        )
        return
    films = OrderedDict()
    films['horrors'] = '1'
    films['fantastic'] = '2'
    films['shooters'] = '3'
    films['thrillers'] = '4'
    films['comedy'] = '6'
    films['melodramas'] = '7'
    films['dramas'] = '8'
    async with aiohttp.ClientSession() as session:
        data = await pregMatch(message.text.lower(), films)
        url = "https://www.kinopoisk.ru/top/id_genre/{id}/".format(id=data)
        list_data = await films_data(url, session)
        print(list_data)
    await message.reply("Films by your request:\n\n" + ",\n".join(list_data))
Esempio n. 20
0
async def register_user(message: types.Message):
    chat_id = message.from_user.id
    referral = message.get_args()
    user = await db.add_new_user(referral=referral)
    id = user.id
    count_users = await db.count_users()

    # Отдадим пользователю клавиатуру с выбором языков
    languages_markup = InlineKeyboardMarkup(inline_keyboard=[[
        InlineKeyboardButton(text="Русский 🇷🇺", callback_data="lang_ru")
    ], [
        [InlineKeyboardButton(text="O'zbek 🇺🇿", callback_data="lang_uz")],
    ]])

    bot_username = (await bot.me).username
    bot_link = f"https://t.me/{bot_username}?start={id}"

    # Для многоязычности, все тексты, передаваемые пользователю должны передаваться в функцию "_"
    # Вместо "текст" передаем _("текст")

    text = _("Приветствую вас!!\n"
             "Сейчас в базе {count_users} человек!\n"
             "\n"
             "Ваша реферальная ссылка: {bot_link}\n"
             "Проверить рефералов можно по команде: /referrals\n"
             "Просмотреть товары: /items").format(count_users=count_users,
                                                  bot_link=bot_link)
    if message.from_user.id == admin_id:
        text += _("\n" "Добавить новый товар: /add_item")
    await bot.send_message(chat_id, text, reply_markup=languages_markup)
Esempio n. 21
0
 async def check(self, message: types.Message):
     payload = message.get_args()
     if not payload:
         return
     cmd, payload = decode_deep_link(payload)
     if cmd == self.deep_link:
         return {'payload': payload}
Esempio n. 22
0
 async def test_start_command_payload_pattern_is_matched(self):
     test_filter = CommandStart(deep_link=self.GOOD_PATTERN)
     message = Message(text=f'{self.START} {self.GOOD}')
     result = await test_filter.check(message)
     assert isinstance(result, dict)
     match = result.get('deep_link')
     assert isinstance(match, Match)
Esempio n. 23
0
async def cmd_donate(message: types.Message) -> None:
    if message.chat.id < 0:
        await message.reply(
            "Slide into my DMs to donate!",
            reply_markup=types.InlineKeyboardMarkup(
                inline_keyboard=[
                    [
                        types.InlineKeyboardButton(
                            "Donate in private",
                            url="https://t.me/on9wordchainbot?start=donate",
                        )
                    ]
                ]
            ),
        )
        return
    arg = message.get_args()
    if not arg:
        await send_donate_msg(message)
    else:
        try:
            amt = int(Decimal(arg).quantize(Decimal("1.00")) * 100)
            assert amt > 0
            await send_donate_invoice(message.chat.id, amt)
        except (ValueError, InvalidOperation, AssertionError):
            await message.reply("Invalid amount.\nPlease enter a positive number.")
        except BadRequest as e:
            if str(e) == "Currency_total_amount_invalid":
                await message.reply(
                    "Sorry, the entered amount was not in range (1-10000). " "Please try another amount."
                )
                return
            raise
Esempio n. 24
0
async def cmd_stats(message: types.Message) -> None:
    rmsg = message.reply_to_message
    if (message.chat.id < 0 and not message.get_command().partition("@")[2]
            or rmsg and (rmsg.from_user.is_bot and rmsg.from_user.id != ON9BOT_ID and not rmsg.forward_from
                         or rmsg.forward_from and rmsg.forward_from.is_bot and rmsg.forward_from.id != ON9BOT_ID)):
        return
    user = rmsg.forward_from or rmsg.from_user if rmsg else message.from_user
    async with pool.acquire() as conn:
        res = await conn.fetchrow("SELECT * FROM player WHERE user_id = $1;", user.id)
    if not res:
        await message.reply(f"No statistics for {user.get_mention(as_html=True)}!", parse_mode=types.ParseMode.HTML)
        return
    await message.reply(
        f"\U0001f4ca Statistics for "
        + user.get_mention(name=user.full_name + (" \u2b50\ufe0f" if user.id in VIP or bool(await amt_donated(user.id))
                                                  else ""), as_html=True)
        + f":\n"
          f"<b>{res['game_count']}</b> games played\n"
          f"<b>{res['win_count']} ("
          f"{'0%' if not res['win_count'] else format(res['win_count'] / res['game_count'], '.0%')})</b> games won\n"
          f"<b>{res['word_count']}</b> total words played\n"
          f"<b>{res['letter_count']}</b> total letters played"
        + (f"\nLongest word used: <b>{res['longest_word'].capitalize()}</b>" if res["longest_word"] else ""),
        parse_mode=types.ParseMode.HTML
    )
Esempio n. 25
0
async def welcome_security_handler_pm(message: Message,
                                      strings,
                                      regexp=None,
                                      state=None,
                                      **kwargs):
    args = message.get_args().split('_')
    chat_id = int(args[1])

    async with state.proxy() as data:
        data['chat_id'] = chat_id
        data['msg_id'] = int(args[3])
        data['to_delete'] = bool(int(args[4])) if len(args) > 4 else True

    db_item = await get_greetings_data(chat_id)

    level = db_item['welcome_security']['level']

    if level == 'button':
        await WelcomeSecurityState.button.set()
        await send_button(message, state)

    elif level == 'math':
        await WelcomeSecurityState.math.set()
        await send_btn_math(message, state)

    elif level == 'captcha':
        await WelcomeSecurityState.captcha.set()
        await send_captcha(message, state)
Esempio n. 26
0
async def cmd_server(message: types.Message):
    args = message.get_args()
    if not args:
        await message.reply("Please send command.")
        return
    responce = RCONCommandSender.send(args)
    await message.reply(responce or "No responce.")
Esempio n. 27
0
async def welcome_security_handler_pm(message: Message,
                                      strings,
                                      regexp=None,
                                      state=None,
                                      **kwargs):
    args = message.get_args().split("_")
    chat_id = int(args[1])

    async with state.proxy() as data:
        data["chat_id"] = chat_id
        data["msg_id"] = int(args[3])
        data["to_delete"] = bool(int(args[4])) if len(args) > 4 else True

    db_item = await get_greetings_data(chat_id)

    level = db_item["welcome_security"]["level"]

    if level == "button":
        await WelcomeSecurityState.button.set()
        await send_button(message, state)

    elif level == "math":
        await WelcomeSecurityState.math.set()
        await send_btn_math(message, state)

    elif level == "captcha":
        await WelcomeSecurityState.captcha.set()
        await send_captcha(message, state)
Esempio n. 28
0
async def bot_start(message: types.Message, state: FSMContext):
    yo=message.get_args()
    try:
        id = message.from_user.id
        referal = int(yo)
        try:
            # config.allowed_user.append(id)
            await db.add_user(id=id,name=message.from_user.full_name,
                                  balance=0, referal=referal)

            friend = await db.select_user(id=referal)
            summa = int(friend['balance'])
            new = summa + 760
            await db.update_balance(balance=new, id=referal)
        except:
            pass
        await message.answer('Вы добавлены в базу данных \n'
                                     'Для продолжения нажмите \n'
                                     '\n'
                                     '/start')
        await state.finish()


    except:
        await message.answer(f'Привет {message.from_user.full_name}! \n'
                         f'Бот работает только по приглашениям или коду \n'
                         f'Введите код :')
        await state.set_state('code')
Esempio n. 29
0
async def query_database(message: types.Message):
    argument = message.get_args()
    Session = sessionmaker(bind=engine)
    session = Session()
    if len(argument) > 0:

        date = datetime.datetime.date(dateparser.parse(argument))
        #logging.info("Requesting tasks for date", date)
        response = session.query(Task).filter(Task.date == date).order_by(
            Task.id_).all()
    else:

        response = session.query(Task).order_by(Task.id_).all()
    #print("RESPONSE", response)
    if len(response) == 0:
        await message.answer("Нет добавленных задач")
    else:
        keyboard = types.InlineKeyboardMarkup()

        #keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)
        for index, t_ in enumerate(response):
            button = types.InlineKeyboardButton(
                f"({t_.id_}). {str(t_.date)}, {t_.task} {emojize(map_priority_to_unicode[t_.priority])}",
                callback_data=t_.id_)
            keyboard.add(button)

        await message.answer("Нажмите на текст задачи, чтобы ее изменить",
                             reply_markup=keyboard)
        await ManageTasks.waiting_for_task_choice.set()
Esempio n. 30
0
async def begin(message: types.Message, state: FSMContext):
    yo = message.get_args()
    print(yo)
    try:
        if len(yo) == 5:
            item_id = int(yo)
            product = await com.one_item(id=item_id)
            text = f"Вы выбрали {product['name']}! Хороший выбор"
            photo = product['photo']
            await message.answer_photo(photo=photo, caption=text, reply_markup=buy_keyboard(item_id=item_id))
            await state.update_data(id=item_id)
        else:
            one = await db.select_user(id=message.from_user.id)
            for param in one:
                balance = one['balance']
            bot_user = await dp.bot.get_me()
            deep_link = f"http://t.me/{bot_user.username}?start={message.from_user.id}"
            await message.answer(f'Привет {message.from_user.first_name}! \n'
                             f'Твой Баланс составляет : {balance} Рублей \n'
                             f'Пригласи друга с помощью ссылки и получи скидку 10$ на следующую покупку:\n'
                             f'{deep_link}',
                             reply_markup=InlineKeyboardMarkup(
                                 inline_keyboard=[
                                     [
                                         InlineKeyboardButton(text='Перейти к покупке',
                                                              switch_inline_query_current_chat='')
                                     ]
                                 ]
                             ))
    except:
        pass