コード例 #1
0
ファイル: test_bot.py プロジェクト: EvaisaGiac/twitch-bot
    def test_blacklist_commands(self):
        dbPath = os.path.join(testPath, '__test_bot_blacklist_commands.sqlite')
        self._delete(dbPath)

        settings = Settings()
        settings.DATABASE_PATH = dbPath

        bot = Bot(settings,
                  None,
                  FakeWrapper,
                  logger=nullLogger,
                  wrap_irc=False)
        bot._initialize_models()
        bot._initialize_blacklists()

        lines = [
            "!blacklist foobar", "!blacklist --banTime=15m foobar2",
            "!unblacklist 1", "!unblacklist 2", "!whitelist foobar",
            "!unwhitelist 1"
        ]

        for line in lines:
            parts = line.split(" ")
            bot.irc_command("#tmp", "mod_user", parts[0][1:], parts[1:], 1)

        assert len(bot.blacklist_managers["#tmp"].blacklist) == 0
        assert len(bot.blacklist_managers["#tmp"].whitelist) == 0
コード例 #2
0
ファイル: ads_view.py プロジェクト: flavluc/flask_app
def show():
    if ("ad_id" in request.args):

        ad = Ad.query.filter_by(id=request.args['ad_id']).first()

        if not ad:
            flash("This is not a valid ID.")
            return render_template("show_error.html")

        bot = Bot()
        if (bot.get_ready()):

            bot.send_msg(ad.rate.comment)
            flash("Message sent successfully!")
            session['num_made_ads'] += 1
            session['comp'] = ""
            session['serv'] = ""
            if ("num_ads" in session and "num_made_ads" in session
                    and session['num_made_ads'] >= session['num_ads']):
                flash("You complete today's batch! Congragulations!")
                return redirect(url_for("ads.index"))

            else:
                return redirect(url_for("ads.handler"))

        else:

            flash("Fail send message, start the bot in the Telegram chat...")
            return render_template("show_error.html")

    else:
        flash("No ad ID specified")
        return render_template("show_error.html")
コード例 #3
0
ファイル: test_bot.py プロジェクト: EvaisaGiac/twitch-bot
    def test_quote_suffix(self):
        dbPath = os.path.join(testPath, '__test_bot_quote_suffix.sqlite')
        self._delete(dbPath)

        settings = Settings()
        settings.QUOTE_AUTO_SUFFIX = True

        now = datetime.now()
        expected_suffix = " - {streamer} @ {year}-{month:02}-{day:02}".format(
            streamer=settings.CHANNEL_LIST["#tmp"],
            year=int(now.strftime("%Y")),
            month=int(now.strftime("%m")),
            day=int(now.strftime("%d")))

        bot = Bot(settings,
                  None,
                  FakeWrapper,
                  logger=nullLogger,
                  wrap_irc=False)
        bot._initialize_models()
        bot._add_quote("#tmp", "foobar", ["test"], timestamp=now)
        quote_id, quote = bot._get_model("#tmp", "quotes").get_random_quote()

        expected = "test" + expected_suffix

        assert quote == expected
コード例 #4
0
ファイル: test_bot.py プロジェクト: EvaisaGiac/twitch-bot
    def test__is_allowed_to_run_command(self):
        bot = Bot()

        bot._get_user_level = Mock(return_value="user")
        assert bot._is_allowed_to_run_command("#a", "a", "addquote") is False
        assert bot._is_allowed_to_run_command("#a", "a", "delquote") is False
        assert bot._is_allowed_to_run_command("#a", "a", "quote") is False
        assert bot._is_allowed_to_run_command("#a", "a", "reg") is False
        assert bot._is_allowed_to_run_command("#a", "a", "def") is False

        bot._get_user_level = Mock(return_value="reg")
        assert bot._is_allowed_to_run_command("#a", "a", "addquote") is True
        assert bot._is_allowed_to_run_command("#a", "a", "delquote") is True
        assert bot._is_allowed_to_run_command("#a", "a", "quote") is True
        assert bot._is_allowed_to_run_command("#a", "a", "reg") is False
        assert bot._is_allowed_to_run_command("#a", "a", "def") is False

        bot._get_user_level = Mock(return_value="mod")
        assert bot._is_allowed_to_run_command("#a", "a", "addquote") is True
        assert bot._is_allowed_to_run_command("#a", "a", "delquote") is True
        assert bot._is_allowed_to_run_command("#a", "a", "quote") is True
        assert bot._is_allowed_to_run_command("#a", "a", "reg") is True
        assert bot._is_allowed_to_run_command("#a", "a", "def") is True

        bot._get_user_level = Mock(return_value="owner")
        assert bot._is_allowed_to_run_command("#a", "a", "addquote") is True
        assert bot._is_allowed_to_run_command("#a", "a", "delquote") is True
        assert bot._is_allowed_to_run_command("#a", "a", "quote") is True
        assert bot._is_allowed_to_run_command("#a", "a", "reg") is True
        assert bot._is_allowed_to_run_command("#a", "a", "def") is True
コード例 #5
0
ファイル: app.py プロジェクト: MichaelRabideau/slack-bot
def main():
    args = sys.argv
    if len(args) == 1 or args[1] == 'bot':
        bot = Bot()
        bot.run()
    else:
        app.run(threaded=True, port=config.PORT)
コード例 #6
0
ファイル: manage.py プロジェクト: ev0x/rowboat-rewrite-public
def bot_run(ctx, shard_count, no_auto_acquire, max_resources):
    from bot.bot import Bot
    try:
        bot = Bot(shard_count, not no_auto_acquire, max_resources)
        bot.run(ctx.obj['config'])
    except KeyboardInterrupt:
        del bot
コード例 #7
0
ファイル: driver.py プロジェクト: styx97/cp-discord-bot
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--log', default='WARNING')
    args = parser.parse_args()
    numeric_level = getattr(logging, args.log.upper(), None)
    if not isinstance(numeric_level, int):
        raise ValueError(f'Invalid log level: {args.log}')
    logging.basicConfig(format='{levelname}:{name}:{message}',
                        style='{',
                        level=numeric_level)

    discord_client = Client(DISCORD_TOKEN,
                            name=NAME,
                            activity_name=ACTIVITY_NAME)
    mongodb_connector = MongoDBConnector(MONGODB_SRV, DB_NAME)
    entity_manager = EntityManager(mongodb_connector)
    sites = [AtCoder(), CodeChef(), Codeforces()]
    site_container = SiteContainer(sites=sites)

    bot = Bot(NAME,
              discord_client,
              site_container,
              entity_manager,
              triggers=TRIGGERS,
              allowed_channels=CHANNELS)

    try:
        asyncio.run(bot.run())
    except Exception as ex:
        logger.exception('Grinding halt')
コード例 #8
0
    def test_punctuation_retry(self):
        """
        Test that bot finds tags that don't
        match because of punctuation, but would
        match otherwise.

        e.g. In the string, "You should look at :h help."
        """

        bot = Bot()
        tags = [
            "'formatlistpat'", "g:var", "c_CTRL-SHIFT-V", ":lhelpgrep",
            ":viusage", "quote.", "+extra", ":import-cycle"
        ]
        punct = [',', '.', ';', ':'] * 2
        text = "Test comment: "
        for tag, punct in zip(tags, punct):
            text = text + " :h " + tag + punct

        reply = bot.create_comment(text, "vim")
        self.assertNotEqual(reply, '')
        for tag in tags:
            self.assertIn(tag, reply)

        reply = bot.create_comment(text, "neovim")
        self.assertNotEqual(reply, '')
        for tag in tags:
            self.assertIn(tag, reply)
コード例 #9
0
def main():
    bot = Bot(token=TOKEN, name=NAME, version=VERSION)
    bot.dispatcher.add_handler(StartCommandHandler(callback=start_cb))
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(callback=buttons_answer_cb))
    bot.start_polling()
    bot.idle()
コード例 #10
0
ファイル: telegram.py プロジェクト: igorB88/pomodoro
    def post(self, request, token):

        try:
            raw = request.body.decode('utf8')
            logging.debug('Telegram raw data %s' % raw)
            update = json.loads(raw)
            if 'message' in update:
                data = message = update['message']
            elif 'callback_query' in update:
                data = update['callback_query']
                message = data['message']
            else:
                logging.error('Can not recognize update {}', update)
                raise TypeError('Not supported')

            current_user = get_telegram_from_seed(message)
            sender = Sender('telegram', current_user.user_id)
            bot = Bot(current_user, sender)
        except (TypeError, ValueError) as e:
            logging.exception("Can not decode message")
            return HttpResponse('Error')

        if token != settings.TELEGRAM_BOT_TOKEN:
            sender = Sender('telegram', current_user.user_id)
            sender.sendMessage('Our bot migrated to @{}'.format(
                settings.TELEGRAM_BOT_NAME),
                               token=token)
            return HttpResponse('ok')

        try:
            flavor = telepot.flavor(data)
            if flavor == 'chat':
                text = message.get('text', '') or message.get(
                    'contact', {}).get('phone_number')
                if not text:
                    return HttpResponse('ok')

                bot.on_chat_message(text)
            elif flavor == 'callback_query':
                msg_id = (data['from']['id'], data['message']['message_id'])
                query_id, from_id, query_data = telepot.glance(
                    data, flavor='callback_query')
                sender.msg_id = msg_id
                sender.query_id = query_id

                data = json.loads(query_data) if query_data else None
                if not data:
                    return HttpResponse('ok')

                bot.on_callback(data)
        except Exception:
            logging.exception('Error on handling bot message')
            try:
                sender.sendMessage('❌❌❌❌❌ Internal error',
                                   reply_markup=bot.get_menu())
            except Exception:
                logging.exception('Error on handling bot message error')

        return HttpResponse('ok')
コード例 #11
0
def main():
    token = os.environ.get('TOKEN', None)
    dbase = os.environ.get('DB', 'data.db')
    if token is None:
        print('Please set TOKEN as environment variable')
    else:
        obormot = Bot(token, dbase)
        obormot.start()
コード例 #12
0
def main():

    bot = Bot(USERNAME, PASSWORD)

    bot.explore_tags()
    bot.follow_users()
    bot.unfollow_users()
    print("All done!")
コード例 #13
0
    def test_url_encoding(self):
        """
        Test that bot url encodes /
        """

        bot = Bot()
        reply = bot.create_comment("`:h s/\\0`", "vim")
        self.assertIn("https://vimhelp.org/change.txt.html#s%2F%5C0", reply)
コード例 #14
0
def start_bots():
    bots = []
    for token in database.get_tokens():
        bot_token = Bot(token=token)
        if bot_token.self_get().json()['ok']:
            bots.append(bot_token)
    for bot in bots:
        bot = handler_bot(bot)
        bot.start_polling()
コード例 #15
0
ファイル: test_bot.py プロジェクト: EvaisaGiac/twitch-bot
 def test_unicode(self):
     settings = Settings()
     bot = Bot(settings,
               None,
               irc_wrapper=FakeWrapper,
               logger=nullLogger,
               wrap_irc=False)
     bot.command_managers["#tmp"] = FakeCommandManager()
     # This shouldn't crash
     bot.irc_command("#tmp", "test", "ヽ༼ຈل͜ຈ༽ノ", ["AMENO", "ヽ༼ຈل͜ຈ༽ノ"], 1)
コード例 #16
0
 def create_bot(self, protocol, username, password, server, port, channel):
     bot = Bot()
     bot.callback(self.receive)
     bot.new_connection(protocol,
                        username=username,
                        password=password,
                        server=server,
                        port=port,
                        channel=channel)
     self._bots[bot] = protocol
     return bot
コード例 #17
0
ファイル: icqnotify.py プロジェクト: viert/xc
def send(message):
    if not ICQ_TOKEN:
        raise RuntimeError("No ICQ_TOKEN variable defined")
    if not ICQ_CHAT_ID:
        raise RuntimeError("No ICQ_CHAT_ID variable defined")
    if not message:
        raise ValueError("message is empty")

    sys.stderr.write("using api base %s\n" % ICQ_API_URL)
    bot = Bot(token=ICQ_TOKEN, api_url_base=ICQ_API_URL)
    r = bot.send_text(chat_id=ICQ_CHAT_ID, text=message)
    sys.stderr.write("response was: %s\n" % r)
コード例 #18
0
    def test_empty_comment(self):
        """
        Test comment is empty if nothing is found
        """
        bot = Bot()
        comment = "Test comment `:h nothingtoseehere`"

        reply = bot.create_comment(comment, "link", "vim")
        self.assertEqual(reply, '')

        reply = bot.create_comment(comment, "link", "neovim")
        self.assertEqual(reply, '')
コード例 #19
0
ファイル: main.py プロジェクト: LouisAsanaka/PyChessBot
    def initialize_bot(self, width, height, top_left):
        # Instantiate a chessboard object (wrapper for a python-chess board)
        self.board = Chessboard(width, height, top_left, self.interface.color)
        self.analyzer = BoardAnalyzer(self.board, self.interface)
        self.bot = Bot(self.binary_dir, self.board,
                       self.analyzer.square_centers)

        if self.board.color == chess.WHITE:
            self.bot.play_move()
            self.analyzer.set_previous_state()
            self.loop()
        else:
            self.loop_initial_check()
コード例 #20
0
def main():
    TOKEN = "001.2422776034.0494128324:752509167"
    bot = Bot(token=TOKEN)

    bot.dispatcher.add_handler(MessageHandler(callback=message_cb))
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(callback=buttons_answer_cb))
    bot.dispatcher.add_handler(
        CommandHandler(command="total_rus", callback=get_info_about_russia))

    bot.start_polling()

    bot.idle()
コード例 #21
0
    def test_exact_match(self):
        """
        Test that it can find exact matches
        """

        bot = Bot()

        # TODO Add more tests
        tests = ["options", "E149", ":number", ":nu", "gj", "quickfix", "%:."]
        for t in tests:
            for subreddit in ["vim", "neovim"]:
                result = bot.search_tag(t, subreddit)
                self.assertEqual(len(result), 1)
コード例 #22
0
ファイル: quiz.py プロジェクト: yarvod/covidbot
def quiz():
    TOKEN = "001.3273522775.2055291012:752357883"

    bot = Bot(token=TOKEN)

    Data_1 = pd.read_excel('Questions 2.xlsx')

    Que = Data_1['Questions']
    ans1 = Data_1['Ans_1']
    ans2 = Data_1['Ans_2']
    ans3 = Data_1['Ans_3']
    for i in range(len(Data_1.iloc[1])):
        for j in range(len(Data_1['Ans_1'])):
            Data_1.iloc[j, i] = str(Data_1.iloc[j, i])

    def message_cb(bot, event):
        if '/q' in event.text:
            id_user = []
            que_user = []
            ans_user = []
            print("Let the quiz begin!")
            for i in range(len(Que)):
                k = i - 1
                if '/qz%d' % k in event.text:
                    bot.send_text(
                        chat_id=event.from_chat,
                        text='%s\n/qz%d1 %s \n/qz%d2 %s \n /qz%d3 %s' %
                        (Que[i], i, ans1[i], i, ans2[i], i, ans3[i]))
                    id_user.append(event.from_chat)
                    que_user.append(Que[i])
                    ans_user.append(event.text)

                elif '/qz%d' % (len(Que) - 1) in event.text:
                    bot.send_text(chat_id=event.from_chat, text='Вы молодец!')
                    id_user.append(event.from_chat)
                    que_user.append(Que[i])
                    ans_user.append(event.text)

                elif event.text == '/quiz' and i == 0:
                    bot.send_text(
                        chat_id=event.from_chat,
                        text='%s\n/qz%d1 %s \n/qz%d2 %s \n /qz%d3 %s' %
                        (Que[0], 0, ans1[0], 0, ans2[0], 0, ans3[0]))
                    id_user.append(event.from_chat)
                    que_user.append(Que[i])
                    ans_user.append(event.text)

    bot.dispatcher.add_handler(MessageHandler(callback=message_cb))

    bot.start_polling()
    bot.idle()
コード例 #23
0
ファイル: bot_test.py プロジェクト: wooque/social_network
 def test_generate_users_posts_data(self):
     bot = Bot()
     users = bot.generate_users_posts()
     self.assertEqual(len(users), bot.config.users)
     for u in users:
         self.assertEqual(
             sorted(u.keys()),
             sorted([
                 'username', 'email', 'password', 'first_name', 'last_name',
                 'posts'
             ]))
         self.assertLessEqual(len(u['posts']), bot.config.posts)
         for p in u.get('posts', []):
             self.assertEqual(p.keys(), ['text'])
コード例 #24
0
 def test_SMA20(self):
     return
     f = open(TEST_SMA_INPUT_FILE, "r")
     sys.stdin = StringIO(f.read())
     f.close()
     b = Bot()
     b.run()
     selected_candles = b.get_selected_candles(CurrencyEnum.USDT_ETH)[:20]
     closing_prices = []
     for candle in selected_candles:
         closing_prices.append(candle.close)
     mean = SMA.SMA(closing_prices)
     r = pd.Series(closing_prices)
     panda_means = r.rolling(window=20).mean()
     panda_mean = panda_means.tolist()[19]
     self.assertTrue(mean == panda_mean)
コード例 #25
0
ファイル: main.py プロジェクト: ksenull/zavalinka-game-bot
def main():
    config = configparser.ConfigParser()
    config.read('config.ini')
    debug = False
    if config['DEFAULT']['Debug'] == 'yes':
        config = config['DEBUG']
        debug = True
        logger.info('Using debug mode')
    else:
        config = config['PROD']
        logger.info('Using prod mode')

    with open(config.get('Token'), 'r') as f:
        TOKEN = f.readline()

    bot = Bot(TOKEN, pathlib.Path('assets'), debug=debug)
    bot.start()
コード例 #26
0
class MockBot(CustomMockMixin, unittest.mock.MagicMock):
    """
    A MagicMock subclass to mock Bot objects.

    Instances of this class will follow the specifications of `discord.ext.commands.Bot` instances.
    For more information, see the `MockGuild` docstring.
    """
    spec_set = Bot(command_prefix=unittest.mock.MagicMock(), loop=_get_mock_loop())
    additional_spec_asyncs = ("wait_for", "redis_ready")

    def __init__(self, **kwargs) -> None:
        super().__init__(**kwargs)

        self.loop = _get_mock_loop()
        self.api_client = MockAPIClient(loop=self.loop)
        self.http_session = unittest.mock.create_autospec(spec=ClientSession, spec_set=True)
        self.stats = unittest.mock.create_autospec(spec=AsyncStatsClient, spec_set=True)
コード例 #27
0
ファイル: test_bot.py プロジェクト: EvaisaGiac/twitch-bot
    def test_get_random_quote(self):
        dbPath = os.path.join(testPath, '__test_bot_get_random_quote.sqlite')
        self._delete(dbPath)

        settings = Settings()
        settings.DATABASE_PATH = dbPath

        bot = Bot(settings,
                  None,
                  FakeWrapper,
                  logger=nullLogger,
                  wrap_irc=False)
        bot._initialize_models()
        quote_id, quote = bot._get_model("#tmp", "quotes").get_random_quote()

        assert quote_id is None
        assert quote is None
コード例 #28
0
def main(sysargv: List[str] = None) -> None:
    """
    This function will initiate the bot and start the trading loop.
    :return: None
    """

    arguments = Arguments(sysargv)
    args = arguments.get_parsed_arg()
    configuration = Configuration(args)

    # Setup the bot
    setup.setup_database(configuration.get_config())

    # Create the bot
    bot = Bot(configuration.get_config())

    # Start all the services
    service_manager = ServiceManager(bot)
コード例 #29
0
ファイル: main.py プロジェクト: cancinconntg/telegram-CallBOT
def main():

    print("Creating the scheduler...")
    scheduler = BackgroundScheduler()
    scheduler.start()

    print("Connecting to the database...")
    db_client = MongoClient(MONGO_URI)
    database = db_client[DB_NAME]

    print("Instantiating the Pyrogram bot client...")
    pyrogram_bot_client = Client(session_name=BOT_SESSION_NAME,
                                 api_id=APP_ID,
                                 api_hash=APP_HASH)

    print("Instantiating the Pyrogram user client...")
    pyrogram_user_client = Client(session_name=USER_SESSION_NAME,
                                  api_id=APP_ID,
                                  api_hash=APP_HASH)

    voip_service = VoIPFileStreamService(pyrogram_user_client,
                                         receive_calls=False)

    print("Instantiating the bot...")

    # prov test group. TODO manage with database and admin commands.
    whitelist = []
    with open("whitelist", "r+") as f:
        for line in f.readlines():
            whitelist.append(int(line))

    bot = Bot(
        name=BOT_NAME,
        user_name=USER_NAME,
        bot_client=pyrogram_bot_client,
        user_client=pyrogram_user_client,
        database=database,
        scheduler=scheduler,
        voip_service=voip_service,
        whitelisted_chats=whitelist,
    )

    bot.load_modules(submodule_advanced_calls=True)
    bot.run()
コード例 #30
0
ファイル: test_bot.py プロジェクト: EvaisaGiac/twitch-bot
    def test_update_global_value(self):
        dbPath = os.path.join(testPath,
                              '__test_bot_update_global_value.sqlite')
        self._delete(dbPath)

        settings = Settings()
        settings.DATABASE_PATH = dbPath

        bot = Bot(settings,
                  None,
                  FakeWrapper,
                  logger=nullLogger,
                  wrap_irc=False)
        bot._initialize_models()
        bot.update_global_value("#tmp", "test", {"key1": "value1"})

        data = bot._load_channel_data("#tmp")

        assert data["test"]["key1"] == "value1"