Exemple #1
0
def main(argv):
    parser = argparse.ArgumentParser(description="Export Telegram messages.")
    parser.add_argument("-o", "--output", help="output path", default="export")
    parser.add_argument(
        "-g",
        "--group",
        help="export every user's avatar in a group or channel",
        action='store_true')
    parser.add_argument("-t",
                        "--type",
                        help="peer type, can be 'user', 'chat', 'channel'",
                        default="user")
    parser.add_argument("-i", "--id", help="peer id", type=int)
    parser.add_argument("-e",
                        "--tgbin",
                        help="Telegram-cli binary path",
                        default="bin/telegram-cli")
    args = parser.parse_args(argv)

    with tgcli.TelegramCliInterface(args.tgbin, run=False) as tc:
        tc.cmd_dialog_list()
        if not os.path.isdir(args.output):
            os.mkdir(args.output)
        if args.group:
            export_avatar_group(tc, args.type, args.id, args.output)
        else:
            export_avatar_peer(
                tc, args.type, args.id,
                os.path.join(args.output, '%s%d.jpg' % (args.type, args.id)))
Exemple #2
0
def main(argv):
    global TGCLI, DLDIR, TG_TEST
    parser = argparse.ArgumentParser(description="Export Telegram messages.")
    parser.add_argument("-o", "--output", help="output path", default="export")
    parser.add_argument("-d", "--db", help="database path", default="tg-export3.db")
    parser.add_argument("-f", "--force", help="force download all messages", action='store_true')
    parser.add_argument("-p", "--peer", help="only download messages for this peer (format: channel#id1001234567, or use partial name/title as shown in tgcli)")
    parser.add_argument("-B", "--batch-only", help="fetch messages in batch only, don't try to get more missing messages", action='store_true')
    parser.add_argument("-t", "--timeout", help="tg-cli command timeout", type=int, default=30)
    parser.add_argument("-l", "--logging", help="logging mode (keep running)", action='store_true')
    parser.add_argument("-L", "--keep-logging", help="first export, then keep logging", action='store_true')
    parser.add_argument("-e", "--tgbin", help="telegram-cli binary path", default="bin/telegram-cli")
    parser.add_argument("-v", "--verbose", help="print debug messages", action='store_true')
    args = parser.parse_args(argv)

    if args.verbose:
        logging.getLogger().setLevel(logging.DEBUG)
        tgcli.logger.setLevel(logging.DEBUG)

    DLDIR = args.output
    init_db(args.db)

    TGCLI = tgcli.TelegramCliInterface(args.tgbin, extra_args=('-W', '-E'), run=False, timeout=args.timeout)
    TGCLI.on_json = MSG_Q.put
    TGCLI.on_info = lambda s: tgcli.logger.info(s) if not re_getmsg.match(s) else None
    #TGCLI.on_text = MSG_Q.put
    #TGCLI.on_start = on_start
    TGCLI.run()
    TGCLI.ready.wait()
    time.sleep(1)

    # the 'test' branch of tg has channel support
    TG_TEST = 'channel' in TGCLI.cmd_help()

    try:
        if not args.logging:
            export_text(args.peer, args.force)
            if not args.batch_only:
                export_holes()
        if args.logging or args.keep_logging:
            while TGCLI.ready.is_set():
                d = MSG_Q.get()
                logging.info(logging_fmt(d))
                process(d)
    finally:
        TGCLI.close()
        purge_queue()
        DB.commit()
Exemple #3
0
{%- elif 'reply_id' in msg %} [Re]
{%- endif %} >{% if msg.text %} {{ msg.text }}{% endif %}{% if msg.media %} [{{ msg.media.type }}]{% endif %}{% if msg.service %} [{{ msg.action.type }}]{% endif %}'''

jinjaenv = jinja2.Environment(loader=jinja2.DictLoader({'txt': txt_template}))
jinjaenv.filters['strftime'] = lambda date, fmt='%Y-%m-%d %H:%M:%S': time.strftime(fmt, time.localtime(date))

template = jinjaenv.get_template('txt')

WIDTH = 35

def print_msg(msg):
    logging.debug(msg)
    try:
        if msg.get('event') in ('message', 'service'):
            s = template.render(msg=msg).strip()
            s = '\n'.join(textwrap.wrap(s, WIDTH)) + '\n'
            sys.stdout.write(s)
            sys.stdout.flush()
    except Exception:
        logging.exception('Failed to process a message.')


with tgcli.TelegramCliInterface(sys.argv[1]) as c:
    c.on_json = print_msg
    for ln in sys.stdin:
        l = ln.strip()
        if l == 'q':
            break
        elif l.isdigit():
            WIDTH = int(l)
Exemple #4
0
     ('unsubscribe', cmd_unsubscribe), ('help', cmd_help), ('start',
                                                            cmd_start)))

if __name__ == '__main__':
    CFG = load_config()
    translation = gettext.translation(
        'tsleepd',
        os.path.join(
            os.path.dirname(
                os.path.abspath(os.path.realpath(sys.argv[0] or 'locale'))),
            'locale'), CFG['languages'])
    translation.install(('ngettext', ))
    DB, CONN = None, None
    MSG_Q = queue.Queue()
    USER_CACHE = {}
    TGCLI = tgcli.TelegramCliInterface(CFG.tgclibin)
    TGCLI.ready.wait()
    TGCLI.on_json = MSG_Q.put
    signal.signal(signal.SIGTERM, sig_exit)
    try:
        USER_CACHE = init_db()
        all_status_update()

        updatebotinfo()
        apithr = threading.Thread(target=getupdates)
        apithr.daemon = True
        apithr.start()

        while 1:
            handle_update(MSG_Q.get())
    finally: