How to Create a Contact Page Using Telegram API

Creating a contact page is an essential part of any website. It provides visitors with a means to reach out, ask questions, and engage with your services. While there are many traditional methods to set up a contact page, integrating it with Telegram API offers a modern, real-time communication channel. This blog will guide you through the steps to create a contact page using Telegram API, ensuring your visitors can easily connect with you through Telegram.

Create a Contact Page Using Telegram API

With the rise of instant messaging apps, providing users with quick and efficient ways to contact you is crucial. Telegram, known for its speed and security, is an excellent choice. By using the Telegram API, you can create a contact page that sends messages directly to your Telegram account or group, ensuring you never miss an important inquiry.

Why Use Telegram API?

  • Real-Time Communication: Receive messages instantly, allowing for prompt responses.
  • Security: Telegram offers robust encryption, ensuring your conversations remain private.
  • Multi-Platform: Accessible on various devices, including smartphones, tablets, and desktops.
  • Automation: You can automate responses and manage contacts more efficiently.


Video Tutorial Related to This Topic

If you don’t feel like reading, then instead of reading you can watch the video below that is related to this topic.

Setting Up Your Telegram Bot

Before you can integrate Telegram into your website, you need to create a Telegram bot. Follow these steps:

  1. Create a Telegram Account: If you don't have one, download the Telegram app and sign up.
  2. Search for BotFather: In the Telegram app, search for the BotFather bot.
  3. Create a New Bot: Start a chat with BotFather and use the command /newbot. Follow the prompts to name your bot and create a username.
  4. Get Your Token: BotFather will provide you with a token. Save this token as it allows you to interact with Telegram's API.

Setting Up Your Telegram Group

  1. Now open web.telegram.org on your browser.
  2. Create a new group or you can use an old one.
  3. Make the group private if it already isn't. So that none can view the messages except for you.
  4. Go to the group and copy the group ID from the URL.
  5. You will see a number at the end of your group URL. That's the ID number of your group.
  6. Finally, invite the bot you just created to your group.

Integrating Telegram API with Your Website

Now that we have our Telegram bot token and a group to receive the messages. We need to set up the contact form. You can use this contact form on Blogger, WordPress or any other website.

Creating the Contact Page

We need a contact page to add our code. If you are using a Blogger website then follow the instructions below to create a contact page.
  • Log in to your Blogger Dashboard.
  • Go to Pages and click on NEW PAGE.
  • Give it a title (eg, Contact or Contact Us)
  • Click on Publish to publish the page.

Creating the Contact Form

Now that we have a contact page, let's add some code to it to make it work. Copy and paste the following codes one by one to your contact page. You must do it in View HTML mode.

Step 1: If you are a Plus UI template user then only copy the below CSS code and add it to your contact page.

<style>
.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, 0.8);font-size:14px;font-family:inherit;border-radius:3px;padding:13px 24px;box-shadow:0 5px 35px rgba(149, 157, 165, 0.3);opacity:0;transition:all 0.1s ease;animation:slideinwards 2s ease forwards;-webkit-animation:slideinwards 2s ease forwards}form#telegram_form{margin:35px;border:2px dashed rgba(0,0,0,0.5);padding:15px;border-radius:35px}.widget input[type=email],.widget input[type=text],.widget 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;line-height:1.6em;transition:var(--trans-1);margin-bottom:10px}button,input,select,textarea{font:inherit;font-size:100%;color:inherit;line-height:normal;margin:10px 0}@media screen and (max-width: 500px){.tNtf span{margin-bottom:20px;left:20px;right:20px;font-size:13px}}@media screen and (max-width: 386px){form#telegram_form{margin:0;border:2px dashed rgba(0,0,0,0.5);padding:15px;border-radius:35px}}@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, 0.2)}
</style>

Step 2: If You are using other template which is not Plus UI then use the below CSScode instead.

<style>
.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, 0.8);font-size:14px;font-family:inherit;border-radius:3px;padding:13px 24px;box-shadow:0 5px 35px rgba(149, 157, 165, 0.3);opacity:0;transition:all 0.1s ease;animation:slideinwards 2s ease forwards;-webkit-animation:slideinwards 2s ease forwards}form#telegram_form{margin:35px;border:2px dashed rgba(0,0,0,0.5);padding:15px;border-radius:35px}.widget input[type=email],.widget input[type=text],.widget 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;line-height:1.6em;transition:var(--trans-1);margin-bottom:10px}button,input,select,textarea{font:inherit;font-size:100%;color:inherit;line-height:normal;margin:10px 0}.button{display:inline-flex;align-items:center;margin:10px 0;padding:12px 15px;outline:0;border:0;border-radius:50px;line-height:20px;color:#fffdfc;background:#ff3333;font-size:14px;font-family:Roboto;white-space:nowrap;overflow:hidden;max-width:320px}@media screen and (max-width: 500px){.tNtf span{margin-bottom:20px;left:20px;right:20px;font-size:13px}}@media screen and (max-width: 386px){form#telegram_form{margin:0;border:2px dashed rgba(0,0,0,0.5);padding:15px;border-radius:35px}}@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, 0.2)}
</style>

Step 3: Now add the following HTML and JavaScript code just below the CSS code.

<!--[ 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 class="button" type="submit">Submit</button>
  </form>
<script>
  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>

Step 4: You need to add another JavaScript code which is the below one. But before you add this code to your contact page, replace the value of the token and chat with your bot token and chat ID

<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: "paste_your_bot_token_here",
    chat: -paste_group_id_here,
  
    // 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>

Step 5: After editing the code, copy it and go to this website. Now paste this code to the website and click on Obfuscate. Copy the obfuscated code and paste it on your contact page. 

Step 6: Finally, click on Update to save the changes in your contact page.

Conclusion

Integrating Telegram API with your website’s contact page offers a quick and secure way for users to reach out. It enhances communication efficiency and ensures you receive messages in real-time. By following the steps outlined above, you can set up a fully functional contact page that leverages the power of Telegram, providing a modern touch to your user interaction strategy.

Remember to test your contact form thoroughly to ensure it works as expected. Happy coding!

Next Post Previous Post
No Comment
Add Comment
comment url