Example #1
0
def todo_edit(update, context):
    """
    Edit todo
    """
    action_status=False
    action_text=False
    action=""
    cid=update.message.chat.id
    
    # validate user
    if not utils._check_user(context, update.effective_user.id, cid):
        return
    
    text=update.message.text.split("_")
    if len(text)==3:
        action=text[1]
        uid=text[2]
        # get content
        data=json.loads(utils.todo_get_data().value)
        # apply action
        if action=="check" or action=="uncheck":
            print("TODO CHECK/UNCHECK", action, uid)
            for d in data:
                if d["uid"]==uid:
                    if action=="check":
                        d["checked"]=True
                    else:
                        d["checked"]=False
                    action_status=True
                    action_text=d["text"]
        elif action=="delete":
            print("TODO DELETE", uid)
            for i in range(len(data)):
                if data[i]["uid"]==uid:
                    action_text=data[i]["text"]
                    del data[i]
                    action_status=True
                    break
        # save changes
        status=model.set_data("TODO", json.dumps(data))
    # send a message
    if action_status:
        context.bot.send_message(chat_id=cid, 
                                 text="{0} has been {1}ed".format(action_text, action),
                                 disable_web_page_preview=True)
    else:
        context.bot.send_message(chat_id=cid, 
                                 text=settings.MESSAGES["unknow"].format("unknown item or format"),
                                 disable_web_page_preview=True)
        
Example #2
0
def todo_get_data():
    data = None
    for d in model.data():
        if d.key == "TODO":
            data = d
            break
    # create if not exist
    if not data:
        status = model.set_data("TODO", json.dumps([]))
        if settings.VERBOSE:
            print("Create TODO:", status)
        for d in model.data():
            if d.key == "TODO":
                data = d
                break
    return data
Example #3
0
def todo(update, context):
    """
    TO DO list
    """
    cid=update.message.chat.id
    
    # validate user
    if not utils._check_user(context, update.effective_user.id, cid):
        return 
        
    # get content
    data=json.loads(utils.todo_get_data().value)
    # add a replied message
    try:
        reply=update.message.reply_to_message
        text=reply.text.split("\n")
        for t in text:
            if t and not utils.todo_item_in_todo(data, t):
                utils.todo_add_item(data, t)
        # save changes
        status=model.set_data("TODO", json.dumps(data))
    except Exception as e:
        pass       
    
    # show list
    text=[]
    print(data)
    for d in data:
        tmp="{0} - {1}\n        /todo_{3}check_{2}\n        /todo_delete_{2}".format(u'\U00002705' if d["checked"] else u'\U0001F17E', d["text"], d["uid"], 'un' if d["checked"] else '')
        if d["checked"]:
            text.insert(0, tmp)
        else:
            text.append(tmp)
    if text:
        context.bot.send_message(chat_id=cid, 
                                 text="\n".join(text)+"\n\nReply a message with /todo command to add it in this list (this action append each line of the message as a single item to the list)",
                                 parse_mode=telegram.ParseMode.HTML,
                                 disable_web_page_preview=True)
    else:
        text='Reply a message with /todo command to add it in this list (this action append each line of the message as a single item to the list)'
        context.bot.send_message(chat_id=cid, 
                                 text=text,
                                 parse_mode=telegram.ParseMode.HTML,
                                 disable_web_page_preview=True)
Example #4
0
def manage_data(update, context):
    """
    Manage stored data on database
    """
    if str(update.effective_user.id) == settings.ADMIN_ID:
        # list all pair key:value
        if update.message.text == "/data":
            data = model.data()
            text = u'\U0001F4C1 Registered data\n\nUse /data_set for add or modify a key\nUse /data_delete for remove data\n\n'
            for d in data:
                tmp = u'<b>key:</b> {0}\n<b>value:</b> {1} ({2})\n\n'.format(
                    html.escape(d.key), html.escape(d.value),
                    html.escape(d.type_of))
                if len(text) + len(
                        tmp) < telegram.constants.MAX_MESSAGE_LENGTH - 5:
                    text += tmp
                else:
                    context.bot.send_message(
                        chat_id=settings.ADMIN_ID,
                        text=text,
                        parse_mode=telegram.ParseMode.HTML,
                        disable_web_page_preview=True)
                    text = ""
            if text:
                context.bot.send_message(chat_id=settings.ADMIN_ID,
                                         text=text,
                                         parse_mode=telegram.ParseMode.HTML,
                                         disable_web_page_preview=True)
        # add or modify a pair key:value
        elif update.message.text.split(" ")[0] == "/data_set":
            tmp = update.message.text.split(" ")
            if len(tmp) > 2:
                value = " ".join(tmp[2:])
                if tmp[2] == "this":
                    value = update.message.chat.id
                status = model.set_data(tmp[1].upper(), value)
                context.bot.send_message(
                    chat_id=settings.ADMIN_ID,
                    text="<b>Data (set)</b>\n\nKey: {0}\nValue: {1}\nStatus: {2}"
                    .format(html.escape(tmp[1].upper()),
                            html.escape(" ".join(tmp[2:])), status),
                    parse_mode=telegram.ParseMode.HTML,
                    disable_web_page_preview=True)
            else:
                context.bot.send_message(
                    chat_id=settings.ADMIN_ID,
                    text=
                    "<b>Invalid format</b>\n<code>/data_set KEY VALUE</code>",
                    parse_mode=telegram.ParseMode.HTML,
                    disable_web_page_preview=True)
        # delete a pair key:value
        elif update.message.text.split(" ")[0] == "/data_delete":
            tmp = update.message.text.split(" ")
            if len(update.message.text.split(" ")) > 1:
                status = model.del_data(tmp[1].upper())
                context.bot.send_message(
                    chat_id=settings.ADMIN_ID,
                    text="<b>Data (delete)</b>\n\nKey: {0}\nStatus: {1}".
                    format(html.escape(tmp[1].upper()), status),
                    parse_mode=telegram.ParseMode.HTML,
                    disable_web_page_preview=True)
            else:
                context.bot.send_message(
                    chat_id=settings.ADMIN_ID,
                    text="<b>Invalid format</b>\n<code>/data_delete KEY</code>",
                    parse_mode=telegram.ParseMode.HTML,
                    disable_web_page_preview=True)
Example #5
0
def _alliances_top(cid, user, content, update, context):
    """
    Alliances top parser
    """
    print("            Alliances top")
    show = False
    export = True
    clean_data = False
    # check UTC battle
    utcnow = datetime.datetime.utcnow()
    utcnow = update.message["forward_date"]
    # request data
    content = content.split(b'\\n')[1:]
    alliances = {"previous": "", "alliances": {}}
    # clean data
    if clean_data:
        status = model.set_data("ALLIANCES", json.dumps(alliances))
        print("            Clean alliances data")
        return
    for d in model.data():
        if d.key == "ALLIANCES":
            alliances = json.loads(d.value)
            break
    # validate message
    parse_status = True
    if alliances["previous"] == b'\\n'.join(content).decode():
        print("            Skip same message")
        parse_status = False
    # parse message
    if parse_status:
        alliances["previous"] = b'\\n'.join(content).decode()
        for alliance in content:
            alliance = alliance.split(b' ')
            score = float(alliance[-1].decode())
            name = b' '.join(alliance[1:-1]).decode()

            scores = alliances["alliances"].get(name, [])
            scores.append([score, str(utcnow)])
            alliances["alliances"][name] = scores
    # save changes
    status = model.set_data("ALLIANCES", json.dumps(alliances))
    # plot data
    try:
        import matplotlib.pyplot as plt
        import numpy as np
    except:
        return
    caption = "Last difference:"
    plt.clf()
    ax = plt.gca()
    for k in alliances["alliances"]:
        scores = np.array([item[0] for item in alliances["alliances"][k]])
        dates = [
            datetime.datetime.fromisoformat(item[1])
            for item in alliances["alliances"][k]
        ]
        if len(dates) > 1:
            caption += "\n  - {0} ({1})".format(k,
                                                round(np.diff(scores)[-1], 2))
            plt.plot(dates[1:],
                     np.diff(scores),
                     marker=".",
                     markersize=5,
                     label=k)
    plt.title("Alliances top (difference)")
    ax.xaxis_date()
    plt.grid(True)
    plt.legend()
    if export:
        plt.savefig("alliances-diff.jpg")
    if show:
        plt.show()
    plt.clf()
    ax = plt.gca()
    for k in alliances["alliances"]:
        scores = np.array([item[0] for item in alliances["alliances"][k]])
        dates = [
            datetime.datetime.fromisoformat(item[1])
            for item in alliances["alliances"][k]
        ]
        plt.plot(dates, scores, marker=".", markersize=5, label=k)
    plt.title("Alliances top (progress)")
    ax.xaxis_date()
    plt.grid(True)
    plt.legend()
    if export:
        plt.savefig("alliances.jpg")
    if show:
        plt.show()
    if export:
        context.bot.send_photo(chat_id=cid,
                               caption=caption,
                               photo=open("alliances.jpg", 'rb'),
                               parse_mode=telegram.ParseMode.HTML,
                               disable_web_page_preview=True)
Example #6
0
# logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger=logging.getLogger(__name__)

# shared data
SHARED_DATA={}

functions.filters.CACHE=SHARED_DATA
functions.commands.CACHE=SHARED_DATA
functions.regex.CACHE=SHARED_DATA
functions.callbacks.CACHE=SHARED_DATA
functions.timers.CACHE=SHARED_DATA

# variables

model.set_data("CRAFT_OUTDATE_INTERVAL_HOURS", 8*3600)
model.set_data("CRAFT_OUTDATE_INTERVAL_DAYS", 3)
model.set_data("BATTLE_TIME_DELTA_MINUTES", 20)
model.set_data("MENTION_ELITE_DELTA", 15)

# ERROR HANDLER

def _error(update, context):
    logger.warning('Update "%s" caused error "%s"', update, context.error)
    # send the error message to the admin
    utils._admin_error(context, "INTERNAL ERROR", error=str(context.error))
    return
    # send the error message to current user if is valid
    try:
        context.bot.send_message(chat_id=update.effective_user.id, 
                                 text=settings.MESSAGES["application-error"].format(update._effective_message.text, context.error),