Building a Telegram bot: Detail tutorial write up

in #utopian-io6 years ago (edited)

In this telegram video tutorial, I will be sharing on the guide on creating a telegram bot on top of steem blockchain. This bot will broadcast out in the Telegram Channel, whenever someone posted on steem with the tag #teammalaysia and #contest.

This bot allow users/subscribers to know the contest at the moment of posting, and participate it immediately.

kenan.jpg

What Will I Learn?

  • Create a bot on Telegram
  • Code the bot on top of steem blockchain, watch for a certain tags (In this case it is #teammalaysia and #contest)

Requirements

  • Telegram account
  • Node.js Installed

Difficulty

Intermediate

Description

This video tutorial is separated into 2 parts, where the first part is to get the necessary keys to start the project and the second part is to code the bot.

Part 1: Setting up the bot

There are 2 keys that we need to extract out before we start coding, which is the telegram bot API key and Channel ID.

Getting telegram bot API key

To get the Bot API key, you just need to message BotFather on telegram, starting with the command /newbot. Follow the instruction given by BotFather and eventually he will give out a message and give you the key.

Screen Shot 2018-03-24 at 5.07.49 PM.png

Getting the channel ID key

For this part, it requires you to use the telegram web interface. After you create a new Channel, add in the bot you created previously and made it an admin. To get the channel ID, just get the URL of the telegram channel, and extract out the first combination of numbers. Then, add -100 as a prefix in front of the numbers.

Screen Shot 2018-03-24 at 5.14.26 PM.png

You can read through the guide on stack overflow

Part 2: Coding the bot

Save both of the key you generated in Part 1 into .env file

In the .env file, it looks like this:

CHANNEL_ID=-100<CHANNEL_ID>
BOT_KEY=<API_KEY>

Initialize the project

Start the project with npm init or yarn init.

Install necessary dependencies.

In this tutorial, I will make use of 3 library:

  • node-telegram-bot-api - an API layer for us to deal with telegram using Node.js
  • steem - Official Steem API, using it to watch all steem new posts.
  • dotenv - a library to use .env file.

To install, just run npm install --save node-telegram-bot-api steem dotenv or yarn add node-telegram-bot-api steem dotenv.

Start Coding

After installing the dependencies, we can just create variables out from the library.

const telegram = require('node-telegram-bot-api');
const steem = require('steem');
const dotenv = require('dotenv');

We import all the .env file with the function:

dotenv.config();

Then, create a new telegram variable by passing in the private API key in the .env file and connect to the telegram bot with the method of long polling.

const bot = new telegram(process.env.BOT_KEY, {
  polling: true
});

Next, we need to watch the Steem transaction. So, whenever there is a transaction (new post) on steem, it will watch for that. It is just like on Web interface, we use JS to watch when a user pressed a button.

steem.api.streamTransactions('head', function(err, result) {
  if (err) {
    return;
  }
  // Insert Code Here
})

From the result of the transaction, we look for 2 data that we need.

  let txType = result.operations[0][0];
  let txData = result.operations[0][1];

Then, we make sure that the post is a post (not a comment), and it is not a resteem

  if (txType === 'comment' && txData.parent_author === '') {
      // Insert Code Here
  } else {
    return;
  }

Next, we try and see wether the post contain tags or not. If it doesn't, just return.

    let tags;

    try {
      tags = JSON.parse(txData.json_metadata).tags;
    } catch (e) {
      return;
    }

Next, we check wether the tags has #teammalaysia and #contest. If it doesn't, just return it.

 if (
      tags.includes('contest') &&
      tags.includes('teammalaysia')
    ) {
    // Insert Code Here
} else {
  return:
}

Then, just extract out the author and permlink , and make it into steemit link.

let link = `@${txData.author}/${txData.permlink}`; // @superoo7/something

Then, we just need to telegram bot to send the message in the channel, by passing in the channel ID from .env and the steemit link.

bot.sendMessage(
        process.env.CHANNEL_ID,
        `https://steemit.com/${link}`
      );

The full source code

const telegram = require('node-telegram-bot-api');
const steem = require('steem');
const dotenv = require('dotenv');

dotenv.config();

const bot = new telegram(process.env.BOT_KEY, {
  polling: true
});

steem.api.streamTransactions('head', function(err, result) {
  if (err) {
    return;
  }

  let txType = result.operations[0][0];
  let txData = result.operations[0][1];

  // Check a post and it is not being resteem
  if (txType === 'comment' && txData.parent_author === '') {
    let tags;

    try {
      tags = JSON.parse(txData.json_metadata).tags;
    } catch (e) {
      return;
    }

    if (
      tags.includes('contest') &&
      tags.includes('teammalaysia')
    ) {
      let link = `@${txData.author}/${txData.permlink}`;

      bot.sendMessage(
        process.env.CHANNEL_ID,
        `https://steemit.com/${link}`
      );
    }
  }
});

Video Tutorial

Video Part 1: Setting up the bot

Link to DTube


Video Part 2: Coding


Link to DTube




Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

  • Interesting project . but it could be much better if you talk more detail about how to use node-telegram-bot-api since your tutorial is about the node-telegram-bot-api repo but not the steem-js repo .

You can contact us on Discord.
[utopian-moderator]

Thank you moderator. I will improve in the next tutorial.

Thank you for sharing your posts with us. This post was curated by TeamMalaysia as part of our community support. Looking forward for more posts from you.

To support the growth of TeamMalaysia Follow our upvotes by using steemauto.com and follow trail of @myach

Vote TeamMalaysia witness bitrocker2020 using this link vote bitrocker2020 witness

Nice tutorial. Thanks for sharing. I will come back to it when I code my first Telegram bot :)

Thanks for supporting! Really appreciate it 😃

it sounds cool . but could you edit it to embedd the video into the tutorial??

hey @cha0s0000 , I think there is some weird behaviour that iframe being sanitize by Utopian and Steem,

You can try busy.org link https://busy.org/utopian-io/@superoo7/building-a-telegram-bot-detail-tutorial-write-up

erm wait, it is not working, let me edit it

Great tutorial you got here. It gave me good insight into using steem Api for creative stuffs. Would definitely make use of this soon. Thanks again!

Sure man. Thanks for stopping by

Kindly make the required corrections as stated by the mod for this to be approved.
It's still in reserve though.

I already done. I uploaded the video on youtube. Some weird behaviour with dtube on steemit , busy and utopian

Great! Enjoy!

Hey @superoo7 I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

such a great read!so much detail thank you so much for this keep up the great work!!

Coin Marketplace

STEEM 0.19
TRX 0.15
JST 0.029
BTC 63592.23
ETH 2551.58
USDT 1.00
SBD 2.75