Posted in raspberrypi, telegram, bot

How is Telegram different from WhatsApp?(photo made by Sfecles Petru)

I spent some time trying to figure out how to create a telegram bot. I really got lost in the official documentation. Then, I found the framework that has made everything easier, telepot.

What is telegram? Telegram is a messaging app that is simple to use and one of the main focuses is security. This sound very similar to WhatsApp, but you can find here how it's different.

I find bots being very useful, especially when I remotely trying to control something from my house. If you like creating bots, find that I created a similar post, but using a discord bot.

The simple hardware 

As you can see in the image below, the circuit is very simple. When you connect the LED to the Raspberry Pi, don't forget to add the resistor (I use one of 1K ohm).

 LED connected to Raspberry Pi Zero

Control your bot like a 'boss'

But first, let's create the bot by chatting with @BotFather (they have a good sense of humor), the bot above all bots. Write the following command /newbot and follow the steps to configure the name and the id for the bot. I named the bot I created it, TheHumbleCodeBot. After you finish this steps you will be given a unique token, save it, we will need it later.

Creating a telegram bot with the help of BotFather

Now, we have to install telepot. It supports multiple version of Python. You can find more details in the introduction of the telepot framework.

pip install telepot

The good thing is that we don't have to make a request in order to see if something wrote something in the chat. Instead, we can use a built-in functionality, Message Loop, from telebot that makes use of Webhooks and continuously will apply a handling function for every message received. 

import RPi.GPIO as GPIO
import telepot
import time
from telepot.loop import MessageLoop

# use channel numbers on the Broadcom SOC
GPIO.setmode(GPIO.BCM)

LED_PIN = 19
GPIO.setup(LED_PIN, GPIO.OUT)

bot = telepot.Bot('579430837:AAEG-ll76_EnQ2XBQqaN3B4wQpptpCB5PY0')

def turnOn(chatId):
    GPIO.output(LED_PIN, True)
    bot.sendMessage(chatId, 'The led is ON now!')

def turnOff(chatId):
    GPIO.output(LED_PIN, False)
    bot.sendMessage(chatId, 'The led is OFF now!')

def handleCommand(msg):
    contentType, chatType, chatId = telepot.glance(msg) # extract “headline info”
    print(contentType, chatType, chatId)

    if contentType != 'text':
        return # nothing to do

    message = msg['text']

    if not message.startswith('!'):
        return # not a command
    
    command = message[1:].lower() # remove ! from the command name
    if command == 'on':
        turnOn(chatId)
    elif command == 'off':
        turnOff(chatId)

if __name__ == '__main__':
    try:
        MessageLoop(bot, handleCommand).run_as_thread()

        while 1:
            # just don't finish the program
            time.sleep(10)
        # close execution by pressing CTRL + C
    except KeyboardInterrupt:
        print("Intrerrupted by user")
        pass
    finally:
        print("Program stopped")
        GPIO.cleanup()

To start the bot is pretty easy, save the above code in a file named bot.py and run it using the following command in the console:

python bot.py

In order to chat with your bot, you can replace the bot id in the following name, https://web.telegram.org/#/im?p=@YOUR_BOT_ID (mine is TheHumbleCodeBot).

Chatting with the telegram bot

Conclusion

The bots have a good potential, especially when you want to control something from your home or just receiving updates. You can append anything you want to your bot, temperature, motion sensor, led matrixes and many others. 

I hope this post helps you to create a bot much easier for your current/future projects.

Thank you for reading, and never stop receiving knowledge!

Posted in raspberrypi, discord, bot

In this post I will use a Discord to turn on/off a led that is attached to a Raspberry Pi Zero. This is going to show how easy is to control something from your house using the Discord. And will demonstrate that even if the Discord is designed for gaming communities it can be used for many more.

blink-blink.gif

How do I do this?

To control the led using Discord we need to run a Bot on Rasbperry Pi Zero. To create a Discord Bot use the following steps that can be found here. After you create the application don't forget to mark it as a Bot (be aware, the action is irreversible). Save the token provided by the application and store it in a json file in order to be used.

In this mini project I named the file auth.json, don't forget to use the token of the Bot you created.

{ 
"token": "PUT_YOUR_TOKEN_HERE"
}

The package.json file for the this project. I may use some old dependencies of rpio (at the moment of writting this), but for this project is enough. Also the discord.js module to interact with Discord, make sure you have the node version 6 or higher. If you don't there are many tutorials on internet that help you achieve this.

{
   "name": "home-manager-led",
   "version": "0.0.1",
   "description": "A bot that helps me to automize my home.",
   "main": "bot.js",
   "author": "TheHumbleCode",
   "dependencies": {
      "rpio": "0.9.12",
      "discord.js": "^11.3.2"
   }
}

The code below allows us to use the keywords !on, !off and !blink in the discord chat to control the led.

First, we import the auth token in order to login to Discord. In this project I have chose to use the PIN 18 from Raspberry Pi Zero. After the led is turned on or off a message is sent to the Discord chat in order to have a feedback when we are not close to the led.

var auth = require('./auth.json');
var Discord = require('discord.js');
var rpio = require('rpio');

// Initialize Discord Bot
var bot = new Discord.Client();
bot.on('ready', (evt) => {
    console.log('Connected');
});

const LED_PIN = 18;
/*
 * Set the initial state to low. The state is set prior to the pin becoming
 * active, so is safe for devices which require a stable setup.
 */
rpio.open(LED_PIN, rpio.OUTPUT, rpio.LOW);

turnOn = (channel) => {
    rpio.write(LED_PIN, rpio.HIGH);
    channel.send('The led is ON now!');
};

turnOff = (channel) => {
    rpio.write(LED_PIN, rpio.LOW);
    channel.send('The led is OFF now!');
}

bot.on('message',  message => {
    // Our bot needs to know if it will execute a command
    // It will listen for messages that will start with `!`
    var text = message.content;
    var channel = message.channel;
    if (text.substring(0, 1) == '!') {
        var args = text.substring(1).split(' ');
        var cmd = args[0];
       
        args = args.splice(1);
        switch(cmd) {
            // !open
            case 'on':
                turnOn(channel);
            break;
            case 'off':
                turnOff(channel);
            break;
            case 'blink':
                turnOn(channel);
                setTimeout(() => {
                    turnOff(channel);
                }, 3000);
            break;
            // Just add any case commands if you want to..
         }
     }
});

bot.login(auth.token);

I put the above code in a file named bot.js and used the command node bot.js to start it.

raspberry_pi_blink.gif

You can add any custom commands or replace the led with something else, like a matrix of leds or a temperature sensor that will tell you how many oC (or fahrenheit) are in the room.  

Thank you for reading!