Esempio n. 1
0
def sendWatcherUpdates(chatId, tickets):
    if len(tickets) > 0:
        debugLog("New tickets in watcher ({0}), sending updates...".format(
            len(tickets)))
        for ticket in tickets:
            if ticket.executors[0] is not None:
                executors = ""

                for i in range(0, len(ticket.executors)):
                    if len(
                            ticket.executors
                    ) - 1 == i:  # if i is the last element, we do not want the comma
                        executors += "{0}".format(ticket.executors[i])
                    else:
                        executors += "{0}, ".format(ticket.executors[i])

                bot.send_message(
                    chat_id=chatId,
                    parse_mode="markdown",
                    text=
                    "*№:* [{0}](https://jack-it.intraservice.ru/Task/View/{0})\n*Создатель:* {1} ({2})\n*Название:* {3}\n*Описание:* {4}\n*Исполнители:* {5}"
                    .format(ticket.id, ticket.creatorName,
                            ticket.creatorCompanyName, ticket.title,
                            ticket.description, executors))
            else:
                bot.send_message(
                    chat_id=chatId,
                    parse_mode="markdown",
                    text=
                    "*№:* [{0}](https://jack-it.intraservice.ru/Task/View/{0})\n*Создатель:* {1} ({2})\n*Название:* {3}\n*Описание:* {4}"
                    .format(ticket.id, ticket.creatorName,
                            ticket.creatorCompanyName, ticket.title,
                            ticket.description))
def authUser(telegramUsername):
    userExist = runQuery(
        "SELECT EXISTS (SELECT 1 FROM users WHERE telegramUsername = '******' LIMIT 1);"
        .format(telegramUsername))[0][0]
    if userExist == 1:
        debugLog("User {0} demanded auth - ACCEPTED".format(telegramUsername))
        return True
    if userExist == 0:
        debugLog("User {0} demanded auth - DENIED".format(telegramUsername))
        return False
def addNewUser(telegramUsername, name=""):
    userExist = runQuery(
        "SELECT EXISTS (SELECT 1 FROM users WHERE telegramUsername = '******' LIMIT 1);"
        .format(telegramUsername))[0][0]
    if userExist == 0:  # 0 - user not exists, 1 - user exists
        runQuery("INSERT INTO users (telegramUsername) VALUES ('{0}')".format(
            telegramUsername))
        debugLog("new user {0} ({1})".format(name, telegramUsername))
        return "ok"
    elif userExist == 1:
        return "exists"
def removeChatToWatch(chatId):
    chatExist = runQuery(
        "SELECT EXISTS (SELECT 1 FROM chats WHERE chatId = '{0}' LIMIT 1);".
        format(chatId))[0][0]
    if chatExist == 1:  # 0 - not exist, 1 - exist
        runQuery("DELETE FROM chats WHERE chatId = '{0}'".format(chatId))
        runQuery("DELETE FROM tickets WHERE chatId = '{0}'".format(chatId))
        debugLog("\tchat {0} removed.".format(chatId))
        return 'removed'
    elif chatExist == 0:
        debugLog("\tchat {0} is not present in watcher list.".format(chatId))
        return 'wasnot'
def addChatToWatch(chatId):
    chatExist = runQuery(
        "SELECT EXISTS (SELECT 1 FROM chats WHERE chatId = '{0}' LIMIT 1);".
        format(chatId))[0][0]
    if chatExist == 0:  # 0 - not exist, 1 - exist
        runQuery("INSERT OR IGNORE INTO chats (chatId) VALUES ('{0}')".format(
            chatId))
        debugLog("\tchat {0} added.".format(chatId))
        return "added"
    elif chatExist == 1:
        debugLog("\tchat {0} already added to watcher.".format(chatId))
        return "already"
def sendWatcherUpdates(chatId, tickets):
    if len(tickets) > 0:
        debugLog("New tickets in watcher ({0}), sending updates...".format(
            len(tickets)))
        for ticket in tickets:
            bot.send_message(
                chat_id=chatId,
                parse_mode="markdown",
                text=
                "*№:* [{0}](https://{5}.intraservice.ru/Task/View/{0})\n*Создатель:* {1} ({2})\n*Название:* {3}\n*Описание:* {4}"
                .format(ticket.id, ticket.creatorName,
                        ticket.creatorCompanyName, ticket.title,
                        ticket.description, config.site))
def sendUpdateFromWatcher():
    debugLog(
        "It's time to send watcher updates to: {0}".format(chatsForWatcher))
    watcherTickets = intraserviceProvider.getWatcher()
    if len(watcherTickets) > 0 and len(chatsForWatcher) > 0:
        #ticketIDs = [ticket.id for ticket in watcherTickets]
        for chat in chatsForWatcher.items():
            debugLog("Filtering new tickets for chat {0}".format(
                chat[1].chatID))
            newTickets = filterNewTickets(chat[1].chatID, watcherTickets)
            if len(newTickets) > 0:
                debugLog("New tickets: {0}".format(newTickets))
                updateFunction(chat[1].chatID, newTickets)
            else:
                debugLog("\tNo new tickets for {}".format(chat[1].chatID))
    else:
        debugLog("\tWatcher is empty or no chats subscribed to updates...")
Esempio n. 8
0
def sendUpdateFromWatcher():
    chats = databaseProvider.getChatsToWatch()
    debugLog("It's time to send watcher updates to: {0}".format(chats))
    watcherTickets = intraserviceProvider.getWatcher()
    if watcherTickets is None:
        return
    if len(watcherTickets) > 0 and len(chats) > 0:
        for chat in chats:
            debugLog("Filtering new tickets for chat {0}".format(chat))
            newTickets = filterNewTickets(chat, watcherTickets)
            if len(newTickets) > 0:
                ticketIDs = list(map(lambda x: x.id, newTickets))
                debugLog("New tickets: {0}".format(",".join(
                    [str(tid) for tid in ticketIDs])))
                updateFunction(chat, newTickets)
            else:
                debugLog("\tNo new tickets for {}".format(chat))
    else:
        debugLog("\tWatcher is empty or no chats subscribed to updates...")
def addChatToWatcher(chatId):
    debugLog("Adding new chat to watcher:")
    chatId = str(chatId)
    with open('data/chats.list', 'a+') as file:
        file.seek(0)
        content = file.read()
        ids = content.split('\n')
        if chatId not in ids:
            file.write('{0}\n'.format(chatId))
            chatsForWatcher[chatId] = chatToWatch(chatId)
            debugLog("\tchat {0} added.".format(chatId))
            return 'added'
        else:
            debugLog("\tchat {0} already added to watcher.".format(chatId))
            return 'already'
Esempio n. 10
0
def initWatcher(bot, fun):
    global chatsForWatcher, telebot, updateFunction
    chatsForWatcher = {}
    telebot = bot
    updateFunction = fun
    debugLog("Initializing watcher... chats to watch:")
    chats = databaseProvider.getChatsToWatch()
    if len(chats) > 0:
        for chatId in chats:
            chatsForWatcher[chatId] = chatToWatch(chatId)
            debugLog("\t{0}".format(chatId))
    timerWatcher = RepeatTimer(config.watcherChekoutInterval,
                               sendUpdateFromWatcher)
    timerWatcher.start()
    debugLog("Check timer is set to {0} seconds".format(
        config.watcherChekoutInterval))
Esempio n. 11
0
def getWatcher():
    for i in range(0, 5):
        try:
            debugLog(
                "Getting watcher tickets from intraservice (attempt {} of 5)..."
                .format(i + 1))
            url = baseUrl + "task?filterid=" + config.filterId
            request = requests.get(url,
                                   auth=requests.auth.HTTPBasicAuth(
                                       login, password))
            if request.status_code >= 400:
                debugLog(
                    "error: can't connect to intraservice API {0}, reason: {1} {2}"
                    .format(request.url, request.status_code, request.reason))
                return None, "error {0} {1}".format(request.status_code,
                                                    request.reason)
            r = request.json()
            tickets = parseJSONintoTicketClass(r)
            debugLog("\tdone.\n{0}".format(tickets))
        except:
            debugLog("error: {0}".format(sys.exc_info()[0]))
            continue
        break
    return tickets, None
def getWatcher():
    for i in range(0, 5):
        try:
            debugLog(
                "Getting watcher tickets from intraservice (attempt {} of 5)..."
                .format(i + 1))
            url = baseUrl + "task?filterid=636"
            r = requests.get(url,
                             auth=requests.auth.HTTPBasicAuth(
                                 login, password)).json()
            tickets = parseJSONintoTicketClass(r)
            debugLog("\tdone.\n{0}".format(tickets))
        except:
            debugLog("error: {0}".format(sys.exc_info()[0]))
            continue
        break
    return tickets
def removeChatFromWatcher(chatId):
    debugLog("Removing chat from watcher:")
    chatId = str(chatId)
    file = open('data/chats.list', 'r')
    content = file.read()
    ids = content.split('\n')
    if chatId in ids:
        stringToReplace = "{0}\n".format(chatId)
        content = content.replace(stringToReplace, "")
        file = open('data/chats.list', 'w+')
        file.write(content)
        chatsForWatcher[chatId].removeFile()
        chatsForWatcher.pop(chatId, None)
        debugLog("\tchat {0} removed.".format(chatId))
        return 'removed'
    else:
        debugLog("\tchat {0} is not present in watcher list.".format(chatId))
        return 'wasnot'
def initWatcher(bot, fun):
    global chatsForWatcher, telebot, updateFunction
    chatsForWatcher = {}
    telebot = bot
    updateFunction = fun
    if os.path.isfile('data/chats.list') is True:
        content = open('data/chats.list', 'r+').read()
        debugLog("Initializing watcher... chats to watch:")
        if len(content) > 0:
            for chatId in content.split('\n'):
                if chatId is "":
                    continue  # skip an empty line at the end of the file
                chatsForWatcher[chatId] = chatToWatch(chatId)
                debugLog("\t{0}".format(chatId))
    timerWatcher = RepeatTimer(config.watcherChekoutInterval,
                               sendUpdateFromWatcher)
    timerWatcher.start()
    debugLog("Check timer is set to {0} seconds".format(
        config.watcherChekoutInterval))
Esempio n. 15
0
def removeChatFromWatcher(chatId):
    debugLog("Removing chat from watcher:")
    chatId = str(chatId)
    return databaseProvider.removeChatToWatch(chatId)
        self.getTicketsFromFile()

    def getTicketsFromFile(self):
        if os.path.isfile('data/chats/{0}.chat'.format(self.chatID)) is True:
            content = open('data/chats/{0}.chat'.format(self.chatID),
                           'r').read()
            if len(content) > 0:
                self.acknowledged = content.split('\n')

    def removeFile(self):
        if os.path.isfile('data/chats/{0}.chat'.format(self.chatID)) is True:
            os.remove('data/chats/{0}.chat'.format(self.chatID))
            self.acknoledged = []


debugLog("Resetting variables...")
chatsForWatcher = {}
telebot = None
updateFunction = None


def initWatcher(bot, fun):
    global chatsForWatcher, telebot, updateFunction
    chatsForWatcher = {}
    telebot = bot
    updateFunction = fun
    if os.path.isfile('data/chats.list') is True:
        content = open('data/chats.list', 'r+').read()
        debugLog("Initializing watcher... chats to watch:")
        if len(content) > 0:
            for chatId in content.split('\n'):
config.filterId = args.filterId
config.watcherChekoutInterval = int(args.interval)
intraserviceProvider.login = login
intraserviceProvider.password = password
intraserviceProvider.setBaseUrl(config.site)

try:
    os.makedirs('./data')
except OSError:
    pass

databaseProvider.createTablesIfNotExists()
for user in args.users.split(','):
    databaseProvider.addNewUser(user)

debugLog("Бот для Интрасервиса запущен (вер. {0})".format(version))


@bot.message_handler(commands=["start"])
def command_start(message):
    if databaseProvider.authUser(message.from_user.username) is True:
        bot.send_message(
            message.chat.id,
            "Вы можете пользоваться ботом. Попробуйте следующие команды:\n/fresh\n/watch\n/stop"
        )
    else:
        bot.send_message(
            message.chat.id,
            "Использование данного бота не авторизовано. Обратитесь к администратору."
        )
Esempio n. 18
0
def addChatToWatcher(chatId):
    debugLog("Adding new chat to watcher:")
    chatId = str(chatId)
    return databaseProvider.addChatToWatch(chatId)