示例#1
0
def send_uptime():
    uptime = sh_utils.execute_command('uptime')
    uptime_pp = uptime[:uptime.find('  ') - 1].strip()
    uptime_pp = "Kolyan's computer uptime:\n%s" % uptime_pp

    # Send uptime information to main chat.
    bot.get_bot().send_to_main(uptime_pp)
示例#2
0
def add_reminder(message, args):
    name = message['id']
    user_id = message['user_id']

    vk_bot = bot.get_bot()

    msg_to_db = copy.deepcopy(message)

    if args.broadcast and args.user_id:
        raise RuntimeError(
            "Невозможно одновременно использовать -broadcast и -user-id"
        )

    if args.broadcast:
        msg_to_db['chat_id'] = vk_bot.main_chat['id']

    if args.user_id:
        msg_to_db['user_id'] = args.user_id

    reminder = reminders.add_reminder(
        msg_to_db,
        name,
        args.count,
        user_id,
        args.pattern,
        args.text
    )

    if not args.silent:
        vk_bot.answer_on_message(
            message,
            "Напоминалка создана; id = %s." % reminder.name
        )
示例#3
0
def send_weather(message, city):
    r = requests.get('http://wttr.in/%s' % city)
    parser = BeautifulSoup(r.content, "html5lib")
    text = parser.find('body').text

    if text.find('┌') == -1:
        raise RuntimeError(text)

    forecast = text[:text.find('┌')]

    forecast_array = forecast.split('\n')

    # Remove first 15 characters starting 3rd line.
    replacement = []
    for item in forecast_array[3:]:
        replacement += [item[15:]]

    replacement[0] = "Forecast:\t%s" % replacement[0]
    replacement[1] = "Temperature:\t%s" % replacement[1]
    replacement[2] = "Wind:\t\t%s" % replacement[2]
    replacement[3] = "Visibility:\t%s" % replacement[3]
    replacement[4] = "Precipitation:\t%s" % replacement[4]

    forecast_array[3:] = replacement

    forecast_array += ["Forecast is taken from wttr.in"]

    vk_bot = bot.get_bot()
    vk_bot.answer_on_message(message, '\n'.join(forecast_array))
示例#4
0
def remove_alias(message, args):
    user = message['user_id']
    id = args.id

    alias_service.delete_alias(user, id)

    vk_bot = bot.get_bot()
    vk_bot.answer_on_message(message, "Алиас удален.")
示例#5
0
def remove_reminder(message, args):
    name = args.id
    user = message['user_id']

    reminders.delete_reminder(name, user)

    vk_bot = bot.get_bot()
    vk_bot.answer_on_message(message, "Напоминалка удалена.")
示例#6
0
def send_euro_info(message=None):
    euro_info = utils.get_euro_info()

    text = (
        u"Курс евро на сегодня: %s.\n"
        u"Курс евро на завтра: %s"
        % (euro_info['today'], euro_info['tomorrow'])
    )

    if not message:
        bot.get_bot().send_to_main_picture(
            EURO_CHART_URL,
            text
        )
    else:
        bot.get_bot().answer_on_message(
            message,
            text,
            EURO_CHART_URL
        )
示例#7
0
    def decorator(message, args):
        if message['user_id'] != ADMIN_USER_ID:
            vk_bot = bot.get_bot()

            vk_bot.answer_on_message(
                message,
                "Только админы могут использовать данную команду."
            )
            return

        func(message, args)
示例#8
0
def send_dollar_info(message=None):
    dollar_info = utils.get_dollar_info()

    text = (
        u"Курс доллара на сегодня: %s.\n"
        u"Курс доллара на завтра: %s"
        % (dollar_info['today'], dollar_info['tomorrow'])
    )

    if not message:
        bot.get_bot().send_to_main_picture(
            DOLLAR_CHART_URL,
            text
        )
    else:
        bot.get_bot().answer_on_message(
            message,
            text,
            DOLLAR_CHART_URL
        )
示例#9
0
def hello(message, args):
    vk_bot = bot.get_bot()

    user_id = message['user_id']
    chat_id = message.get('chat_id')
    user_name = vk_bot.get_user_name(user_id)
    msg_to_send = "Hello, %s!" % user_name

    if args.private or not chat_id:
        # Send message directly.
        vk_bot.send_to(msg_to_send, user_id=user_id)
    else:
        vk_bot.send_to(msg_to_send, chat_id=chat_id)
示例#10
0
def help_message(message, args):
    vk_bot = bot.get_bot()

    cmds = SUB_PARSER._actions[1]

    output = []

    for cmd in cmds.choices:
        output += ["%s:" % cmd]
        output += cmds.choices[cmd].format_help().split('\n')[:-3]
        output += ['']

    vk_bot.answer_on_message(message, '\n'.join(output))
示例#11
0
def anekdot(message):
    vk_bot = bot.get_bot()

    resp = requests.get(ANEKDOT_URL, headers={'User-Agent': 'HTTPie/0.9.2'})
    parsed = BeautifulSoup(resp.content, "html5lib")

    anekdots = parsed.findAll('div', {'class': 'text'})

    if not anekdots:
        vk_bot.answer_on_message(message, "Страница с анекдотами недоступна")
        return

    anekdot = "\n".join(list(anekdots[0].strings))

    vk_bot.answer_on_message(message, anekdot)
示例#12
0
def process_commands():
    vk_bot = bot.get_bot()

    messages = vk_bot.wait_for_messages()

    for msg in messages:
        if utils.is_command(msg['body']):
            try:
                LOG.info("Executing command '%s'..." % msg['body'])
                commands.execute_cmd(msg, msg['body'])
            except Exception as e:
                e_msg = "'%s' cmd failed: %s" % (msg['body'], e.message)
                LOG.warn(e_msg)
                vk_bot.answer_on_message(msg, e_msg)

    if messages:
        vk_bot.mark_messages_as_read(messages)
示例#13
0
def show_help(message, args):
    parser = get_parser(message)
    vk_bot = bot.get_bot()

    if not args.command:
        help_str = parser.format_help()
        vk_bot.answer_on_message(message, help_str)

        return

    commands = parser._subparsers._actions[0]

    if args.command not in commands.choices:
        raise RuntimeError("Command does not exist: %s" % args.command)

    help_str = commands.choices[args.command].format_help()
    vk_bot.answer_on_message(message, help_str)
示例#14
0
def create_alias(message, args):
    name = args.name
    command = args.command
    user = message['user_id']

    if not is_command(command):
        raise RuntimeError("Некорректная команда для алиаса: %s" % command)

    if is_command(name):
        raise RuntimeError(
            "Имя алиаса пересекается с существующей командой: %s" % name
        )

    vk_bot = bot.get_bot()

    alias = alias_service.create_alias(name, command, user)

    vk_bot.answer_on_message(message, 'Алиас создан. id = %s.' % alias.id)
示例#15
0
def get_aliases(message, args):
    aliases = alias_service.get_aliases()

    vk_bot = bot.get_bot()

    if not aliases:
        vk_bot.answer_on_message(message, "Ещё нет алиасов.")
        return

    output = []
    for i, a in enumerate(aliases):
        output.append(
            "%s. %s, команда = '%s'" % (
                a.id,
                a.name,
                a.command
            )
        )

    vk_bot.answer_on_message(message, '\n'.join(output))
示例#16
0
def get_main_chat(message, args):
    vk_bot = bot.get_bot()

    chat = vk_bot.main_chat
    chat_id = chat['id']
    chat_name = chat['title']

    last_message = vk_bot.api.messages.getHistory(
        peer_id=2000000000 + int(chat_id),
        count=1,
        user_id=message['user_id'],
        v=5.38
    )['items'][0]

    last_update = datetime.datetime.fromtimestamp(int(last_message['date']))

    vk_bot.answer_on_message(
        message,
        "Main chat: %s. %s, Посл.обновление: %s" % (
            chat_id, chat_name, last_update
        )
    )
示例#17
0
def get_reminders(message, args):
    user_reminders = reminders.get_reminders(message['user_id'])

    vk_bot = bot.get_bot()

    if not user_reminders:
        vk_bot.answer_on_message(message, "Ещё нет напоминалок.")
        return

    output = []
    for index, r in enumerate(user_reminders):
        arguments = json.loads(r.arguments)
        output.append(
            "%s. %s, '%s', След.выполнение: %s"
            % (
                index + 1,
                r.name,
                arguments['text'],
                r.execution_time.strftime("%H:%M:%S, %d.%m.%Y")
            )
        )

    vk_bot.answer_on_message(message, '\n'.join(output))
示例#18
0
文件: test.py 项目: nmakhotkin/vk_bot
def main():
    vk_bot = bot.get_bot()

    LOG.info("Start test...")

    vk_bot.test()
示例#19
0
def cat(message):
    vk_bot = bot.get_bot()

    vk_bot.answer_on_message(message, "Котики", photo_url=CAT_URL)
示例#20
0
def rulez(message):
    vk_bot = bot.get_bot()

    vk_bot.answer_on_message(message, "Absolutely agree!")
示例#21
0
def send_no(message):
    vk_bot = bot.get_bot()

    vk_bot.answer_on_message(message, "", photo_url=random.choice(NO_URLS))
示例#22
0
文件: base.py 项目: nmakhotkin/vk_bot
 def setUp(self):
     self.bot = bot.get_bot()
示例#23
0
def cat(message):
    vk_bot = bot.get_bot()

    vk_bot.answer_on_message(message, "", doc_url=CAT_URL)
示例#24
0
def show_help(message, args):
    parser = get_parser(message)
    vk_bot = bot.get_bot()

    help = parser.format_help()
    vk_bot.answer_on_message(message, help)
示例#25
0
 def exit(self, status=0, message=None):
     if message:
         self._print_message(message, sys.stderr)
         bot.get_bot().answer_on_message(self.vk_message, message)
示例#26
0
def answer_on_message(message, text):
    vk_bot = bot.get_bot()

    vk_bot.answer_on_message(message, text)