예제 #1
0
파일: tests.py 프로젝트: Luisgc98/Boticenv1
 def test_insert_bot(self):
     u = User(first_name='Anabel', last_name='Almaraz')
     u.set_user_secret('*****@*****.**')
     bot = Bot(name='botica-test', description='prueba', user=u)
     bot.set_bot_secret('botica-test')
     self.assertTrue(bot.user_id == u.id)
     self.assertTrue(bot.is_active == None)
예제 #2
0
def handle_client(sock, addr):
    """Send commands, receive responses and update database for a single bot"""
    try:
        b = Bot.query.filter_by(ip=addr[0]).one()
    except:
        b = Bot(ip=addr[0])
    if not addr[0] in queue.keys():
        queue.update({addr[0]:list()})
        b.sleep_interval = None
    b.last_seen_time = datetime.now()
    if b.os == None and not "get os" in queue[addr[0]]:
        queue[addr[0]].append("get os")
    if b.sleep_interval == None and not "get sleep" in queue[addr[0]]:
        queue[addr[0]].append("get sleep")
    db.session.add(b)
    db.session.commit()
    inp = select([sock], [], [], 1)
    if inp[0]:
        action(sock.recv(4096), b)
    if addr[0] in queue.keys() and len(queue[addr[0]]) != 0:
        cmd = queue[addr[0]][0]
        queue[addr[0]].remove(cmd)
        sock.send(cmd)
        b.current_command = cmd
        db.session.add(b)
        db.session.commit()
    sock.close()
예제 #3
0
파일: server.py 프로젝트: upkash/botnet
def initdb():
    db.drop_all()
    db.create_all()
    bot = Bot("1234")
    bot.ip = 'asdfas'
    db.session.add(bot)
    db.session.commit()
예제 #4
0
파일: views.py 프로젝트: Onapsis/pytron
def publish_bot(request):
    if request.is_ajax():
        user_prof = UserProfile.objects.get(user=request.user)
        new_bot_code = json.loads(request.body)['msg']

        if len(new_bot_code.strip('')) == 0:
            return HttpResponse("Can not publish an empty bot")

        # Get the last bot, and check delta
        try:
            latest_bot = Bot.objects.filter(owner=user_prof).latest('creation_date')
            if compare_bots(latest_bot.code, new_bot_code):
                error = "Can not publish this bot, looks like the previous one!"
                return HttpResponse(error)

        except ObjectDoesNotExist:
            # This is the first bot for this user
            pass

        bot = Bot()
        bot.owner = user_prof
        bot.code = new_bot_code
        bot.save()
        user_prof.current_bot = bot
        user_prof.my_buffer = new_bot_code
        user_prof.save()
    return HttpResponse(json.dumps({'success' : True}),
        mimetype='application/json')
예제 #5
0
파일: __init__.py 프로젝트: motord/banter
def populate():
    q=Channel.gql("WHERE id=:1", 'koan')
    channel=q.get()
    code="""
__author__ = 'peter'

from application import settings
import logging

MSG_TYPE_TEXT = u'text'
MSG_TYPE_LOCATION = u'location'
MSG_TYPE_IMAGE = u'image'

def process_text(remark, retort):
    if remark['content']:
        retort['content']='Bot Spawned!'
        retort['msgType']=MSG_TYPE_TEXT
        retort['funcFlag']=0
    return retort

def process_location(remark, retort):
    return retort

def process_image(remark, retort):
    return retort
    """
    bot=Bot(name=u'spawn', code=code, channel=channel.key)
    bot.put()
    return 'populated.'
예제 #6
0
def lookup_entity(query, exact=True):
    """
    Searches for a Bot or User contained in the query
    """
    if exact:
        try:
            return Bot.by_username(query, include_disabled=True)
        except Bot.DoesNotExist:
            pass

        try:
            return Bot.get(chat_id=int(query))
        except ValueError:
            pass
        except Bot.DoesNotExist:
            pass

        try:
            return User.by_username(query)
        except User.DoesNotExist:
            pass

        try:
            return User.get(chat_id=query)
        except User.DoesNotExist:
            pass
        return None
    def finish(self):
        # set last update
        self.channel.last_update = datetime.date.today()
        self._save_channel()

        new_bots = Bot.select_new_bots()
        if not self.silent and len(new_bots) > 0:
            self.notify_admin("Sending notifications to subscribers...")
            subscribers = Notifications.select().where(Notifications.enabled == True)
            notification_count = 0
            for sub in subscribers:
                try:
                    util.send_md_message(self.bot, sub.chat_id,
                                         messages.BOTLIST_UPDATE_NOTIFICATION.format(
                                             n_bots=len(new_bots),
                                             new_bots=Bot.get_new_bots_markdown()))
                    notification_count += 1
                    sub.last_notification = datetime.date.today()
                    sub.save()
                except TelegramError:
                    pass
            self.sent['notifications'] = "Notifications sent to {} users.".format(
                notification_count)

        changes_made = len(self.sent) > 1 or len(self.sent['category']) > 0
        if changes_made:
            text = util.success('{}{}'.format('BotList updated successfully:\n\n',
                                              mdformat.results_list(self.sent)))
        else:
            text = mdformat.none_action("No changes were necessary.")

        log.info(self.sent)
        self.bot.formatter.send_or_edit(self.chat_id, text, to_edit=self.message_id)
예제 #8
0
    def post_bot(payload):
        body = request.get_json()
        count = Bot.query.count()

        try:
            record = Bot(id=body.get('id'),
                         name=body.get('name'),
                         active=body.get('active'),
                         strategy_id=body.get('strategy_id'),
                         timeframe=body.get('timeframe'),
                         param_values=body.get('param_values').split(', '))
            record.insert()

            response = {
                'success': True,
                'id': record.id,
                'name': record.name,
                'active': record.active,
                'param_values': record.param_values,
                'timeframe': record.timeframe,
                'strategy_id': record.strategy_id
            }

            return jsonify(response), 200

        except Exception:
            abort(400)
예제 #9
0
def mybots(request):
    user_prof = UserProfile.objects.get(user=request.user)
    if request.method == 'POST':
        form = BotBufferForm(request.POST)
        if not form.is_valid():
            print "ERROR in form!"
            return
        new_code = form.cleaned_data['code']
        user_prof.code = new_code

        if 'publish_buffer' in request.POST:
            bot = Bot()
            bot.owner = user_prof
            bot.code = new_code
            bot.save()
            validate_bot.delay(bot.id, new_code)
            user_prof.current_bot = bot

        user_prof.save()
        return redirect('/mybots')
    else:
        form = BotBufferForm(instance=user_prof)

    return render(request, "my_bots.html", {
        'form': form,
        'user_prof': user_prof,
        'tab': 'mybots',
        'my_bots': reversed(Bot.objects.filter(owner=user_prof))
    })
예제 #10
0
    def post(self):
        """Creates a bot"""
        error_status = 0
        user = users.get_current_user()
        if not user:
            self.response.out.write("not registered in google")
        name = self.request.get('name')
        password = self.request.get('password')
        feed = self.request.get('feed')

        # Verify the account information
        gae_twitter = GAETwitter(username=name, password=password)
        verify_result = gae_twitter.verify()
        if (verify_result != True):
            error_status = error_status + 1

        # Verify the feed URL
        d = feedparser.parse(feed)

        if (d.bozo > 0):
            error_status = error_status + 2
        server_error = ""
        if (error_status == 0):
            bot = Bot(name=name, password=password, feed=feed)
            bot.user = user
            try:
                bot.put()
            except Exception, e:
                error_status |=  4
                server_error = str(e)
예제 #11
0
파일: views.py 프로젝트: excid3/irc_bothost
def common_new(request):
    port = 6667
    if request.POST:
        name = request.POST.get("name")
        server = request.POST.get("server")
        type = int(request.POST.get("type"))
        channels = request.POST.get("channels")
        port = request.POST.get("port")
        nick = name

        # Validate
        errors = {}
        if len(name) > 36 or len(name) < 1:
            errors["name"] = "Username must be 36 characters or less"
        # test name for invalid characters
        
        if Bot.objects.filter(name=name, server=server):
            errors["name"] = "Nick already taken on %s" % server
        
        if not isinstance(type, int):
            errors["type"] = "Invalid bot type"
            
        #TODO: Regex!
        if len(server) < 5:
            errors["server"] = "Invalid server name"

        #TODO: Better checking
        if len(channels) < 1:
            errors["channels"] = "Specify at least one channel"
        elif len(channels) > 2000:
            errors["channels"] = "Too many channels specified"
           
        if len(port) > 5:
            errors["port"] = "Invalid port number, 6667 is default"
            
        if not port:
            port = 6667
        port = int(port)

        if not errors:
            bot = Bot(owner=request.user, name=name, nick=nick, server=server, port=port, type=type, channels=channels, status=0)
            bot.save()

#            args = (type, bot.owner_id, name, server, port, channels)
            args = (server, port, nick, channels)

            # Create the bot on the daemon
            bus = dbus.SessionBus()
            service = bus.get_object('com.excid3.bothost', '/com/excid3/bothost')
            new_bot = service.get_dbus_method('new_bot', 'com.excid3.bothost')
            new_bot(type, bot.id, args)

            #TODO: Display a "successfully created" message at the top of the dashboard
            return HttpResponseRedirect("/")

    locals().update(bottypes=BOT_TYPES)            
    t = loader.get_template("common/new.html")
    c = RequestContext(request, locals())
    return HttpResponse(t.render(c))
def delete_bot(bot, update, to_edit: Bot):
    username = to_edit.username
    to_edit.disable(Bot.DisabledReason.banned)
    to_edit.save()
    bot.formatter.send_or_edit(update.effective_user.id,
                               "Bot has been disabled and banned.",
                               to_edit=util.mid_from_update(update))
    Statistic.of(update, 'disable', username, Statistic.IMPORTANT)
예제 #13
0
def _new_bots_text():
    new_bots = Bot.select_new_bots()
    if len(new_bots) > 0:
        txt = "Fresh new bots since the last update 💙:\n\n{}".format(
            Bot.get_new_bots_markdown())
    else:
        txt = 'No new bots available.'
    return txt
예제 #14
0
def create():
    data = request.json
    bot = Bot(name=data['name'],
              strategy=data['strategy'],
              notation=data['notation'])
    db.session.add(bot)
    db.session.commit()
    os.system("gnome-terminal -e 'sh scripts/create_bot.sh %r'" % bot.id)
    return json.dumps(bot.to_dict())
예제 #15
0
def new(request):
    if request.method == 'POST':
        form = BotForm(request.POST)
        if form.is_valid():
            bot = Bot(**form.cleaned_data)
            bot.save()
            return HttpResponseRedirect(bot.get_absolute_url())
    else:
        form = BotForm()
    return render_to_response('bots/new.html', {'form': form}, context_instance=RequestContext(request))
예제 #16
0
    def parse_bad_bots(self):
        """ Entry point """

        # The threshold confidence of the bot. If the bot confidence score is equal or higher than the threshold,
        # block the bot.
        bot_confidence_threshold = 7

        # Setup properties
        bot = Bot()
        bot.source_ip = str(
            self.event['requestContext']['identity']['sourceIp'])
        bot.source_ip_type = self.get_ip_type_by_address(bot.source_ip)
        bot.http_user_agent = str(self.event['headers']['User-Agent'])
        bot.http_method = str(self.event['httpMethod'])
        bot.http_body = str(self.event['body'])
        bot.http_query_string_parameters = str(
            self.event['queryStringParameters'])

        if bot.source_ip_type == self.SourceIPType.IPV4:
            bot.geolocation = self.get_geolocation(bot.source_ip)
        else:
            bot.geolocation = None

        # Do confidence check based on bot properties
        bot_confidence_score = self.check_bot_confidence(bot)

        # Was detected as bot? For diagnostics
        is_bot = False

        if bot_confidence_score >= bot_confidence_threshold:

            is_bot = True

            # Check the source IP type and then update the respective IP set
            if bot.source_ip_type == self.SourceIPType.IPV4:
                self.update_bad_bots_ip_set(
                    self.SourceIPType.IPV4,
                    [IPv4Network(bot.source_ip).with_prefixlen])
            if bot.source_ip_type == self.SourceIPType.IPV6:
                self.update_bad_bots_ip_set(
                    self.SourceIPType.IPV6,
                    [IPv6Network(bot.source_ip).with_prefixlen])

        bad_bots_output = {
            "source_ip": bot.source_ip,
            "source_ip_type": bot.source_ip_type.value,
            "is_bot": is_bot,
            "bot_confidence_score": bot_confidence_score
        }

        return bad_bots_output
예제 #17
0
    def update_bot_details(self, to_check: BotModel, peer):
        """
        Set basic properties of the bot
        """
        if isinstance(peer, ResolvedPeer):
            peer = self.resolve_peer(peer.peer.user_id)
        elif isinstance(peer, InputPeerUser):
            pass
        else:
            peer = self.resolve_peer(peer.id)

        try:
            user = self.send(GetUsers([peer]))[0]
        except:
            traceback.print_exc()
            print("this peer does not work for GetUsers:")
            print(type(peer))
            print(peer)
            return None

        if hasattr(user, 'bot') and user.bot is True:
            # Regular bot
            to_check.official = bool(user.verified)
            to_check.inlinequeries = bool(user.bot_inline_placeholder)
            to_check.name = user.first_name
            to_check.bot_info_version = user.bot_info_version
        else:
            # Userbot
            to_check.userbot = True
            to_check.name = helpers.format_name(user)

        # In any case
        to_check.chat_id = int(user.id)
        to_check.username = '******' + str(user.username)
예제 #18
0
 def add_bot(self, channel, name):
     channel = channel.lower()
     name = name.lower()
     try:
         Bot.get(Bot.name == name)
     except peewee.DoesNotExist:
         pass  # this seems really unpythonic somehow
     else:
         raise KeyError('Bot already exists')
     try:
         chan_o = Channel.get(Channel.name == channel)
     except peewee.DoesNotExist:
         chan_o = Channel.create(name=channel)
     Bot.create(name=name,
                channel=chan_o)
예제 #19
0
    def _execute_command(self,
                         command=None,
                         bot_name=None,
                         human=None,
                         status=None):

        if command in COMMANDS:
            bot = Bot(self.config['bots'][bot_name])
            if command == 'delete':
                bot.delete_status(status=status)
        else:
            api = self._get_api()
            api.send_direct_message(
                user_id=human,
                text="{0} command not found.".format(command))
예제 #20
0
def test_db():
    """
    Just a function used for debugging purposes. Ignore me!!! 
    """
    bot_ip = [
        '10.1.1.2', '10.1.1.3', '10.1.1.4', '10.1.1.5', '10.1.1.6', '10.1.1.7',
        '10.1.1.8', '10.2.1.2', '10.2.1.3', '10.2.1.4', '10.2.1.5', '10.2.1.6',
        '10.2.1.7', '10.2.1.8', '10.3.1.2', '10.3.1.3', '10.3.1.4', '10.3.1.5',
        '10.3.1.6', '10.3.1.7', '10.3.1.8', '10.4.1.2', '10.4.1.3', '10.4.1.4',
        '10.4.1.5', '10.4.1.6', '10.4.1.7', '10.4.1.8', '10.5.1.2', '10.5.1.3',
        '10.5.1.4', '10.5.1.5', '10.5.1.6', '10.5.1.7', '10.5.1.8', '10.6.1.2',
        '10.6.1.3', '10.6.1.4', '10.6.1.5', '10.6.1.6', '10.6.1.7', '10.6.1.8',
        '10.7.1.2', '10.7.1.3', '10.7.1.4', '10.7.1.5', '10.7.1.6', '10.7.1.7',
        '10.7.1.8', '10.8.1.2', '10.8.1.3', '10.8.1.4', '10.8.1.5', '10.8.1.6',
        '10.8.1.7', '10.8.1.8', '10.9.1.2', '10.9.1.3', '10.9.1.4', '10.9.1.5',
        '10.9.1.6', '10.9.1.7', '10.9.1.8', '10.10.1.2', '10.10.1.3',
        '10.10.1.4', '10.10.1.5', '10.10.1.6', '10.10.1.7', '10.10.1.8'
    ]
    hostname = [
        'annebonny', 'williamkidd', 'calicojack', 'maryread', 'edwardteach',
        'captaincrapo', 'canoot', 'nemo', 'gunner', 'laurellabonaire',
        'lockelamora', 'hook'
    ]
    bot_user = [
        'root', 'whiteteam', 'Administrator', 'duder', 'NT Authority\SYSTEM'
    ]
    bot_pid = '5000'

    counter = 0
    idx = 0
    for ip in bot_ip:
        counter += 1
        if counter % 8 == 0:
            idx += 1
        bot = Bot(ip, hostname[idx],
                  bot_user[random.randint(0,
                                          len(bot_user) - 1)],
                  random.randint(100, 20000))
        db.session.add(bot)
        db.session.commit()

    bot = Bot('10.1.1.2', 'annebonny', 'root', random.randint(100, 20000))
    db.session.add(bot)
    bot = Bot('10.1.1.2', 'annebonny', 'root', random.randint(100, 20000))
    db.session.add(bot)
    bot = Bot('10.1.1.2', 'annebonny', 'root', random.randint(100, 20000))
    db.session.add(bot)
    db.session.commit()
예제 #21
0
파일: tasks.py 프로젝트: xorduna/telemock
def random_replay(keyboard, chat, type='chat'):
    """
        when type=chat take create_message_response
        when type=callback_query take create_callback_query_response
    """
    # select random answer
    print(keyboard[0])
    #options = keyboard
    answer = random.choice(keyboard[0])
    if 'text' in answer:
        answer = answer['text']

    bot = Bot.get(chat['botname'])
    user = User.get(chat['username'])

    if type == 'chat':
        response = create_fake_message(user, bot, chat, answer)
    elif type == 'callback_query':
        text, data = answer['text'], answer['callback_data']
        response = create_callback_query_response(user, bot, text, data)
    else:
        raise ValueError("type must be chat or callback_query")

    logger.info('random_replay[type=%s] response: %s' % (type, response))
    # send random answer to the callback_url
    print(response)
    r = requests.post(bot['callback'], json=response)
    print(r.text)
예제 #22
0
def ping_bots_job(bot, job):
    bot_checker: BotChecker = job.context.get('checker')
    stop_event: threading.Event = job.context.get('stop')
    loop = bot_checker.event_loop

    all_bots = BotModel.select(BotModel).where(
        (BotModel.approved == True)
        &
        ((BotModel.disabled_reason == BotModel.DisabledReason.offline) |
         BotModel.disabled_reason.is_null())
    ).order_by(
        BotModel.last_ping.asc()
    )

    start = time.time()
    result = loop.run_until_complete(run(bot, bot_checker, all_bots, stop_event))  # type: Counter
    end = time.time()

    if not result:
        msg = "👎 BotChecker encountered problems."
    else:
        msg = "ℹ️ BotChecker completed in {}s:\n".format(round(end - start))
        for k, v in result.items():
            msg += "\n● {} {}".format(v, k)
    bot.send_message(settings.BOTLIST_NOTIFICATIONS_ID, msg)
    log.info(msg)
예제 #23
0
파일: tasks.py 프로젝트: xorduna/telemock
def send_message(chat, message):
    bot, user = Bot.get(chat['botname']), User.get(chat['username'])
    response = create_fake_message(user, bot, chat, message)
    logger.info('send message to bot response: %s' % (response))
    print(response)
    r = requests.post(bot['callback'], json=response)
    print(r.text)
예제 #24
0
def send_category(bot, update, chat_data, category):
    uid = util.uid_from_update(update)
    cid = update.effective_chat.id
    bots = Bot.of_category_without_new(
        category)[:settings.MAX_BOTS_PER_MESSAGE]
    bots_with_description = [b for b in bots if b.description is not None]
    detailed_buttons_enabled = len(
        bots_with_description) > 0 and util.is_private_message(update)

    callback = CallbackActions.SEND_BOT_DETAILS

    if detailed_buttons_enabled:
        buttons = [
            InlineKeyboardButton(
                x.username,
                callback_data=util.callback_for_action(callback, {"id": x.id}),
            ) for x in bots_with_description
        ]
    else:
        buttons = []
    menu = util.build_menu(buttons, 2)
    menu.insert(
        0,
        [
            InlineKeyboardButton(
                captions.BACK,
                callback_data=util.callback_for_action(
                    CallbackActions.SELECT_CATEGORY),
            ),
            InlineKeyboardButton(
                "Show in BotList",
                url="http://t.me/botlist/{}".format(
                    category.current_message_id),
            ),
            InlineKeyboardButton("Share", switch_inline_query=category.name),
        ],
    )
    txt = "There are *{}* bots in the category *{}*:\n\n".format(
        len(bots), str(category))

    if uid in settings.MODERATORS and util.is_private_message(update):
        # append admin edit buttons
        txt += "\n".join(["{} — /edit{} 🛃".format(b, b.id) for b in bots])
    else:
        txt += "\n".join([str(b) for b in bots])

    if detailed_buttons_enabled:
        txt += "\n\n" + util.action_hint(
            "Press a button below to get a detailed description.")

    reply_markup = InlineKeyboardMarkup(menu)
    reply_markup, callback = botlistchat.append_restricted_delete_button(
        update, chat_data, reply_markup)
    msg = bot.formatter.send_or_edit(cid,
                                     txt,
                                     to_edit=util.mid_from_update(update),
                                     reply_markup=reply_markup)
    callback(msg)
    Statistic.of(update, "menu", "of category {}".format(str(category)),
                 Statistic.ANALYSIS)
예제 #25
0
 def shutdown_and_redeploy(self):
     live_bots = self.fetch_live_bots()
     for bot in live_bots:
         allocation = bot.allocation
         name = Bot.get(id=bot.id).name
         self.shutdown_bot(name)
         self.start_bot(name, allocation)
예제 #26
0
 def shutdown_bot(self, name):
     b = Bot.get(name=name)
     settings = BotSettings.get(id=b.id)
     subprocess.Popen(["kill", "-9", str(settings.pid)])
     settings.bot_live = False
     settings.save()
     print("Killed bot: {}".format(name))
예제 #27
0
    def send_footer(self):
        num_bots = Bot.select_approved().count()
        self.notify_admin('Sending footer...')

        # add footer as notification
        footer = '\n```'
        footer += '\n' + mdformat.centered("• @BotList •\n{}\n{} bots".format(
            datetime.date.today().strftime("%Y-%m-%d"), num_bots))
        footer += '```'

        if self.resend or not self.silent:
            try:
                self._delete_message(self.channel.footer_mid)
            except BadRequest as e:
                pass
            footer_to_edit = None
        else:
            footer_to_edit = self.channel.footer_mid

        footer_msg = self.bot.formatter.send_or_edit(
            self.channel.chat_id,
            footer,
            to_edit=footer_to_edit,
            timeout=120,
            disable_notifications=self.silent,
            reply_markup=self.portal_markup)
        if footer_msg:
            self.channel.footer_mid = footer_msg.message_id
            self.sent['footer'] = "Footer sent"
        self._save_channel()
예제 #28
0
파일: decorators.py 프로젝트: motord/banter
 def decorated_view(*args, **kwargs):
     channel=kwargs['channel']
     bot=kwargs['bot']
     bot=Bot.gql("WHERE name = :1", bot).get()
     if bot:
         kwargs['bot']=bot
         return func(*args, **kwargs)
     return redirect(url_for('qq.list_bots', channel=channel.id))
예제 #29
0
파일: __init__.py 프로젝트: motord/banter
def create_bot(channel):
    form = BotForm()
    if form.validate_on_submit():
        bot = Bot(
            name = form.name.data,
            activated = form.activated.data,
            code = form.code.data,
            channel = channel.key
        )
        try:
            bot.put()
            flash(u'Bot %s successfully saved.' % bot.name, 'success')
            return redirect(url_for('qq.edit_bot', channel=channel.id, bot=bot.name))
        except CapabilityDisabledError:
            flash(u'App Engine Datastore is currently in read-only mode.', 'info')
            return redirect(url_for('qq.list_bots', channel=channel.id))
    return render_template("new_bot.html", channel=channel, form=form)
def test_new(client: BotIntegrationClient):
    uname = '@test__bot'
    try:
        try:
            b = Bot.get(username=uname)
            b.delete_instance()
        except Bot.DoesNotExist:
            pass

        res = client.send_command_await("new", [uname])
        if client.get_me().id in settings.MODERATORS:
            assert 'is currently pending' in res.full_text.lower()
            assert res.inline_keyboards[0].find_button(r'.*Accept.*')
        else:
            assert re.search('you submitted.*for approval', res.full_text, re.IGNORECASE)
    finally:
        Bot.delete().where(Bot.username == uname)
def send_random_bot(bot, update):
    from components.explore import send_bot_details

    random_bot = (Bot.select().where(
        (Bot.approved == True, Bot.disabled == False),
        (Bot.description.is_null(False)),
    ).order_by(fn.Random()).limit(1)[0])
    send_bot_details(bot, update, random_bot)
예제 #32
0
def get_status(bot_id):
    bot = Bot.query.get(bot_id)  #set bot equal to var
    if not bot:  #if doesnt exist then create new bot obj and add to db (new bot)
        bot = Bot(bot_id)
    info = request.get_json(
    )  #api call by post with json obj, update the db with the json obj
    print(info)
    if info:  #updates bot info each time
        if 'platform' in info:
            bot.os = info['platform']
        if 'hostname' in info:
            bot.hostname = info['hostname']
        if 'username' in info:
            bot.username = info['username']
    bot.ip = request.remote_addr  #update ip address and last ping to now
    bot.last_ping = datetime.now()
    db.session.add(bot)
    db.session.commit()
    pending_cmd = ''  #check if the bot has any commands pending, if so then delete it and return it
    cmd = bot.commands.order_by(Command.timestamp.desc()).first()
    if cmd:
        pending_cmd = cmd.cmd
        db.session.delete(cmd)
        db.session.commit()
    return pending_cmd
예제 #33
0
def _admin_buttons(send_botlist_button=False, logs_button=False):
    n_unapproved = len(Bot.select().where(Bot.approved == False,
                                          Bot.disabled == False))
    n_suggestions = len(Suggestion.select_all())
    n_pending = len(Bot.select_pending_update())

    second_row = list()
    if n_unapproved > 0:
        second_row.append(
            KeyboardButton(
                captions.APPROVE_BOTS +
                " {}🆕".format(mdformat.number_as_emoji(n_unapproved))))
    if n_suggestions > 0:
        second_row.append(
            KeyboardButton(
                captions.APPROVE_SUGGESTIONS +
                " {}⁉️".format(mdformat.number_as_emoji(n_suggestions))))

    buttons = [
        [KeyboardButton(captions.EXIT),
         KeyboardButton(captions.REFRESH)],
        [
            KeyboardButton(captions.FIND_OFFLINE),
            KeyboardButton(captions.SEND_CONFIG_FILES),
        ],
    ]

    update_row = list()
    if n_pending > 0:
        update_row.append(
            KeyboardButton(captions.PENDING_UPDATE + " {}{}".format(
                mdformat.number_as_emoji(n_pending),
                captions.SUGGESTION_PENDING_EMOJI,
            )))
    if send_botlist_button:
        update_row.append(KeyboardButton(captions.SEND_BOTLIST))
    if logs_button:
        update_row.append(KeyboardButton(captions.SEND_ACTIVITY_LOGS))

    if len(update_row) > 0:
        buttons.insert(1, update_row)
    if len(second_row) > 0:
        buttons.insert(1, second_row)

    return buttons
예제 #34
0
 def get(self):
     key = self.request.get('key')
     bot = Bot.get(key)
     template_values = {
         'bot': bot,
         'logout_url': users.create_logout_url("/"),
         }
     path = template_path("edit")
     self.response.out.write(template.render(path, template_values))
예제 #35
0
def apply_all_changes(bot, update, chat_data, to_edit):
    user = User.from_update(update)

    user_suggestions = Suggestion.select_all_of_user(user)
    for suggestion in user_suggestions:
        suggestion.apply()

    refreshed_bot = Bot.get(id=to_edit.id)
    edit_bot(bot, update, chat_data, refreshed_bot)
    Statistic.of(update, "apply", refreshed_bot.username)
def random_bot():
    """
    Returns a random bot from the BotList. By default, only "interesting" bots with description and tags are shown.
    Use the parameter `?all=True` to receive _all_ possible choices.
    """
    show_all = bool(request.args.get("all", False))

    if show_all:
        random_bot = Bot.select().order_by(fn.Random()).limit(1)[0]
    else:
        random_bot = random.choice(Bot.explorable_bots())
    data = random_bot.serialize

    if data:
        res = jsonify({'search_result': data, 'meta': {'url': request.url}})
        res.status_code = 200
    else:
        res = _error("No bot found.")
    return res
예제 #37
0
파일: tasks.py 프로젝트: xorduna/telemock
def start_chat(chat):
    bot, user = Bot.get(chat['botname']), User.get(chat['username'])
    print(bot)
    #response = create_message_response(user, bot, "/start")
    response = create_fake_message(user, bot, chat, "/start")

    logger.info('send START message to bot response: %s' % (response))
    print(response)
    r = requests.post(bot['callback'], json=response)
    print(r.text)
예제 #38
0
def bots(page):
    q = request.args.get('q', '', type=str)
    page = 1 if page is None else int(page)
    if q:
        bots, total = Bot.search(f'(user_id:{current_user.id}) AND {q}*', page,
                                 current_app.config['BOTS_PER_PAGE'])
        bots.total = total
    else:
        bots = get_bots(page)
    return render_template("fragments/bots.html", bots=bots)
예제 #39
0
def explore(bot, update, chat_data):
    cid = update.effective_chat.id
    uid = update.effective_user.id
    mid = util.mid_from_update(update)
    explorable_bots = Bot.explorable_bots()

    chat_data["explored"] = chat_data.get("explored", list())

    # don't explore twice
    for explored in chat_data["explored"]:
        explorable_bots.remove(explored)

    if len(explorable_bots) == 0:
        util.send_md_message(
            bot,
            cid,
            mdformat.none_action(
                "You have explored all the bots. Congratulations, you might be the first 😜"
            ),
        )
        return

    random_bot = random.choice(explorable_bots)

    buttons = [
        [
            InlineKeyboardButton(
                captions.ADD_TO_FAVORITES,
                callback_data=util.callback_for_action(
                    CallbackActions.ADD_TO_FAVORITES, {"id": random_bot.id}),
            ),
            InlineKeyboardButton(captions.SHARE,
                                 switch_inline_query=random_bot.username),
        ],
        [
            InlineKeyboardButton(
                random_explore_text(),
                callback_data=util.callback_for_action(
                    CallbackActions.EXPLORE_NEXT),
            )
        ],
    ]

    markup = InlineKeyboardMarkup(buttons)

    text = random_bot.detail_text

    if uid in settings.MODERATORS and util.is_private_message(update):
        text += "\n\n🛃 /edit{}".format(random_bot.id)

    msg = bot.formatter.send_or_edit(cid,
                                     text,
                                     to_edit=mid,
                                     reply_markup=markup)
    chat_data["explored"].append(random_bot)
예제 #40
0
def edit_bot(bot, update, chat_data, to_edit=None):
    uid = util.uid_from_update(update)
    message_id = util.mid_from_update(update)
    user = User.from_update(update)

    if not to_edit:
        if update.message:
            command = update.message.text

            if "edit" in command:
                b_id = re.match(r"^/edit(\d+)$", command).groups()[0]
            elif "approve" in command:
                b_id = re.match(r"^/approve(\d+)$", command).groups()[0]
            else:
                raise ValueError("No 'edit' or 'approve' in command.")

            try:
                to_edit = Bot.get(id=b_id)
            except Bot.DoesNotExist:
                update.message.reply_text(
                    util.failure("No bot exists with this id."))
                return
        else:
            bot.formatter.send_failure(uid, "An unexpected error occured.")
            return

    # if not to_edit.approved:
    #     return approve_bots(bot, update, override_list=[to_edit])

    pending_suggestions = Suggestion.pending_for_bot(to_edit, user)
    reply_markup = InlineKeyboardMarkup(
        _edit_bot_buttons(to_edit, pending_suggestions, uid
                          in settings.MODERATORS))
    pending_text = ("\n\n{} Some changes are pending approval{}.".format(
        captions.SUGGESTION_PENDING_EMOJI,
        "" if user.chat_id in settings.MODERATORS else " by a moderator",
    ) if pending_suggestions else "")
    meta_text = ("\n\nDate added: {}\nMember since revision {}\n"
                 "Submitted by {}\nApproved by {}".format(
                     to_edit.date_added,
                     to_edit.revision,
                     to_edit.submitted_by,
                     to_edit.approved_by,
                 ))
    bot.formatter.send_or_edit(
        uid,
        "🛃 Edit {}{}{}".format(
            to_edit.detail_text,
            meta_text if user.id in settings.MODERATORS else "",
            pending_text,
        ),
        to_edit=message_id,
        reply_markup=reply_markup,
    )
예제 #41
0
    def update_new_bots_list(self):
        text = self._read_file(self.NEW_BOTS_FILE)

        # insert spaces and the name of the bot
        new_bots_joined = Bot.get_new_bots_markdown()
        text = text.format(new_bots_joined)

        msg = self.send_or_edit(text, self.channel.new_bots_mid)
        self.sent['new_bots_list'] = "List of new bots sent"
        if msg:
            self.channel.new_bots_mid = msg.message_id
        self._save_channel()
예제 #42
0
파일: choir.py 프로젝트: motord/banter
def chant(remark):
    retort = {"toUser": remark["fromUser"], "fromUser": remark["toUser"], "createTime": int(time.time())}
    channel = remark["channel"]
    q = Bot.gql("WHERE channel = :1 AND activated = True", channel.key)
    for bot in q:
        module = LoadBot(channel, bot)
        retort = {
            MSG_TYPE_TEXT: module.process_text,
            MSG_TYPE_IMAGE: module.process_image,
            MSG_TYPE_LOCATION: module.process_location,
            MSG_TYPE_LINK: module.process_link,
            MSG_TYPE_EVENT: module.process_event,
        }[remark["msgType"]](remark, retort)
    retort["message"] = render_template("message.xml", message=retort)
    logging.info(retort["message"])
    return retort
예제 #43
0
파일: __init__.py 프로젝트: motord/banter
def list_bots(channel):
    """List channel bots"""
    bots = Bot.query(Bot.channel==channel.key)
    return render_template('list_bots.html', channel=channel, bots = bots)
예제 #44
0
def newbot(request):
    bot = Bot(name=request.GET['n'])
    bot.save()
    return HttpResponse("successfully created bot named '{1}' with id: {0}".format(bot.id, bot.name))
예제 #45
0
파일: choir.py 프로젝트: motord/banter
def ReloadAllBots(channel, bot):
    # Get the list of modules from the database and load them all
    q = Bot.gql("WHERE channel = :1 AND activated = True", channel.key)
    for bot in q:
        ReloadBot(channel, bot)