Hackster is hosting Hackster Holidays, Ep. 7: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Friday!Stream Hackster Holidays, Ep. 7 on Friday!
KRISHNARAJ V
Published © CC BY-ND

Smart Mirror with Home Automation using chats

The mirror which shows news with date, calendar and quotes. Home automation can be controlled by Telegram chat.

AdvancedFull instructions provided10 hours14,224
Smart Mirror with Home Automation using chats

Things used in this project

Hardware components

Raspberry Pi 2 Model B
Raspberry Pi 2 Model B
×1
PC Monitor with VGA Cable
×1
Wifi Receiver
×1
Two way mirror acrylic sheet
×1
5v Relay Module
×1
Jumper wires (generic)
Jumper wires (generic)
×1

Software apps and online services

Raspbian
Raspberry Pi Raspbian
Telegram App

Hand tools and fabrication machines

Hot glue gun (generic)
Hot glue gun (generic)

Story

Read more

Code

index.php

PHP
Codes are already given in folders
<!DOCTYPE html>

<html lang="en">


<head>
    <meta http-equiv="refresh" content="900"> <!-- Refresh every 15 minutes -->
<title>mSmart Home</title>
	<meta charset="utf-8">
    <meta http-equiv=Content-Type content="text/html; charset=utf-8">


	<link rel="stylesheet" href="css/calendar.css" media="screen">
    
    
    	
<style>
/* Paste this css to your style sheet file or under head tag */
/* This only works with JavaScript, 
if it's not present, don't show loader */
.no-js #loader { display: none;  }
.js #loader { display: block; position: absolute; left: 100px; top: 0; }
.se-pre-con {
	position: fixed;
	left: 0px;
	top: 0px;
	width: 100%;
	height: 100%;
	z-index: 9999;
	background: url(img/Preloader.gif) center no-repeat #15191f;
}
</style>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.js"></script>
<script>
	//paste this code under head tag or in a seperate js file.
	// Wait for window load
	$(window).load(function() {
		// Animate loader off screen
		$(".se-pre-con").fadeOut("slow");;
	});
</script>

    
    
    
    
	<style type="text/css">
        body{                          
            cursor:none;
            background:black repeat;
            background color: black;
            width:960px;margin:0 auto}
        .footer{
            margin-top:100px;
            text-align:center;
            color:#666;
            font:bold 14px Arial}
        .footer a{
            color:#999;
            text-decoration:none}
        #wrapper{
            padding: 50px 0 0 325px;}
        #calendar{
            margin:25px auto; 
            width: 370px;}
        .logo {
            text-align:right;
    width: 180px;
    height: 110px;
    /* background: url('https://s22.postimg.org/8lnlahok1/m_Smart_Logo.png') no-repeat; */
    /* margin: 30px auto; */
}
    </style>
<meta name="robots" content="noindex,follow" />
    
    
<style type="text/css">
html {
     cursor:none;
overflow:hidden;
}
</style>
    
    
<script type="text/javascript" src="js/jquery-1.11.2.min.js"></script>    
<script type="text/javascript">
			/*
			This code has been created by Alexandre Barfuhok and has been taken on Fooyok: http://fooyok.com/gadgets/how-to-build-an-homemade-high-tech-mirror-with-an-old-phone
			You can use this code, edit it, do whatever you want, but simply give me credit and link to my blog post.
			Thanks :)			
			*/
			
			//Refresh the document once in a while to get file updates
			setTimeout(function(){location.reload(true)},"3600000");
			
			$( document ).ready(function() {
				var quotes = [
					[["Life is about making an impact, not making an income."], ["Kevin Kruse"]],
					[["Whatever the mind of man can conceive and believe, it can achieve."], ["Napoleon Hill"]],
					[["Strive not to be a success, but rather to be of value."], ["Albert Einstein"]],
					[["Two roads diverged in a wood, and I—I took the one less traveled by, And that has made all the difference."], ["Robert Frost"]],
					[["I attribute my success to this: I never gave or took any excuse."], ["Florence Nightingale"]],
					[["You miss 100% of the shots you don’t take."], ["Wayne Gretzky"]],
					[["The most difficult thing is the decision to act, the rest is merely tenacity."], ["Amelia Earhart"]],
					[["Every strike brings me closer to the next home run."], ["Babe Ruth"]],
					[["Definiteness of purpose is the starting point of all achievement."], ["W. Clement Stone"]],
					[["Life isn’t about getting and having, it’s about giving and being."], ["Kevin Kruse"]],
					[["Life is what happens to you while you’re busy making other plans."], ["John Lennon"]],
					[["We become what we think about."], ["Earl Nightingale"]],
					[["Life is 10% what happens to me and 90% of how I react to it."], ["Charles Swindoll"]],
					[["The most common way people give up their power is by thinking they don’t have any."], ["Alice Walker"]],
					[["The mind is everything. What you think you become."], ["Buddha"]],
					[["The best time to plant a tree was 20 years ago. The second best time is now."], ["Chinese Proverb"]],
					[["An unexamined life is not worth living."], ["Socrates"]],
					[["Eighty percent of success is showing up."], ["Woody Allen"]],
					[["Your time is limited, so don’t waste it living someone else’s life."], ["Steve Jobs"]],
					[["Winning isn’t everything, but wanting to win is."], ["Vince Lombardi"]],
					[["I am not a product of my circumstances. I am a product of my decisions."], ["Stephen Covey"]],
					[["Every child is an artist. The problem is how to remain an artist once he grows up."], ["Pablo Picasso"]],
					[["You can never cross the ocean until you have the courage to lose sight of the shore."], ["Christopher Columbus"]],
					[["I’ve learned that people will forget what you said, people will forget what you did, but people will never forget how you made them feel."], ["Maya Angelou"]],
					[["Either you run the day, or the day runs you."], ["Jim Rohn"]],
					[["Whether you think you can or you think you can’t, you’re right."], ["Henry Ford"]],
					[["The two most important days in your life are the day you are born and the day you find out why."], ["Mark Twain"]],
					[["Whatever you can do, or dream you can, begin it. Boldness has genius, power and magic in it."], ["Johann Wolfgang von Goethe"]],
					[["The best revenge is massive success."], ["Frank Sinatra"]],
					[["People often say that motivation doesn’t last. Well, neither does bathing. That’s why we recommend it daily."], ["Zig Ziglar"]],
					[["Life shrinks or expands in proportion to one’s courage."], ["Anais Nin"]],
					[["The only person you are destined to become is the person you decide to be."], ["Ralph Waldo Emerson"]],
					[["Go confidently in the direction of your dreams. Live the life you have imagined."], ["Henry David Thoreau"]],
					[["Few things can help an individual more than to place responsibility on him, and to let him know that you trust him."], ["Booker T. Washington"]],
					[["Certain things catch your eye, but pursue only those that capture the heart."], [" Ancient Indian Proverb"]],
					[["Believe you can and you’re halfway there."], ["Theodore Roosevelt"]],
					[["Everything you’ve ever wanted is on the other side of fear."], ["George Addair"]],
					[["We can easily forgive a child who is afraid of the dark; the real tragedy of life is when men are afraid of the light."], ["Plato"]],
					[["Teach thy tongue to say, “I do not know,” and thous shalt progress."], ["Maimonides"]],
					[["Start where you are. Use what you have. Do what you can."], ["Arthur Ashe"]],
					[["Fall seven times and stand up eight."], ["Japanese Proverb"]],
					[["When one door of happiness closes, another opens, but often we look so long at the closed door that we do not see the one that has been opened for us."], ["Helen Keller"]],
					[["Everything has beauty, but not everyone can see."], ["Confucius"]],
					[["How wonderful it is that nobody need wait a single moment before starting to improve the world."], ["Anne Frank"]],
					[["When I let go of what I am, I become what I might be."], ["Lao Tzu"]],
					[["Life is not measured by the number of breaths we take, but by the moments that take our breath away."], ["Maya Angelou"]],
					[["Happiness is not something readymade. It comes from your own actions."], ["Dalai Lama"]],
					[["If you’re offered a seat on a rocket ship, don’t ask what seat! Just get on."], ["Sheryl Sandberg"]],
					[["If the wind will not serve, take to the oars."], ["Latin Proverb"]],
					[["You can’t fall if you don’t climb. But there’s no joy in living your whole life on the ground."], ["Unknown"]],
					[["We must believe that we are gifted for something, and that this thing, at whatever cost, must be attained."], ["Marie Curie"]],
					[["Too many of us are not living our dreams because we are living our fears."], ["Les Brown"]],
					[["Challenges are what make life interesting and overcoming them is what makes life meaningful."], ["Joshua J. Marine"]],
					[["If you want to lift yourself up, lift up someone else."], ["Booker T. Washington"]],
					[["I have been impressed with the urgency of doing. Knowing is not enough; we must apply. Being willing is not enough; we must do."], ["Leonardo da Vinci"]],
					[["Limitations live only in our minds. But if we use our imaginations, our possibilities become limitless."], ["Jamie Paolinetti"]],
					[["You take your life in your own hands, and what happens? A terrible thing, no one to blame."], ["Erica Jong"]],
					[["What’s money? A man is a success if he gets up in the morning and goes to bed at night and in between does what he wants to do."], ["Bob Dylan"]],
					[["I didn’t fail the test. I just found 100 ways to do it wrong."], ["Benjamin Franklin"]],
					[["In order to succeed, your desire for success should be greater than your fear of failure."], ["Bill Cosby"]],
					[["A person who never made a mistake never tried anything new."], [" Albert Einstein"]],
					[["The person who says it cannot be done should not interrupt the person who is doing it."], ["Chinese Proverb"]],
					[["There are no traffic jams along the extra mile."], ["Roger Staubach"]],
					[["It is never too late to be what you might have been."], ["George Eliot"]],
					[["You become what you believe."], ["Oprah Winfrey"]],
					[["I would rather die of passion than of boredom."], ["Vincent van Gogh"]],
					[["A truly rich man is one whose children run into his arms when his hands are empty."], ["Unknown"]],
					[["It is not what you do for your children, but what you have taught them to do for themselves, that will make them successful human beings."], ["Ann Landers"]],
					[["If you want your children to turn out well, spend twice as much time with them, and half as much money."], ["Abigail Van Buren"]],
					[["Build your own dreams, or someone else will hire you to build theirs."], ["Farrah Gray"]],
					[["Education costs money. But then so does ignorance."], ["Sir Claus Moser"]],
					[["I have learned over the years that when one’s mind is made up, this diminishes fear."], ["Rosa Parks"]],
					[["It does not matter how slowly you go as long as you do not stop."], ["Confucius"]],
					[["If you look at what you have in life, you’ll always have more. If you look at what you don’t have in life, you’ll never have enough."], ["Oprah Winfrey"]],
					[["Remember that not getting what you want is sometimes a wonderful stroke of luck."], ["Dalai Lama"]],
					[["You can’t use up creativity. The more you use, the more you have."], ["Maya Angelou"]],
					[["Dream big and dare to fail."], ["Norman Vaughan"]],
					[["Our lives begin to end the day we become silent about things that matter."], ["Martin Luther King Jr."]],
					[["Do what you can, where you are, with what you have."], ["Teddy Roosevelt"]],
					[["If you do what you’ve always done, you’ll get what you’ve always gotten."], ["Tony Robbins"]],
					[["Dreaming, after all, is a form of planning."], ["Gloria Steinem"]],
					[["It’s your place in the world; it’s your life. Go on and do all you can with it, and make it the life you want to live."], ["Mae Jemison"]],
					[["You may be disappointed if you fail, but you are doomed if you don’t try."], ["Beverly Sills"]],
					[["Remember no one can make you feel inferior without your consent."], ["Eleanor Roosevelt"]],
					[["Life is what we make it, always has been, always will be."], ["Grandma Moses"]],
					[["The question isn’t who is going to let me; it’s who is going to stop me."], ["Ayn Rand"]],
					[["When everything seems to be going against you, remember that the airplane takes off against the wind, not with it."], ["Henry Ford"]],
					[["It’s not the years in your life that count. It’s the life in your years."], ["Abraham Lincoln"]],
					[["Change your thoughts and you change your world."], ["Norman Vincent Peale"]],
					[["Either write something worth reading or do something worth writing."], ["Benjamin Franklin"]],
					[["Nothing is impossible, the word itself says, “I’m possible!”"], ["Audrey Hepburn"]],
					[["The only way to do great work is to love what you do."], ["Steve Jobs"]],
					[["If you can dream it, you can achieve it."], ["Zig Ziglar"]]
				];
				
				function getQuote() {
					var random = Math.floor(Math.random() * quotes.length);
					var quote = quotes[random][0].toString();
					var author = quotes[random][1].toString();
					$( ".quote, .author" ).animate({
						opacity: 0
					}, 3000, function() {
						if(quote.length < 50) { //94
							$(".quote").css("font-size", "20px");
						} else if(quote.length >= 50 && quote.length < 80) { //89
							$(".quote").css("font-size", "18px");
						} else { 
							$(".quote").css("font-size", "15px");
						}
						$(".quote").html(quote);
						$(".author").html("&#8212; " + author);
						$( ".quote, .author" ).animate({opacity: 1}, 3000);
					});
					setTimeout(function () {
						getQuote();
					}, 30000);
				}
				
				getQuote();
			});

		</script>

		<style type="text/css">
			body {
				background:#000;
                background-image: url("http://msmart.tk/upload/uploads/msmart.jpg");
                background-size: auto 100%;                  
                -webkit-background-size: cover;
                -moz-background-size: cover;
                -o-background-size: cover;
                background-size: cover;
				font-family:arial;
				margin:0;
				margin-left:10px;
  
  
  
			}
            .img {
                  filter: grayscale(0);
  filter: sepia(0);
  filter: saturate(1);
  filter: hue-rotate(0deg);
  filter: invert(0);
  filter: opacity(1);
  filter: brightness(0.3);
  filter: contrast(1);
  filter: blur(0px);
        }
			
			
			.quote {
				color:#fff;
				font-size:10px;
			}
			
			.author {
				color:#fff;
				font-size:13px;
				float:right;
				display:block;
				font-style:oblique
			}
			
		</style>    
    
    
     <script>
function startTime() {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    m = checkTime(m);
    s = checkTime(s);
    var hours =
    ["12","1","2","3","4","5","6","7","8","9","10","11","12","1","2","3","4","5","6","7","8","9","10","11"];

    var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];

    var months =
    ["January","February","March","April","May","June","July","August","September","October","November","December"];

    var ampm = "";

    if(today.getHours<12)
    {
        ampm = "AM";
    }
    else
    {
        ampm = "PM";
    }

    var blinkSec = " ";

    if(s%2 != 0)
    {
        blinkSec= ".";
    }

    else
    {
        blinkSec= "..";
    }

    document.getElementById('txt').innerHTML =
    hours[h] + ":" + m + " " + ampm;

    document.getElementById('sec').innerHTML = blinkSec;

    document.getElementById('date').innerHTML =
    days[today.getDay()] + ", " + months[today.getMonth()] + " " + today.getDate() + ", " + today.getFullYear();

    var t = setTimeout(startTime, 500);
}

function checkTime(i) {
    if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
    return i;
}
</script>   
    
    

</head>

<body class="img" onload="startTime()">
    <!-- Paste this code after body tag -->
	<div class="se-pre-con"></div>
	<!-- Ends -->
<div style="cursor: none;">
<!--  *******************Time Display Left******************** --> 
    <table style="width:100%">
  <tr>
    <td>
<div align="left" style="color:white">

<div>
    <div id="sec" style="color: red;text-align: center; font-family: helvetica;font-size: 20px;"></div>
    <div id="txt" style="color: white; text-align: center; font-family: helvetica; font-weight: normal; font-size: 70px;"></div>
    <div id="date" style="color: white;text-align: center; font-family: helvetica;font-size: 20px;"></div>
  </div>
<!--

    
 <!--  
<pre>   


    <iframe scrolling="no" frameborder="no" clocktype="html5" style="overflow:hidden;border:0;margin:0;padding:0;width:240px;height:80px;"src="http://www.clocklink.com/html5embed.php?clock=004&timezone=GMT0530&color=white&size=240&Title=&Message=&Target=&From=2016,1,1,0,0,0&Color=white"></iframe>
    <p align="left" style="margin:15;font-size:100%;font-family:Lucida Console">
    <script language="Javascript" >

var dayName = new Array ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
var monName = new Array ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
var now = new Date
document.write(dayName[now.getDay()] + ", " + monName[now.getMonth()] + " "+now.getDate() +".")

</script></p>  
  </pre>
  -->
  
  
  
  
  
  
  
  
  
  
</div>
</td>
      <!--  *******************Time Display Right******************** --> 
      
      <td>

    <div id="calendar" align="left" style="color:white"></div>

<script src="files/jquery.min.js"></script>
<script src="js/jquery-ui-datepicker.min.js"></script>
<script>
	$('#calendar').datepicker({
		inline: true,
		firstDay: 0,
		showOtherMonths: true,
		dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
	});
</script>

</td>

  </tr>
  
</table>
    

    
    
    
  <div class="footerq" >  
<p class="msg" style="width:300px">
				<span class="quote"></span>
				<span class="author"></span>				
			</p>
      <br>
</div>

    <div class="footerc"> 

        
        <font color="white" ><strong>mSmart - News Digest</strong></font><br>
      <!-- start feedwind code --><script type="text/javascript">document.write('\x3Cscript type="text/javascript" src="' + ('https:' == document.location.protocol ? 'https://' : 'http://') + 'feed.mikle.com/js/rssmikle.js">\x3C/script>');</script><script type="text/javascript">(function() {var params = {rssmikle_url: "http://www.dnaindia.com/feeds/scitech.xml|http://www.gizbot.com/rss/news-fb.xml|http://www.careerindia.com/rss/education-news-fb.xml|http://www.hindustantimes.com/rss/topnews/rssfeed.xml",rssmikle_frame_width: "250",rssmikle_frame_height: "300",frame_height_by_article: "0",rssmikle_target: "_blank",rssmikle_font: "Geneva, Arial, sans-serif",rssmikle_font_size: "9",rssmikle_border: "off",responsive: "off",rssmikle_css_url: "",text_align: "left",text_align2: "justify",corner: "off",scrollbar: "off",autoscroll: "on",scrolldirection: "down",scrollstep: "5",mcspeed: "20",sort: "New",rssmikle_title: "off",rssmikle_title_sentence: "News Feed",rssmikle_title_link: "http://newsrack.in/crawled.feeds/hindu.todayspaper.rss.xml",rssmikle_title_bgcolor: "#0066FF",rssmikle_title_color: "#FFFFFF",rssmikle_title_bgimage: "",rssmikle_item_bgcolor: "#000000",rssmikle_item_bgimage: "",rssmikle_item_title_length: "100",rssmikle_item_title_color: "#FFFFFF",rssmikle_item_border_bottom: "on",rssmikle_item_description: "title_only",item_link: "off",rssmikle_item_description_length: "150",rssmikle_item_description_color: "#666666",rssmikle_item_date: "off",rssmikle_timezone: "Asia/Calcutta",datetime_format: "%b %e, %Y %l:%M %p",item_description_style: "text",item_thumbnail: "crop",item_thumbnail_selection: "auto",article_num: "150",rssmikle_item_podcast: "off",keyword_inc: "",keyword_exc: ""};feedwind_show_widget_iframe(params);})();</script><!--  end  feedwind code -->
        
      </div>
    <div class="footerl" style="color:#565656">
        
      
        Designed by Krishna V | <strong>mSmart - Automation Project</strong>.
          
        
    </div>
    
</div>
</body>



</html>

finala.py

Python
Python code for Raspberry
Codes are given in respective folder in above links
import sys
import telepot
import sys  #importing system files
import os #importing os files
import time #importing time control
import telepot #importing telecommunication files
import shlex
from datetime import datetime #importing date files for specifying particular date
from datetime import timedelta #importing date files for specifying particular time
import datetime as dt
import random
import subprocess as sub

import RPi.GPIO as GPIO #importing GPIO files
from functools import partial



from telepot.delegate import (
    per_chat_id_in, per_application, call, create_open, pave_event_space)


GPIO.setwarnings(False) #Stop Warnings 
GPIO.setmode(GPIO.BOARD) #Set pins mode


GPIO.setup(29,GPIO.OUT) #Set Raspi 29th pin as OUTPUT
GPIO.setup(31,GPIO.OUT) #Set Raspi 31th pin as OUTPUT
GPIO.setup(33,GPIO.OUT)#Set Raspi 33th pin as OUTPUT
GPIO.setup(35,GPIO.OUT) #Set Raspi 35th pin as OUTPUT
GPIO.setup(37,GPIO.OUT) #Set Raspi 37th pin as OUTPUT


GPIO.output(29,0) #Make pin to OFF
GPIO.output(33,0) #Make pin to OFF
GPIO.output(35,1) #Make pin to OFF
GPIO.output(37,0) #Make pin to OFF


"""
$ python3.5 finala.py <token> <owner_id>
"""




# Simulate a database to store unread messages
class UnreadStore(object):
    def __init__(self):
        self._db = {}

    def put(self, msg):
        chat_id = msg['chat']['id']

        if chat_id not in self._db:
            self._db[chat_id] = []

        self._db[chat_id].append(msg)

    # Pull all unread messages of a `chat_id`
    def pull(self, chat_id):
        messages = self._db[chat_id]
        del self._db[chat_id]

        # sort by date
        messages.sort(key=lambda m: m['date'])
        return messages

    # Tells how many unread messages per chat_id
    def unread_per_chat(self):
        return [(k,len(v)) for k,v in self._db.items()]


# Accept commands from owner. Give him unread messages.
class OwnerHandler(telepot.helper.ChatHandler):
    def __init__(self, seed_tuple, store, **kwargs):
        super(OwnerHandler, self).__init__(seed_tuple, **kwargs)
        self._store = store

    def _read_messages(self, messages):
        for msg in messages:
            # assume all messages are text
            self.sender.sendMessage(msg['text'])

    def on_chat_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)

        if content_type != 'text':
            self.sender.sendMessage("I don't understand")
            return

        command = msg['text'].strip().lower()
################################       Commands      #################################################
        # Tells who has sent you how many messages
        if command == '/start':
            self.sender.sendMessage("Welcome mSmart User! \nHow can I help you? \nGet HELP => /help ")
        if command == '/reboot':
            self.sender.sendMessage("This opeartion will turn OFF all the devices connected to it.\nPlease conform your operation by clicking clicking here /restart_now")
        elif "reboot" in command:
            self.sender.sendMessage("This opeartion will turn OFF all the devices connected to it.\nPlease conform your operation by clicking clicking here /restart_now")
        if command == '/restart_now':
            self.sender.sendMessage("You must wait 3 minutes to complete reboot! :)")
            os.system('sudo reboot')

            
            ######################################  Relays ##################################################

        if "fan on" in command:
            self.sender.sendMessage("Fan: ON")
            GPIO.output(37,1)
        if "on fan" in command:
            self.sender.sendMessage("Fan: ON")
            GPIO.output(37,1)
        if command == '/fan_on':
            self.sender.sendMessage("Fan: ON")
            GPIO.output(37,1)
            #######
        if "off fan" in command:
            self.sender.sendMessage("Fan: OFF")
            GPIO.output(37,0)
        if "fan off" in command:
            self.sender.sendMessage("Fan: OFF")
            GPIO.output(37,0)
        if command == '/fan_off':
            self.sender.sendMessage("Fan: OFF")
            GPIO.output(37,0)
            ########
        if "light on" in command:
            self.sender.sendMessage("Light: ON")
            GPIO.output(33,1)
        if "on light" in command:
            self.sender.sendMessage("Light: ON")
            GPIO.output(33,1)
        if command == '/light_on':
            self.sender.sendMessage("Light: ON")
            GPIO.output(33,1)
            #######
        if "off light" in command:
            self.sender.sendMessage("Light: OFF")
            GPIO.output(33,0)
        if "light off" in command:
            self.sender.sendMessage("Light: OFF")
            GPIO.output(33,0)
        if "lights off" in command:
            self.sender.sendMessage("Light: OFF")
            GPIO.output(33,0)
        if command == '/light_off':
            self.sender.sendMessage("Light: OFF")
            GPIO.output(33,0)
            #########
        if "cooler on" in command:
            self.sender.sendMessage("Cooler: ON")
            self.sender.sendMessage("Cooling makes the device to work proper.")
            self.sender.sendMessage("Good! Go ahead.")
            GPIO.output(35,1)
        if "on cooler" in command:
            self.sender.sendMessage("Cooler: ON")
            self.sender.sendMessage("Cooling makes the device to work proper.")
            self.sender.sendMessage("Good! Go ahead.")
            GPIO.output(35,1)
        if command == '/cooler_on':
            self.sender.sendMessage("Cooler: ON")
            self.sender.sendMessage("Cooling makes the device to work proper.")
            self.sender.sendMessage("Good! Go ahead.")
            GPIO.output(35,1)
            #########
        if "off cooler" in command:
            self.sender.sendMessage("Cooler: OFF")
            self.sender.sendMessage("Good to save energy when it is not needed. But make sure that your device is cool! ;)")
            GPIO.output(35,0)
        if "cooler off" in command:
            self.sender.sendMessage("Cooler: OFF")
            self.sender.sendMessage("Good to save energy when it is not needed. But make sure that your device is cool! ;)")
            GPIO.output(35,0)
        if command == '/cooler_off':
            self.sender.sendMessage("Cooler: OFF")
            self.sender.sendMessage("Good to save energy when it is not needed. But make sure that your device is cool! ;)")
            GPIO.output(35,0)
            ##########
        if "all off" in command:
            self.sender.sendMessage("Are you really want turn off all devices? \n To confirm click /turn_off_done")
        if "off all" in command:
            self.sender.sendMessage("Are you really want turn off all devices? \n To confirm click /turn_off_done")
        if command == '/turn_off_all':
            self.sender.sendMessage("Are you really want turn off all devices? \n To confirm click /turn_off_done")
        if command == '/turn_off_done':
            self.sender.sendMessage("Wait ;)")
            
            GPIO.output(33,0)
            GPIO.output(35,1)
            GPIO.output(37,0)
            self.sender.sendMessage("Everything is OFF now.")
            self.sender.sendMessage("Thanks for making me to save energy!!")
            ############
        if "id" in command:
            self.sender.sendMessage("Your ID is:")
            self.sender.sendMessage(chat_id)
            
        if command == '/id':
            self.sender.sendMessage("Your ID is:")
            self.sender.sendMessage(chat_id)
            
        if (command == '/help') or (command == '?'):
            self.sender.sendMessage("Are you struggling in anything? [OR] \nHow can I help you? \n\n mSmart App support these commands:\n\n/light_on - Turn ON room light \n/light_off - Turn OFF room light \n/fan_on - Turn ON fan\n/fan_off - Turn OFF fan\n/turn_off_all - Turn OFF all when you are out \n/id - To get unique id \n/help - To get help \n/contact - Contact mSmart \n/reboot - To reboot your mSmart device\n\n\n Thankyou for using our device.")
        if command == '/contact':
            self.sender.sendMessage("Have any query? \n Interest to ask quote for our project?\n\nContact @krishna4291083")

##################################  Chat Conversation   ##############################################
        hiw = ["hi", "hai", "hello", "hey"]
        if any(x in command for x in hiw):
            him = ["Hello","Hai","Hai Hai","Hey"]
            himm=random.choice(him)
            self.sender.sendMessage(himm)
            
        if command == 'good morning':
            self.sender.sendMessage("Good morning,, buddy")
        if command == 'gn':
            self.sender.sendMessage("Good night")
        if command == 'gm':
            self.sender.sendMessage("Good morning")
        if command == 'tc':
            self.sender.sendMessage("Take care.")
        if command == 'sri':
            self.sender.sendMessage("Krishna")
        if command == 'db':
            self.sender.sendMessage("Kittu")
            ####
        if "blah" in command:
            self.sender.sendMessage("ya! Bla Bla!")



################################# End of Conversation ###############################################
class MessageSaver(telepot.helper.Monitor):
    def __init__(self, seed_tuple, store, exclude):
        # The `capture` criteria means to capture all messages.
        super(MessageSaver, self).__init__(seed_tuple, capture=[[lambda msg: not telepot.is_event(msg)]])
        self._store = store
        self._exclude = exclude

    # Store every message, except those whose sender is in the exclude list, or non-text messages.
    def on_chat_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)

        if chat_id in self._exclude:
            print('Chat id %d is excluded.' % chat_id)
            return

        if content_type != 'text':
            print('Content type %s is ignored.' % content_type)
            return

        print('Storing message: %s' % msg)
        self._store.put(msg)


import threading

class CustomThread(threading.Thread):
    def start(self):
        print('CustomThread starting ...')
        super(CustomThread, self).start()

# Note how this function wraps around the `call()` function below to implement
# a custom thread for delegation.
def custom_thread(func):
    def f(seed_tuple):
        target = func(seed_tuple)

        if type(target) is tuple:
            run, args, kwargs = target
            t = CustomThread(target=run, args=args, kwargs=kwargs)
        else:
            t = CustomThread(target=target)

        return t
    return f


class ChatBox(telepot.DelegatorBot):
    def __init__(self, token, owner_id):
        self._owner_id = owner_id
        self._seen = set()
        self._store = UnreadStore()

        super(ChatBox, self).__init__(token, [
            # Here is a delegate to specially handle owner commands.
            pave_event_space()(
                per_chat_id_in([owner_id]), create_open, OwnerHandler, self._store, timeout=20),

            # Only one MessageSaver is ever spawned for entire application.
            (per_application(), create_open(MessageSaver, self._store, exclude=[owner_id])),

            # For senders never seen before, send him a welcome message.
            (self._is_newcomer, custom_thread(call(self._send_welcome))),
        ])

    # seed-calculating function: use returned value to indicate whether to spawn a delegate
    def _is_newcomer(self, msg):
        if telepot.is_event(msg):
            return None

        chat_id = msg['chat']['id']
        if chat_id == self._owner_id:  # Sender is owner
            return None  # No delegate spawned

        if chat_id in self._seen:  # Sender has been seen before
            return None  # No delegate spawned

        self._seen.add(chat_id)
        return []  # non-hashable ==> delegates are independent, no seed association is made.

    def _send_welcome(self, seed_tuple):
        chat_id = seed_tuple[1]['chat']['id']


        print('Sending welcome ...')
        self.sendMessage(chat_id, 'Hello! You do not have any authority  to use this bot. Contact mSmart Device Manager @krishna4291083')


TOKEN = sys.argv[1]
OWNER_ID = int(sys.argv[2])

bot = ChatBox(TOKEN, OWNER_ID)
bot.message_loop(run_forever='Listening ...')

Credits

KRISHNARAJ V
1 project • 61 followers
Software Trainee | Electrical and Electronics Engineer | Embedded Systems | Internet of Things | Electronic Hobbiest

Comments