예제 #1
0
def pin(update, context):
    """
    Pin a message
    """
    cid=update.message.chat.id
    
    # validate user
    if not utils._check_user(context, update.effective_user.id, cid):
        return 
       
    try:
        reply=update.message.reply_to_message
        context.bot.pin_chat_message(chat_id=cid, 
                                     message_id=reply.message_id, 
                                     disable_notification=None)
        return
    except Exception as e:
        pass       
    # text
    text=" ".join(update.message.text.split(" ")[1:])
    if text:
        context.bot.pin_chat_message(chat_id=cid, 
                                     message_id=update.message.message_id, 
                                     disable_notification=None)
    else:
        text='Use /pin <i>text</i> or reply a message for pin some content in the current chat'
        context.bot.send_message(chat_id=cid, 
                                 text=text,
                                 parse_mode=telegram.ParseMode.HTML,
                                 disable_web_page_preview=True)
예제 #2
0
def stomp(update, context):
    """
    Mention stronger users for stomp the hostile creatures
    """
    if settings.VERBOSE:
        print("[REGEX] help for stomp hostile creatures")
    cid=update.message.chat.id
    
    # validate user
    if not utils._check_user(context, update.effective_user.id, cid):
        return
        
    # telegram user
    user=model.User(id=update.effective_user.id,
                    username=update.effective_user.username,
                    full_name=update.effective_user.full_name,
                    link=update.effective_user.link,
                    is_bot=update.effective_user.is_bot)
    # parse message
    msg=update.message.text[7:].split("@")[0].split("_")
    if settings.VERBOSE:
        print("       ", msg)
    # validate the user
    if msg[1]==str(update.effective_user.id):
        # list users
        users=model.filtered_users(user, int(msg[0]), 20)
        i=0
        tmp=""
        for u in users[1]:
            if u.id==str(update.effective_user.id):
                continue
            tmp+="@{0} ".format(u.username)
            i+=1
            if not i%3:
                i=0
                try:
                    context.bot.send_message(chat_id=cid, 
                                             text="Someone needs your help for stomp the hostile creatures\n"+tmp,
                                             parse_mode=telegram.ParseMode.HTML,
                                             disable_web_page_preview=True)
                except Exception as e:
                    utils._admin_error(context, "regex stomp: accepted", user=user, error=str(e))
                tmp=""
        if tmp:
            try:
                context.bot.send_message(chat_id=cid, 
                                         text="Someone needs your help for stomp the hostile creatures\n"+tmp,
                                         parse_mode=telegram.ParseMode.HTML,
                                         disable_web_page_preview=True)
            except Exception as e:
                utils._admin_error(context, "regex stomp: accepted", user=user, error=str(e))
    else:
        try:
            context.bot.send_message(chat_id=cid, 
                                     text=u'\U0001F622 Only the owner of this encounter can request for help',
                                     parse_mode=telegram.ParseMode.HTML,
                                     disable_web_page_preview=True)
        except Exception as e:
            utils._admin_error(context, "regex stomp: denied", user=user, error=str(e))
예제 #3
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)
        
예제 #4
0
def craft(update, context):
    """
    """
    cid=update.message.chat.id
    
    # validate user
    if not utils._check_user(context, update.effective_user.id, cid):
        return 
        
    update.callback_query=telegram.CallbackQuery(id="new-message", 
                                                 from_user=update.effective_user, 
                                                 chat_instance="", 
                                                 data="")
    callbacks.craft_resume(update, context)
예제 #5
0
def elite(update, context):
    """
    Mention the elite 
    """
    cid=update.message.chat.id
    
    # validate user
    if not utils._check_user(context, update.effective_user.id, cid):
        return 
        
    # telegram user
    user=model.User(id=update.effective_user.id,
                    username=update.effective_user.username,
                    full_name=update.effective_user.full_name,
                    link=update.effective_user.link,
                    is_bot=update.effective_user.is_bot)
    # mention users
    users=model.users()
    i=0
    tmp=""
    max_cw_level=0
    for u in users:
        if u.cw_level>max_cw_level:
            max_cw_level=u.cw_level
    for u in users:
        if u.id==str(update.effective_user.id) or u.cw_level<max_cw_level-model.get_data("MENTION_ELITE_DELTA", 15):
            continue
        tmp+="@{0} ".format(u.username)
        i+=1
        if not i%3:
            i=0
            try:
                context.bot.send_message(chat_id=cid, 
                                         text=u"\U0000270A Sir! Yes Sir!\n"+tmp,
                                         parse_mode=telegram.ParseMode.HTML,
                                         disable_web_page_preview=True)
            except Exception as e:
                utils._admin_error(context, "/elite", user=user, error=str(e))
            tmp=""
    if tmp:
        try:
            context.bot.send_message(chat_id=cid, 
                                     text=u"\U0000270A Sir! Yes Sir!\n"+tmp,
                                     parse_mode=telegram.ParseMode.HTML,
                                     disable_web_page_preview=True)
        except Exception as e:
            utils._admin_error(context, "/elite", user=user, error=str(e))
예제 #6
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)
예제 #7
0
def everybody(update, context):
    """
    Mention all subscribed users
    """
    cid=update.message.chat.id
    
    # validate user
    if not utils._check_user(context, update.effective_user.id, cid):
        return 
        
    # telegram user
    user=model.User(id=update.effective_user.id,
                    username=update.effective_user.username,
                    full_name=update.effective_user.full_name,
                    link=update.effective_user.link,
                    is_bot=update.effective_user.is_bot)
    # mention users 
    users=model.users()
    i=0
    tmp=""
    for u in users:
        if u.id==str(update.effective_user.id):
            continue
        tmp+="@{0} ".format(u.username)
        i+=1
        if not i%3:
            i=0
            try:
                context.bot.send_message(chat_id=cid, 
                                         text=tmp,
                                         parse_mode=telegram.ParseMode.HTML,
                                         disable_web_page_preview=True)
            except Exception as e:
                utils._admin_error(context, "/everybody", user=user, error=str(e))
            tmp=""
    if tmp:
        try:
            context.bot.send_message(chat_id=cid, 
                                     text=tmp,
                                     parse_mode=telegram.ParseMode.HTML,
                                     disable_web_page_preview=True)
        except Exception as e:
            utils._admin_error(context, "/everybody", user=user, error=str(e))
예제 #8
0
def craft_reset(update, context):
    """
    Reset craft operation
    """
    global CACHE
    cid=update.message.chat.id
    
    # validate user
    if not utils._check_user(context, update.effective_user.id, cid):
        return 
        
    tmp=update.message.text.split(" ")
    if len(tmp)>1:
        if tmp[1]=="yes":
            # reset users
            for user in model.users():
                user.crafting="{}"
                status=model.update_user(user)
            # reset guild
            CACHE["guild"]={"resources": {},
                            "parts": {},
                            "recipes": {}}
            context.bot.send_message(chat_id=cid, 
                                     text="Crafting operation restarted...",
                                     parse_mode=telegram.ParseMode.HTML,
                                     disable_web_page_preview=True)
        else:
            user=model.user_by_id(tmp[1])
            if user:
                user.crafting="{}"
                status=model.update_user(user)
                context.bot.send_message(chat_id=cid, 
                                         text="Crafting operation restarted [{1}]... for @{0}".format(html.escape(user.username), status),
                                         parse_mode=telegram.ParseMode.HTML,
                                         disable_web_page_preview=True)
                
    else:
        context.bot.send_message(chat_id=cid, 
                                 text='Type "/craft_reset <i>yes</i>" to reset all operation and stored data',
                                 parse_mode=telegram.ParseMode.HTML,
                                 disable_web_page_preview=True)
예제 #9
0
def resource(update, context):
    """
    Show info about an specific resource
    """
    global CACHE
    day_range=7
    if settings.VERBOSE:
        print("[REGEX] resource")
    cid=update.message.chat.id
    
    # validate user
    if not utils._check_user(context, update.effective_user.id, cid):
        return
        
    # list of resources
    recipes=""
    parts=""
    # code
    r_recipe=utils.item_by_code("r{0}".format(update.message.text.split("@")[0][2:]), "recipes")
    r_recipe_amount=0
    r_part=utils.item_by_code("k{0}".format(update.message.text.split("@")[0][2:]), "parts", adjust_part_code=True)
    r_part_amount=0
    if r_recipe and r_part:
        # guild
        if "guild" in CACHE:
            # recipes
            tmp=CACHE["guild"]["recipes"].get(r_recipe["name"].lower(), 0)
            if tmp:
                r_recipe_amount+=tmp
                recipes+="\n    - {0} x {1}".format(settings.GUILD_NAME.decode('unicode_escape'), tmp)
            # parts
            tmp=CACHE["guild"]["parts"].get(r_part["name"].lower(), 0)
            if tmp:
                r_part_amount+=tmp
                parts+="\n    - {0} x {1}".format(settings.GUILD_NAME.decode('unicode_escape'), tmp)
        # users
        for u in model.users():
            crafting=json.loads(u.crafting)
            if crafting:
                # validate the date
                dated=""
                t=datetime.datetime.fromisoformat(crafting["datetime"])
                if (datetime.datetime.today()-t).total_seconds()/(day_range*24.0*60.0*60.0)>1:
                    dated=u' \U0000231B'
                # recipes
                tmp=crafting["recipes"].get(r_recipe["name"].lower(), 0)
                if tmp:
                    r_recipe_amount+=tmp
                    recipes+='\n    - <a href="https://t.me/share/url?url=/g_deposit%20{2}%20{1}">{0}</a> x {1}{3}'.format(html.escape(u.username), tmp, r_recipe["code"], dated)
                # parts
                tmp=crafting["parts"].get(r_part["name"].lower(), 0)
                if tmp:
                    r_part_amount+=tmp
                    parts+='\n    - <a href="https://t.me/share/url?url=/g_deposit%20{2}%20{1}">{0}</a> x {1}{3}'.format(html.escape(u.username), tmp, r_part["code"], dated)
        # send message
        crafteable=u'\U00002705' if utils.item_is_crafteable(r_recipe, r_recipe_amount, r_part_amount) else u'\U0001F17E'
        text="{1} <b>{0}</b>\n(links are deposit shortcuts)\n\n".format(r_recipe["name"][:-7], crafteable)
        text+="{0} ({1}){2}\n\n{3} ({4}){5}".format(r_recipe["name"], r_recipe_amount, recipes if recipes else "", r_part["name"], r_part_amount, parts if parts else "")
        context.bot.send_message(chat_id=cid, 
                                 text=text,
                                 parse_mode=telegram.ParseMode.HTML,
                                 disable_web_page_preview=True)             
    else:
        context.bot.send_message(chat_id=cid, 
                                 text=settings.MESSAGES["unknow"].format(""),
                                 disable_web_page_preview=True)
예제 #10
0
def forwarded(update, context):
    """
    Main handler function for forwarded messages
    """
    global CACHE
    cid = update.message.chat.id

    # validate user
    if not utils._check_user(context, update.effective_user.id, cid):
        return

    # process forward message from Chat Wars
    if update.message.forward_from and update.message.forward_from.id == settings.CW_BOT_ID:
        if settings.VERBOSE:
            print("[Forwarded] from Chat Wars")
        # telegram user
        user = model.User(id=update.effective_user.id,
                          username=update.effective_user.username,
                          full_name=update.effective_user.full_name,
                          link=update.effective_user.link,
                          is_bot=update.effective_user.is_bot)
        # create cache
        CACHE.setdefault(
            user.id, {
                "resources": {
                    "guild": {},
                    "reinforcement": {},
                    "datetime": datetime.datetime.today()
                }
            })
        CACHE.setdefault("guild", {
            "resources": {},
            "parts": {},
            "recipes": {}
        })
        # escape content
        try:
            content = update.message.text.encode(encoding="unicode_escape")
            # print(content)
        except Exception as e:
            utils._admin_error(context,
                               "encode message",
                               user=user,
                               error=str(e),
                               trace=False)
            return

        # hostile creatures
        if b'You met some hostile creatures. Be careful:' in content and b'/fight_' in content:
            _action_fight(cid, user, content, update, context)
            return

        # battle report
        if settings.GUILD_NAME in content and b' Lvl: ' in content and b'Your result on the battlefield' in content:
            _action_battle_report(cid, user, content, update, context)
            return

        # materials needed for reinforcement (blacksmith's store message)
        if content.split(b'\\n')[0].startswith(b'Materials needed for '):
            _action_reinforcement(cid, user, content, update, context)
            return

        # guild warehouse
        if content.split(b'\\n')[0].startswith(b'Guild Warehouse:'):
            _action_reinforcement(cid, user, content, update, context)
            return

        # guild roster
        if content.split(b'\\n')[0].startswith(
                settings.GUILD_NAME[:10]) and content.split(
                    b'\\n')[-1].startswith(b'#'):
            _action_roster(cid, user, content, update, context)
            return

        # guild deposit
        if content.startswith(b'Deposited successfully: '):
            _action_deposit(cid, user, content, update, context)
            return

        # parts and recipes
        if (content.startswith(b'\\U0001f4c3')
                or content.startswith(b'\\U0001f9e9')
            ) and not (b'Equipment' in content or b'Storage' in content
                       or b'/use_' in content or b'U0001f3f7' in content):
            _action_crafting_list(cid, user, content, update, context)
            return

        # alliances top
        if content.split(b'\\n')[0] == b'\\U0001f91dAlliances top:':
            _alliances_top(cid, user, content, update, context)
            return