tdryer / hangups

the first third-party instant messaging client for Google Hangouts
https://hangups.readthedocs.io/
MIT License
1.71k stars 191 forks source link

Add more comments to examples #389

Open usamitysam opened 6 years ago

usamitysam commented 6 years ago

Thanks for the project!!!! The fact that examples exist is amazingly great. I have a philosophy recommendation for you. The examples exist so you don't have to answer stupid questions. In that spirit of saving you time and effort, you might want to spend a few minutes and adding clean separation in the code, remove command nesting and line splits. Finally consider adding painfully excessive comments to the examples. You don't need to teach a Python fundamentals course, but more package specific detailed comments would be a great addition. Helping use stupid people understand the package save you time. Example - send_message.py is ...(sorry)... pretty much unreadable. I can sort it out but by the time I get to the end of the ~20 lines I get tripped up my the nesting and line splits and have to start over from the top.

Thanks for the project, I truly appreciate it!!

tdryer commented 6 years ago

Example - send_message.py is ...(sorry)... pretty much unreadable. I can sort it out but by the time I get to the end of the ~20 lines I get tripped up my the nesting and line splits and have to start over from the top.

This is somewhat unavoidable due to the structure of the protocol messages. Perhaps using some intermediate variables would improve readability.

Thanks for the feedback!

epizarro2 commented 5 years ago
import asyncio
import datetime
import hangups
import sys
import os

REFRESH_TOKEN = '/usr/lib/zabbix/alertscripts/hangouts.token'
HANGOUTS_IDS = '/usr/lib/zabbix/alertscripts/hangouts.ids'
IMG_NAME = 'warning_black_48x48.png'
LOG = '/var/log/zabbix/zabbix_scripts.log'

if not os.path.isfile(REFRESH_TOKEN):
    print('Ejecutar: hangups --token-path '+ REFRESH_TOKEN)
    sys.exit(1)
if len(sys.argv) == 3:
    HANGOUTS_NAME = sys.argv[1]
    MESSAGE = sys.argv[2]
else:
    print('Uso: hangouts.py <HANGOUTS_NAME> <MESSAGE>')
    sys.exit(1)
if not os.path.isdir(LOG.rsplit('/',1)[0]):
    print('No existe la carpeta de logs '+ LOG.rsplit('/',1)[0])
    sys.exit(1)

def logger(log_message):
    ts = datetime.datetime.now().strftime('%d/%b/%Y:%H:%M:%S    ')
    with open(LOG, 'a+') as logger:
        logger.write(ts + log_message + '\n')

class HangupsClass(object):
    def __init__(self):
        logger('Enviando mensaje a ' + HANGOUTS_NAME)
        self.conversation_id = None
        if os.path.isfile(HANGOUTS_IDS):
            with open(HANGOUTS_IDS, encoding='utf8') as ids:
                for id in ids.readlines():
                    if HANGOUTS_NAME in id:
                        self.conversation_id = id.split('=')[1].strip()
                        logger('ID encontrado ' + self.conversation_id)
                        break
        self.refresh_token_path = REFRESH_TOKEN
        self.client = None
        self.test_hangups()

    def test_hangups(self):
        cookies = hangups.auth.get_auth_stdin(self.refresh_token_path)

        self.client = hangups.Client(cookies)
        self.client.on_connect.add_observer(lambda: asyncio.async(self.hangout_notifier(hclient=self.client, image=None)))
        loop = asyncio.get_event_loop()
        loop.run_until_complete(self.client.connect())

        self.client = hangups.Client(cookies)
        self.client.on_connect.add_observer(lambda: asyncio.async(self.hangout_notifier(hclient=self.client, image=open(IMG_NAME,'rb'))))
        loop = asyncio.get_event_loop()
        loop.run_until_complete(self.client.connect())

    async def hangout_notifier(self, hclient, image):
        notification_message = MESSAGE
        user_list, conversation_list = await hangups.build_user_conversation_list(hclient)

        # busca ID en lista de conversaciones
        if self.conversation_id is None:
            logger('ID no encontrado, buscando en listas de conversaciones')
            all_conversations = conversation_list.get_all(include_archived=False)
            exit_flag = False
            for conversation in all_conversations:
                if conversation.name:
                    if HANGOUTS_NAME in conversation.name:
                        self.conversation_id = conversation.id_
                        logger('Nuevo nombre ' + conversation.name)
                        logger('Nuevo ID ' + self.conversation_id)
                        with open(HANGOUTS_IDS, 'a+') as ids:
                            ids.write(conversation.name + '=' + self.conversation_id + '\n')
                        exit_flag = True
                else:
                    if conversation.users:
                        for user in conversation.users:
                            if HANGOUTS_NAME in user.emails and not user.is_self:
                                self.conversation_id = conversation.id_
                                logger('Nuevo correo ' + user.emails[0])
                                logger('Nuevo ID ' + self.conversation_id)
                                with open(HANGOUTS_IDS, 'a+') as ids:
                                    ids.write(user.emails[0] + '=' + self.conversation_id + '\n')
                                exit_flag = True
                if exit_flag:
                    break

        if self.conversation_id is not None:
            this_conversation = conversation_list.get(self.conversation_id)
            if image is None:
                await this_conversation.send_message([hangups.ChatMessageSegment(notification_message)], image_file=None)  # Solo mensaje
            else:
                await this_conversation.send_message([], image_file=image)  # Solo foto
        else:
            logger('ID no encontrado, saliendo')
        await hclient.disconnect()

if __name__ == '__main__':
    HangupsClass()