Exemple #1
0
def get_client():
    if is_python2():
        if not os.path.exists("/usr/lib/python2.7/dist-packages/pip"):
            log.clear(NAME)
            log.info(NAME, _('PIP is not installed.'))
            log.info(NAME, _('Please wait installing python-pip...'))
            log.info(NAME, _('This operation takes longer (minutes)...'))
            cmd = "sudo apt-get install python-pip -y"
            proc_install(cmd)
    else:
        if not os.path.exists("/usr/lib/python3/dist-packages/pip"):
            log.clear(NAME)
            log.info(NAME, _('PIP3 is not installed.'))
            log.info(NAME, _('Please wait installing python3-pip...'))
            log.info(NAME, _('This operation takes longer (minutes)...'))
            cmd = "sudo apt-get install python3-pip -y"
            proc_install(cmd)                

    try:
        import paho.mqtt.client as mqtt
    except ImportError:
        log.error(NAME, _('MQTT Plugin requires paho mqtt.'))
        log.info(NAME, _('Paho-mqtt is not installed.'))
        log.info(NAME, _('Please wait installing paho-mqtt...'))
        log.info(NAME, _('This operation takes longer (minutes)...'))
        if is_python2():
            cmd = "sudo pip install paho-mqtt"
        else:
            cmd = "sudo pip3 install paho-mqtt"    
        proc_install(cmd)
    try:
        import paho.mqtt.client as mqtt
    except ImportError:      
        mqtt = None
        log.error(NAME, _('Error try install paho-mqtt manually.'))
        time.sleep(60)
 
    if mqtt is not None and plugin_options["use_mqtt"]:  
        try:
            _client = mqtt.Client(options.name)                  # Use system name as client ID 
            _client.on_connect = on_connect                      # flag = 1 is connected
            _client.on_disconnect = on_disconnect                # flag = 0 is disconnected
            _client.on_message = on_message                      # Attach function to callback            
            log.clear(NAME)
            log.info(NAME, datetime_string() + ' ' + _('Connecting to broker') + '...')
            _client.username_pw_set(plugin_options['user_name'], plugin_options['user_password'])
            _client.connect(plugin_options['broker_host'], plugin_options['broker_port'], 60)
            _client.loop_start()
            log.info(NAME, datetime_string() + ' ' + _('OK'))
            return _client
            
        except Exception:
            log.error(NAME, _('MQTT plugin couldnot initalize client') + ':\n' + traceback.format_exc())
            pass
            return None
Exemple #2
0
    def run(self):
        last_msg = ''
        act_msg = ''
        ven_blind = None

        if plugin_options['use_footer']:
            ven_blind = showInFooter(
            )  #  instantiate class to enable data in footer
            ven_blind.button = "venetian_blind/home"  # button redirect on footer
            ven_blind.label = _(u'Venetian blind')  # label on footer

        while not self._stop_event.is_set():
            try:
                if plugin_options['use_control']:  # if plugin is enabled
                    show_msg = read_blinds_status()
                    if plugin_options['use_footer']:  # if footer is enabled
                        if ven_blind is not None:
                            if is_python2():  # in Python 2
                                ven_blind.val = show_msg
                            else:  # in Python 3
                                ven_blind.val = show_msg.encode('utf8').decode(
                                    'utf8')  # value on footer
                else:
                    act_msg = _('Venetian blind is disabled.')
                    if act_msg != last_msg:
                        log.clear(NAME)
                        log.info(NAME, act_msg)
                        last_msg = act_msg
                        if plugin_options['use_footer']:
                            if ven_blind is not None:
                                if is_python2():
                                    ven_blind.val = act_msg
                                else:
                                    ven_blind.val = act_msg.encode(
                                        'utf8').decode(
                                            'utf8')  # value on footer

                self._sleep(2)

            except Exception:
                log.error(
                    NAME,
                    _('Venetian blind plug-in') + ':\n' +
                    traceback.format_exc())
                pass
Exemple #3
0
 def _announce(self, txt):
     bot = self.bot
     for chat_id in list(self._currentChats):
         try:
             if is_python2():
                 bot.sendMessage(chat_id, text=txt.encode('utf-8'))
             else:    
                 bot.sendMessage(chat_id, text=txt) 
         except:
             pass    
Exemple #4
0
 def _botCmd_subscribe(self, bot, update):
     chats = self._currentChats
     txt=''
     if update.message.chat.id not in list(chats):
         chats.append(update.message.chat.id)
         self._currentChats = chats
         plugin_options['currentChats'] = chats
         txt= _(u'Hi! you are now added to the {} announcement.').format(options.name)
         log.info(NAME, txt)
         if is_python2():
             bot.sendMessage(update.message.chat.id, text=txt.encode('utf-8'))
         else:    
             bot.sendMessage(update.message.chat.id, text=txt)            
     else:
         txt= _(u'Sorry, please enter the correct AccessKey!')
         log.info(NAME, txt)
         if is_python2():
             bot.sendMessage(update.message.chat.id, text=txt.encode('utf-8'))
         else:    
             bot.sendMessage(update.message.chat.id, text=txt) 
Exemple #5
0
 def _botCmd_disable(self, bot, update):                   # msg for switch scheduler to off
     chat_id = update.message.chat.id
     if chat_id in list(self._currentChats):
         txt = _(u'{} System - scheduler OFF.').format(options.name)
         options.scheduler_enabled = False 
     else:
         txt = _(u'Sorry I can not do that.')
     if is_python2():
         bot.sendMessage(chat_id, text=txt.encode('utf-8'))
     else:    
         bot.sendMessage(chat_id, text=txt)
Exemple #6
0
def average_list(lst):
    ### Average of a list ###
    try:
        if is_python2():
            return int(sum(lst) / float(len(lst)))
        else:
            import statistics
            return int(statistics.mean(lst))
    except:
        log.error(
            NAME,
            _(u'Water Tank Monitor plug-in') + ':\n' + traceback.format_exc())
        return -1
Exemple #7
0
 def _botCmd_stop(self, bot, update):                      # msg for stop all station and disable scheduler
     chat_id = update.message.chat.id
     if chat_id in list(self._currentChats):
         txt = _(u'{} System - scheduler OFF. All stations OFF.').format(options.name)
         programs.run_now_program = None
         run_once.clear()
         log.finish_run(None)
         stations.clear() 
     else:
         txt = _(u'Sorry I can not do that.')   
     if is_python2():
         bot.sendMessage(chat_id, text=txt.encode('utf-8'))
     else:    
         bot.sendMessage(chat_id, text=txt)    
Exemple #8
0
 def _botCmd_help(self, bot, update):
     chat_id = update.message.chat.id
     if chat_id in list(self._currentChats):
         txt = _(u'Help: /{}\n Info Command: /{}\n Enable Command: /{}\n Disable Command: /{}\n Stop Command: /{}\n Run Once Command: /{}\n (use program number as argument).\n /subscribe Subscribe to the Announcement list, need an access Key.').format(
             plugin_options['help_cmd'],
             plugin_options['info_cmd'],
             plugin_options['enable_cmd'],
             plugin_options['disable_cmd'],
             plugin_options['stop_cmd'],
             plugin_options['runOnce_cmd']
         )
     else:
         txt = _(u'Sorry I can not do that.')
     if is_python2():
         bot.sendMessage(chat_id, text=txt.encode('utf-8'))
     else:    
         bot.sendMessage(chat_id, text=txt) 
Exemple #9
0
def send_data(text):
    """Send GET data"""
    if remote_options['use'] != '' and remote_options[
            'api'] != '' and remote_options['rem_adr'] != '':
        if is_python2():
            from urllib2 import urlopen
            from urllib import quote_plus
        else:
            from urllib.request import urlopen
            from urllib.parse import quote_plus

        url = remote_options['rem_adr'] + 'save.php/?' + text
        data = urlopen(url)
        log.info(
            NAME,
            _(u'Remote server reply') + ':\n' + data.read().decode('utf-8'))
    else:
        raise Exception(_(u'Remote plug-in is not properly configured') + '!')
Exemple #10
0
 def _botCmd_runOnce(self, bot, update, args):             # run-now program xx
     chat_id = update.message.chat.id
     if chat_id in list(self._currentChats):
         txt = _(u'{} RunOnce: program {}.').format(options.name, args)
         for program in programs.get():
             if (program.index == int(args-1)):   
                 options.manual_mode = False   
                 log.finish_run(None)
                 stations.clear()    
                 programs.run_now(program.index)
                 break       
             program.index+1
     else:
         txt = _(u'Sorry I can not do that.')   
     if is_python2():
         bot.sendMessage(chat_id, text=txt.encode('utf-8'))
     else:    
         bot.sendMessage(chat_id, text=txt)
Exemple #11
0
    def _is_started(self):
        """Returns true if watchdog is started."""
        try:
            cmd = "sudo service watchdog status"
            run_process(cmd)
            if is_python2():
                import commands
                output = commands.getoutput('ps -A')
            else:
                output = subprocess.getoutput('ps -A')
            if 'watchdog' in output:
                self.status['service_state'] = True
            else:
                self.status['service_state'] = False

        except Exception:
            self.started.set()
            log.error(
                NAME,
                _('System watchodg plug-in') + ':\n' + traceback.format_exc())
            self._sleep(60)
Exemple #12
0
def postRequest(url, params, json_resp=True, body_size=65535):
    # Netatmo response body size limited to 64k (should be under 16k)
    if is_python2():
        params = urlencode(params)
        headers = {
            "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
        }
        req = urllib2.Request(url=url, data=params, headers=headers)
        resp = urllib2.urlopen(req).read(body_size)
    else:
        req = urllib.request.Request(url)
        req.add_header("Content-Type",
                       "application/x-www-form-urlencoded;charset=utf-8")
        params = urllib.parse.urlencode(params).encode('utf-8')
        resp = urllib.request.urlopen(req,
                                      params).read(body_size).decode("utf-8")

    if json_resp:
        return json.loads(resp)
    else:
        return resp
Exemple #13
0
 def _botCmd_info(self, bot, update):
     chat_id = update.message.chat.id
     if chat_id in list(self._currentChats):
         txt =  _(u'Info from {}\n').format(options.name)
         for station in stations.get():
             txt += _(u'Station: {} State: ').format(station.name)
             if station.active:
                 txt += _(u'ON') + u' ('
                 if(station.remaining_seconds == -1):
                     txt += _(u'Forever') + u')'
                 else:    
                     txt += _(u'{}').format(str(int(station.remaining_seconds))) + u')'
             else:
                 txt += _(u'OFF')
             txt += '\n'    
         txt += _(u'Scheduler is {}.\n').format( _(u'enabled') if options.scheduler_enabled else _(u'disabled'))    
     else:
         txt = _(u'Sorry I can not do that.')
     if is_python2():
         bot.sendMessage(chat_id, text=txt.encode('utf-8'))
     else:    
         bot.sendMessage(chat_id, text=txt)
Exemple #14
0
    def run(self):
        once_text = True
        two_text = True

        while not self._stop_event.is_set():
            try:
                if sms_options["use_sms"]:  # if use_sms is enable (on)
                    if two_text:
                        log.clear(NAME)
                        log.info(NAME, _(u'SMS Modem plug-in is enabled'))
                        once_text = True
                        two_text = False
                        if not os.path.exists("/usr/bin/gammu"):
                            #http://askubuntu.com/questions/448358/automating-apt-get-install-with-assume-yes
                            #sudo apt-get install -y gammu
                            #sudo apt-get install -y python-gammu
                            #sudo apt-get install python3-gammu
                            log.clear(NAME)
                            log.info(NAME, _(u'Gammu is not installed.'))
                            log.info(NAME,
                                     _(u'Please wait installing Gammu...'))
                            cmd = "sudo apt-get install -y gammu"
                            proc_install(self, cmd)
                            if is_python2():
                                log.info(
                                    NAME,
                                    _(u'Please wait installing Python-Gammu...'
                                      ))
                                cmd = "sudo apt-get install -y python-gammu"
                            else:
                                log.info(
                                    NAME,
                                    _(u'Please wait installing Python3-Gammu...'
                                      ))
                                cmd = "sudo apt-get install -y python3-gammu"
                            proc_install(self, cmd)
                            log.info(NAME,
                                     _(u'Testing attached GSM ttyUSB...'))
                            cmd = "sudo dmesg | grep tty"
                            proc_install(self, cmd)
                        if not os.path.exists("/root/.gammurc"):
                            log.info(
                                NAME,
                                _(u'Saving Gammu config to /root/.gammurc...'))
                            f = open("/root/.gammurc", "w")
                            f.write("[gammu]\n")
                            f.write("port = /dev/ttyUSB0\n")
                            f.write("model = \n")
                            f.write("connection = at19200\n")
                            f.write("synchronizetime = yes\n")
                            f.write("logfile =\n")
                            f.close()
                    sms_check(self)  # Check SMS command from modem

                else:
                    if once_text:
                        log.clear(NAME)
                        log.info(NAME, _(u'SMS Modem plug-in is disabled'))
                        once_text = False
                        two_text = True

                self._sleep(10)

            except Exception:
                log.error(
                    NAME,
                    _(u'SMS Modem plug-in') + ':\n' + traceback.format_exc())
                self._sleep(60)
Exemple #15
0
import datetime
import web
from ospy.helpers import stop_onrain, is_python2
from ospy.log import log
from ospy.options import options, rain_blocks
from ospy.webpages import ProtectedPage
from ospy.weather import weather
from plugins import PluginOptions, plugin_url
from time import strftime

from ospy.webpages import showInFooter  # Enable plugin to display readings in UI footer

import imghdr
import warnings

if is_python2():
    from urllib import urlencode
    import urllib2
else:
    import urllib.parse, urllib.request

NAME = 'Weather-based Rain Delay'
MENU = _(u'Package: Weather-based Rain Delay')
LINK = 'settings_page'

plugin_options = PluginOptions(
    NAME, {
        'enabled': False,
        'delay_duration': 24,
        'use_netatmo': False,
        'netatmo_id': '',
Exemple #16
0
 def lcd_putc(self, char):
     if is_python2():
         self.lcd_write_char(ord(char))
     else:
         self.lcd_write_char(char)
Exemple #17
0
 def _echo(self, bot, update):
     txt= _(u'You write: {}').format(update.message.text)
     if is_python2():
         bot.sendMessage(update.message.chat.id, text=txt.encode('utf-8'))
     else:    
         bot.sendMessage(update.message.chat.id, text=txt) 
Exemple #18
0
    def run(self):
        Temperature = 0
        Humidity = 0

        last_millis = 0  # timer for save log
        var1 = True  # Auxiliary variable for once on
        var2 = True  # Auxiliary variable for once off

        air_temp = None

        if plugin_options['use_footer']:
            air_temp = showInFooter(
            )  #  instantiate class to enable data in footer
            air_temp.button = "air_temp_humi/settings"  # button redirect on footer
            air_temp.label = _(u'Temperature')  # label on footer

        regulation_text = ''

        #flow = showOnTimeline()  #  instantiate class to enable data display
        #flow.unit = _(u'Liters')
        #flow.val = 10
        #flow.clear

        while not self._stop_event.is_set():
            try:
                if plugin_options['enabled']:  # if plugin is enabled
                    log.clear(NAME)
                    log.info(NAME, datetime_string())
                    tempText = ""

                    if plugin_options[
                            'enable_dht']:  # if DHTxx probe is enabled
                        try:
                            result = 1  # 1=ERR_MISSING_DATA
                            if plugin_options['dht_type'] == 0:  # DHT11
                                result = instance.read()
                            if plugin_options['dht_type'] == 1:  # DHT22
                                result = instance22.read()

                            if result.is_valid(
                            ):  # 0=ERR_NO_ERROR, 1=ERR_MISSING_DATA, 2=ERR_CRC
                                Temperature = result.temperature
                                Humidity = result.humidity

                                global tempDHT, humiDHT

                                tempDHT = Temperature
                                humiDHT = Humidity

                        except:
                            log.clear(NAME)
                            log.info(NAME, datetime_string())
                            if plugin_options['dht_type'] == 0:  # DHT11
                                log.info(NAME, _(u'DHT11 data is not valid'))
                                tempText += ' ' + _(u'DHT11 data is not valid')
                            if plugin_options['dht_type'] == 1:  # DHT22
                                log.info(NAME, _(u'DHT22 data is not valid'))
                                tempText += ' ' + _(u'DHT22 data is not valid')

                        if Humidity and Temperature != 0:
                            self.status['temp'] = Temperature
                            self.status['humi'] = Humidity
                            log.info(
                                NAME,
                                _(u'Temperature') + ' ' + _(u'DHT') + ': ' +
                                u'%.1f \u2103' % Temperature)
                            log.info(
                                NAME,
                                _(u'Humidity') + ' ' + _(u'DHT') + ': ' +
                                u'%.1f' % Humidity + ' %RH')
                            tempText += ' ' + _(
                                u'DHT'
                            ) + ': ' + u'%.1f \u2103' % Temperature + ' ' + u'%.1f' % Humidity + ' %RH' + ' '

                            if plugin_options['enabled_reg']:
                                log.info(NAME, regulation_text)

                            station = stations.get(
                                plugin_options['control_output'])

                            if plugin_options[
                                    'enabled_reg']:  # if regulation is enabled
                                if Humidity > (plugin_options['humidity_on'] +
                                               plugin_options['hysteresis'] /
                                               2) and var1 is True:
                                    start = datetime.datetime.now()
                                    sid = station.index
                                    end = datetime.datetime.now(
                                    ) + datetime.timedelta(
                                        seconds=plugin_options['reg_ss'],
                                        minutes=plugin_options['reg_mm'])
                                    new_schedule = {
                                        'active':
                                        True,
                                        'program':
                                        -1,
                                        'station':
                                        sid,
                                        'program_name':
                                        _('Air Temperature'),
                                        'fixed':
                                        True,
                                        'cut_off':
                                        0,
                                        'manual':
                                        True,
                                        'blocked':
                                        False,
                                        'start':
                                        start,
                                        'original_start':
                                        start,
                                        'end':
                                        end,
                                        'uid':
                                        '%s-%s-%d' %
                                        (str(start), "Manual", sid),
                                        'usage':
                                        stations.get(sid).usage
                                    }

                                    log.start_run(new_schedule)
                                    stations.activate(new_schedule['station'])
                                    var1 = False
                                    var2 = True
                                    self.status['outp'] = 1
                                    regulation_text = datetime_string(
                                    ) + ' ' + _(
                                        u'Regulation set ON.'
                                    ) + ' ' + ' (' + _('Output') + ' ' + str(
                                        station.index + 1) + ').'
                                    update_log(self.status)

                                if Humidity < (plugin_options['humidity_off'] -
                                               plugin_options['hysteresis'] /
                                               2) and var2 is True:
                                    sid = station.index
                                    stations.deactivate(sid)
                                    active = log.active_runs()
                                    for interval in active:
                                        if interval['station'] == sid:
                                            log.finish_run(interval)
                                    var1 = True
                                    var2 = False
                                    self.status['outp'] = 0
                                    regulation_text = datetime_string(
                                    ) + ' ' + _(
                                        u'Regulation set OFF.'
                                    ) + ' ' + ' (' + _('Output') + ' ' + str(
                                        station.index + 1) + ').'
                                    update_log(self.status)

                    if plugin_options[
                            'ds_enabled']:  # if in plugin is enabled DS18B20
                        DS18B20_read_data(
                        )  # get read DS18B20 temperature data to global tempDS[xx]
                        tempText += _(u'DS') + ': '
                        for i in range(0, plugin_options['ds_used']):
                            self.status['DS%d' % i] = tempDS[i]
                            log.info(
                                NAME,
                                _(u'Temperature') + ' ' + _(u'DS') +
                                str(i + 1) + ' (' +
                                u'%s' % plugin_options['label_ds%d' % i] +
                                '): ' +
                                u'%.1f \u2103' % self.status['DS%d' % i])
                            tempText += u' %s' % plugin_options[
                                'label_ds%d' %
                                i] + u' %.1f \u2103' % self.status['DS%d' % i]

                    if plugin_options['enabled_reg']:
                        tempText += ' ' + regulation_text

                    if plugin_options['use_footer']:
                        if air_temp is not None:
                            if is_python2():
                                air_temp.val = tempText  # value on footer
                            else:
                                air_temp.val = tempText.encode('utf8').decode(
                                    'utf8')  # value on footer

                    if plugin_options['enable_log']:  # enabled logging
                        millis = int(round(time.time() * 1000))
                        interval = (plugin_options['log_interval'] * 60000)
                        if (millis - last_millis) > interval:
                            last_millis = millis
                            update_log(self.status)

                self._sleep(5)

            except Exception:
                log.error(
                    NAME,
                    _(u'Air Temperature and Humidity Monitor plug-in') +
                    ':\n' + traceback.format_exc())
                self._sleep(60)
Exemple #19
0
def get_overview():
    """Returns the info data as a list of lines."""
    result = []
    try:
        meminfo = helpers.get_meminfo()
        netdevs = helpers.get_netdevs()

        result.append(_('System release') + ': {}'.format(platform.release()))
        result.append(_('System name') + ': {}'.format(platform.system()))
        result.append(_('Node') + ': {}'.format(platform.node()))
        result.append(_('Machine') + ': {}'.format(platform.machine()))
        if is_python2():
            result.append(
                _('Distribution') +
                ': {} {}'.format(platform.linux_distribution()[0],
                                 platform.linux_distribution()[1]))
        else:
            try:  # python > 3.9
                import distro
                result.append(
                    _('Distribution') +
                    ': {} {}'.format(distro.linux_distribution()[0],
                                     distro.linux_distribution()[1]))
            except:  # python <= 3.9
                result.append(
                    _('Distribution') +
                    ': {} {}'.format(platform.linux_distribution()[0],
                                     platform.linux_distribution()[1]))
                pass
        result.append(_('Total memory') + ': {}'.format(meminfo['MemTotal']))
        result.append(_('Free memory') + ': {}'.format(meminfo['MemFree']))
        result.append(_('Python') + ': {}'.format(platform.python_version()))
        if netdevs:
            for dev, info in netdevs.items():
                result.append('%-16s %s MiB %s MiB' %
                              (dev + ': ', info['rx'], info['tx']))
        else:
            result.append(_('Network: Unknown'))
        result.append(_('Uptime') + ': {}'.format(helpers.uptime()))
        result.append(
            _('CPU temp') + ': {} {}'.format(
                helpers.get_cpu_temp(options.temp_unit), options.temp_unit))
        result.append(
            _('CPU usage') + ': {} %'.format(helpers.get_cpu_usage()))
        result.append(
            _('CPU serial number') + ': {}'.format(helpers.cpu_info()))
        result.append(_('MAC adress') + ': {}'.format(helpers.get_mac()))
        result.append(_('I2C HEX Adress') + ': ')
        try:
            result.append(get_all_addr())
        except Exception:
            result.append(_('Could not open any i2c device!'))

        # I2C test for Air Temperature and Humidity Monitor plugin
        if find_address(0x03):
            result.append(
                _('Found ATMEGA328 for Air Temperature and Humidity Monitor plugin (0x03).'
                  ))

        # I2C test for Water Tank Monitor plugin
        if find_address(0x04):
            result.append(
                _('Found ATMEGA328 for Water Tank Monitor plugin (0x04).'))

        # I2C test for Humidity Monitor plugin
        if find_address(0x05):
            result.append(
                _('Found ATMEGA328 for Humidity Monitor plugin (0x05).'))

        # I2C test for Button Control plugin
        if find_address(0x27):
            result.append(
                _('Found MCP23017 for Button Control plugin (0x27).'))

        # I2C test for LCD Display plugin
        search_range = {addr: 'PCF8574' for addr in range(32, 40)}
        search_range.update({addr: 'PCF8574A' for addr in range(56, 63)})
        if find_address(search_range, range=True):
            if find_address(0x27):
                result.append(
                    _('Warning: MCP23017 found for Button Control plugin (0x27). The address for PCF8574 must be different, not 0x27! If it is the same, change it on the LCD display board.'
                      ))
            result.append(
                _('Found PCF8574 for LCD Display plugin (0x20-0x28, 0x38-0x3F).'
                  ))

        # I2C test for Wind Speed Monitor/ Water Meter meter plugin
        search_range = {addr: 'PCF8583' for addr in range(80, 81)}
        if find_address(search_range, range=True):
            result.append(
                _('Found PCF8583 for Wind Speed Monitor or Water Meter plugin (0x50-0x51).'
                  ))

        # I2C test for Real Time and NTP time plugin
        if find_address(0x68):
            result.append(
                _('Found DS1307 for Real Time and NTP time plugin (0x68).'))

    except Exception:
        log.error(NAME, traceback.format_exc())
        pass

    return result
Exemple #20
0
 def _botCmd_start_chat(self, bot, update):
     txt= _(u'Hi! I am a Bot to interface with {}. /{}').format(options.name, plugin_options['help_cmd'])
     if is_python2():
         bot.sendMessage(update.message.chat.id, text=txt.encode('utf-8'))
     else:    
         bot.sendMessage(update.message.chat.id, text=txt)
Exemple #21
0
    def run(self):
        tempText = ''

        telegram_ftr = None
        
        if plugin_options['use_footer']:
            telegram_ftr = showInFooter()                         # instantiate class to enable data in footer
            telegram_ftr.button = "telegram_bot/settings"         # button redirect on footer
            telegram_ftr.label =  _(u'Telegram Bot')              # label on footer
        
        telegram_bad_import_test = False

        try:
            import telegram
        except:
            telegram_bad_import_test = True
            pass

        if telegram_bad_import_test:
            log.clear(NAME)
            log.error(NAME, _(u'Telegram not found, installing. Please wait...'))
            if is_python2():
                # https://pypi.org/project/python-telegram-bot/2.4/
                cmd = "sudo pip install python-telegram-bot==2.4"       # python 2.7 end telegram support
            else:    
                cmd = "sudo pip3 install python-telegram-bot --upgrade" # python 3+
            proc = subprocess.Popen(cmd,stderr=subprocess.STDOUT,stdout=subprocess.PIPE,shell=True)
            output = proc.communicate()[0].decode('utf8')
            log.info(NAME, u'{}'.format(output))
        
        try:
            import telegram
        except:
            telegram_bad_import_test = True
            pass

        try:
            # https://www.toptal.com/python/telegram-bot-tutorial-python
            if plugin_options['use_plugin'] and plugin_options['botToken'] != "" and not telegram_bad_import_test:    
                log.clear(NAME)
                self._currentChats = plugin_options['currentChats']
                self._lastChatDate = plugin_options['lastChatDate']

                self.bot = telegram.Bot(token = plugin_options['botToken'])
                getbot = self.bot.getMe()
                info_id = getbot.id
                plugin_options['botID'] = info_id
                info_username = getbot.username
                info_first_name = getbot.first_name
                log.info(NAME, _(u'Hi connect is OK my ID: {}, User Name: {}, First Name: {}.').format(info_id, info_username, info_first_name))
                
                if plugin_options['use_footer']:
                    tempText = _(u'Hi connect is OK my Name: {}.').format(info_username)
                    if telegram_ftr is not None:
                        telegram_ftr.val = tempText.encode('utf8').decode('utf8')

                self._announce(_(u'Bot on {} has just started!').format(options.name))

        except Exception:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            err_string = u"".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
            log.error(NAME, _(u'Telegram Bot plug-in') + ':\n' + err_string)
            if plugin_options['use_footer']:
                tempText = _(u'Telegram Bot has error, check in plugin status!')
                if telegram_ftr is not None:
                    telegram_ftr.val = tempText.encode('utf8').decode('utf8')

        zone_change = signal('zone_change')
        zone_change.connect(notify_zone_change)

        while not self._stop_event.is_set() and self.bot is not None:
            try:
                updates = self.bot.getUpdates()
                if updates:
                    for update in updates:
                        if update.message:
                            message = update.message
                        else:
                            message = None
  
                        if message is not None:
                            chat_date = message.date      # time stamp
                            chat_id = message.chat.id     # chat ID
                            msg_id = message.message_id   # msg ID
                            msg_text = message.text       # msg text
                            msg_from = u'{} {}'.format(message.chat.first_name, message.chat.last_name) # from user: first name last name

                            if msg_id != self._lastMsgID and chat_date not in self._lastChatDate:
                                self._lastMsgID = msg_id
                                self._lastChatDate.append(chat_date)
                                plugin_options['lastChatDate'] = chat_date #self._lastChatDate

                                log.clear(NAME)
                                log.info(NAME, _(u'New message: {} ID: {}.').format(msg_text, msg_id))
                                log.info(NAME, _(u'From: {} ID: {}.').format(msg_from, chat_id))
                                
                                self._echo(self.bot, update)

                                if msg_text == u'/start':
                                    self._botCmd_start_chat(self.bot, update)                                    
                                    tempText = _('Last msg: /start')
                                    log.info(NAME, tempText)
                                    plugin_options['lastChatDate'] = []
                                elif msg_text == u'/{}'.format(plugin_options['help_cmd']):
                                    self._botCmd_help(self.bot, update)
                                    tempText = _('Last msg: /{}').format(plugin_options['help_cmd'])
                                    log.info(NAME, tempText)
                                elif msg_text == u'/{}'.format(plugin_options['info_cmd']):
                                    self._botCmd_info(self.bot, update)
                                    tempText = _('Last msg: /{}').format(plugin_options['info_cmd'])
                                    log.info(NAME, tempText)
                                elif msg_text == u'/{}'.format(plugin_options['enable_cmd']):
                                    self._botCmd_enable(self.bot, update)
                                    tempText = _('Last msg: /{}').format(plugin_options['enable_cmd'])
                                    log.info(NAME, tempText)
                                elif msg_text == u'/{}'.format(plugin_options['disable_cmd']):
                                    self._botCmd_disable(self.bot, update)
                                    tempText = _('Last msg: /{}').format(plugin_options['disable_cmd'])
                                    log.info(NAME, tempText)
                                elif msg_text == u'/{}'.format(plugin_options['stop_cmd']):
                                    self._botCmd_stop(self.bot, update)
                                    tempText = _('Last msg: /{}').format(plugin_options['stop_cmd'])
                                    log.info(NAME, tempText)                                    
                                elif u'/{}'.format(plugin_options['runOnce_cmd']) in msg_text:
                                    runlen = len(u'/{}'.format(plugin_options['runOnce_cmd']))
                                    pgmid = int(msg_text[runlen:])
                                    args = pgmid
                                    self._botCmd_runOnce(self.bot, update, args)
                                    tempText = _('Last msg: /{} arg: {}').format(plugin_options['runOnce_cmd'], args)
                                    log.info(NAME, tempText)
                                elif u'/{}'.format(plugin_options['botID']) in msg_text:
                                    self._botCmd_subscribe(self.bot, update)
                                    tempText = _('Last msg: /subscribe')
                                    log.info(NAME, tempText)                                    
                                else:
                                    txt= _('Sorry command "{}" is not supported!').format(msg_text)
                                    self.bot.sendMessage(update.message.chat.id, text= txt)
                                    log.info(NAME, txt)
                                    tempText = txt
                                
                                if plugin_options['use_footer']:
                                    if telegram_ftr is not None:
                                        telegram_ftr.val = tempText.encode('utf8').decode('utf8')                                       

                self._sleep(5)
 
            except Exception:
                exc_type, exc_value, exc_traceback = sys.exc_info()
                err_string = u"".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
                log.error(NAME, _(u'Telegram Bot plug-in') + ':\n' + err_string) 
                self._sleep(30)