コード例 #1
0
ファイル: tg.py プロジェクト: subins2000/wat-bridge
def add_contact(message):
    """Add a new Whatsapp contact to the database.

    Message has the following format:

        /add <name> <phone>

    Args:
        message: Received Telegram message.
    """
    if message.chat.id != SETTINGS['owner']:
        tgbot.reply_to(message, 'You are not the owner of this bot')
        return

    # Get name and phone
    args = telebot.util.extract_arguments(message.text)
    name, phone = args.split(maxsplit=1)

    if not name or not phone:
        tgbot.reply_to(message, 'Syntax: /add <name> <phone>')
        return

    # Check if it already exists
    if get_contact(phone) or get_phone(name):
        tgbot.reply_to(message, 'A contact with those details already exists')
        return

    # Add to database
    db_add_contact(name, phone)

    tgbot.reply_to(message, 'Contact added')
コード例 #2
0
def link(message):
    """Link a WhatsApp group

    Message has the following format:

        /link <group_id>

    Args:
        message: Received Telegram message.
    """
    if message.chat.type not in ['group', 'supergroup']:
        tgbot.reply_to(message, 'This operation can be done only in a group')
        return

    # Get name and message
    wa_group_id = telebot.util.extract_arguments(message.text)
    wa_group_name = wa_id_to_name(wa_group_id)

    if not wa_group_id:
        tgbot.reply_to(message, 'Syntax: /link <groupID>')
        return

    # Add to database
    db_add_contact(wa_group_name, wa_group_id)

    # Add to database
    db_set_group(wa_group_name, message.chat.id)

    tgbot.reply_to(
        message,
        'Bridge Connected. Please subscribe to @WhatAppStatus for the bridge server informations. \r\n While this service is free, I still have to pay for the servers, so please consider becoming a supporter at https://buymeacoff.ee/SpEcHiDe \r\n This message won\'t appear again! Enjoy the \'free\' service!!'
    )
コード例 #3
0
ファイル: tg.py プロジェクト: subins2000/wat-bridge
def link(message):
    """Link a WhatsApp group

    Message has the following format:

        /link <group_id>

    Args:
        message: Received Telegram message.
    """
    if message.chat.type not in ['group', 'supergroup']:
        tgbot.reply_to(message, 'This operation can be done only in a group')
        return

    # Get name and message
    wa_group_id = telebot.util.extract_arguments(message.text)
    wa_group_name = wa_id_to_name(wa_group_id)

    if not wa_group_id:
        tgbot.reply_to(message, 'Syntax: /link <groupID>')
        return

    # Add to database
    db_add_contact(wa_group_name, wa_group_id)

    # Add to database
    db_set_group(wa_group_name, message.chat.id)

    tgbot.reply_to(
        message,
        'Bridge Connected. Please subscribe to @WhatAppStatus for the bridge server informations.'
    )
コード例 #4
0
    def on_message(self, message):
        """Received a message."""
        # Parse information
        sender = message.getFrom(full=False)
        oidtotg = message.getFrom(full=True)

        logger.debug('received message from %s' % oidtotg)

        # Send receipt
        receipt = OutgoingReceiptProtocolEntity(message.getId(),
                                                message.getFrom(), 'read',
                                                message.getParticipant())

        self.toLower(receipt)

        # https://github.com/tgalal/yowsup/issues/1411#issuecomment-203419530
        # if isinstance(type(message), unicode) :
        # message = message.encode('utf-8')
        # entity = TextMessageProtocolEntity(message, sender)
        # self.toLower(entity)

        # Do stuff
        if is_blacklisted(sender):
            logger.debug('phone is blacklisted: %s' % sender)
            return

        participant = message.getParticipant()
        if participant:
            participant = participant.strip("@s.whatsapp.net")
        else:
            participant = sender

        contact_name = get_contact(participant)

        # body = "<" + oidtotg + ">: " + message.getBody()
        # body = "NULL"
        if message.getType() == "text":
            logger.debug("is text message")
            body = message.getBody().decode()

            if body == '/getID' or body == '/link':
                self.send_msg(phone=sender, message="/link " + sender)

                HelpInstructions = "Please send the above message in the Telegram group that you would like to bridge!"
                self.send_msg(phone=sender, message=HelpInstructions)
                # self.send_msg(phone=sender, message="new registrations are closed. please contact https://youtu.be/9r-yzKfL8xw for bridging Telegram ")
                return
            elif body[0:5] == '/add ':
                if participant == sender:
                    name = body[5:]
                    if not name:
                        ReplyMessage = "Syntax: /add <name>"
                    else:
                        if contact_name:
                            db_rm_contact(contact_name)
                            db_add_contact(name, sender)
                            ReplyMessage = "name already existed. name removed and added. Pleae verify with ```/me```"
                        else:
                            db_add_contact(name, sender)
                            ReplyMessage = "name added. Pleae verify with ```/me```"
                    self.send_msg(phone=sender, message=ReplyMessage)
                    return
            elif body == '/me':
                if not contact_name:
                    ReplyMessage = "Please send ```/add NAME``` to add you to my contacts."
                else:
                    ReplyMessage = "I have saved your name as " + contact_name + ". You can edit your name in my contacts by sending ```/add NAME```!"
                if participant == sender:
                    self.send_msg(phone=sender, message=ReplyMessage)
                    return

            elif body == '/bridgeOn':
                toggle = db_toggle_bridge_by_wa(sender, True)

                if toggle is None:
                    Message = 'This group is not bridged to anywhere. Use ```/link``` to start bridging.'
                else:
                    Message = 'Bridge has been turned on!'

                self.send_msg(phone=sender, message=Message)

                return

            elif body == '/bridgeOff':
                toggle = db_toggle_bridge_by_wa(sender, False)

                if toggle is None:
                    Message = 'This group is not bridged to anywhere. Use ```/link``` to start bridging.'
                else:
                    Message = 'Bridge has been turned off. Use ```/bridgeOn``` to turn it back on.'

                self.send_msg(phone=sender, message=Message)

                return

            if not db_is_bridge_enabled_by_wa(sender):
                return

            logger.info("prefix WHO send this message, to message")
            if contact_name:
                TheRealMessageToSend = "<#" + contact_name + ">: " + body
            else:
                TheRealMessageToSend = "<" + participant + ">: " + body

            # Relay to Telegram
            logger.info('relaying message to Telegram')
            SIGNAL_TG.send('wabot',
                           phone=sender,
                           message=TheRealMessageToSend,
                           media=False)

        if message.getType() == "media":
            if not os.path.exists("./DOWNLOADS"):
                os.makedirs("./DOWNLOADS")
            # set unique filename
            uniqueFilename = "./DOWNLOADS/%s-%s%s" % (hashlib.md5(
                str(message.getFrom(False)).encode('utf-8')).hexdigest(),
                                                      uuid.uuid4().hex,
                                                      message.getExtension())
            if message.getMediaType() == "image":
                logger.info("Echoing image %s to %s" %
                            (message.url, message.getFrom(False)))
                data = message.getMediaContent()
                f = open(uniqueFilename, 'wb')
                f.write(data)
                f.close()
            # https://github.com/AragurDEV/yowsup/pull/37
            elif message.getMediaType() == "video":
                logger.info("Echoing video %s to %s" %
                            (message.url, message.getFrom(False)))
                data = message.getMediaContent()
                f = open(uniqueFilename, 'wb')
                f.write(data)
                f.close()
            elif message.getMediaType() == "audio":
                logger.info("Echoing audio %s to %s" %
                            (message.url, message.getFrom(False)))
                data = message.getMediaContent()
                f = open(uniqueFilename, 'wb')
                f.write(data)
                f.close()
            elif message.getMediaType() == "document":
                logger.info("Echoing document %s to %s" %
                            (message.url, message.getFrom(False)))
                data = message.getMediaContent()
                f = open(uniqueFilename, 'wb')
                f.write(data)
                f.close()
            elif message.getMediaType() == "location":
                logger.info("Echoing location (%s, %s) to %s" %
                            (message.getLatitude(), message.getLongitude(),
                             message.getFrom(False)))
                uniqueFilename = "LOCATION=|=|=" + message.getLatitude(
                ) + "=|=|=" + message.getLongitude()
            elif message.getMediaType() == "vcard":
                logger.info("Echoing vcard (%s, %s) to %s" %
                            (message.getName(), message.getCardData(),
                             message.getFrom(False)))
                uniqueFilename = "VCARDCONTACT=|=|=" + message.getName(
                ) + "=|=|=" + message.getCardData()
            if contact_name:
                TheRealMessageToSend = contact_name + "=|=|=" + uniqueFilename
            else:
                TheRealMessageToSend = participant + "=|=|=" + uniqueFilename
            # Relay to Telegram
            logger.info('relaying message to Telegram')
            SIGNAL_TG.send('wabot',
                           phone=sender,
                           message=TheRealMessageToSend,
                           media=True)
コード例 #5
0
ファイル: wa.py プロジェクト: RMPR/voltaire-bot
    def on_message(self, message):
        """Received a message."""
        # Parse information
        sender = message.getFrom(full=False)
        oidtotg = message.getFrom(full=True)

        logger.debug('received message from %s' % oidtotg)

        # Send receipt
        receipt = OutgoingReceiptProtocolEntity(message.getId(),
                                                message.getFrom(), 'read',
                                                message.getParticipant())

        self.toLower(receipt)

        # https://github.com/tgalal/yowsup/issues/1411#issuecomment-203419530
        # if isinstance(type(message), unicode) :
        # message = message.encode('utf-8')
        # entity = TextMessageProtocolEntity(message, sender)
        # self.toLower(entity)

        # Do stuff
        if is_blacklisted(sender):
            logger.debug('phone is blacklisted: %s' % sender)
            return

        participant = message.getParticipant()
        if participant:
            participant = participant.strip("@s.whatsapp.net")
        else:
            participant = sender

        contact_name = get_contact(participant)

        # body = "<" + oidtotg + ">: " + message.getBody()
        # body = "NULL"
        if message.getType() == "text":
            logger.debug("is text message")
            if (isinstance(message, TextMessageProtocolEntity)):
                body = message.conversation
            else:
                body = message.text

            if body == '/getID' or body == '/link':
                self.send_msg(phone=sender, message="/link " + sender)

                HelpInstructions = "Please send the above message in the Telegram group that you would like to bridge!"
                self.send_msg(phone=sender, message=HelpInstructions)
                # self.send_msg(phone=sender, message="new registrations are closed. please contact https://youtu.be/9r-yzKfL8xw for bridging Telegram ")
                return
            elif body[0:5] == '/add ':
                if participant == sender:
                    name = body[5:]
                    if not name:
                        ReplyMessage = "Syntax: /add <name>"
                    else:
                        if contact_name:
                            db_rm_contact(contact_name)
                            db_add_contact(name, sender)
                            ReplyMessage = "name already existed. name removed and added. Pleae verify with ```/me```"
                        else:
                            db_add_contact(name, sender)
                            ReplyMessage = "name added. Pleae verify with ```/me```"
                    self.send_msg(phone=sender, message=ReplyMessage)
                    return
            elif body == '/me':
                if not contact_name:
                    ReplyMessage = "Please send ```/add NAME``` to add you to my contacts."
                else:
                    ReplyMessage = "I have saved your name as " + contact_name + ". You can edit your name in my contacts by sending ```/add NAME```!"
                if participant == sender:
                    self.send_msg(phone=sender, message=ReplyMessage)
                    return

            elif body == '/bridgeOn':
                toggle = db_toggle_bridge_by_wa(sender, True)

                if toggle is None:
                    Message = 'This group is not bridged to anywhere. Use ```/link``` to start bridging.'
                else:
                    Message = 'Bridge has been turned on!'

                self.send_msg(phone=sender, message=Message)

                return

            elif body == '/bridgeOff':
                toggle = db_toggle_bridge_by_wa(sender, False)

                if toggle is None:
                    Message = 'This group is not bridged to anywhere. Use ```/link``` to start bridging.'
                else:
                    Message = 'Bridge has been turned off. Use ```/bridgeOn``` to turn it back on.'

                self.send_msg(phone=sender, message=Message)

                return

            if not db_is_bridge_enabled_by_wa(sender):
                return

            logger.info("prefix WHO send this message, to message")
            if contact_name:
                TheRealMessageToSend = "<#" + contact_name + ">: " + body
            else:
                TheRealMessageToSend = "<" + participant + ">: " + body

            # Relay to Telegram
            logger.info('relaying message to Telegram')
            SIGNAL_TG.send('wabot',
                           phone=sender,
                           message=TheRealMessageToSend,
                           media=False)

        if message.getType() == "media":
            pass
            """