Example #1
0
    def test(self):
        command = StatsCommand()
        self.bot.get_updates = MagicMock(return_value=[self.fake_update()])
        command.reply_stats = MagicMock()
        update_event = self.bot.get_updates().pop()
        update_event.message.reply_text = MagicMock(return_value=None)

        context = MagicMock()
        context.bot = self.bot

        command.can_get_stats = MagicMock(return_value=True)
        command.handler(update_event, context)

        # case when there is exactly one human in the entire pool
        command.reply_stats.assert_called_with(update_event.message, 100.0, 1,
                                               0.0, 0, ["unknown: 100.00%"])

        # Create required db records for calculating stats
        channel = Channel.query.filter_by(chat_id="1").first()
        random_human_1 = Human(user_id="3", user_name="tt", country_code="us")
        random_human_2 = Human(user_id="4", user_name="tt", country_code="us")
        random_human_3 = Human(user_id="5", user_name="tt")
        random_bot_1 = Bot(user_id="5", user_name="tt")
        random_bot_2 = Bot(user_id="6", user_name="tt")
        random_bot_3 = Bot(user_id="7", user_name="tt")
        random_bot_4 = Bot(user_id="8", user_name="tt")
        db.session.add(random_human_1)
        db.session.flush()
        db.session.add(random_human_2)
        db.session.flush()
        db.session.add(random_human_3)
        db.session.flush()
        db.session.add(random_bot_1)
        db.session.flush()
        db.session.add(random_bot_2)
        db.session.flush()
        db.session.add(random_bot_3)
        db.session.flush()
        db.session.add(random_bot_4)
        db.session.flush()

        command.handler(update_event, context)
        # can get stats
        command.reply_stats.assert_called_with(
            update_event.message, 50.0, 4, 50.0, 4,
            ["unknown: 50.00%", "us: 50.00%"])

        # can't get stats
        command.can_get_stats = MagicMock(return_value=False)

        command.handler(update_event, context)

        update_event.message.reply_text.assert_called()
        self.assertEqual(update_event.message.reply_text.call_count, 1)
        update_event.message.reply_text.assert_has_calls(
            [call("You don't have permission to get stats")])
def db_first_insert_run(twitter_screen_name):
    if not twitter_screen_name:
        print('--twitter_screen_nameオプションを指定し実行してください。@以下のユーザー名です。')
        return

    try:
        # user
        password = generateRandomString(8)
        user = User.create('admin', password, 1)

        # bot
        twitter_user = usersShow(screen_name=twitter_screen_name)
        bot = Bot.create(owner_id=user.id,
                         twitter_user_id=twitter_user.getUser().getUserId(),
                         screen_name=twitter_screen_name)

        # commit
        db.session.commit()
        print('初期データ挿入成功。\nuser_name : ' + user.name + '\npassword : '******'APIアクセスでHTTPErrorが発生しました。エラーコード:{err.code}')
        raise err

    except Exception as exce:
        db.session.rollback()
        print(exce)
        print('初期データ挿入失敗。')
Example #3
0
def post_bot(id=0):
    incoming = request.get_json()
    print(incoming)
    new_rules = incoming["rules"]
    bot = Bot.query.get(id)
    if bot:
        bot.name = incoming["bot"]["name"]
        bot.prefix = incoming["bot"]["prefix"]
        bot.user_id = incoming["bot"]["userId"]
        bot.description = incoming["bot"]["description"]
        bot.is_draft = incoming["bot"]["isDraft"]
        for old_rule in bot.rules:
            db.session.delete(old_rule)
        for new_rule in new_rules:
            new_rule_content = json.dumps(new_rule["content"])
            db.session.add(Rule(content=new_rule_content, bot_id=bot.id))
    else:
        bot = Bot(name=incoming["bot"]["name"],
                  prefix=incoming["bot"]["prefix"],
                  user_id=incoming["bot"]["userId"],
                  description=incoming["bot"]["description"],
                  is_draft=incoming["bot"]["isDraft"])
        db.session.add(bot)
        db.session.commit()
        print(bot)
        for new_rule in new_rules:
            new_rule_content = json.dumps(new_rule["content"])
            db.session.add(Rule(content=new_rule_content, bot_id=bot.id))
    db.session.commit()
    return jsonify(True)
Example #4
0
def create_bot():
    role_bot = SystemRole.query.filter_by(name=role_bot_name).first()
    user_bot = SystemUser(login=bot_login_dump_creator,
                          password='******',
                          system_role=role_bot,
                          enabled=True)
    bot = Bot(fio='создатель дампов', system_user=user_bot)
    db.session.add(user_bot)
    db.session.add(bot)
    db.session.commit()
def add(data):
    form = BotForm()
    if form.validate_on_submit():
        try:
            bot = Bot(name=form.name.data,
                      year_of_birth=form.year_of_birth.data,
                      sex=form.sex.data)
            db.session.add(bot)
            db.session.commit()
        except IntegrityError:
            flash('Bot already exists')
    return redirect(url_for('bots'))
Example #6
0
def register_bot():
    form = RegistrationBotForm()
    if form.validate_on_submit():
        role_bot = SystemRole.query.filter_by(name=role_bot_name).first()
        user_bot = SystemUser(login=form.login.data, password=form.password.data, system_role=role_bot,
                              enabled=form.enabled.data)
        bot = Bot(fio=form.fio.data, system_user=user_bot)
        db.session.add(user_bot)
        db.session.add(bot)
        flash('бот {} создан.'.format(form.login.data))
        return redirect(url_for('.bots_list'))
    return render_template('users/form_register_edit.html', form=form, class_name='бота', creating=True)
Example #7
0
def syncTwitterBotData(bot: Bot):
    error_text = 'データの同期に失敗しました。表示されている情報はtwitterで閲覧できる情報と相違がある可能性があります。'
    try:
        response = usersShow(user_id=bot.twitter_user_id)
    except urllib.error.HTTPError as err:
        text = getHttpErrorText(err)
        flash(error_text)
    except Exception as err:
        flash(error_text)
    else:
        # 同期した内容でDBを更新
        twitter_user_data = response.getUser()
        profile_image_url = twitter_user_data.getProfileImageUrlHttps(
        ).replace('_normal', '')
        bot.update(screen_name=twitter_user_data.getScreenName(),
                   profile_name=twitter_user_data.getUserName(),
                   url=twitter_user_data.getUrl(),
                   location=twitter_user_data.getLocation(),
                   description=twitter_user_data.getDescription(),
                   profile_image_url=profile_image_url)
        db.session.commit()
Example #8
0
def create_bot():
    require_login()

    schema = {
        "type": "object",
        "properties": {
            "name": {
                "type": "string",
                "minLength": 1,
                "maxLength": 30
            },
            "game_id": {
                "type": "integer"
            },
        },
        "required": ["name", "game_id"]
    }
    req = get_json_request(schema)
    name, game_id = req["name"], req["game_id"]

    bot = get_bot(name=name, fail=False)
    if bot is not None:
        ErrorMessage.BOT_NAME_ALREADY_EXISTS.abort(name=name)

    game = get_game(id=game_id)

    token = generate_token()
    bot = Bot(name=name,
              rank=DEFAULT_RANK,
              owner=cur_user(),
              game=game,
              access_token=token)
    db.session.add(bot)
    db.session.commit()

    return {"bot": bot.to_json(owner=True, game=True), "access_token": token}
Example #9
0
def newbot():
    user = User.query.filter_by(username=current_user.username).first()
    if user.userlevel == 1:
        form = NewbotForm()
        if form.validate_on_submit():
            bot = Bot(botname=form.botname.data,
                      botdescription=form.botdescription.data)
            db.session.add(bot)
            db.session.commit()
            flash('Se ha registrado un nuevo Bot en la aplicación')
            return redirect(url_for('main.bot', botname=bot.botname))
        return render_template('newbot.html',
                               title='Registrar nuevo Bot',
                               form=form)
    return redirect(url_for('main.index'))
def _assign_bots(data):
    form = RandomBotForm()
    conversation = Conversations.query.filter_by(
        token=repr(form.conversation.data)).first()
    if form.validate_on_submit():
        if form.options.data:
            bots = Bot.query.filter_by(sex=form.sex.data, default=True).filter(
                Bot.year_of_birth >= int(form.date_range_start.data),
                Bot.year_of_birth <= int(form.date_range_end.data)).order_by(
                    func.random()).limit(int(form.amount.data)).all()
        else:
            bots = Bot.query.filter_by(default=True).order_by(
                func.random()).limit(int(form.amount.data)).all()

        for bot in bots:
            if form.participant_id.data:
                new_bot = Bot(name=randomize_bot_names(bot.name),
                              year_of_birth=bot.year_of_birth,
                              sex=bot.sex,
                              default=False)
                conversation.bot.append(new_bot)
                print(new_bot)
            else:
                conversation.bot.append(bot)
            db.session.add(conversation)
            db.session.commit()

    tmpl = """
        {% import 'bootstrap/wtf.html' as wtf %}
                 <p><button type="button" class="btn btn-default pull-right" hx-target="#status_response" hx-post="{{ url_for('_kill', conversation=conversation.token)}}">Disconnect All</button></p>
                 <br>
                 <br>
                 <hr>
                 <h3>{{conversation.name}}</h3> 
                 <pre id="status_response"></pre>
                 <table class="table table-striped">
                     <thead>
                     <th>Name</th>
                     <th>Emojis</th>
                     <th>Messages</th>
                     <th>Actions</th>
                     </thead>
                     {% for bot in conversation.bot %}
                    <tr id="bot_{{bot.id}}">
                     <td hx-post="{{ url_for('_heartbeat', conversation=conversation.token, id=bot.name)}}" hx-swap="innerHTML" hx-target="#bot_status_{{bot.id}}"  hx-trigger="every 30s">{{bot}} <span id="bot_status_{{bot.id}}"><i class="fas fa-spinner fa-spin"></i></td>
                     <td><div class="btn-group" role="group">
                     <button type="button" class="btn btn-default" hx-target="#status_response" hx-post="{{ url_for('_post_emoji', channel=conversation.token, botname=bot.name, message='�')}}">�</button>
                     <button type="button" class="btn btn-default" hx-target="#status_response" hx-post="{{ url_for('_post_emoji', channel=conversation.token, botname=bot.name, message='😀')}}">😀</button>
                     </div>
                     </td>
                     <td>
                      <form method="POST" action="{{ url_for('_post_message',channel=conversation.token, botname=bot.name, message=selectMessageForm) }}">
                     <small>{{selectMessageForm.message}}</small>

                     <button class="btn btn-default btn-xs" hx-target="#status_response" hx-post="{{ url_for('_post_message',channel=conversation.token, botname=bot.name, message=selectMessageForm) }}" value="Send">Send</button>

                     </form>
                     </td>
                     <td> <div class="btn-group" role="group">
                         <button type="button" class="btn btn-default" hx-target="#bot_status_{{bot.id}}" hx-swap="innerHTML" hx-post="{{ url_for('_join', channel=conversation.token,botname=bot.name)}}">
                            <i class="fas fa-phone"></i>

                         </button>
                        <button type="button" class="btn btn-default" hx-target="#bot_{{bot.id}}" hx-swap="outerHTML" hx-post="{{ url_for('_delete_bot_from_conversation', id=bot.id, conversation=conversation.token)}}">
                            <i class="far fa-trash-alt"></i>
                         </button>
                         </div>
                     </td>
                    </tr>
                     {% endfor %}
                 </table>               
               """
    return render_template_string(tmpl,
                                  conversation=conversation,
                                  selectMessageForm=SelectMessageForm())
import csv
from app import app, db
from app.models import Bot
from sqlalchemy.exc import IntegrityError

with open('bot_names.csv', 'r', encoding='utf-8') as f:
    reader = csv.reader(f, delimiter=',')
    next(reader)

    for name, year_of_birth, sex in reader:
        try:
            bot = Bot(name=name,
                      year_of_birth=year_of_birth,
                      sex=sex,
                      default=True)
            db.session.add(bot)
            db.session.commit()
        except IntegrityError:
            print(f'{name} already exists')
            db.session.rollback()
            continue
Example #12
0
    def test(self):
        command = LeftChatMemberFilter()
        chat = Chat(id=1, type="supergroup", title="channel 1")
        not_added_chat = Chat(id=2, type="supergroup", title="channel 2")

        channel = Channel.query.filter_by(chat_id="1").first()
        random_user_1 = User(id=111,
                             first_name="tt",
                             user_name="test",
                             is_bot=False)
        random_user_2 = User(id=112,
                             first_name="tt",
                             user_name="test1",
                             is_bot=False)
        random_bot_1 = User(id=11,
                            first_name="tt",
                            user_name="test2",
                            is_bot=True)
        random_bot_2 = User(id=12,
                            first_name="tt",
                            user_name="test3",
                            is_bot=True)

        # Create required db records
        human_1 = Human(user_id="111", user_name="tt")
        human_2 = Human(user_id="112", user_name="tt")
        bot_1 = Bot(user_id="11", user_name="tt")
        bot_2 = Bot(user_id="12", user_name="tt")
        db.session.add(human_1)
        db.session.flush()
        human1_id = human_1.id
        db.session.add(human_2)
        db.session.flush()
        human2_id = human_2.id
        db.session.add(bot_1)
        db.session.flush()
        bot1_id = bot_1.id
        db.session.add(bot_2)
        db.session.flush()
        bot2_id = bot_2.id
        # Add memberships
        db.session.add(
            HumanChannelMember(human_id=human1_id, channel_id=channel.id))
        db.session.add(
            HumanChannelMember(human_id=human2_id, channel_id=channel.id))
        db.session.add(BotChannelMember(bot_id=bot1_id, channel_id=channel.id))
        db.session.add(BotChannelMember(bot_id=bot2_id, channel_id=channel.id))

        bot_user = self.bot

        self.bot.get_updates = MagicMock(return_value=[
            # handle case when the bot leave
            self.fake_update(left_chat_member=bot_user, chat=chat),
            # handle case when a random bot leave
            self.fake_update(left_chat_member=random_bot_1, chat=chat),
            # handle case when a random user leave
            self.fake_update(left_chat_member=random_user_1, chat=chat),
            # handle case when channel doesn't exists
            self.fake_update(left_chat_member=bot_user, chat=not_added_chat),
        ])

        context = MagicMock()
        context.bot = self.bot

        # handle case when channel doesn't exists
        command.handler(self.bot.get_updates().pop(), context)
        self.assertTrue(Channel.query.filter_by(chat_id="1").one_or_none())

        # handle case when a random user leave
        command.handler(self.bot.get_updates().pop(), context)
        self.assertTrue(Channel.query.filter_by(chat_id="1").one_or_none())
        self.assertFalse(
            HumanChannelMember.query.filter_by(
                channel_id=channel.id, human_id=human1_id).one_or_none())
        self.assertTrue(
            HumanChannelMember.query.filter_by(
                channel_id=channel.id, human_id=human2_id).one_or_none())

        # handle case when a random bot leave
        command.handler(self.bot.get_updates().pop(), context)
        self.assertTrue(Channel.query.filter_by(chat_id="1").one_or_none())
        self.assertFalse(
            BotChannelMember.query.filter_by(channel_id=channel.id,
                                             bot_id=bot1_id).one_or_none())
        self.assertTrue(
            BotChannelMember.query.filter_by(channel_id=channel.id,
                                             bot_id=bot2_id).one_or_none())

        # handle case when the bot leave (channel get removed from the database)
        command.handler(self.bot.get_updates().pop(), context)
        self.assertFalse(Channel.query.filter_by(chat_id="1").one_or_none())
        self.assertFalse(
            HumanChannelMember.query.filter_by(
                channel_id=channel.id, human_id=human2_id).one_or_none())
        self.assertFalse(
            BotChannelMember.query.filter_by(channel_id=channel.id,
                                             bot_id=bot2_id).one_or_none())
Example #13
0
    user1 = User(username="******",
                 email="*****@*****.**",
                 password="******")
    user2 = User(username="******",
                 email="*****@*****.**",
                 password="******")
    user3 = User(username="******",
                 email="*****@*****.**",
                 password="******")
    user4 = User(username="******",
                 email="*****@*****.**",
                 password="******")

    bot1 = Bot(user_id=1,
               name="fakebot1",
               prefix="!",
               description="The first fake bot ever here",
               is_draft=False)
    bot2 = Bot(user_id=2,
               name="fakebot2",
               prefix="@",
               description="The second fake bot ever here",
               is_draft=False)
    bot3 = Bot(user_id=3,
               name="fakebot3",
               prefix="#",
               description="The third fake bot ever here",
               is_draft=False)
    bot4 = Bot(user_id=4,
               name="fakebot4",
               prefix="//",