Join Us On Telegram Contact Us Join Now!
Posts

How to Create a Contact Form using Telegram Bot API

How to add a contact page on your blog?

Steps to Make a Contact Form?

Step 1: First of all Login to your Blogger Dashboard.

Step 2: On Blogger Dashboard, click Pages.

Step 3: Either create a new page by clicking on icon or click on the existing page to add codes there.

Step 4: Switch to HTML view.

Step 5: Paste the following codes in it and Publish your page.
<style>
  /*<![CDATA[*/
  /* 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>

<!--[ Toast Notification ]-->
<div id='toastNotifC' class='tNtf'></div>

<script>
  /*<![CDATA[*/
  /* Toast */ function toast(e){var tNotif = document.getElementById('toastNotifC'); if (tNotif != null){tNotif.innerHTML = '<span>' + e + '</span>'}};
  /*]]>*/
</script>

<p>Got a question? We'd love to hear from you. Send us a message and we'll respond as soon as possible.</p>

<div class='ContactForm'>
  <form name='cForm'>
    <div class='cArea'>
      <label>
        <input class='cInpt cName' name='name' id='name' type='text' />
        <span class='n'>Name</span>
      </label>
    </div>
    <div class='cArea'>
      <label>
        <input class='cInpt cMail' name='email' id='email' type='email' />
        <span class='n req'>Email</span>
      </label>
      <span class='h'>Valid email is required</span>
    </div>
    <div class='cArea'>
      <label>
        <input class='cInpt cMob' name='mobile' id='mobile' type='text' />
        <span class='n'>Mobile Number</span>
      </label>
      <span class='h'>This field is optional</span>
    </div>
    <!--[ Extra ]-->
    <!--<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'>Message</span>
      </label>
      <span class='h'>Must not contain more than 3000 characters</span>
    </div>
    <div class='cArea'>
      <button class='cBtn button' type='submit'>Send</button>
    </div>
  </form>
</div>

<script>
  /*<![CDATA[*/
  (function(){
    /* Form Configuration - Sensitive (obfuscate it after making changes) */
    var formConfig = {
      botToken: '110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw',
      chatId: '-1001200190470',
      text: '#NEW_FORM_SUBMISSION #WebCoderHub\n{{FORMDATA}}',
      form: 'form[name=cForm]',
      blogData: {
        homeTitle: 'WebCoderHub',
        homeUrl: 'https://' + window.location.host,
        pageTitle: document.title,
        pageUrl: 'https://' + window.location.host + window.location.pathname,
      },
      callbacks: {
        success: () => {
          /* Let's redirect user to a location on success */
          setTimeout(() => {
            toast('Redirecting you to Homepage...');
            setTimeout(() => {
              /* Location to assign after form is successfully submitted */
              window.location.assign('/')
            }, 3000)
          }, 3000)
        },
        started: () => {
          /* Disable submit button to prevent multiple submits */
          document.querySelector('form[name=cForm] .cBtn.button').disabled = true
        },
        error: () => {
          /* Enable submit button on error so user can re-submit it */
          document.querySelector('form[name=cForm] .cBtn.button').disabled = false
        },
        offline: () => {},
        tooLong: () => {}
      },
      toast: {
        blankName: 'Name cannot be blank',
        blankMessage: 'Message cannot be blank',
        longMessage: 'Message cannot contain more than 3000 characters',
        invalidEmail: 'A valid email is required',
        success: 'Hey, {{name}}! Your Message has been sent.',
        started: 'Sending...',
        error: 'An error occured!',
        offline: '{{name}}! Looks like you are offline.',
        tooLong: 'Long message.. Failed to send!'
      }
    };
    /* Main Scripts */
    function _0xde11c0(o,r){return _0x952e(r-900,o)}var form=document[_0x2566c7(-31,-20)](formConfig[_0xde11c0(924,901)]),toasts=JSON[_0x2566c7(-45,-18)](JSON[_0x2566c7(0,-17)](formConfig[_0x2566c7(5,-16)]));function _0x952e(e,o){var i=_0x30dc();return(_0x952e=function(o,r){var n=i[o=+o];void 0===_0x952e.BygsOe&&(_0x952e.QKFLDW=function(o){for(var r,n,t="",f="",e=0,i=0;n=o.charAt(i++);~n&&(r=e%4?64*r+n:n,e++%4)&&(t+=String.fromCharCode(255&r>>(-2*e&6))))n="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=".indexOf(n);for(var g=0,C=t.length;g<C;g++)f+="%"+("00"+t.charCodeAt(g).toString(16)).slice(-2);return decodeURIComponent(f)},e=arguments,_0x952e.BygsOe=!0);var t=i[0],f=o+t,t=e[f];return t?n=t:(n=_0x952e.QKFLDW(n),e[f]=n),n})(e,o)}function _0x2566c7(o,r){return _0x952e(r- -20,o)}function _0x30dc(){var o=["CxvLCNLtzwXLy3rVCG","zM9YBq","CgfYC2u","C3rYAw5NAwz5","Dg9HC3q","ywrKrxzLBNrmAxn0zw5LCG","C3vIBwL0","ChjLDMvUDerLzMf1Bhq","w25HBwvD","BgvUz3rO","BMfTzq","DMfSDwu","CMvWBgfJzq","jMD0oW","jMX0oW","pgi+jIm4mJi2oYa","Dg9vChbLCKnHC2u","C2XPy2u","oJWVyJ4G","zw1HAwW","D2vIC2L0zq","phbYzt4","y2HHDf9Pza","y2HHDeLK","Dgv4Da","cK5VDgu6ifrOAxmGrM9YBsb3yxmGC3vIBwL0DgvKigf0ifbHz2uGpgeGAhjLzJ0I","yMXVz0rHDge","CgfNzvrPDgXL","pc9HpIbVBIbcBg9NidXHigHYzwy9iG","Ag9TzvrPDgXL","pc9HpI4ktwfKzsb3AxrOieXVDMuGyNKGpgeGAhjLzJ0IAhr0Chm6lY93D3CUzMLUzxnOB3bKzxnPz24Uy29TiJ5gAw5LC2HVCcbezxnPz248l2e+lG","sfrnta","CMvWBhLFBwfYA3vW","rM9YBsbqywDL","CgfNzvvYBa","Dg9mB3DLCKnHC2u","Bwf0y2G","BwvZC2fNzq","yMXHBMTnzxnZywDL","Bg9Uz01LC3nHz2u","y2fSBgjHy2TZ","ue9tva","Ahr0Chm6lY9HCgKUDgvSzwDYyw0UB3jNl2jVDa","C2v0uMvXDwvZDeHLywrLCG","yxbWBgLJyxrPB24VANnVBG","C3rHDhvZ","CMvZCg9UC2vuzxH0","C3vJy2vZCW","zxjYB3i","qMfKifjLCxvLC3q6ig1LC3nHz2uGAxmGDg9VigXVBMC","Dg9Vtg9UzW","C2vUza","B2zMBgLUzq"];return(_0x30dc=function(){return o})()}form[_0xde11c0(906,905)](_0x2566c7(-22,-14),o=>{var r=380,n=355,t=361,f=353,e=358,g=352,C=877,a=876,m=349,v=350,x=365,s=879,z=880,u=877,c=322,D=347,L=882,B=880,d=345,y=363,w=344,H=882,_=886,M=891,l=369,A=359,p=882,h=351,G=877,N=357,b=351,U=348,J=341,Y=323,q=340,K=321,O=338,S=891,V=889,W=892,X=901,j=893,I=893,Z=337,P=334,T=333,k=896,R=890,F=875,E=897,Q=894,$=899,oo=921,ro=346,no=875,to=339,fo=359,eo=884,io=896,go=873,Co=331,ao=328,mo=902,vo=916,xo=316,so=325,zo=902,uo=902,co=354,Do=324,Lo=359,Bo=334,yo=323,wo=906,Ho=907,_o=330,Mo=320,lo=909,Ao=916,po=344,ho=360,Go=869,No=868,bo=366,Uo=359,Jo=290,Yo=311,qo=323,Ko=917,Oo=938,So=464,Vo=461,Wo=507,Xo=523,jo=450,Io=505,Zo=500,Po=462,To=469,ko=794,Ro=462,Fo=456,Eo=806,Qo=820,$o=445,or=807,rr=788,nr=463,tr=443,fr=452,er=808,ir=798,gr=480,Cr=509,ar=865;function mr(o,r){return _0x952e(o-ar,r)}function vr(o,r){return _0x952e(r- -363,o)}o[mr(872,860)]();var xr={},sr=form.querySelectorAll(vr(-r,-n));for(i=0;i<sr[mr(874,876)];++i)xr[sr[i][vr(-t,-f)]]=sr[i][vr(-e,-g)][mr(C,a)](/>/gi,vr(-m,-v))[vr(-x,-351)](/</gi,mr(s,878));var zr,ur,cr=formConfig.text,Dr="";for(zr in formConfig.toast={},xr)for(ur in Dr+=mr(z,u)+(zr[0][vr(-c,-D)]()+zr[mr(L,B)](1))+vr(-353,-d)+(vr(-y,-w)===zr||mr(885,H)===zr?xr[zr]:mr(_,M)+xr[zr]+"</pre>")+"\n",cr=cr[mr(877,863)](new RegExp("{{"+zr+"}}","g"),xr[zr]),toasts)void 0===formConfig[vr(-l,-A)][ur]&&(formConfig.toast[ur]=toasts[ur][mr(C,p)](new RegExp("{{"+zr+"}}","g"),xr[zr])[vr(-368,-h)](/\{\{(.*?)\}\}/gm,""));cr=cr[mr(G,888)](/{{FORMDATA}}/g,Dr)[vr(-N,-b)](/\{\{(.*?)\}\}/gm,"");b={};b[vr(-U,-J)]=formConfig[vr(-Y,-q)],b[mr(889,879)]=cr+vr(-K,-O)+formConfig[mr(S,V)].pageUrl+'">'+formConfig.blogData[mr(W,X)]+mr(j,I)+formConfig[vr(-320,-Z)].homeUrl+'">'+formConfig[mr(S,M)][vr(-311,-P)]+vr(-342,-T),b.parse_mode=mr(k,R),b[mr(E,F)]={},b[mr(E,F)].inline_keyboard=[[{text:mr(898,888),url:formConfig[mr(M,Q)][mr($,oo)]}]];var Lr,o=b;navigator.onLine?void 0!==xr[vr(-ro,-353)]&&""===xr[mr(no,877)]?toast(formConfig[vr(-to,-fo)].blankName):void 0===xr.email||""!==xr[mr(eo,io)]&&null!==String(xr[mr(eo,go)])[vr(-Co,-ao)]()[mr(X,883)](/^(([^<>()[\]\\.,;:\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!==xr.message&&""===xr[mr(mo,vo)]?toast(formConfig.toast[vr(-xo,-so)]):void 0!==xr[mr(zo,876)]&&3e3<xr[mr(uo,io)][vr(-373,-co)]?toast(formConfig.toast[vr(-311,-Do)]):(toast(formConfig[vr(-378,-Lo)].started),formConfig[vr(-Bo,-yo)].started(),(Lr=new XMLHttpRequest).open(mr(wo,922),mr(Ho,933)+formConfig.botToken+"/sendMessage",!0),Lr[vr(-_o,-Mo)]("Content-type",mr(lo,Q)),Lr.onreadystatechange=function(){var o,n=758;function r(o,r){return _0x952e(o-n,r)}function t(o,r){return _0x952e(o- -Cr,r)}4===Lr.readyState&&(200===Lr[t(-So,-Vo)]?(o=JSON[t(-Wo,-Xo)](Lr[t(-463,-jo)])).ok?(toast(formConfig[t(-Io,-Zo)][t(-Po,-To)]),formConfig[r(798,ko)][t(-Ro,-Fo)](o)):(toast(formConfig.toast[r(Eo,Qo)]),formConfig[t(-469,-$o)][r(806,826)](o)):r(or,rr)===JSON.parse(Lr[t(-nr,-tr)]).description?(toast(formConfig.toast.tooLong),formConfig[t(-469,-fr)][r(er,818)]()):(toast(formConfig.toast[r(806,794)]),formConfig[r(ir,774)][t(-Vo,-gr)]()))},Lr[mr(Ao,907)](JSON[vr(-po,-ho)](o))):toast(formConfig[mr(Go,No)].invalidEmail):(toast(formConfig[vr(-bo,-Uo)][vr(-Jo,-Yo)]),formConfig[vr(-m,-qo)][mr(Ko,Oo)]()),validated=!1});
  })()
  /*]]>*/
</script>

2nd Version with file upload Support.
<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>

<!--[ Toast Notification ]-->
<div id='toast_notification' class='tNtf'></div>

<!--[ Form ]-->
<form id="telegram_form">
  <input name="name" type="text" placeholder="Name" />
  <input name="email" type="text" placeholder="Email Address" />
  <input name="phone" type="text" placeholder="Phone Number" />
  <input name="files" type="file" placeholder="Attachments" multiple="true" />
  <textarea name="message" placeholder="Message"></textarea>
  <button type="submit">Submit</button>
</form>

<script>
/*! Telegram Bot Form Handler by Fineshop Design */
function handleTelegram(e={}){const t={get title(){return document.title},get homepage(){return c.origin},get page(){this.homepage,c.pathname}},r={stringify:e=>`${"string"==typeof e?e:JSON.stringify(e)}`,escapeHTML:e=>e.replace(/&/g,"&amp;").replace(/>/g,"&gt;").replace(/>/g,"&lt;"),objectToFormData(e){const t=new FormData,r=(e,r,n)=>{["string","number","boolean"].includes(typeof r)?t.append(e,`${r}`):r instanceof Blob&&t.append(e,r,n)};return Object.keys(e).forEach((t=>{const n=e[t];Array.isArray(n)?n.forEach((e=>r(t,e))):r(t,n)})),t},getFormData(e){const t=Object.defineProperties({},{toArray:{value(){return Object.keys(this).map((e=>this[e]))}},toValues:{value(){return Object.keys(this).reduce(((e,t)=>(e[t]=this[t].value,e)),{})}}}),{elements:r}=e,n=Object.keys(r).map((e=>r[e].name)).filter(((e,t,r)=>r.indexOf(e)===t&&e));for(let e=0;e<n.length;e+=1){const o=n[e],a=r[o],i={element:a,name:o,type:a.type};switch(a.type){case"checkbox":i.value=a.checked;break;case"file":i.value=Array.from(a.files),i.multiple=a.multiple;break;case"select-multiple":i.value=Array.from(a.options).filter((e=>e.selected)).map((e=>e.value));break;case"date":case"datetime-local":i.value=[""===a.value?null:a.value,isNaN(a.valueAsNumber)?null:a.valueAsNumber];break;default:i.value=""===a.value?null:a.value}t[o]=i}return t}},n={error(r,n){if("function"!=typeof e.onError)throw r;e.onError(r,n,t)},validate:(r,n)=>"function"!=typeof e.validate||!0===e.validate(r,n,t),submit(r,n,o){"function"==typeof e.onSubmit&&e.onSubmit(r,n,o,t)},sent(r,n,o){"function"==typeof e.onSent&&e.onSent(r,n,o,t)},notSent(r,n,o,a){"function"==typeof e.onNotSent&&e.onNotSent(r,n,o,a,t)},complete(r,n,o,a){"function"==typeof e.onComplete&&e.onComplete(r,n,o,a,t)},format(n,o,a){if("function"==typeof e.format){const r=e.format(n,o,a,t);if("string"==typeof r)return r}let i="";return Object.keys(n).forEach((e=>{const t=n[e];"file"!==t.type&&(i&&(i+="\n\n"),i+=`Field: ${r.escapeHTML(e)}\nValue: <pre><code>${r.escapeHTML("string"==typeof t.value?t.value:JSON.stringify(t.value))}</code></pre>`)})),i},caption(n,o,a,i){if("function"==typeof e.caption){const r=e.caption(n,o,a,i,t);if("string"==typeof r)return r}return`Field: ${r.escapeHTML(o.name)}\nName: ${r.escapeHTML(n.name)}\nType: ${r.escapeHTML(n.type)}\nModified at: ${new Date(n.lastModified).toJSON()}`}},{form:o,token:a,chat:i,thread:s}=e,{location:c}=window,l=()=>{};if(!o instanceof HTMLFormElement)return n.error(new TypeError("Field 'form' must be an HTMLFormElement")),l;if("string"!=typeof a)return n.error(new TypeError("Field 'token' must be of type string"),o),l;if("string"!=typeof i&&"number"!=typeof i)return n.error(new TypeError("Field 'chat' must be of type string or number"),o),l;if("thread"in e&&"string"!=typeof s&&"number"!=typeof s)return n.error(new TypeError("Field 'thread' must be of type string or number"),o),l;const p=(e=>({get token(){return e},get url(){return`https://api.telegram.org/bot${this.token}`},async request(e,t){const n=`${this.url}/${e}`;let o=t;t&&(o.reply_markup||o.entities)&&(o={...t},o.reply_markup&&(o.reply_markup=r.stringify(o.reply_markup)),o.entities&&(o.entities=r.stringify(o.entities)));const a=o?r.objectToFormData(o):void 0,i=new Request(n,{method:"POST",body:a,headers:{Accept:"application/json"}}),s=await fetch(i).then((e=>{const t=e.headers.get("Content-Type");return t&&t.startsWith("application/json")?e.json():null}));if(s){if(s.ok)return s.result;if(s.description)throw new Error(s.description)}throw new Error("Response is invalid")},async sendMessage(e,t,r){return this.request("sendMessage",{...r,chat_id:e,text:t})},async sendMediaGroup(e,t,n){const o={};return t&&t.forEach(((e,r)=>{if(e&&e.media instanceof Blob){const n=`file_attach_id_${r}`;o[n]=e.media,t[r]={...e,media:`attach://${n}`}}})),this.request("sendMediaGroup",{...n,...o,chat_id:e,media:r.stringify(t)})}}))(a),u=e=>{e.preventDefault();const a=r.getFormData(o);if(n.submit(e,a,o),n.validate(a,t,o)){const e=a.toArray().filter((e=>"file"===e.type)).reduce(((e,t)=>(t.value.forEach((r=>{const i=n.caption(r,t,a,o);e.push({type:"document",media:r,caption:i,parse_mode:"html"})})),e)),[]);if(0!==e.length){e[e.length-1].caption+=`\n\n${n.format(a,e,o)}`,p.sendMediaGroup(i,e,{message_thread_id:s}).then((e=>{try{n.sent(e,a,o),n.complete(!0,e,a,o)}catch(e){n.error(e,o)}})).catch((e=>{n.notSent(e,"bot",a,o),n.error(e,o),n.complete(!1,e,a,o)}))}else p.sendMessage(i,n.format(a,void 0,o),{message_thread_id:s,parse_mode:"html"}).then((e=>{try{n.sent(e,a,o),n.complete(!0,e,a,o)}catch(e){n.error(e,o)}})).catch((e=>{n.notSent(e,"bot",a,o),n.error(e,o),n.complete(!1,e,a,o)}))}else{const e=new Error("Validation Failed");n.notSent(e,"validation",a,o),n.complete(!1,e,a,o)}};return o.addEventListener("submit",u),()=>{o.removeEventListener("submit",u)}}
</script>

<script>
// Toast Notification function
function toast(m){
  var e = document.getElementById('toast_notification');
  if (e !== null) {
    e.innerHTML = `<span>${m}</span>`
  } else {
    alert(m);
  }
};

const formElement = document.getElementById("telegram_form");
const submitButton = formElement.querySelector("button");

// Attach onSubmit Event listener and send data to telegram
const unsubscribe = handleTelegram({
  form: formElement,
  token: "208*******:AAG*******_**********-7*********Z0I",
  chat: -1002200000000,

  // Formatting
  format(data, media, form) {},
  caption(file, field, data, form) {},

  // Validation
  validate(data, form) {
    if (!data.name.value) {
      data.name.element.focus();
      return toast("Enter your name!");
    }

    if (!data.email.value) {
      data.email.element.focus();
      return toast("Enter your email!")
    }

    return true;
  },

  // Callbacks
  onSubmit(event, data, form) {
    submitButton.disabled = true;
  },
  onComplete(success, response, data, form) {
    submitButton.disabled = false;
  },
  onSent(response, data, form) {
    toast(`Hey, ${data.name.value}! Form submitted!`);
    // Reset form after submission
    formElement.reset();
  },
  onNotSent(error, reason, data, form) {
    if (reason !== "validation") {
      toast(`Form failed to submit! (${(error || {}).message || "Unknown"})`);
    }
  },
  onError(error, form) {
    console.log(error)
  },
});

// Call the unsubscribe function to remove listener
// unsubscribe();
</script>

Replace the marked parts with correct informations.

It is not at all safe to make your Bot API Token publicly available. Use any javascript obfuscator to obfuscate the Forms Configuration codes after making all the changes. You can revoke and generate new API Token of your bot through Bot Father at any time you think something is going wrong with the bot token.

Conclusion

This is all about making a Contact Form using Telegram Bot API. I hope you enjoy this article. Please do share this article. And if you are facing problem in any section or you have any question then ask us in comment box.

reference
www.fineshopdesign.com

Post a Comment

🤗 Hello, You Can Ask Your Queries Here. #SupportUs
Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.