Exemple #1
0
def admin_post(message):
    if len(message.text.split()) > 1:

        global_lock.acquire()
        if message.text.split()[1] == "edit":
            try:
                with open(config.file_location_lastbotpost,
                          'r',
                          encoding='utf-8') as file:
                    last_msg_id = int(file.read())
                my_edited_message = ' '.join(message.text.split()[2:])
                my_bot.edit_message_text(my_edited_message,
                                         config.my_chatID,
                                         last_msg_id,
                                         parse_mode="Markdown")
                user_action_log(
                    message, "has edited message {}:\n{}".format(
                        last_msg_id, my_edited_message))
            except (IOError, OSError):
                my_bot.reply_to(message, "Мне нечего редактировать.")
        else:
            my_message = ' '.join(message.text.split()[1:])
            sent_message = my_bot.send_message(config.my_chatID,
                                               my_message,
                                               parse_mode="Markdown")
            with open(config.file_location_lastbotpost, 'w',
                      encoding='utf-8') as file_lastmsgID_write:
                file_lastmsgID_write.write(str(sent_message.message_id))
            user_action_log(message,
                            "has posted this message:\n{}".format(my_message))
        global_lock.release()
    else:
        my_bot.reply_to(message, "Мне нечего постить.")
Exemple #2
0
def anti_disa(message):
    global_lock.acquire()
    try:
        with open(config.file_location_disa, 'r',
                  encoding='utf-8') as file_disa_read:
            disa_chromo = int(file_disa_read.read())
    except (IOError, OSError, ValueError):
        disa_chromo = 46
        pass
    disa_chromo -= 1

    with open(config.file_location_disa, 'w',
              encoding='utf-8') as file_disa_write:
        file_disa_write.write(str(disa_chromo))
    global_lock.release()
    user_action_log(message, "removed chromosome to Disa")
Exemple #3
0
def update_bot(message):
    if not hasattr(update_bot, "check_sure"):
        update_bot.check_sure = True
        return

    global_lock.acquire()
    try:
        file_update_write = open(config.bot_update_filename,
                                 'w',
                                 encoding='utf-8')
        file_update_write.close()
    except RuntimeError:
        pass
    global_lock.release()

    my_bot.reply_to(message, "Ух, ухожу на обновление...")
    user_action_log(message, "remotely ran update script.")
    os.execl('/bin/bash', 'bash', 'bot_update.sh')
Exemple #4
0
def kill_bot(message):
    if not hasattr(kill_bot, "check_sure"):
        kill_bot.check_sure = True
        return
    global_lock.acquire()
    try:
        file_killed_write = open(config.bot_killed_filename,
                                 'w',
                                 encoding='utf-8')
        file_killed_write.close()
    except RuntimeError:
        pass
    global_lock.release()

    my_bot.send_document(message.chat.id,
                         "https://t.me/mechmath/169445",
                         caption="Ухожу на отдых!",
                         reply_to_message_id=message.message_id)
    user_action_log(message, "remotely killed bot.")
    os._exit(0)
Exemple #5
0
def disa_vk_report(disa_chromo, message):
    login, password = tokens.vk_disa_login, tokens.vk_disa_password
    vk_session = vk_api.VkApi(login, password)
    vk_session.auth()
    vk = vk_session.get_api()
    wall = vk.wall.get(owner_id=config.vk_disa_groupID, count=1)
    if time.localtime(wall['items'][0]['date'])[2] == time.localtime()[2]:
        disa_chromo_post = disa_chromo - 46
        try:
            old_chromo = int(wall['items'][0]['text'])
            disa_chromo_post += old_chromo
        except Exception as ex:
            logging.error(ex)
            disa_chromo_post = disa_chromo
        vk.wall.edit(owner_id=config.vk_disa_groupID,
                     post_id=wall['items'][0]['id'],
                     message=str(disa_chromo_post))
    else:
        disa_chromo_post = 46 + disa_chromo
        vk.wall.post(owner_id=config.vk_disa_groupID,
                     message=str(disa_chromo_post))

    if 1 < disa_chromo - 46 % 10 < 5:
        chromo_end = "ы"
    elif disa_chromo - 46 % 10 == 1:
        chromo_end = "а"
    else:
        chromo_end = ""

    my_bot.reply_to(
        message, "С последнего репорта набежало {0} хромосом{1}.\n"
        "Мы успешно зарегистрировали этот факт: "
        "https://vk.com/disa_count".format((disa_chromo - 46), chromo_end))
    action_log("Disa summary printed")
    disa_chromo = 46
    global_lock.acquire()
    with open(config.file_location_disa, 'w',
              encoding='utf-8') as file_disa_write:
        file_disa_write.write(str(disa_chromo))
    global_lock.release()
    disa.disa_first = True
Exemple #6
0
def admin_post(message):
    if len(message.text.split()) > 1:

        global_lock.acquire()
        if message.text.split()[1] == "edit":
            try:
                with open(config.file_location['last_post'], 'r', encoding='utf-8') as file:
                    last_msg_id = int(file.read())
                my_edited_message = ' '.join(message.text.split()[2:])
                my_bot.edit_message_text(my_edited_message, config.mm_chat, last_msg_id, parse_mode="Markdown")
                user_action_log(message, "has edited message {}:\n{}".format(last_msg_id, my_edited_message))
            except (IOError, OSError):
                my_bot.reply_to(message, "Мне нечего редактировать.")
        else:
            my_message = ' '.join(message.text.split()[1:])
            sent_message = my_bot.send_message(config.mm_chat, my_message, parse_mode="Markdown")
            with open(config.file_location['last_post'], 'w', encoding='utf-8') as file_lastmsgID_write:
                file_lastmsgID_write.write(str(sent_message.message_id))
            user_action_log(message, "has posted this message:\n{}".format(my_message))
        global_lock.release()
    else:
        my_bot.reply_to(message, "Мне нечего постить.")
Exemple #7
0
def disa(message):
    if not hasattr(disa, "disa_first"):
        disa.disa_first = True
    if not hasattr(disa, "disa_bang"):
        disa.disa_bang = time.time()
    if not hasattr(disa, "disa_crunch"):
        disa.disa_crunch = disa.disa_bang + 60 * 60

    disa_init = False
    global_lock.acquire()
    # пытаемся открыть файл с количеством Дисиных хромосом
    try:
        with open(config.file_location_disa, 'r',
                  encoding='utf-8') as file_disa_read:
            disa_chromo = int(file_disa_read.read())
    except (IOError, OSError, ValueError):
        disa_chromo = 46
        pass
    disa_chromo += 1
    with open(config.file_location_disa, 'w',
              encoding='utf-8') as file_disa_write:
        file_disa_write.write(str(disa_chromo))
    global_lock.release()

    user_action_log(message, "added chromosome to Disa")
    if message.chat.type == "supergroup":
        if disa.disa_first:
            disa.disa_bang = time.time()
            disa.disa_crunch = disa.disa_bang + 60 * 60
            disa.disa_first = False
        elif (not disa.disa_first) and (time.time() >= disa.disa_crunch):
            disa_init = True

    # запись счетчика в вк
    if disa_init:
        disa_vk_report(disa_chromo, message)
Exemple #8
0
        time.sleep(1)

    # из-за Telegram API иногда какой-нибудь пакет не доходит
    except ReadTimeout as e:
        action_log("Read Timeout. Because of Telegram API. We are offline. Reconnecting in 5 seconds.")
        time.sleep(5)

    # если пропало соединение, то пытаемся снова
    except ConnectionError as e:
        action_log("Connection Error. We are offline. Reconnecting...")
        time.sleep(5)

    # если Python сдурит и пойдёт в бесконечную рекурсию (не особо спасает)
    except RecursionError as e:
        action_log("Recursion Error. Restarting...")
        global_lock.acquire()
        message_dump_lock.acquire()
        os._exit(0)

    # если Python сдурит и пойдёт в бесконечную рекурсию (не особо спасает)
    except RuntimeError as e:
        action_log("Runtime Error. Retrying in 3 seconds.")
        time.sleep(3)

    # кто-то обратился к боту на кириллице
    except UnicodeEncodeError as e:
        action_log("Unicode Encode Error. Someone typed in cyrillic. Retrying in 3 seconds.")
        time.sleep(3)

    # завершение работы из консоли стандартным Ctrl-C
    except KeyboardInterrupt as e:
Exemple #9
0
 def save(self):
     global_lock.acquire()
     with open(self.file_name, 'w', encoding='utf-8') as file:
         json.dump(self.data, file, indent=True)
     global_lock.release()
Exemple #10
0
 def load(self):
     if is_non_zero_file(self.file_name):
         global_lock.acquire()
         with open(self.file_name, 'r', encoding='utf-8') as file:
             self.data = json.load(file)
         global_lock.release()
Exemple #11
0
    # из-за Telegram API иногда какой-нибудь пакет не доходит
    except ReadTimeout as e:
        action_log(
            "Read Timeout. Because of Telegram API. We are offline. Reconnecting in 5 seconds."
        )
        time.sleep(5)

    # если пропало соединение, то пытаемся снова
    except ConnectionError as e:
        action_log("Connection Error. We are offline. Reconnecting...")
        time.sleep(5)

    # если Python сдурит и пойдёт в бесконечную рекурсию (не особо спасает)
    except RecursionError as e:
        action_log("Recursion Error. Restarting...")
        global_lock.acquire()
        message_dump_lock.acquire()
        os._exit(0)

    # если Python сдурит и пойдёт в бесконечную рекурсию (не особо спасает)
    except RuntimeError as e:
        action_log("Runtime Error. Retrying in 3 seconds.")
        time.sleep(3)

    # кто-то обратился к боту на кириллице
    except UnicodeEncodeError as e:
        action_log(
            "Unicode Encode Error. Someone typed in cyrillic. Retrying in 3 seconds."
        )
        time.sleep(3)
Exemple #12
0
def lock_function(fun,*args,**kwargs):
    global_lock.acquire()
    fun(*args,**kwargs)
    global_lock.release()
Exemple #13
0
def periodic_call(delay, func, *args, **kwargs):
    while True:
        global_lock.acquire()
        func(*args, **kwargs)
        global_lock.release()
        time.sleep(delay)