Hướng dẫn tạo Biểu mẫu liên hệ sử dụng Telegram Bot API

Tạo biểu mẫu liên hệ sử dụng Telegram Bot API thông báo Nội dung vào group riêng tư trên Telegram.

Chào mọi người, lâu lắm không gặp

Như mình biết, API biểu mẫu liên hệ của Blogger đã được cập nhật gần đây. Trong phiên bản mới đó thì cần một token cho mỗi lần gửi biểu mẫu. Để có token đó cần phải thêm tiện ích Biểu mẫu liên hệ qua Bố cục từ Blogger. Điều này sẽ khiến trang web cồng kềnh hơn và lại mình muốn những thứ mới. Cho nên mình có một cách mới để tạo một biểu mẫu liên hệ là sử dụng Telegram Bot API.

Feature Image tạo Biểu mẫu liên hệ sử dụng Telegram Bot API
Link demo ở phía dưới

Cần chuẩn bị

  • Tài khoản Telegram: Đương nhiên rồi, cần một tài khoản telegram để tạo bot, group. Nếu bạn chưa có hãy tải telegram và đăng ký một tài khoản nhé.
  • Telegram Bot: Tạo một con bot. Hướng dẫn chi tiết: Cách tạo bot telegram.
  • Telegram Group: Tạo một group để bot gửi thông tin từ biểu mẫu vào. Sau đó hãy lưu lại Group ID. Nếu bạn chưa biết cách hãy xem hướng dẫn: Lấy Telegram Group ID.
  • Kiến thức HTML CSS JS căn bản, không có cũng không sao :v

Tạo biểu mẫu liên hệ

Tạo giao diện

Bắt đầu cần một giao diện để người dùng có thể thao tác. Mình không phải dân chuyên thiết kế nên chỉ viết được như này thôi nha. Nếu bạn sẵn lòng làm cho nó đẹp hơn thì tuyệt vời, mình xin ghi nhận nhé.

<script>
    document.head.insertAdjacentHTML('beforeend', `<style>
/* Toast Notification */ .tNtf span { position: fixed; left: 24px; bottom: -70px; display: inline-flex; align-items: center; text-align: center; justify-content: center; margin-bottom: 20px; z-index: 99981; background: #323232; color: rgba(255, 255, 255, .8); font-size: 14px; font-family: inherit; border-radius: 3px; padding: 13px 24px; box-shadow: 0 5px 35px rgba(149, 157, 165, .3); opacity: 0; transition: all .1s ease; animation: slideinwards 2s ease forwards; -webkit-animation: slideinwards 2s ease forwards } @media screen and (max-width:500px) { .tNtf span { margin-bottom: 20px; left: 20px; right: 20px; font-size: 13px } } @keyframes slideinwards { 0% { opacity: 0 } 20% { opacity: 1; bottom: 0 } 50% { opacity: 1; bottom: 0 } 80% { opacity: 1; bottom: 0 } 100% { opacity: 0; bottom: -70px; visibility: hidden } } @-webkit-keyframes slideinwards { 0% { opacity: 0 } 20% { opacity: 1; bottom: 0 } 50% { opacity: 1; bottom: 0 } 80% { opacity: 1; bottom: 0 } 100% { opacity: 0; bottom: -70px; visibility: hidden } } .drK .tNtf span { box-shadow: 0 10px 40px rgba(0, 0, 0, .2) }
</style>`)
    // Xóa đoạn dưới này đi nếu bạn đang sử dụng theme Plus UI
    document.head.insertAdjacentHTML('beforeend', `<style>
/* Widget ContactForm */ .ContactForm{max-width:500px;font-size:14px} .cArea:not(:last-child){margin-bottom:25px} .cArea label{display:block;position:relative} .cArea label .n{display:block;position:absolute;left:0;right:0;top:0; color:rgba(8,16,43,.4);line-height:1.6em;padding:15px 16px 0;border-radius:4px 4px 0 0;transition:all .1s ease;} .cArea label .n.req::after{content:'*';font-size:85%} .cArea textarea{height:100px} .cArea textarea:focus, .cArea textarea[data-text=fl]{height:200px} .cArea input:focus ~ .n, .cArea textarea:focus ~ .n, .cArea input[data-text=fl] ~ .n, .cArea textarea[data-text=fl] ~ .n{padding-top:5px;color:rgba(8,16,43,.7);font-size:90%;background:#ececec} .cArea .h{display:block;font-size:90%;padding:5px 16px 0;opacity:.7;line-height:normal} .nArea .contact-form-error-message-with-border{color:#d32f2f} .nArea .contact-form-success-message-with-border{color:#2e7b32} .tNtf img.contact-form-cross{display:none} .ContactForm input[type=text], .ContactForm input[type=email], .ContactForm textarea{display:block;width:100%;outline:0;border:0;border-bottom:1px solid rgba(0,0,0,.25);border-radius:4px 4px 0 0;background:#f3f3f4; padding:25px 16px 8px 16px; line-height:1.6em; transition: all .1s ease;} .ContactForm input[type=text]:hover, .ContactForm input[type=email]:hover, .ContactForm textarea:hover{border-color:rgba(0,0,0,.42);background:#ececec} .ContactForm input[type=text]:focus, .ContactForm input[type=email]:focus, .ContactForm textarea:focus, .ContactForm input[data-text=fl], .ContactForm textarea[data-text=fl]{border-color:var(#482dff);background:#ececec} .ContactForm input[type=button], .ContactForm input[type=submit]{display:inline-flex;align-items:center; padding:12px 30px; outline:0;border:0;border-radius:4px; color:#fffdfc; background:var(#482dff); font-size:14px; white-space:nowrap;overflow:hidden;max-width:100%} .ContactForm input[type=button]:hover, .ContactForm input[type=submit]:hover{opacity:.7}
</style>`)
</script>
<!--[ Toast Notification ]-->
<div id='toastNotifC' class='tNtf'></div>


<div class='ContactForm' id="CtFm">
    <p>Gửi các yêu cầu hoặc thắc mắc của bạn xuống phía dưới, chúng tôi sẽ phản hồi bạn sớm nhất có thể</p>
    <form name='cForm'>
        <div class='cArea'>
            <label>
                <input class='cInpt cName' name='name' id='name' type='text' /> <span class='n req'>Tên</span>
            </label>
        </div>
        <div class='cArea'>
            <label>
                <input class='cInpt cMail' name='email' id='email' type='email' /><span class='n '>Email</span>
            </label>
            <span class='h'>Yêu cầu email hợp lệ</span>
        </div>
        <!--[ Extra Number
        <div class='cArea'>
            <label>
                <input class='cInpt cMob' name='mobile' id='mobile' type='text' /><span class='n'>Số điện thoại</span>
            </label>
            <span class='h'>This field is optional</span>
        </div>-->
        <!--[ Extra Telegram
        <div class='cArea'>
            <label>
                <input class='cInpt cTel' name='telegram' id='telegram' type='text' />
                <span class='n'>Telegram Username</span>
            </label>
            <span class='h'>This field is optional</span>
        </div> ]-->
        <div class='cArea'>
            <label>
                <textarea style='resize:vertical' class='cInpt cMsg' name='message' id='message' rows='3'></textarea><span class='n req'>Nội dung</span>
            </label>
            <span class='h'>Phải bé hơn 3000 ký tự</span>
        </div>
        <div class='cArea'>
            <button class='cBtn button' type='submit'>Send</button>
        </div>
    </form>
</div>
<script> var inputs = document.querySelectorAll('.ContactForm input[type=text], .ContactForm input[type=email], .ContactForm textarea'); for (var i = 0; i < inputs.length; i++) { var input = inputs[i]; input.addEventListener('input', function() {var bg = this.value ? 'fl' : 'nfl';console.log(bg); this.setAttribute('data-text',bg);}); }
</script>
    

Xử lí chức năng.

Tiếp theo hãy làm cho nó hoạt động bằng Javascript.

Hãy thay các phần botToken, chatId bằng thông tin chính xác của bạn nhé. Ngoài ra bạn có thể tùy chỉnh nó theo cách riêng của bạn.


    
<script>
    (function () {
        function toast(e) { var tNotif = document.getElementById('toastNotifC'); if (tNotif != null) { tNotif.innerHTML = '<span>' + e + '</span>' } };
        /* formConfig - Cấu hình cho form - Sensitive (obfuscate it after making changes) */
        var formConfig = {
            botToken: '5550731882:AAFIYk98gs00PUjTnkeoQoZYgzSiJVhXXn4',
            chatId: '-600762152',
            text: '#NEW_FORM_SUBMISSION #FayeDarkForm\n{{FORMDATA}}',
            form: 'form[name=cForm]',
            blogData: {
                homeTitle: window.location.host,
                homeUrl: window.location.protocol + "//" + window.location.host,
                pageTitle: document.title,
                pageUrl: window.location.protocol + "//" + window.location.host + window.location.pathname,
            },
            toast: {
                blankName: 'Tên không được để trống',
                blankMessage: 'Nội dung không được để trống',
                longMessage: 'Nội dung không được dài quá 3000 ký tự',
                invalidEmail: 'Yêu cầu email hợp lệ',
                success: 'Hey, {{name}}! Tin nhắn của bạn đã được gửi.',
                started: 'Sending...',
                error: 'Có lỗi xảy ra!',
                offline: '{{name}}! Có vẻ như bạn đang offline.',
                tooLong: 'Tin nhắn quá dài... Gửi thất bại!'
            },
            callbacks: {
                success: () => {
                    /* Đoạn code sẽ chạy khi gửi form thành công */
                    var div = document.createElement('div');
                    div.innerHTML = 'Tin nhắn đã được gửi đi.<br> Cám ơn bạn đã liên hệ với chúng tôi!';
                    div.style = "height: 120px;font-size: 1.25em;display: flex;align-items: center;width: 100%;border-bottom: 1px solid;border-top: 1px solid;"
                    document.getElementById("CtFm").innerHTML = ""
                    document.getElementById("CtFm").insertAdjacentElement('beforeend', div);
                },
                /* Disable submit button to prevent multiple submits */
                started: () => { document.querySelector('form[name=cForm] .cBtn.button').disabled = true },
                /* Enable submit button on error so user can re-submit it */
                error: () => {document.querySelector('form[name=cForm] .cBtn.button').disabled = false},
                offline: () => { },
                tooLong: () => { }
            }
        };

        /* Main Scripts */
        var form=document.querySelector(formConfig.form),toasts=JSON.parse(JSON.stringify(formConfig.toast));form.addEventListener("submit",f=>{f.preventDefault();var b={},g=form.querySelectorAll("[name]");for(i=0;i<g.length;++i)b[g[i].name]=g[i].value.replace(/>/gi,"&gt;").replace(/</gi,"&lt;");var a,d,c=formConfig.text,h="";for(a in formConfig.toast={},b)for(d in h+="<b>&#8226; "+(a[0].toUpperCase()+a.slice(1))+":</b> "+("email"===a||"website"===a?b[a]:"<pre>"+b[a]+"</pre>")+"\n",c=c.replace(new RegExp("{{"+a+"}}","g"),b[a]),toasts)void 0===formConfig.toast[d]&&(formConfig.toast[d]=toasts[d].replace(new RegExp("{{"+a+"}}","g"),b[a]).replace(/\{\{(.*?)\}\}/gm,""));c=c.replace(/{{FORMDATA}}/g,h).replace(/\{\{(.*?)\}\}/gm,""),(a={}).chat_id=formConfig.chatId,a.text=c+'Note: This Form was submitted at Page <a href="'+formConfig.blogData.pageUrl+'">'+formConfig.blogData.pageTitle+'</a> on Blog <a href="'+formConfig.blogData.homeUrl+'">'+formConfig.blogData.homeTitle+'</a>.',a.parse_mode="HTML",a.reply_markup={},a.reply_markup.inline_keyboard=[[{text:"Form Page",url:formConfig.blogData.pageUrl}]],a.disable_web_page_preview=!0;var e,f=a;navigator.onLine?void 0!==b.name&&""===b.name?toast(formConfig.toast.blankName):void 0===b.email||""!==b.email&&null!==String(b.email).toLowerCase().match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)?void 0!==b.message&&""===b.message?toast(formConfig.toast.blankMessage):void 0!==b.message&&3e3<b.message.length?toast(formConfig.toast.longMessage):(toast(formConfig.toast.started),formConfig.callbacks.started(),(e=new XMLHttpRequest).open("POST","https://api.telegram.org/bot"+formConfig.botToken+"/sendMessage",!0),e.setRequestHeader("Content-type","application/json"),e.onreadystatechange=function(){var a;4===e.readyState&&(200===e.status?(a=JSON.parse(e.responseText)).ok?(toast(formConfig.toast.success),formConfig.callbacks.success(a)):(toast(formConfig.toast.error),formConfig.callbacks.error(a)):"Bad Request: message is too long"===JSON.parse(e.responseText).description?(toast(formConfig.toast.tooLong),formConfig.callbacks.tooLong()):(toast(formConfig.toast.error),formConfig.callbacks.error()))},e.send(JSON.stringify(f))):toast(formConfig.toast.invalidEmail):(toast(formConfig.toast.offline),formConfig.callbacks.offline()),validated=!1})
    })()
</script>
    

Lưu ý: Nó không tốt lắm khi để Bot API Token công khai. Vì thế mình đề xuất mã hóa mã javascript của bạn. Khi mà bạn thấy có gì đó không ổn với bot của bạn hãy gỡ bot Token qua botFather. Sau đó bạn sẽ nhận được token mới và token cũ không còn tác dụng nữa.

Tạo trang liên hệ cho Blog (Blogger)

Bước 1: Đăng nhập vào trang quản lí blog của bạn - draft.blogger.com

Bước 2: Vào menu tiếp theo nhấn vào Page (Trang)

Bước 3: Nhấn vào New page (Tạo trang mới) hoặc nhấn vào trang đã tạo trước đó

Bước 4: Chuyển sang chế độ HTML view (Chế độ xem HTML)

Bước 5: Copy và dán 2 phần code vào và chỉnh sửa cho đúng thông tin của bạn

Hình ảnh cho dễ hình dung

Sau khi hoàn thành tất cả các bước các bạn hãy xuất bản bài đăng và xem thành quả thôi. Nếu các bạn gặp vấn đề gì đừng ngại comment hỏi nhé.

Demo và lời kết

Demo

Tính năng này khá ổn nếu như bạn không muốn dùng biểu mẫu liên hệ của blogger. Thông báo sẽ được cập nhật qua Telegram. Còn về Bot Token nếu để lộ ra thì không phải chuyện lớn lắm, chỉ phiền chút thôi và không ảnh hưởng đến các thứ liên quan và bạn có thể tạo token mới bất cứ lúc nào. Chúc các bạn thành công!

Getting Info...

About the Author

ntdm | @ntdm11

Đăng nhận xét

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.